问:
Redirecting to a new tab in PHP
I have seen this question being asked many times here, but I couldn't get an answer that works!

i am trying to redirect to a load.php TO A NEW TAB using the following script:

```<code>echo '<script>window.open("load.php","_blank)</script>';
</code>```

for some reason it is not working and it stays on the same page.

i am using chrome!

is there any possible way to redirect to a new tab?
thanks a lot

答:
Most browsers will block window.open unless it is a result of a direct user interaction i.e. the onclick event handle of an anchor tag being fired.

There are ways you can try and "trick" popup blockers, but it is unreliable and considered bad practice. If a user has chosen to enable a popup blocker, it should be respected.

What I would suggest is to also add a link on your page along the lines of the following:

```<code><a href="load.php" target="_blank">Click here</a> if the window does not open in a seperate window.
</code>```

This would ensure that the user can still open the window manually should it be supressed by a popup blocker.

Title: Redirecting to a new tab in PHP

Body:
I have seen this question being asked many times here, but I couldn't get an answer that works!

i am trying to redirect to a load.php TO A NEW TAB using the following script:

echo '';

for some reason it is not working and it stays on the same page.

i am using chrome!

is there any possible way to redirect to a new tab?
thanks a lot

Body:
Most browsers will block window.open unless it is a result of a direct user interaction i.e. the onclick event handle of an anchor tag being fired.

There are ways you can try and "trick" popup blockers, but it is unreliable and considered bad practice. If a user has chosen to enable a popup blocker, it should be respected.

What I would suggest is to also add a link on your page along the lines of the following:

<a href="load.php" target="_blank">Click here</a> if the window does not open in a seperate window.

This would ensure that the user can still open the window manually should it be supressed by a popup blocker.


来源: stackexchange

问:
Rails js files & Page specific js
On rails I put all the JavaScript files into application js file.

```<code>//= require jquery
//= require jquery_ujs
//= require dropzone
//= require jquery.cookie
//= require toastr

//VENDOR JS BEGINS
//= require pace/pace.min
//= require modernizr.custom
//= require jquery-ui/jquery-ui.min
//= require boostrapv3/js/bootstrap.min
//= require jquery/jquery-easy
//= require jquery-unveil/jquery.unveil.min
//= require jquery-bez/jquery.bez.min
//= require jquery-ios-list/jquery.ioslist.min
//= require jquery-actual/jquery.actual.min
//= require jquery-scrollbar/jquery.scrollbar.min
//= require bootstrap-select2/select2.min
//= require switchery/js/switchery.min
//= require imagesloaded/imagesloaded.pkgd.min
//= require jquery-isotope/isotope.pkgd.min
//= require classie/classie
//= require codrops-stepsform/js/stepsForm
//= require bootstrap-datepicker/js/bootstrap-datepicker
</code>```

Then I call javascript in the head of application.html.erb as;

```<code>...
<head>
..
<%= javascript_include_tag 'application' %>
..
</head>
...
</code>```

Then I check the speed of the website and I am suggested to take this JS call to body. I know I should BTW. But the problem is with the page specific JS code.

Imagine I have home.html.erb where users select date. So I put datapicker code into this page.

If I take <%= javascript_include_tag 'application' %> into at the bottom of body, this time because the jquery & datepicker not loaded yet so page specific JS gives no method error

What would be the best approach?

答:
There is a very good answer to this at http://brandonhilkert.com/blog/page-specific-javascript-in-rails/.

Basically, you want to open your app/views/layouts/application.html.erb and convince it to give you  controller and view information each time it renders a page. To do so you change the body tag from

```<code><body>
  <%= yield %>
</body
</code>```

to

```<code><body class="<%= controller_name %> <%= action_name %>">
  <%= yield %>
</body>
</code>```

So, when rails renders the body tag it will now add a class for the controller and one of the actions in the controller.

Say you have a controller called static_pages, and the static_pages controller has

```<code>def home
end
</code>```

When rails renders the view/page home it will now add to the body tag a class of static_pages and a class of home.

```<code><body class="static_pages home">
    the home view is rendered here
</body>
</code>```

This will be a site wide change, so if you go to an index page/view from the users controller the body tag would be:

```<code><body class="users index">
    the index view is rendered here
</body>
</code>```

Now, make a file called vendor/assets/javascripts/jquery-readyselector.js containing:

```<code>(function ($) {
  var ready = $.fn.ready;
  $.fn.ready = function (fn) {
    if (this.context === undefined) {
      // The $().ready(fn) case.
      ready(fn);
    } else if (this.selector) {
      ready($.proxy(function(){
        $(this.selector, this.context).each(fn);
      }, this));
    } else {
      ready($.proxy(function(){
        $(this).each(fn);
      }, this));
    }
  }
})(jQuery);
</code>```

That file must be properly referenced in application.js

```<code>...
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery-readyselector
//= require_tree .
</code>```

Once all that is done you can test it by making a simple alert specific to the view you want test like so:

```<code>// app/assets/javascripts/static_pages_home.js

$(".static_pages.home").ready(function() {
  return alert("You should only see this on the static pages home page.");
});

// app/assets/javascripts/user_index.js

$(".users.index").ready(function() {
  return alert("You should only see this on the users index page.");
});
</code>```

You could also make a script controller specific by not referencing the action.

```<code>$(".users").ready(function() {
  return alert("You should only see this on a users controller controlled page.");
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rails js files & Page specific js

Body:
On rails I put all the JavaScript files into application js file.

//= require jquery
//= require jquery_ujs
//= require dropzone
//= require jquery.cookie
//= require toastr

//VENDOR JS BEGINS
//= require pace/pace.min
//= require modernizr.custom
//= require jquery-ui/jquery-ui.min
//= require boostrapv3/js/bootstrap.min
//= require jquery/jquery-easy
//= require jquery-unveil/jquery.unveil.min
//= require jquery-bez/jquery.bez.min
//= require jquery-ios-list/jquery.ioslist.min
//= require jquery-actual/jquery.actual.min
//= require jquery-scrollbar/jquery.scrollbar.min
//= require bootstrap-select2/select2.min
//= require switchery/js/switchery.min
//= require imagesloaded/imagesloaded.pkgd.min
//= require jquery-isotope/isotope.pkgd.min
//= require classie/classie
//= require codrops-stepsform/js/stepsForm
//= require bootstrap-datepicker/js/bootstrap-datepicker

Then I call javascript in the head of application.html.erb as;

...

..
<%= javascript_include_tag 'application' %>
..

...

Then I check the speed of the website and I am suggested to take this JS call to body. I know I should BTW. But the problem is with the page specific JS code.

Imagine I have home.html.erb where users select date. So I put datapicker code into this page.

If I take <%= javascript_include_tag 'application' %> into at the bottom of body, this time because the jquery & datepicker not loaded yet so page specific JS gives no method error

What would be the best approach?

Body:
There is a very good answer to this at http://brandonhilkert.com/blog/page-specific-javascript-in-rails/.

Basically, you want to open your app/views/layouts/application.html.erb and convince it to give you  controller and view information each time it renders a page. To do so you change the body tag from

<body>
  <%= yield %>
</body

to

<body class="<%= controller_name %> <%= action_name %>">
  <%= yield %>
</body>

So, when rails renders the body tag it will now add a class for the controller and one of the actions in the controller.

Say you have a controller called static_pages, and the static_pages controller has

def home
end

When rails renders the view/page home it will now add to the body tag a class of static_pages and a class of home.

<body class="static_pages home">
    the home view is rendered here
</body>

This will be a site wide change, so if you go to an index page/view from the users controller the body tag would be:

<body class="users index">
    the index view is rendered here
</body>

Now, make a file called vendor/assets/javascripts/jquery-readyselector.js containing:

(function ($) {
  var ready = $.fn.ready;
  $.fn.ready = function (fn) {
    if (this.context === undefined) {
      // The $().ready(fn) case.
      ready(fn);
    } else if (this.selector) {
      ready($.proxy(function(){
        $(this.selector, this.context).each(fn);
      }, this));
    } else {
      ready($.proxy(function(){
        $(this).each(fn);
      }, this));
    }
  }
})(jQuery);

That file must be properly referenced in application.js

...
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery-readyselector
//= require_tree .

Once all that is done you can test it by making a simple alert specific to the view you want test like so:

// app/assets/javascripts/static_pages_home.js

$(".static_pages.home").ready(function() {
  return alert("You should only see this on the static pages home page.");
});

// app/assets/javascripts/user_index.js

$(".users.index").ready(function() {
  return alert("You should only see this on the users index page.");
});

You could also make a script controller specific by not referencing the action.

$(".users").ready(function() {
  return alert("You should only see this on a users controller controlled page.");
});


问:
c# Loop not incrementing as expected
Hi I had a loop that was stepping through an array with each index being multiplied by two. However I changed it so that the index is multiplied by 0, then 1, then 2 etc til it hits 10. (This is j in the code below) j is not incrementing as expected and just multiplies by nine. Can anyone help? Tks</p>

```<code>using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}
</code>```

答:
in your for-loop for j

a[i] = i * j;

above line of code will always overwrite by last value of j which is 9
so, you will get
i = 1..9, multiple fixed j=9.

```<code>using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}
</code>```

Title: c# Loop not incrementing as expected

Body:
Hi I had a loop that was stepping through an array with each index being multiplied by two. However I changed it so that the index is multiplied by 0, then 1, then 2 etc til it hits 10. (This is j in the code below) j is not incrementing as expected and just multiplies by nine. Can anyone help? Tks

using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}

Body:
in your for-loop for j

a[i] = i * j;

above line of code will always overwrite by last value of j which is 9
so, you will get
i = 1..9, multiple fixed j=9.

using System;

namespace ArrayandStringPractice
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int[] a = new int[10];

      for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
        {
          {
            a[i] = i * j;
            //Console.WriteLine(a[i]);
          }
        }

      foreach (int i in a)
      {
        Console.WriteLine(i);
      }
    }
  }
}


问:
reshaping k columns to 2 columns representing sequential pairs of the values of the k variables
I have a data frame like this:

```<code>id y1 y2 y3 y4
--+--+--+--+--
a |12|13|14|
b |12|18|  |
c |13|  |  |
d |13|14|15|16
</code>```

I want to reshape in such a way that I end with two columns. The above example would then become:

```<code>id from to
--+----+---
a |12  |13
a |13  |14
a |14  |
b |12  |18
b |18  |
c |13  |
d |13  |14
d |14  |15
d |15  |16
</code>```

Each id has a 'from' and a 'to' per pair of year values.

Does anybody know of an easy way to do this? I tried using reshape2. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.

答:
You can use lapply to loop over the pairs of columns and rbind to union them:

```<code>do.call(rbind,
        lapply(2:(length(df)-1),
               function(x) setNames(df[!is.na(df[,x]),c(1,x,x+1)],
                                    c("id", "from", "to"))))
   id from to
1   a   12 13
2   b   12 18
3   c   13 NA
4   d   13 14
11  a   13 14
21  b   18 NA
41  d   14 15
12  a   14 NA
42  d   15 16
</code>```

Body:
I have a data frame like this:

id y1 y2 y3 y4
--+--+--+--+--
a |12|13|14|
b |12|18|  |
c |13|  |  |
d |13|14|15|16

I want to reshape in such a way that I end with two columns. The above example would then become:

id from to
--+----+---
a |12  |13
a |13  |14
a |14  |
b |12  |18
b |18  |
c |13  |
d |13  |14
d |14  |15
d |15  |16

Each id has a 'from' and a 'to' per pair of year values.

Does anybody know of an easy way to do this? I tried using reshape2. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.

Body:
You can use lapply to loop over the pairs of columns and rbind to union them:

do.call(rbind,
        lapply(2:(length(df)-1),
               function(x) setNames(df[!is.na(df[,x]),c(1,x,x+1)],
                                    c("id", "from", "to"))))
   id from to
1   a   12 13
2   b   12 18
3   c   13 NA
4   d   13 14
11  a   13 14
21  b   18 NA
41  d   14 15
12  a   14 NA
42  d   15 16


问:
ASP.Net MVC: How to iterate in authorize or restricted controllers and actions name
i want to get controllers and protected action name and populate my class with controller and action name.

see the below code

```<code>[Authorize]
public class Test1Controller : Controller
{
    public ActionResult Index1()
    {
        return View();
    }

    public ActionResult Index2()
    {
        return View();
    }

    [AllowAnonymous]
    public ActionResult Index3()
    {
        return View();
    }
}

[AllowAnonymous]
public class Test2Controller : Controller
{
    [Authorize]
    public ActionResult Index1()
    {
        return View();
    }

    [Authorize]
    public ActionResult Index2()
    {
        return View();
    }

    public ActionResult Index3()
    {
        return View();
    }
}

public class Test3Controller : Controller
{
    public ActionResult Index1()
    {
        return View();
    }

    public ActionResult Index2()
    {
        return View();
    }

    public ActionResult Index3()
    {
        return View();
    }
}
</code>```

1) Test1Controller is protected but Index3 action has Anonymous access. so i want to iterate in such a way as a result i will get Test1Controller name and two its action name which has no allow Anonymous attribute.

2) Test2Controller has Anonymous attribute but two of its action is protected. so i want to get Test2Controller name and two of its action name.

3) Test3Controller has no protection for any of its action so this controller name and any of its action name will not come when i will iterate in controller and action collection.

the below code give me all controller and action name which is not my requirement

```<code>Assembly asm = Assembly.GetExecutingAssembly();

var controlleractionlists = asm.GetTypes()
            .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
            .Select(x => new { Controller = x.DeclaringType.Name.Replace("Controller",string.Empty), Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();
</code>```

so please tell me what kind of change i need to incorporate in above code as a result those controllers name i will get which has at least one protected action.

please help me with rectified code. thanks

答:
```<code>//for actions with AuthorizeAttribute
var actions = asm.GetTypes()
            .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => m.GetCustomAttributes(typeof(System.Web.Mvc.AuthorizeAttribute), true).Any())
            .Select(x => new { Controller = x.DeclaringType.Name.Replace("Controller", string.Empty), Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action);

//for controllers with AuthorizeAttribute
var controllers = asm.GetTypes()
            .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
            .Select(type => type.GetTypeInfo())
            .Where(type => type.GetCustomAttributes(typeof(System.Web.Mvc.AuthorizeAttribute), true).Any())
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => !m.GetCustomAttributes(typeof(System.Web.Mvc.AllowAnonymousAttribute), false).Any())
            .Select(x => new { Controller = x.DeclaringType.Name.Replace("Controller", string.Empty), Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action);

var controlleractionlists = actions.Concat(controllers).ToList();
</code>```

If AuthorizeAttribute is set for action and controller level, this action will be in result twice but it can be fixed easly.

Body:
i want to get controllers and protected action name and populate my class with controller and action name.

see the below code

[Authorize]
public class Test1Controller : Controller
{
    public ActionResult Index1()
    {
        return View();
    }

    public ActionResult Index2()
    {
        return View();
    }

    [AllowAnonymous]
    public ActionResult Index3()
    {
        return View();
    }
}

[AllowAnonymous]
public class Test2Controller : Controller
{
    [Authorize]
    public ActionResult Index1()
    {
        return View();
    }

    [Authorize]
    public ActionResult Index2()
    {
        return View();
    }

    public ActionResult Index3()
    {
        return View();
    }
}

public class Test3Controller : Controller
{
    public ActionResult Index1()
    {
        return View();
    }

    public ActionResult Index2()
    {
        return View();
    }

    public ActionResult Index3()
    {
        return View();
    }
}

1) Test1Controller is protected but Index3 action has Anonymous access. so i want to iterate in such a way as a result i will get Test1Controller name and two its action name which has no allow Anonymous attribute.

2) Test2Controller has Anonymous attribute but two of its action is protected. so i want to get Test2Controller name and two of its action name.

3) Test3Controller has no protection for any of its action so this controller name and any of its action name will not come when i will iterate in controller and action collection.

the below code give me all controller and action name which is not my requirement

Assembly asm = Assembly.GetExecutingAssembly();

var controlleractionlists = asm.GetTypes()
            .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
            .Select(x => new { Controller = x.DeclaringType.Name.Replace("Controller",string.Empty), Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();

so please tell me what kind of change i need to incorporate in above code as a result those controllers name i will get which has at least one protected action.

please help me with rectified code. thanks

Body:
//for actions with AuthorizeAttribute
var actions = asm.GetTypes()
            .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => m.GetCustomAttributes(typeof(System.Web.Mvc.AuthorizeAttribute), true).Any())
            .Select(x => new { Controller = x.DeclaringType.Name.Replace("Controller", string.Empty), Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action);

//for controllers with AuthorizeAttribute
var controllers = asm.GetTypes()
            .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
            .Select(type => type.GetTypeInfo())
            .Where(type => type.GetCustomAttributes(typeof(System.Web.Mvc.AuthorizeAttribute), true).Any())
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => !m.GetCustomAttributes(typeof(System.Web.Mvc.AllowAnonymousAttribute), false).Any())
            .Select(x => new { Controller = x.DeclaringType.Name.Replace("Controller", string.Empty), Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action);

var controlleractionlists = actions.Concat(controllers).ToList();

If AuthorizeAttribute is set for action and controller level, this action will be in result twice but it can be fixed easly.


问:
Resolve a AsyncStorage promise inside componenDidMount
I'm trying to check if a user is authenticated. I do this by checking some record in asyncStorage, I have the following code

App.js

```<code>let AuthService = require('./app/layouts/AuthService/AuthService.js');
export default class App extends React.Component {

    componentDidMount() {
        AuthService.getAuthInfo((err, authInfo) => {
            this.setState({
                checkingAuth: false,
                isLoggedIn: authInfo != null
            })
        });
    }
}
</code>```

Auth.js

```<code>'use strict';

let AsyncStorage = require('react-native').AsyncStorage;
let _ = require('lodash');

const authKey = 'auth';
const userKey = 'user';

class AuthService {
    getAuthInfo(cb){
        AsyncStorage.multiGet([authKey, userKey], (err, val)=> {
            if(err){
                return cb(err);
            }
            if(!val){
                return cb();
            }
            let zippedObj = _.zipObject(val);
            if(!zippedObj[authKey]){
                return cb();
            }
            let authInfo = {
                header: {
                    Authorization: 'Basic ' + zippedObj[authKey]
                },
                user: JSON.parse(zippedObj[userKey])
            }
            return cb(null, authInfo);
        });
    }
}
module.exports = new AuthService();
</code>```

In app.js, I'm trying to use this function from Auth.js, but I get no response from the fuction, I get console logs from getAuthInfo before I get into the AsyncStorage function. Im pretty new to react-native and ES6, and I think is a promise or async problem but I cant make it work. In app.js im redering a ActivityIndicator so I dont block the UI with checkingAuth and isLoggedIn.
I tried to use some .then in app.js with no results.

答: First of all, you return your callback function instead of calling it. Try to call it by removing return like this : cb(null, authInfo);.

Body:
I'm trying to check if a user is authenticated. I do this by checking some record in asyncStorage, I have the following code

App.js

let AuthService = require('./app/layouts/AuthService/AuthService.js');
export default class App extends React.Component {

    componentDidMount() {
        AuthService.getAuthInfo((err, authInfo) => {
            this.setState({
                checkingAuth: false,
                isLoggedIn: authInfo != null
            })
        });
    }
}

Auth.js

'use strict';

let AsyncStorage = require('react-native').AsyncStorage;
let _ = require('lodash');

const authKey = 'auth';
const userKey = 'user';

class AuthService {
    getAuthInfo(cb){
        AsyncStorage.multiGet([authKey, userKey], (err, val)=> {
            if(err){
                return cb(err);
            }
            if(!val){
                return cb();
            }
            let zippedObj = _.zipObject(val);
            if(!zippedObj[authKey]){
                return cb();
            }
            let authInfo = {
                header: {
                    Authorization: 'Basic ' + zippedObj[authKey]
                },
                user: JSON.parse(zippedObj[userKey])
            }
            return cb(null, authInfo);
        });
    }
}
module.exports = new AuthService();

In app.js, I'm trying to use this function from Auth.js, but I get no response from the fuction, I get console logs from getAuthInfo before I get into the AsyncStorage function. Im pretty new to react-native and ES6, and I think is a promise or async problem but I cant make it work. In app.js im redering a ActivityIndicator so I dont block the UI with checkingAuth and isLoggedIn.
I tried to use some .then in app.js with no results.


问:
Which file does API call go?
Sorry for the basic question, but where does an API call go in swift (using Alamofire or session.dataTask)? Should I place this in a view controller or make a separate class with a method that calls the Api and then call that from my view controller?</p>

答:
Separate your concerns for code reusability. If you think there is even the slightest chance that the API call you are creating can be used in another file at some time, put it in its own file. I usually create API client classes that are as loosely coupled from the rest of the project as I can manage. It makes for easier reuse, easier updates, and easier debugging. There is no shame in having files with very few lines of code if you can justify it.

Also, think of view controllers as a way to display and interact with a GUI. If you are writing something in a view controller that doesn't have to do with one of those two concerns, it might not be well placed there.

Title: Which file does API call go?


问:
What causes udp reception delay?
I have noticed that when I am sending packets at even intervals from a udp socket, the first packet sent seems to be delayed. For example, if I am sending the packets every 100 ms, I find the delay between receiving the packets to be normally distributed with mean 100ms and average standard deviation of 4, on my network. However, the gap between the receive time for the first and second packets is usually around 10 to 40 ms - as you can see, that's clearly a statistically significant difference, and so my question is, what's causing it?

I'm using the sendto function from C on linux. Someone suggested the delay might be caused by arp resolution preventing the packet from being sent until the destination ip has been converted to a mac address - is this likely? If I restart the sending program the first packet again takes too long though, and the delay is inconsistent - 10 to 40 ms is a pretty big range.

I need to find out why this first packet is taking too long, and how to work around it.

Edit: Further analysis with pcap indicates that the sending program is sending the packets at the right interval. Problem must be with the receiver, which is using select() to wait for a readable socket, then calling recvfrom and printing the packet. Is there some sort of buffering going on there I might not know about?

答: Is this on a single LAN? If so, it is (probably) down to ARP and/or hostname resolution. If it's across a larger network, it may be anything (although probbaly related to route lookup and cache population).</p>

ContentLicense: CC BY-SA 2.5

Title: What causes udp reception delay?


问:
Read Only Class Variables (C++) and Operator Overloading
Take the following code:

```<code>#include <string>
#include <iostream>

template <class T, class U>
class readonly
{
  friend U;
  private:
    T data;
    T operator=(const T& arg) {data = arg; return data;}
    T operator+=(const T& arg) {data = data + arg; return data;}
    T operator-=(const T& arg) {data = data - arg; return data;}
    T operator*=(const T& arg) {data = data * arg; return data;}
    T operator/=(const T& arg) {data = data / arg; return data;}
  public:
    operator const T&() const {return data;}
};

class myClass
{
  private:
    typedef readonly<int, myClass> RO_int;
    typedef readonly<std::string, myClass> RO_string;

  public:
    RO_int x;
    RO_string y;

    void f()
    {
      x = 55;
      y = "Howdy";
      std::cout << x << "\n\n";  // compiles fine
      std::cout << y << "\n\n";  // compile error
    }
};
</code>```

I'm using these template classes to make sure that certain public variables x and y are "read-only" outside of the class, but can be modified within the class itself.  Everything in this code compiles fine except the very last line where I'm trying to display the variable y which is of string type.  I don't understand why I'm able to display x but not y.  If I need to overload the << operator, why do I have to do it for std::string but not for int?

答:
First, but not your question, your operators should return readonly& or T& not T.  Don't break convention like that.

Now for an actual answer.

It is because operator<< that string uses is a template, and template functions do not consider conversions when pattern matching.  The << that takes an int is not a template, so it does consider conversions.

We can fix this in general by creating an operator<< that doesn't convert:

Simply add

```<code>friend std::ostream& operator<<(std::ostream& os, readonly const& self)
{
  return os<<self.data;
}
</code>```

to your readonly type and things should work.  This will be found via ADL.

We could make it fancier with SFINAE and the like by taking the first argument by template and checking that << works and that the first argument is derived from std::ostream, or similarly for the second argument.

Body:
Take the following code:

#include <string>
#include <iostream>

template <class T, class U>
class readonly
{
  friend U;
  private:
    T data;
    T operator=(const T& arg) {data = arg; return data;}
    T operator+=(const T& arg) {data = data + arg; return data;}
    T operator-=(const T& arg) {data = data - arg; return data;}
    T operator*=(const T& arg) {data = data * arg; return data;}
    T operator/=(const T& arg) {data = data / arg; return data;}
  public:
    operator const T&() const {return data;}
};

class myClass
{
  private:
    typedef readonly<int, myClass> RO_int;
    typedef readonly<std::string, myClass> RO_string;

  public:
    RO_int x;
    RO_string y;

    void f()
    {
      x = 55;
      y = "Howdy";
      std::cout << x << "\n\n";  // compiles fine
      std::cout << y << "\n\n";  // compile error
    }
};

I'm using these template classes to make sure that certain public variables x and y are "read-only" outside of the class, but can be modified within the class itself.  Everything in this code compiles fine except the very last line where I'm trying to display the variable y which is of string type.  I don't understand why I'm able to display x but not y.  If I need to overload the << operator, why do I have to do it for std::string but not for int?

Body:
First, but not your question, your operators should return readonly& or T& not T.  Don't break convention like that.

Now for an actual answer.

It is because operator<< that string uses is a template, and template functions do not consider conversions when pattern matching.  The << that takes an int is not a template, so it does consider conversions.

We can fix this in general by creating an operator<< that doesn't convert:

Simply add

friend std::ostream& operator<<(std::ostream& os, readonly const& self)
{
  return os<<self.data;
}

to your readonly type and things should work.  This will be found via ADL.

We could make it fancier with SFINAE and the like by taking the first argument by template and checking that << works and that the first argument is derived from std::ostream, or similarly for the second argument.


问:
PayPal sandbox button goes to My Account Summary
Here's my problem. I've tried being logged into my Developer Account with PayPal, but every time I test the button I made in Sandbox I just get redirected as follows and can't complete the test transaction:

Using my details (obviously I've replaced my details with fake ones here).

I go to my test site and click on the button I created in Sandbox mode:

Which takes me here. I use the buyer sandbox email to login.

Then, no matter what I do, I end up here with an incomplete transaction.

I've been going around in circles, clearing caches, cookies, going incognito but can't make it work! Any help would be greatly appreciated!

答: We had a known issue at PayPal's end which is causing this issue. The engineering team is working on this issue for a fix. No ETA at the moment. Will update here once the issue gets fixed.</p>


问:
Python mkdir issue, file exists error
Im trying to create directories and a files within each folder, using data from an input file.

It works for the first one but then gives me the FileExistsError

I have been staring at this for hours now and just can't seem to get it, any help would be appreciated.

File data looks like this

```<code>>unique id
string of unknown length
</code>```

and the code I've tried is this

```<code>import os

# find a character

CharLocArray = []

NewLineArray = []

with open('/home/tjbutler/software/I-TASSER5.0/seqdata/Egg_protein/seq.fasta', 'r') as myfile:

    data = myfile.read()
    GreaterThan = '>'
    NewLine = '\n'

    # code to read char into var
    # myfile.read().index('>')
    index = 0
    while index < len(data):
        index = data.find('>', index)
        CharLocArray.append(index)
        if index == -1:
            break

        index += 2

    index2 = 0
    while index2 < len(data):
        index2 = data.find('\n', index2)
        NewLineArray.append(index2)
        if index2 == -1:
            break

        index2 += 2

    i = 0
    print(len(CharLocArray))

    while i < len(CharLocArray):
        print(i)
        CurStr = data[CharLocArray[i]:]
        CurFolder = CurStr[CharLocArray[i]:NewLineArray[i]]
        print(CurFolder)
        CurData = CurStr[CharLocArray[i]:CharLocArray[i + 1]]
        print(CurData)
        newpath = r'/home/tjbutler/software/I-TASSER5.0/seqdata/Egg_protein/'
        DirLocation = newpath + CurFolder
        print(DirLocation)
        FileLocation = DirLocation + '/seq.fasta'
        print(FileLocation)
        i = i + 1
        print(i)
        if not os.makedirs(DirLocation):
            os.makedirs(DirLocation)
            file = open(FileLocation, 'w+')
            file.write(CurData)
            file.close()
</code>```

答:
os.makedirs() should not be used that way - use its exist_ok argument instead:

```<code>    os.makedirs(DirLocation, exist_ok=True)  # instead of the condition!
    with open(FileLocation, 'w+') as f:
        f.write(CurData)
</code>```

also, don't manually create your own paths (i.e. FileLocation = DirLocation + '/seq.fasta'), use os.path facilities instead, e.g.: FileLocation = os.path.join(DirLocation, seq.fasta).

Title: Python mkdir issue, file exists error

Body:
Im trying to create directories and a files within each folder, using data from an input file.

It works for the first one but then gives me the FileExistsError

I have been staring at this for hours now and just can't seem to get it, any help would be appreciated.

File data looks like this

>unique id
string of unknown length

and the code I've tried is this

import os

# find a character

CharLocArray = []

NewLineArray = []

with open('/home/tjbutler/software/I-TASSER5.0/seqdata/Egg_protein/seq.fasta', 'r') as myfile:

    data = myfile.read()
    GreaterThan = '>'
    NewLine = '\n'

    # code to read char into var
    # myfile.read().index('>')
    index = 0
    while index < len(data):
        index = data.find('>', index)
        CharLocArray.append(index)
        if index == -1:
            break

        index += 2

    index2 = 0
    while index2 < len(data):
        index2 = data.find('\n', index2)
        NewLineArray.append(index2)
        if index2 == -1:
            break

        index2 += 2

    i = 0
    print(len(CharLocArray))

    while i < len(CharLocArray):
        print(i)
        CurStr = data[CharLocArray[i]:]
        CurFolder = CurStr[CharLocArray[i]:NewLineArray[i]]
        print(CurFolder)
        CurData = CurStr[CharLocArray[i]:CharLocArray[i + 1]]
        print(CurData)
        newpath = r'/home/tjbutler/software/I-TASSER5.0/seqdata/Egg_protein/'
        DirLocation = newpath + CurFolder
        print(DirLocation)
        FileLocation = DirLocation + '/seq.fasta'
        print(FileLocation)
        i = i + 1
        print(i)
        if not os.makedirs(DirLocation):
            os.makedirs(DirLocation)
            file = open(FileLocation, 'w+')
            file.write(CurData)
            file.close()

Body:
os.makedirs() should not be used that way - use its exist_ok argument instead:

    os.makedirs(DirLocation, exist_ok=True)  # instead of the condition!
    with open(FileLocation, 'w+') as f:
        f.write(CurData)

also, don't manually create your own paths (i.e. FileLocation = DirLocation + '/seq.fasta'), use os.path facilities instead, e.g.: FileLocation = os.path.join(DirLocation, seq.fasta).


问:
How to make this list stay at the bottom of the page?
Want this to be at the bottom of my page. No blank space beneath it. I'm a little confused as the normal CSS to make text stay at the bottom wont work here.

    .footer li{
      display:inline;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <footer>
    <div class="footer">
    <ul style="float:left;list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
    </footer></code>```

答:
What you're looking for is a "sticky" footer, since you don't want it fixed to the bottom of the viewport all of the time and just want it to always be at the bottom of the page.

The easiest/modern way to do this is to use a flex container and set the footer to margin-top: auto so it will push itself to the bottom of the container. Set the container to min-height: 100vh; and the footer will always be at the bottom of the page.

.footer li{
  display:inline;
}
body {
display: flex;
flex-direction: column;
margin: 0;
min-height: 100vh;
}
footer {
margin-top: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>nav</nav>
<main>main</main>
<footer>
    <div class="footer">
    <ul style="float:left;list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
</footer></code>```

Another way to do it is to assign a height to footer, and absolutely position it at the bottom of the window, and add padding to body that matches the height of the footer

.footer li{
  display:inline;
}
body {
box-sizing: border-box;
padding-bottom: 50px;
margin: 0;
min-height: 100vh;
position: relative;
}
footer {
height: 50px;
position: absolute;
bottom: 0; left; 0; right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>nav</nav>
<main>main</main>
<footer>
    <div class="footer">
    <ul style="float:left;list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
</footer></code>```

Body:
Want this to be at the bottom of my page. No blank space beneath it. I'm a little confused as the normal CSS to make text stay at the bottom wont work here.

    .footer li{
      display:inline;
    }

Advertising

Business

About

Privacy

Terms

Settings

Body:
What you're looking for is a "sticky" footer, since you don't want it fixed to the bottom of the viewport all of the time and just want it to always be at the bottom of the page.

The easiest/modern way to do this is to use a flex container and set the footer to margin-top: auto so it will push itself to the bottom of the container. Set the container to min-height: 100vh; and the footer will always be at the bottom of the page.

.footer li{
  display:inline;
}
body {
display: flex;
flex-direction: column;
margin: 0;
min-height: 100vh;
}
footer {
margin-top: auto;
}

<nav>nav</nav>
<main>main</main>
<footer>
    <div class="footer">
    <ul style="float:left;list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
</footer>

Another way to do it is to assign a height to footer, and absolutely position it at the bottom of the window, and add padding to body that matches the height of the footer

.footer li{
  display:inline;
}
body {
box-sizing: border-box;
padding-bottom: 50px;
margin: 0;
min-height: 100vh;
position: relative;
}
footer {
height: 50px;
position: absolute;
bottom: 0; left; 0; right: 0;
}

<nav>nav</nav>
<main>main</main>
<footer>
    <div class="footer">
    <ul style="float:left;list-style-type:none;">
          <li>Advertising</li>
          <li>Business</li>
          <li>About</li>
       </ul>

       <ul style="float:right;list-style-type:none;">
          <li>Privacy</li>
          <li>Terms</li>
          <li>Settings</li>
       </ul>
    </div>
</footer>


问:
Aplication freezing right after splash screen (Delphi Berlin Android)
I've made a simple app on Embarcadero Delphi Berlin and I've being compiling it directly to a smartphone (Samsung Galaxy E7) to test, but most of the time when it shows the first Form the application freezes, only a TBannerAd works, I must rotate the phone and change the actual orientation for the app to unfreeze. Someone knows what may be causing that? Thanks!</p>

答: I have this problem with Tokyo now, it was there from the beginning of Tokyo, so I switched back to Berlin upd2, and it show up there. Download and reinstall iso for Berlin upd2. Make sure no virus or firewalls are active. Uninstall all of Berlin, and delete and remaining Berlin files using Windows Explorer, i.e. Berlin is v18 in Program Files x86 under embarcadero. Use the defaults FireMonkey chooses when adding the Android SDK. It like v23 of Android SDK. That fixed it on my system.</p>


问:
How to authorize Azure Python SDK on VM instance?
In AWS, you can assign a role to a VM, which then authorizes the instance when it makes queries to the AWS SDK. I am looking for similar functionality in Azure, or something that would enable me to do close to that.

I found this post which suggests that this is not possible in the way AWS does it. Are there any workarounds for this? I really don't want the system administrator to have to login to the instance and give their Azure Active Directory credentials to authorize it.

答:
Excellent question :). I would suggest to wait a few days, we have something in progress that seems to fit your need. I created this issue for tracking.

The most simple would be to create a Service Principal credentials for these VMs. To do that, execute a post deployment script to install the CLI and "az ad sp create-for-rbac --sdk-auth >~/mycredentials.json". Then, you can start SDK script reading this credential file.

The "create-for-rbac" commands already exists if you want to look at it (--sdk-auth is the new option coming), so you can see that you can specify all scope and permissions needed in this command.

(I own the Azure SDK for Python at MS)


问:
Calculating values in dynamically created DOM
I have created an html table that is dynamically created in the DOM.  It has 4 columns and two of the columns will have tetboxes that a user can enter values into and then will be subtracted as a value in the last column.  'Delta' = 'State Before' - 'State After'.  I am able to get the value when it is entered but not sure how to get the value of the other field to do the computation.

HTML

```<code>    <table id="deptState" border="1">
    <tr>
        <th>Department</th>
        <th>State Before</th>
        <th>State After</th>
        <th>Delta</th>
    </tr>
</table>
</code>```

JAVASCRIPT

```<code>   var deptArray = ["Human Resources", "Accounting and Finance", "IT", "Marketing", "Purchasing Department"];
var state = ["stateBefore", "stateAfter", "Delta"];

for(var x=0; x<deptArray.length; x++) {
    var html = "<tr>";
        html +="<td>"+deptArray[x]+"</td>";
        for(var y=0; y<state.length; y++) {
            if (state[y] === "stateBefore")
            {
                html += "<td><input type='text' class='.nrm-text' id='"+deptArray[x]+state[0]+"'></td>";
            }else if (state[y] === "stateAfter") {
                html += "<td><input type='text' class='.nrm-text' id='"+deptArray[x]+state[1]+"'></td>";
            }else if (state[y] === "Delta") {
                html += "<td><input type='text' id='"+deptArray[x]+state[2]+"'></td>";
            }
        }
      html += "</tr>";
      $("#deptState").append(html);
  }

  var allTextBoxes = document.querySelector("#deptState");
  console.dir(allTextBoxes);
  allTextBoxes.addEventListener("change", function( e ){
    if (e.target.tagName === 'INPUT'){
              alert("Value: "+document.getElementById(e.target.id).value);
            console.log("Save data to SharePoint list");
    }
  })
</code>```

It's easier to show.  Here's the jsfiddle:

In one of the rows, enter 9 in 'State Before' and 5 in 'State After'.  'Delta' should then have 4

http://jsfiddle.net/isogunro/pq4uref9/

答:
try this :

```<code>if (e.target.tagName === 'INPUT'){
  // start
  var rowNode = e.target.parentNode.parentNode;
  var rowInputs = rowNode.getElementsByTagName('input');
  var before = rowInputs[0].value || 0;
  var after = rowInputs[1].value || 0;
  if(before && after){
    rowInputs[2].value = before - after;
  }
  // end
          alert("Value: "+document.getElementById(e.target.id).value);
        console.log("Save data to SharePoint list");
}
</code>```

http://jsfiddle.net/pq4uref9/10/

Body:
I have created an html table that is dynamically created in the DOM.  It has 4 columns and two of the columns will have tetboxes that a user can enter values into and then will be subtracted as a value in the last column.  'Delta' = 'State Before' - 'State After'.  I am able to get the value when it is entered but not sure how to get the value of the other field to do the computation.

HTML

        Department
        State Before
        State After
        Delta

JAVASCRIPT

   var deptArray = ["Human Resources", "Accounting and Finance", "IT", "Marketing", "Purchasing Department"];
var state = ["stateBefore", "stateAfter", "Delta"];

for(var x=0; x<deptArray.length; x++) {
    var html = "
";
        html +=""+deptArray[x]+"	";
        for(var y=0; y<state.length; y++) {
            if (state[y] === "stateBefore")
            {
                html += "<input type='text' class='.nrm-text' id='"+deptArray[x]+state[0]+"'>	";
            }else if (state[y] === "stateAfter") {
                html += "<input type='text' class='.nrm-text' id='"+deptArray[x]+state[1]+"'>	";
            }else if (state[y] === "Delta") {
                html += "<input type='text' id='"+deptArray[x]+state[2]+"'>	";
            }
        }
      html += "
";
      $("#deptState").append(html);
  }

  var allTextBoxes = document.querySelector("#deptState");
  console.dir(allTextBoxes);
  allTextBoxes.addEventListener("change", function( e ){
    if (e.target.tagName === 'INPUT'){
              alert("Value: "+document.getElementById(e.target.id).value);
            console.log("Save data to SharePoint list");
    }
  })

It's easier to show.  Here's the jsfiddle:

In one of the rows, enter 9 in 'State Before' and 5 in 'State After'.  'Delta' should then have 4

http://jsfiddle.net/isogunro/pq4uref9/

Body:
try this :

if (e.target.tagName === 'INPUT'){
  // start
  var rowNode = e.target.parentNode.parentNode;
  var rowInputs = rowNode.getElementsByTagName('input');
  var before = rowInputs[0].value || 0;
  var after = rowInputs[1].value || 0;
  if(before && after){
    rowInputs[2].value = before - after;
  }
  // end
          alert("Value: "+document.getElementById(e.target.id).value);
        console.log("Save data to SharePoint list");
}

http://jsfiddle.net/pq4uref9/10/


问:
Javascript Echo Result in PHP
Ok so I have some Javascript code that I'm wanting to echo.

Here is the Code im wanting to echo, I'm wanting it to basically print out the response from the generated "hospital" and "scramble" I've got this far just can't echo the result in PHP.

```<code><script language="JavaScript">
<!--
 function hospital() {
  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  var string_length = Math.floor(Math.random() * (3000 - 256 + 1)) + 256;
  var prngstring = '';

  for (var i = 0; i < string_length; i++) {
   var rnum = Math.floor(Math.random() * chars.length);
   prngstring += chars.substring(rnum,rnum+1);
  }
  document.theform.hospital.value += prngstring;
 }

 function catchme() {
     var rounds = 812;
        var scramble = "lbwnaoJJgJbQCc1zxfiQugycOhboPrdbciAVBaBeqnzXzhztbPddaBWzNjcrafefibAcnJohbDQDbuaueudckuGvAuccEhPmehbjZdaecgAMphcPAeabFvxsGwteWS";

        for (var i = 0; i <= rounds; i++) {
            scramble = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(scramble)).toUpperCase();
        }
        document.theform.waste.value += scramble;
        hospital();
    }
-->
</script>
</code>```

Would appreciate and support.

答:
There is no call to catchme function. You need to call catchme function so the following statements work.

document.theform.waste.value += scramble;

document.theform.hospital.value += prngstring;

Make catchme a self invoked function.

```<code>(function catchme() {
     var rounds = 812;
        var scramble = "lbwnaoJJgJbQCc1zxfiQugycOhboPrdbciAVBaBeqnzXzhztbPddaBWzNjcrafefibAcnJohbDQDbuaueudckuGvAuccEhPmehbjZdaecgAMphcPAeabFvxsGwteWS";

        for (var i = 0; i <= rounds; i++) {
            scramble = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(scramble)).toUpperCase();
        }
        document.theform.waste.value += scramble;
        hospital();
    })();
</code>```

Title: Javascript Echo Result in PHP

Body:
Ok so I have some Javascript code that I'm wanting to echo.

Here is the Code im wanting to echo, I'm wanting it to basically print out the response from the generated "hospital" and "scramble" I've got this far just can't echo the result in PHP.

Would appreciate and support.

Body:
There is no call to catchme function. You need to call catchme function so the following statements work.

document.theform.waste.value += scramble;

document.theform.hospital.value += prngstring;

Make catchme a self invoked function.

(function catchme() {
     var rounds = 812;
        var scramble = "lbwnaoJJgJbQCc1zxfiQugycOhboPrdbciAVBaBeqnzXzhztbPddaBWzNjcrafefibAcnJohbDQDbuaueudckuGvAuccEhPmehbjZdaecgAMphcPAeabFvxsGwteWS";

        for (var i = 0; i <= rounds; i++) {
            scramble = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(scramble)).toUpperCase();
        }
        document.theform.waste.value += scramble;
        hospital();
    })();


问:
highest palindrome with 3 digit numbers in python
In problem 4 from http://projecteuler.net/ it says:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.

Find the largest palindrome made from the product of two 3-digit numbers.

I have this code here

```<code>def isPalindrome(num):
    return str(num) == str(num)[::-1]
def largest(bot, top):
    for x in range(top, bot, -1):
        for y in range(top,bot, -1):
            if isPalindrome(x*y):
                return x*y
print largest(100,999)
</code>```

It should find the largest palindrome, it spits out 580085 which I believe to be correct, but project euler doesn't think so, do I have something wrong here?

When I revered the for loop I didn't think it through, I removed the thing that checks for the biggest, silly me. Heres the working code

```<code>def isPalindrome(num):
    return str(num) == str(num)[::-1]
def largest(bot, top):
    z = 0
    for x in range(top, bot, -1):
        for y in range(top,bot, -1):
            if isPalindrome(x*y):
                if x*y > z:
                    z = x*y
    return z
print largest(100,999)
</code>```

it spits out 906609

答:
Here is my code to solve this problem. </p>

```<code>lst = []
for i in range(100,1000):
    for n in range(2,i) :
        lst.append (i* n)
        lst.append(i*i)

lst2=[]
for i in lst:
    if str(i) == str(i)[::-1]:
        lst2.append(i)
print max(lst2)
</code>```

Body:
In problem 4 from http://projecteuler.net/ it says:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.

Find the largest palindrome made from the product of two 3-digit numbers.

I have this code here

def isPalindrome(num):
    return str(num) == str(num)[::-1]
def largest(bot, top):
    for x in range(top, bot, -1):
        for y in range(top,bot, -1):
            if isPalindrome(x*y):
                return x*y
print largest(100,999)

It should find the largest palindrome, it spits out 580085 which I believe to be correct, but project euler doesn't think so, do I have something wrong here?

When I revered the for loop I didn't think it through, I removed the thing that checks for the biggest, silly me. Heres the working code

def isPalindrome(num):
    return str(num) == str(num)[::-1]
def largest(bot, top):
    z = 0
    for x in range(top, bot, -1):
        for y in range(top,bot, -1):
            if isPalindrome(x*y):
                if x*y > z:
                    z = x*y
    return z
print largest(100,999)

it spits out 906609

Body:
Here is my code to solve this problem.

lst = []
for i in range(100,1000):
    for n in range(2,i) :
        lst.append (i* n)
        lst.append(i*i)

lst2=[]
for i in lst:
    if str(i) == str(i)[::-1]:
        lst2.append(i)
print max(lst2)


问:
on button click load/display local html file from asset in android
I'm new to android programming, is there a way to load or display the html file form asset folder in android by using View.OnClickListener

let me rephrase my question:
Is it possible to write a code similar the below to call/load/display the local html file form asset folder when button is clicked

```<code>public class testing extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testing);
        Button butt4 = (Button)findViewById(R.id.secition2);

butt4.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v) {
        String url = "http://google.com";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i)
    }
});
</code>```

Do let me know if i'm not clear enough..

Many thanks in advance!!!!

答:
Create a activity with webview

and pass the url in bundle extra on button click

"file:///android_asset/test.html";

get the url and load into webview

```<code>webView.loadUrl("file:///android_asset/test.html");
</code>```

Body:
I'm new to android programming, is there a way to load or display the html file form asset folder in android by using View.OnClickListener

let me rephrase my question:
Is it possible to write a code similar the below to call/load/display the local html file form asset folder when button is clicked

public class testing extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testing);
        Button butt4 = (Button)findViewById(R.id.secition2);

butt4.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v) {
        String url = "http://google.com";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i)
    }
});

Do let me know if i'm not clear enough..

Many thanks in advance!!!!

Body:
Create a activity with webview

and pass the url in bundle extra on button click

"file:///android_asset/test.html";

get the url and load into webview

webView.loadUrl("file:///android_asset/test.html");


问:
pyparsing a field that may or may not contain values
I have a dataset that resemebles the following:

Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:

The problem that I am having is I can't figure out how I could properly write a capture for the "Capture MICR - Serial Field". This field could either be blank or contain an alphanumeric of varying length (I have the same problem with the other fields that could either be populated or blank.

I have tried some variations of the following, but am still coming up short.

pp.Literal("Capture  MICR - Serial:") + pp.White(" ", min=1, max=0) + (pp.Word(pp.printables) ^ pp.White(" ", min=1, max=0))("crd_micr_serial") + pp.FollowedBy(pp.Literal("Pos44:"))

I think that part of the problem is that the Or matches a parse for the longest match, which in this case could be a long whitespace character, with a single alphanumeric, but I would still want to capture the single value.

Thanks for everyone's help.

答:
Does this do what you want?

I used the Combine merely so that both arms of the Or would produce similar results, ie, with 'Pos44:' at the end of the result string where it can be plucked off. I'm unhappy about resorting to a regex.

```<code>>>> import pyparsing as pp
>>> record_A = 'Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:'
>>> record_B = 'Capture MICR - Serial: 76ZXP67            Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:'
>>> parser_fragment = pp.Combine(pp.White()+pp.Literal('Pos44:'))
>>> parser = pp.Literal('Capture MICR - Serial:')+pp.Or([parser_fragment,pp.Regex('.*?(?:Pos44\:)')])
>>> parser.parseString(record_A)
(['Capture MICR - Serial:', '                  Pos44:'], {})
>>> parser.parseString(record_B)
(['Capture MICR - Serial:', '76ZXP67            Pos44:'], {})
</code>```

Body:
Does this do what you want?

I used the Combine merely so that both arms of the Or would produce similar results, ie, with 'Pos44:' at the end of the result string where it can be plucked off. I'm unhappy about resorting to a regex.

>>> import pyparsing as pp
>>> record_A = 'Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:'
>>> record_B = 'Capture MICR - Serial: 76ZXP67            Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:'
>>> parser_fragment = pp.Combine(pp.White()+pp.Literal('Pos44:'))
>>> parser = pp.Literal('Capture MICR - Serial:')+pp.Or([parser_fragment,pp.Regex('.*?(?:Pos44\:)')])
>>> parser.parseString(record_A)
(['Capture MICR - Serial:', '                  Pos44:'], {})
>>> parser.parseString(record_B)
(['Capture MICR - Serial:', '76ZXP67            Pos44:'], {})


问:
Render a component when another component is clicked
I want to render BlackSpark when RedSpark is clicked, but I'm not sure how to change the state of  a component in another component. I know how to set state in the component itself, but how do I affect another component when I click a different component?

```<code>class BlackSpark extends React.Component {
    render() {
        return (
            <div className="black"></div>
        );
    }
}

class RedSpark extends React.Component {
    render() {
        return (
            <div className="red"></div>
        );
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
             <BlackSpark />
             <RedSpark />
            </div>
        );
    }
}
</code>```

答:
I know how to set state in the component itself, but how do I affect another component when I click a different component?

The recommended way to do it would be to create a parent component that has the state. You'd then use that state to determine when to render the other child component.

I want to render BlackSpark when RedSpark is clicked, but I'm not sure how to change the state of a component in another component. Also, what if I want to hide BlackSpark when GreenSpark is clicked and GreenSpark is inside BlackSpark?

In this case, here's how you'd do it.

```<code>const GreenSpark = ({ onClick }) => (
  <button className="green" onClick={onClick}>X</button>
)

const BlackSpark = ({ onClick }) => (
  <div className="black">
    <GreenSpark onClick={onClick} />
  </div>
)

const RedSpark = ({ onClick }) => (
  <div className="red" onClick={onClick}></div>
)

class Spark extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      showBlack: false
    }

    this.boundShowBlack = this.showBlack.bind(this)
    this.boundHideBlack = this.hideBlack.bind(this)
  }

  showBlack() {
    this.setState({ showBlack: true })
  }

  hideBlack() {
    this.setState({ showBlack: false })
  }

  render() {
    return (
      <div>
        <RedSpark onClick={this.boundShowBlack} />
        {this.state.showBlack && <BlackSpark onClick={this.boundHideBlack} />}
      </div>
    )
  }
}
</code>```

Body:
I want to render BlackSpark when RedSpark is clicked, but I'm not sure how to change the state of  a component in another component. I know how to set state in the component itself, but how do I affect another component when I click a different component?

class BlackSpark extends React.Component {
    render() {
        return (

        );
    }
}

class RedSpark extends React.Component {
    render() {
        return (

        );
    }
}

class App extends React.Component {
    render() {
        return (

             <BlackSpark />
             <RedSpark />

        );
    }
}

Body:
I know how to set state in the component itself, but how do I affect another component when I click a different component?

The recommended way to do it would be to create a parent component that has the state. You'd then use that state to determine when to render the other child component.

I want to render BlackSpark when RedSpark is clicked, but I'm not sure how to change the state of a component in another component. Also, what if I want to hide BlackSpark when GreenSpark is clicked and GreenSpark is inside BlackSpark?

In this case, here's how you'd do it.

const GreenSpark = ({ onClick }) => (
  <button className="green" onClick={onClick}>X</button>
)

const BlackSpark = ({ onClick }) => (
  <div className="black">
    <GreenSpark onClick={onClick} />
  </div>
)

const RedSpark = ({ onClick }) => (
  <div className="red" onClick={onClick}></div>
)

class Spark extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      showBlack: false
    }

    this.boundShowBlack = this.showBlack.bind(this)
    this.boundHideBlack = this.hideBlack.bind(this)
  }

  showBlack() {
    this.setState({ showBlack: true })
  }

  hideBlack() {
    this.setState({ showBlack: false })
  }

  render() {
    return (
      <div>
        <RedSpark onClick={this.boundShowBlack} />
        {this.state.showBlack && <BlackSpark onClick={this.boundHideBlack} />}
      </div>
    )
  }
}


问:
Magento Price Not Updating
We've recently installed Simple Configurable Products on our 1.4.2.0 Magento install but the price on the product isn't updating when the user selects an option, if you configure the product and add to cart the price show's up correct in the cart, just not on the product at the time of selection.

If anyone could help out on this that would be great.

答: Solved using the solution at - http://www.magentocommerce.com/boards/viewthread/52582/</p>

Title: Magento Price Not Updating


问:
React Native Clock - setting a timer for a long period of time
I am trying to create an app with React Native that needs to show a clock on screen (only minutes need to update correct, not seconds). The app may be on screen (visible) for multiple minutes.

Is there a correct way to do this, as so far every way I have tried brings up 'Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android...'.

How can I accomplish a simple clock with correctness and minimal effect on battery etc.

The clock works fine, I just get the warning. I've tried various methods including regular setTimeout/Interval and this.setTimeout, also react-native-background-timer.

I also only need to update the clock when this screen comes back into view so I cancel the timer on componentDidUnmount. The clock only needs to update on minutes, not seconds, and doesn't need to be 100% accurate i.e. a small delay until the minutes updates is fine.

Thanks!

Code:

```<code>import React, {Component} from 'react';
import {View, Image, AppState} from 'react-native';
import {Text} from 'react-native';
import Styles from '../../styles/Styles';
import BackgroundTimer from 'react-native-background-timer';

/*
 Digital Clock
 */

export default class UIDigitalClock extends Component {

    // Render -----------------

    render() {

        var label = this.formatAMPM(this.state.time);

        return (
            <Text style={[Styles.h0,{fontSize:80,opacity:0.7}]}>{label}</Text>
        );
    }

    formatAMPM(date) {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes;
        return strTime;
    }

    //--------------------------------

    constructor(props) {
        super(props);
        this.state = {
            time: new Date()
        }

    }

    timer = null;

    componentWillMount() {
        AppState.addEventListener('change', this.handleAppStateChange);
        console.log('Digital Clock - Mount - Start');
        this.startTimer();
    }

    componentWillUnmount() {
        AppState.removeEventListener('change', this.handleAppStateChange);
        this.stopTimer();
    }

    startTimer() {
        return;
        if (this.timer>0) return;   // Already started
        this.timer = BackgroundTimer.setInterval(() => {
            // this will be executed every 200 ms
            // even when app is the the background
            this.updateTime();
        }, 1000);
    }
    stopTimer() {
        console.log("Digital Clock - stop ");
        if (this.timer>0) {
            BackgroundTimer.clearInterval(this.timer);
            this.timer = -1;
        }
    }

    handleAppStateChange = (appState) => {
        console.log("Digital Clock app state: "+appState);
        if (appState=='background') {
            console.log('Digital Clock - App in Background - Stop');
            this.stopTimer();
        } else if (appState=='active') {
            console.log('Digital Clock - App is Active - Start');
            this.startTimer();
        }

    }

    updateTime() {
        let time = this.state.time;
        let newTime = new Date();
        // TODO - check if the app is in the foreground
        console.log('Digital Clock - Tic ');
        // Only update the render when the time changes...
        if (!time || (time.getMinutes() != newTime.getMinutes() || time.getHours() != newTime.getHours())) {
            console.log('Digital Clock - Time changed (mins/hours) - updating...');
            this.setState({time: newTime});
        }
    }

}
</code>```

答:
Take a look at Later.js. You could set a schedule to fire every minutes</p>

```<code>const schedule = later.parse.text('every 1 mins');
later.date.localTime();

later.setTimeout(<your function>, schedule);
</code>```

Body:
I am trying to create an app with React Native that needs to show a clock on screen (only minutes need to update correct, not seconds). The app may be on screen (visible) for multiple minutes.

Is there a correct way to do this, as so far every way I have tried brings up 'Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android...'.

How can I accomplish a simple clock with correctness and minimal effect on battery etc.

The clock works fine, I just get the warning. I've tried various methods including regular setTimeout/Interval and this.setTimeout, also react-native-background-timer.

I also only need to update the clock when this screen comes back into view so I cancel the timer on componentDidUnmount. The clock only needs to update on minutes, not seconds, and doesn't need to be 100% accurate i.e. a small delay until the minutes updates is fine.

Thanks!

Code:

import React, {Component} from 'react';
import {View, Image, AppState} from 'react-native';
import {Text} from 'react-native';
import Styles from '../../styles/Styles';
import BackgroundTimer from 'react-native-background-timer';

/*
 Digital Clock
 */

export default class UIDigitalClock extends Component {

    // Render -----------------

    render() {

        var label = this.formatAMPM(this.state.time);

        return (
            <Text style={[Styles.h0,{fontSize:80,opacity:0.7}]}>{label}</Text>
        );
    }

    formatAMPM(date) {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes;
        return strTime;
    }

    //--------------------------------

    constructor(props) {
        super(props);
        this.state = {
            time: new Date()
        }

    }

    timer = null;

    componentWillMount() {
        AppState.addEventListener('change', this.handleAppStateChange);
        console.log('Digital Clock - Mount - Start');
        this.startTimer();
    }

    componentWillUnmount() {
        AppState.removeEventListener('change', this.handleAppStateChange);
        this.stopTimer();
    }

    startTimer() {
        return;
        if (this.timer>0) return;   // Already started
        this.timer = BackgroundTimer.setInterval(() => {
            // this will be executed every 200 ms
            // even when app is the the background
            this.updateTime();
        }, 1000);
    }
    stopTimer() {
        console.log("Digital Clock - stop ");
        if (this.timer>0) {
            BackgroundTimer.clearInterval(this.timer);
            this.timer = -1;
        }
    }

    handleAppStateChange = (appState) => {
        console.log("Digital Clock app state: "+appState);
        if (appState=='background') {
            console.log('Digital Clock - App in Background - Stop');
            this.stopTimer();
        } else if (appState=='active') {
            console.log('Digital Clock - App is Active - Start');
            this.startTimer();
        }

    }

    updateTime() {
        let time = this.state.time;
        let newTime = new Date();
        // TODO - check if the app is in the foreground
        console.log('Digital Clock - Tic ');
        // Only update the render when the time changes...
        if (!time || (time.getMinutes() != newTime.getMinutes() || time.getHours() != newTime.getHours())) {
            console.log('Digital Clock - Time changed (mins/hours) - updating...');
            this.setState({time: newTime});
        }
    }

}

Body:
Take a look at Later.js. You could set a schedule to fire every minutes

const schedule = later.parse.text('every 1 mins');
later.date.localTime();

later.setTimeout(<your function>, schedule);


问:
AutoHotKey doesn't recognise the Shuttle Xpress
For some reason, I need the Shuttle Xpress keypad to map to keys like "Caps lock + v", "Ins + a". But the shuttle doesn't recognise the "Caps lock" as a modifier key. It can only map "Caps" or "Ins" alone. I try to use AutoHotKey software, but it failed to catch the shuttle's input signal.
The shuttle has its own driver. How can I catch the Shuttle Xpress signal, and map it to any key combinations I want?

答:
I made a workaround that enables me to map ShuttleXpress buttons to any keystroke sequence or scripts. The input is routed to ahk via the Fn keys. This works very well for my use, could be worth a try.

1: Remap Shuttle Xpress buttons to function keys between 13-24. (1-12 is of course also possible, but then you would tie up the physical Fn keys on the keyboard.)

2: Use ahk to remap the same function keys to any script or keystroke.


问:
Loop through fields when creating sqlalchemy object
I am trying to loop through a dict that I received via json and save the results to a database via sqlalchemy. I've kept the field names the same as the key names from the dict. It seems repetitive to list each field and dict over and over. But when I try to use something like c.keys() it does not work. If that were the case I could do:
    for key in c.keys():
        customer.key = c[key]

But that does not work. My current code is:

```<code>for c in response['Customers']:
    customer = Customer()
    customer.ID = c['ID']
    customer.Name = c['Name']
    customer.Currency = c['Currency']
    customer.PaymentTerm = c['PaymentTerm']
    customer.Discount = c['Discount']
    customer.TaxRule = c['TaxRule']
    customer.Carrier = c['Carrier']
    session.add(customer)
session.commit()
</code>```

答:
You may use Python's setattr function, which as per the document:

setattr(object, name, value)

The arguments are an object, a string and an arbitrary value. The string
  may name an existing attribute or a new attribute. The function
  assigns the value to the attribute, provided the object allows it.

For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

Hence you may write your code as:

```<code>for c in response['Customers']:
    customer = Customer()
    for key, value in c.items():
        setattr(customer, key, value)
        # ^ usage of `setattr(...)` here
    session.add(customer)

session.commit()
</code>```

where I am assuming that you have all the properties defined in your class corresponding to the keys present in your dict object c.

Body:
I am trying to loop through a dict that I received via json and save the results to a database via sqlalchemy. I've kept the field names the same as the key names from the dict. It seems repetitive to list each field and dict over and over. But when I try to use something like c.keys() it does not work. If that were the case I could do:
    for key in c.keys():
        customer.key = c[key]

But that does not work. My current code is:

for c in response['Customers']:
    customer = Customer()
    customer.ID = c['ID']
    customer.Name = c['Name']
    customer.Currency = c['Currency']
    customer.PaymentTerm = c['PaymentTerm']
    customer.Discount = c['Discount']
    customer.TaxRule = c['TaxRule']
    customer.Carrier = c['Carrier']
    session.add(customer)
session.commit()

Body:
You may use Python's setattr function, which as per the document:

setattr(object, name, value)

The arguments are an object, a string and an arbitrary value. The string
  may name an existing attribute or a new attribute. The function
  assigns the value to the attribute, provided the object allows it.

For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

Hence you may write your code as:

for c in response['Customers']:
    customer = Customer()
    for key, value in c.items():
        setattr(customer, key, value)
        # ^ usage of `setattr(...)` here
    session.add(customer)

session.commit()

where I am assuming that you have all the properties defined in your class corresponding to the keys present in your dict object c.


问:
Replace contents in a file in only specific lines
I have a sample use case, where i want to replace "glob" with "url" in only some limited lines in the file. The rest of the file need not be replaced.

```<code>/publishfarm
        {
        # client headers which should be passed through to the render instances
        # (feature supported since dispatcher build 2.6.3.5222)
        /clientheaders
          {
                $include "clientheaders.any"
          }
        # hostname globbing for farm selection (virtual domain addressing)
        /virtualhosts
          {
                $include "publish-vhosts.any"
          }
        # the load will be balanced among these render instances
        /renders
          {
          $include "publish-renders.any"
          }
        # only handle the requests in the following acl. default is 'none'
        # the glob pattern is matched against the first request line
        /filter
          {
          # deny everything and allow specific entries
          /0001 { /type "deny"  /glob "*" }

          # open consoles
        #    /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
        #    /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

          # allow non-public content directories
        #    /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
        #    /0022 { /type "allow" /glob "* /bin/*"    }

        #    /0024 { /type "allow" /glob "* /libs/*"   }
        #    /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

        #    /0026 { /type "allow" /glob "* /home/*"   }
        #    /0027 { /type "allow" /glob "* /tmp/*"    }
        #    /0028 { /type "allow" /glob "* /var/*"    }

          /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

          # enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
      /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
      /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
      /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
      /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg

      # enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*" }  # enable personalization
      /0063 { /type "allow" /glob "POST /content/[.]*.commerce.cart.json" }  # allow POSTs to update the shopping cart

          # deny content grabbing
          /0081 { /type "deny"  /glob "GET *.infinity.json*" }
          /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
          /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
          /0084 { /type "deny"  /glob "GET *.docview.json*"  }
          /0085 { /type "deny"  /glob "GET *.docview.xml*"   }
          /0086 { /type "deny"  /glob "GET *.*[0-9].json*"   }
          /0087 { /type "deny"  /glob "GET *.feed.xml*"      }
        #    /0088 { /type "allow" /glob "GET *.1.json*"        }  # allow one-level json requests
</code>```

I want to replace glob by url in only these blocks and not for the entire file.
The contents which i want to be replaced are

```<code>      # enable specific mime types in non-public content directories
  /0041 { /type "allow" /glob "* *.css *"   }  # enable css
  /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
  /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
  /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
  /0045 { /type "allow" /glob "* *.png *"   }  # enable png
  /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
  /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
  /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
  /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
  /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
  /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg
</code>```

Now the catch here is the line numbers are not fixed. How can i accomplish this in ansible.

I used to do this :41,51s/glob/url in this file opening in vim and then note the start and the end line. But as i said these line numbers keep on changing.

答: I will suggest that you can write a script to locate all the line that has enable css, enable gifs and etc. to replace the glob into url.

Body:
I have a sample use case, where i want to replace "glob" with "url" in only some limited lines in the file. The rest of the file need not be replaced.

/publishfarm
        {
        # client headers which should be passed through to the render instances
        # (feature supported since dispatcher build 2.6.3.5222)
        /clientheaders
          {
                $include "clientheaders.any"
          }
        # hostname globbing for farm selection (virtual domain addressing)
        /virtualhosts
          {
                $include "publish-vhosts.any"
          }
        # the load will be balanced among these render instances
        /renders
          {
          $include "publish-renders.any"
          }
        # only handle the requests in the following acl. default is 'none'
        # the glob pattern is matched against the first request line
        /filter
          {
          # deny everything and allow specific entries
          /0001 { /type "deny"  /glob "*" }

          # open consoles
        #    /0012 { /type "allow" /glob "* /crx/*"    }  # allow content repository
        #    /0013 { /type "allow" /glob "* /system/*" }  # allow OSGi console

          # allow non-public content directories
        #    /0021 { /type "allow" /glob "* /apps/*"   }  # allow apps access
        #    /0022 { /type "allow" /glob "* /bin/*"    }

        #    /0024 { /type "allow" /glob "* /libs/*"   }
        #    /0025 { /type "deny"  /glob "* /libs/shindig/proxy*" } # if you enable /libs close access to proxy

        #    /0026 { /type "allow" /glob "* /home/*"   }
        #    /0027 { /type "allow" /glob "* /tmp/*"    }
        #    /0028 { /type "allow" /glob "* /var/*"    }

          /0023 { /type "allow" /glob "* /content*" }  # disable this rule to allow mapped content only

          # enable specific mime types in non-public content directories
      /0041 { /type "allow" /glob "* *.css *"   }  # enable css
      /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
      /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
      /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
      /0045 { /type "allow" /glob "* *.png *"   }  # enable png
      /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
      /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
      /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
      /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
      /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
      /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg

      # enable features
      /0061 { /type "allow" /glob "POST /content/[.]*.form.html" }  # allow POSTs to form selectors under content
      /0062 { /type "allow" /glob "* /libs/cq/personalization/*" }  # enable personalization
      /0063 { /type "allow" /glob "POST /content/[.]*.commerce.cart.json" }  # allow POSTs to update the shopping cart

          # deny content grabbing
          /0081 { /type "deny"  /glob "GET *.infinity.json*" }
          /0082 { /type "deny"  /glob "GET *.tidy.json*"     }
          /0083 { /type "deny"  /glob "GET *.sysview.xml*"   }
          /0084 { /type "deny"  /glob "GET *.docview.json*"  }
          /0085 { /type "deny"  /glob "GET *.docview.xml*"   }
          /0086 { /type "deny"  /glob "GET *.*[0-9].json*"   }
          /0087 { /type "deny"  /glob "GET *.feed.xml*"      }
        #    /0088 { /type "allow" /glob "GET *.1.json*"        }  # allow one-level json requests

I want to replace glob by url in only these blocks and not for the entire file.
The contents which i want to be replaced are

      # enable specific mime types in non-public content directories
  /0041 { /type "allow" /glob "* *.css *"   }  # enable css
  /0042 { /type "allow" /glob "* *.gif *"   }  # enable gifs
  /0043 { /type "allow" /glob "* *.ico *"   }  # enable icos
  /0044 { /type "allow" /glob "* *.js *"    }  # enable javascript
  /0045 { /type "allow" /glob "* *.png *"   }  # enable png
  /0046 { /type "allow" /glob "* *.swf *"   }  # enable flash
  /0047 { /type "allow" /glob "* *.svg *"   }  # enable SVG
  /0048 { /type "allow" /glob "* *.woff *"  }  # enable woff
  /0049 { /type "allow" /glob "* *.ttf *"   }  # enable ttf
  /0050 { /type "allow" /glob "* *.eot *"   }  # enable eot
  /0051 { /type "allow" /glob "* *.jpg *"   }  # enable jpg

Now the catch here is the line numbers are not fixed. How can i accomplish this in ansible.

I used to do this :41,51s/glob/url in this file opening in vim and then note the start and the end line. But as i said these line numbers keep on changing.


问:
Maven java compile error can not access CommonClassA
Background:

I am developing Maven multi module project.

One of the module is common module needed by other all modules.

This module contain CommonClassA.java.

common module is properly compiled.

It is installed into maven local repository properly.

One of the class(Billtype.java) in other module (EmployeeBilling) refers this class(CommonClassA.java).

Maven Dependency for common module is properly specified in pom.xml of EmployeeBilling module.

Problem:

While compiling EmployeeBilling module it  throws

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project EmployeeBilling: Compilation failure
[ERROR] \MyWorkspace\Biz\EmployeeBilling\src\main\java\com\employee\Billtype.java:[79,19] error: cannot access CommonClassA
[ERROR] -> [Help 1]**
</code>```

Supporting details:

dependency defined in EmployeeBilling> pom.xml:

Other classes from common module seems accessible as no error observed

There are no other errors like Class not found/file not found.

The class CommonCLassA implements Serializable

Same error occurs from Eclipse as well as commond line

I am using M2E plugin

Tools:

jdk1.7.0_02

OS: Windows  7

Eclipse JUNO and apache-maven-3.1.0

Thanks in advance!

答: I had the same problem. Even the jar dependency has the required class files. Finally I deleted the local maven repo and restarted the build. Now it worked without any issue.</p>

Body:
Background:

I am developing Maven multi module project.

One of the module is common module needed by other all modules.

This module contain CommonClassA.java.

common module is properly compiled.

It is installed into maven local repository properly.

One of the class(Billtype.java) in other module (EmployeeBilling) refers this class(CommonClassA.java).

Maven Dependency for common module is properly specified in pom.xml of EmployeeBilling module.

Problem:

While compiling EmployeeBilling module it  throws

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project EmployeeBilling: Compilation failure
[ERROR] \MyWorkspace\Biz\EmployeeBilling\src\main\java\com\employee\Billtype.java:[79,19] error: cannot access CommonClassA
[ERROR] -> [Help 1]**

Supporting details:

dependency defined in EmployeeBilling> pom.xml:

Other classes from common module seems accessible as no error observed

There are no other errors like Class not found/file not found.

The class CommonCLassA implements Serializable

Same error occurs from Eclipse as well as commond line

I am using M2E plugin

Tools:

jdk1.7.0_02

OS: Windows  7

Eclipse JUNO and apache-maven-3.1.0

Thanks in advance!


问:
SQL Server 2005 Temporary Tables
In a stored procedure, when is #Temptable created in SQL Server 2005?  When creating the query execution plan or when executing the stored procedure?</p>

```<code>if (@x = 1)
    begin
        select 1 as Text into #Temptable
    end
else
    begin
        select 2 as Text into #Temptable
    end
</code>```

答: Whilst it may be automatically dropped at the end of a session, it is good practice to drop the table yourself when you're done with it.</p>

OwnerDisplayName: Robert Wilkinson

Title: SQL Server 2005 Temporary Tables

Body:
In a stored procedure, when is #Temptable created in SQL Server 2005?  When creating the query execution plan or when executing the stored procedure?

if (@x = 1)
    begin
        select 1 as Text into #Temptable
    end
else
    begin
        select 2 as Text into #Temptable
    end

LastEditorDisplayName: Kevin Fairchild

OwnerDisplayName: Scott


问:
Having trouble with the output/structure of a nested Array in PHP and MySQL
Im trying to make a neat, structured list of, in this case, films and showdates.

```<code>$shows = array(
    array(
        "Thursday" => array(
            "17:00",
            "19:00")),
    array(
        "Friday" => array(
            "16:30",
            "18:45"
            "20:10")),
    array(
        "Saturday" => array(
            "18:30",
            "21:00"))
);
</code>```

The problem is that I cant seem to be able to print the things out in a reasonable way.
The days are supposed to be dynamic, not hard corded as of this case.

```<code>for ($row = 0; $row < $shows.length(); $row++) //Haven't got a clue about the 'length()'
{
    print $shows[$row] . "<br>"; //Print the day.

    for (

   $col = 0; $col < $shows[$row].length(); $col++) //Loop through each day.
    {
        print (">" . $shows[$row][$col] . "<br>"); //Print each time of the day.
    }

}
</code>```

And what im trying to do is to print out each day with the corresponding times.
Should come out as something like this.

```<code>Thursday - 17:00
           19:00

Friday   - 16:30
           18:45
           20:10
</code>```

答:
```<code>foreach ($shows as $show) {
    foreach ($show as $day => $times) {
        echo $day;
        foreach ($times as $time) {
            echo $time;
        }
    }
}
</code>```

But, really, you should simplify this a little like this:

```<code>$shows = array(
    array('day' => 'Saturday', 'times' => array('17:00', '19:00')),
    …
);

foreach ($shows as $show) {
    echo $show['day'];
    foreach ($show['times'] as $time) {
        echo $time;
    }
}
</code>```

Or, to do it really properly and in a computer parseable manner:

```<code>$shows = array(
    strtotime('2010-12-24 17:00:00'),
    strtotime('2010-12-24 19:00:00'),
    …
);

$lastDate = null;
foreach ($shows as $show) {
    if (!$lastDate || date('Y-m-d', $show) != date('Y-m-d', $lastDate)) {
        echo date('l', $show);
    }
    echo date('H:i', $show);
    $lastDate = $show;
}
</code>```

:o)

Body:
Im trying to make a neat, structured list of, in this case, films and showdates.

$shows = array(
    array(
        "Thursday" => array(
            "17:00",
            "19:00")),
    array(
        "Friday" => array(
            "16:30",
            "18:45"
            "20:10")),
    array(
        "Saturday" => array(
            "18:30",
            "21:00"))
);

The problem is that I cant seem to be able to print the things out in a reasonable way.
The days are supposed to be dynamic, not hard corded as of this case.

for ($row = 0; $row < $shows.length(); $row++) //Haven't got a clue about the 'length()'
{
    print $shows[$row] . "
"; //Print the day.

    for (

   $col = 0; $col < $shows[$row].length(); $col++) //Loop through each day.
    {
        print (">" . $shows[$row][$col] . "
"); //Print each time of the day.
    }

}

And what im trying to do is to print out each day with the corresponding times.
Should come out as something like this.

Thursday - 17:00
           19:00

Friday   - 16:30
           18:45
           20:10

Body:
foreach ($shows as $show) {
    foreach ($show as $day => $times) {
        echo $day;
        foreach ($times as $time) {
            echo $time;
        }
    }
}

But, really, you should simplify this a little like this:

$shows = array(
    array('day' => 'Saturday', 'times' => array('17:00', '19:00')),
    …
);

foreach ($shows as $show) {
    echo $show['day'];
    foreach ($show['times'] as $time) {
        echo $time;
    }
}

Or, to do it really properly and in a computer parseable manner:

$shows = array(
    strtotime('2010-12-24 17:00:00'),
    strtotime('2010-12-24 19:00:00'),
    …
);

$lastDate = null;
foreach ($shows as $show) {
    if (!$lastDate || date('Y-m-d', $show) != date('Y-m-d', $lastDate)) {
        echo date('l', $show);
    }
    echo date('H:i', $show);
    $lastDate = $show;
}

:o)


问:
Cannot access properties of object
I have ran into a very weird issue I cannot seem to fix. Basically I am taking a CSV file and parsing it into a JSON object to hold in my redux store. I have the parsing and everything working...or so it looks like it is working and everything compiled into a nice JSON object sitting in my store.

When I map over each item and log the object in my component it also seems to look correct and I have access to everything I need...so it looks.

The issue is when I try to use a property from those objects I get undefined no matter what. So for example console.log(weatherData[i]) or console.log(weatherData.keyname) I can log the object as seen above. However when I try to log something like this console.log(weatherData[i].capital) or console.log(weatherData.keyname.capital) I get undefined.

I have no idea why this is happening and am very lost now, so if anyone has any ideas please let me know. I also have used componentWillMount and 'setTimeout' to ensure I have all the data before requesting it, but that doesn't fix anything for me either

答: Just found the issue, was very stupid but the keys on my object had double quotes around them which was causing issues when trying to target them! Couldn't tell since inspect and redux tool both also format with double quotes</p>

Title: Cannot access properties of object