问:
how to add custom logging level in log4j
I want to add custom logging level security to my log4j.xml file and this log level should be above debug and less than level trace.How to configure the custom logging level in log4j.xml file and when i use the level debug in root element of log4j.xml file  the log level security should not be printed in log file wwhereas if i use custom level security in root element of log4j.xml file all the levels up security  should be printed but not trace.</p>

答:
Log4J 2 supports custom log levels. Custom log levels can be defined in code or in configuration.

To create custom log levels in configuration (log4j.xml), use the following example snippet,

```<code><CustomLevels>
      <CustomLevel name="CUSTOM" intLevel="350" />
</CustomLevels>
</code>```

The intLevel parameter (350 in the example above) determines where the custom level exists in relation to the standard levels built-in to Log4J 2.

In your case,
since you need a log level above DEBUG and less than TRACE, use the following code snippet in log4j.xml

```<code><CustomLevels>
      <CustomLevel name="CUSTOM" intLevel="550" />
</CustomLevels>
</code>```

Since the intLevel of DEBUG is 500 and TRACE is 600 (according to Log4J 2), we have set the intLevel for the custom log level as 550.

For more information, refer the following link,

https://logging.apache.org/log4j/2.x/manual/customloglevels.html

Body:
Log4J 2 supports custom log levels. Custom log levels can be defined in code or in configuration.

To create custom log levels in configuration (log4j.xml), use the following example snippet,

<CustomLevels>
      <CustomLevel name="CUSTOM" intLevel="350" />
</CustomLevels>

The intLevel parameter (350 in the example above) determines where the custom level exists in relation to the standard levels built-in to Log4J 2.

In your case,
since you need a log level above DEBUG and less than TRACE, use the following code snippet in log4j.xml

<CustomLevels>
      <CustomLevel name="CUSTOM" intLevel="550" />
</CustomLevels>

Since the intLevel of DEBUG is 500 and TRACE is 600 (according to Log4J 2), we have set the intLevel for the custom log level as 550.

For more information, refer the following link,

https://logging.apache.org/log4j/2.x/manual/customloglevels.html


来源: stackexchange

问:
Single dictionary initialization with different types of keys
Has anyone used class initialization like this:

```<code>var dictionary = new Dictionary {
    [address] = address,
    [person] = person,
    [biz] = biz
};
</code>```

How do I declare such class Dictionary which initializes using above line,
Never used [] in dictionary initialization which takes different types as key

address, person, biz are objects off different classes Address, Person and Biz

reference: problem I am solving

Updates

```<code>public class BaseEntity
{
    public string Id { get; set; }

    public bool Save()
    {
        return true;
    }

    public bool Delete()
    {
        return true;
    }
}

public class Address : BaseEntity
{
    public Address() { }

    public Address(string addressLine1, string addressLine2, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.State = state;
        this.ZipCode = zip;
    }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public static Address Find(string id)
    {
        return null;
    }
}

public class Business : BaseEntity
{
    public Business() { }

    public Business(string businessName, Address address)
    {
        this.Name = businessName;
        this.Address = address;
    }

    public string Name { get; set; }
    public Address Address { get; set; }

    public static Business Find(string id)
    {
        return null;
    }
}

public class Person : BaseEntity
{
    public Person() { }

    public Person(string fname, string lname, Address address)
    {
        this.FirstName = fname;
        this.LastName = lname;
        this.Address = address;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public static Person Find(string id)
    {
        return null;
    }
}
</code>```

答:
One approach to consider:</p>

```<code>// Some example data of different types
var address = "";
var person = new object();
var biz = new List<int>();

var dictionary = new Dictionary<object,object> { [address] = address, [person] = person, [biz] = biz };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Has anyone used class initialization like this:

var dictionary = new Dictionary {
    [address] = address,
    [person] = person,
    [biz] = biz
};

How do I declare such class Dictionary which initializes using above line,
Never used [] in dictionary initialization which takes different types as key

address, person, biz are objects off different classes Address, Person and Biz

reference: problem I am solving

Updates

public class BaseEntity
{
    public string Id { get; set; }

    public bool Save()
    {
        return true;
    }

    public bool Delete()
    {
        return true;
    }
}

public class Address : BaseEntity
{
    public Address() { }

    public Address(string addressLine1, string addressLine2, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.State = state;
        this.ZipCode = zip;
    }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public static Address Find(string id)
    {
        return null;
    }
}

public class Business : BaseEntity
{
    public Business() { }

    public Business(string businessName, Address address)
    {
        this.Name = businessName;
        this.Address = address;
    }

    public string Name { get; set; }
    public Address Address { get; set; }

    public static Business Find(string id)
    {
        return null;
    }
}

public class Person : BaseEntity
{
    public Person() { }

    public Person(string fname, string lname, Address address)
    {
        this.FirstName = fname;
        this.LastName = lname;
        this.Address = address;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public static Person Find(string id)
    {
        return null;
    }
}

Body:
One approach to consider:

// Some example data of different types
var address = "";
var person = new object();
var biz = new List<int>();

var dictionary = new Dictionary<object,object> { [address] = address, [person] = person, [biz] = biz };


问:
Embedded Web Server
We currently have a web application which should be accessible from multiple sub-domains and from multiple actual domains. E.g. clients sign up and if they want to they can use their own domains. As far as I know this would be achieved by them pointing that domains A record at us and then our web server, which would have to be embedded so we can update at run-time, adding a virtual host dynamically.

Our web application is written in PHP (although playing around with HipHop to convert to C++) with static HTML and CSS. This web application communicates with a back-end Java API that uses the Restlet framework.

Does anyone know of a web server that could be embedded that will work with PHP (and would work with HipHop if we used that)? I have had a look at AppWeb but I wondered if there were any others.

I wonder if maybe I would be better moving my web app to something like Java and using Jetty?

Thanks,

答:
Not sure if I get correctly where you want to embed it. But if PHP is a requirement, there is the option of using http://pear.php.net/package/HTTP_Server. It's rather minimalistic, but should thus be easily adaptable and have less issues with a HipHop transformation.

The second alternative would be Nanoweb. While that's designed as a real webserver and feature-wise comparable to Apache, it's not suitable for embedding. But there are probably others, if you want to go that particular route.

ContentLicense: CC BY-SA 2.5

Title: Embedded Web Server


问:
Jquery Flip Issue
I am using the jquery flip plugin and i have an issue where when i place the front and back on my two divs everything is visible on the page like so.

Does anyone know why this is happening i have the simplest version of the jquery code any help would be appreciated.

Flip Code:

```<code>$("#card").ready(function () {
  $("#card").flip({
    // axis: 'y',
    speed: '700',
    trigger: 'click'
  });
});
</code>```

答:
It looks as though the plugin hasn't loaded.

Try calling your code within

```<code>$(document).ready(...
</code>```

Title: Jquery Flip Issue

Body:
I am using the jquery flip plugin and i have an issue where when i place the front and back on my two divs everything is visible on the page like so.

Does anyone know why this is happening i have the simplest version of the jquery code any help would be appreciated.

Flip Code:

$("#card").ready(function () {
  $("#card").flip({
    // axis: 'y',
    speed: '700',
    trigger: 'click'
  });
});

Body:
It looks as though the plugin hasn't loaded.

Try calling your code within

$(document).ready(...


问:
Unable to create array of objects in angularjs in foreach loop
I am developing web application in angularjs. I have one foreach loop to loop through scope object. Below is my js code.

```<code>$scope.details = [];
$scope.apply = function() {
    angular.forEach($scope.screenMap, function(value, key) {
        //$scope.details.push(value.scrn_id, value.Read, value.Write);
        $scope.details.push("ID", value.scrn_id);
        $scope.details.push("Read", value.Read);
        $scope.details.push("Write", value.Write);
    });
    console.log($scope.details);
}
</code>```

After looping I get total 18 entries for 3 iterations.

What I am expecting is

```<code>  ID:1  Read:True  Write: False
  ID:2  Read:False  Write: True
  ID:3  Read:True  Write: False
  ID:4  Read:False  Write: True
</code>```

may I know how can I get array in above format?

答:
Your pushing 3 times in a loop that too two objects at a time. Dont use commas to insert key value pair(object name : value)

javascript Object annotation is as follows
var x = {"nameofthe Object1":object value1,
         "nameofthe Object2":object value2
        }
3*2*3 = 18 and these are single entries.

create a javascript object and push into the $scope.details

```<code>    $scope.details = [];
    $scope.apply = function () {
        angular.forEach($scope.screenMap, function (value, key) {
            //$scope.details.push(value.scrn_id, value.Read, value.Write);
            $scope.details.push({"ID": value.scrn_id,
                                 "Read": value.Read,
                                 "Write": value.Write});
        });
        console.log($scope.details);
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing web application in angularjs. I have one foreach loop to loop through scope object. Below is my js code.

$scope.details = [];
$scope.apply = function() {
    angular.forEach($scope.screenMap, function(value, key) {
        //$scope.details.push(value.scrn_id, value.Read, value.Write);
        $scope.details.push("ID", value.scrn_id);
        $scope.details.push("Read", value.Read);
        $scope.details.push("Write", value.Write);
    });
    console.log($scope.details);
}

After looping I get total 18 entries for 3 iterations.

What I am expecting is

  ID:1  Read:True  Write: False
  ID:2  Read:False  Write: True
  ID:3  Read:True  Write: False
  ID:4  Read:False  Write: True

may I know how can I get array in above format?

Body:
Your pushing 3 times in a loop that too two objects at a time. Dont use commas to insert key value pair(object name : value)

javascript Object annotation is as follows
var x = {"nameofthe Object1":object value1,
         "nameofthe Object2":object value2
        }
3*2*3 = 18 and these are single entries.

create a javascript object and push into the $scope.details

    $scope.details = [];
    $scope.apply = function () {
        angular.forEach($scope.screenMap, function (value, key) {
            //$scope.details.push(value.scrn_id, value.Read, value.Write);
            $scope.details.push({"ID": value.scrn_id,
                                 "Read": value.Read,
                                 "Write": value.Write});
        });
        console.log($scope.details);
    }


问:
oozie -- Output data exceeds its limit [2048]
I am trying to run a simple workflow executing a hive script.
This hive script just calls joining(tables is very large);
Once the hive script execution ends I was expecting to see the workflow status changing from RUNNING to successful, but this is not happening.

This is the content of the workflow log:

```<code>2016-05-31 15:52:34,590 WARN

org.apache.oozie.action.hadoop.HiveActionExecutor:
SERVER[hadoop02] U
SER[scapp]
GROUP[-]
TOKEN[]
APP[wf-sqoop-hive-agreement]
JOB[0000001-160531143657136-oozie-oozi-W]
ACTION[0000001-160531143657136-oozie-oozi-W@hive-query-agreement] Launcher
ERROR, reason: Main class [org.apache.oozie.action.hadoop.HiveMain], exception invoking main(), Output data exceeds its limit [2048] 2016-05-31 15:52:34,591

WARN org.apache.oozie.action.hadoop.HiveActionExecutor:
SERVER[hadoop02]
USER[scapp]
GROUP[-]
TOKEN[]
APP[wf-sqoop-hive-agreement]
JOB[0000001-160531143657136-oozie-oozi-W]
ACTION[0000001-160531143657136-oozie-oozi-W@hive-query-agreement]
Launcher exception: Output data exceeds its limit [2048]
org.apache.oozie.action.hadoop.LauncherException: Output data exceeds its limit [2048]
at org.apache.oozie.action.hadoop.LauncherMapper.getLocalFileContentStr(LauncherMapper.java:415)
at org.apache.oozie.action.hadoop.LauncherMapper.handleActionData(LauncherMapper.java:391)
at org.apache.oozie.action.hadoop.LauncherMapper.map(LauncherMapper.java:275) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
</code>```

答:
I assume that you might have included <capture-output> element in your hive action or any other actions of the workflow. Try removing that element from the workflow and run it again.

<capture-output> will hold the STDOUT of the ssh command and is limited to 2KiB [2048 bytes]

You can learn more about it here

Body:
I am trying to run a simple workflow executing a hive script.
This hive script just calls joining(tables is very large);
Once the hive script execution ends I was expecting to see the workflow status changing from RUNNING to successful, but this is not happening.

This is the content of the workflow log:

2016-05-31 15:52:34,590 WARN

org.apache.oozie.action.hadoop.HiveActionExecutor:
SERVER[hadoop02] U
SER[scapp]
GROUP[-]
TOKEN[]
APP[wf-sqoop-hive-agreement]
JOB[0000001-160531143657136-oozie-oozi-W]
ACTION[0000001-160531143657136-oozie-oozi-W@hive-query-agreement] Launcher
ERROR, reason: Main class [org.apache.oozie.action.hadoop.HiveMain], exception invoking main(), Output data exceeds its limit [2048] 2016-05-31 15:52:34,591

WARN org.apache.oozie.action.hadoop.HiveActionExecutor:
SERVER[hadoop02]
USER[scapp]
GROUP[-]
TOKEN[]
APP[wf-sqoop-hive-agreement]
JOB[0000001-160531143657136-oozie-oozi-W]
ACTION[0000001-160531143657136-oozie-oozi-W@hive-query-agreement]
Launcher exception: Output data exceeds its limit [2048]
org.apache.oozie.action.hadoop.LauncherException: Output data exceeds its limit [2048]
at org.apache.oozie.action.hadoop.LauncherMapper.getLocalFileContentStr(LauncherMapper.java:415)
at org.apache.oozie.action.hadoop.LauncherMapper.handleActionData(LauncherMapper.java:391)
at org.apache.oozie.action.hadoop.LauncherMapper.map(LauncherMapper.java:275) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)


答:
If the Dictionary needs to key on the type, it can be done thus:

```<code>var dict = new Dictionary<Type, Object> {
    [typeof(Address)] = new Address(),
    [typeof(Person)] = new Person(),

    // If you have an existing object, then like this.
    [address.GetType()] = address
};
</code>```

The code that reads the dictionary can then do something like:

```<code>foreach (KeyValuePair<Type, Object> kv in dict) {
    var castedObject = Convert.ChangeType(kv.Value, kv.Key);
}
</code>```

Title: Single dictionary initialization with different types of keys

Body:
If the Dictionary needs to key on the type, it can be done thus:

var dict = new Dictionary<Type, Object> {
    [typeof(Address)] = new Address(),
    [typeof(Person)] = new Person(),

    // If you have an existing object, then like this.
    [address.GetType()] = address
};

The code that reads the dictionary can then do something like:

foreach (KeyValuePair<Type, Object> kv in dict) {
    var castedObject = Convert.ChangeType(kv.Value, kv.Key);
}


问:
How to set store id to cms block output
I am using below code to display static block content but it display only first store block every time.I am load this cms block on admin side.
I have two block with same identifier but assign it to diffrent store so i would like to display it store wise.

Here is code i m using but it didn't help.

```<code>Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdf_page_of')->setStoreId($storeId)->toHtml()
</code>```

答:
Please use the below with different $storeId</p>

```<code>$block = Mage::getModel('cms/block')->setStoreId($storeId)->load('newest_product');
echo $block->getTitle();
echo $block->getContent();
</code>```

Title: How to set store id to cms block output

Body:
I am using below code to display static block content but it display only first store block every time.I am load this cms block on admin side.
I have two block with same identifier but assign it to diffrent store so i would like to display it store wise.

Here is code i m using but it didn't help.

Mage::app()->getLayout()->createBlock('cms/block')->setBlockId('pdf_page_of')->setStoreId($storeId)->toHtml()

Body:
Please use the below with different $storeId

$block = Mage::getModel('cms/block')->setStoreId($storeId)->load('newest_product');
echo $block->getTitle();
echo $block->getContent();


问:
Trying to get the right diagonal of a matrix results in a "vector out of range" error
I have this code where I am trying to take the diagonal elements from a matrix stored in a vector from the top right, but I get a "vector out of range" error

```<code>     const int size_rows = 3;
     const int size_cols = 3;

    vector< vector<int> > matrixs(size_rows, vector<int>(size_cols)); //multidimensional vector
    for (size_t i = size_rows - 1; i >= 0; )
        {
            for (size_t j = 0; j < size_cols; j++)
            {
                cout << matrixs[i][j] << " ";

                i--;
            }
            cout << endl;
        }
</code>```

if my input is this matrix

```<code>4 9 2
3 5 7
8 1 5
</code>```

I should get this output:

```<code>2,5,8
</code>```

But I get an error stating vector subscript out of range!
how can I fix this ?

答:
```<code>for (size_t i = size_rows - 1; i >= 0; )
</code>```

Your loop runs forever, because an unsigned value is always greater than or equal to 0, and size_t is unsigned. Once you reach 0 and subtract, you'll wrap around to the highest possible value of size_t, which is well out of range of your vector.

Running your program in a debugger would have revealed this.

Iterating towards zero with an unsigned value is tricky business. You might be better off iterating upwards but adjusting your counter for use:

```<code>for (size_t i = 0; i < size_rows; ) {
   const size_t real_i = size_rows - 1 - i;
   // now use real_i instead
   i--;
}
</code>```

Alternatively you could switch from size_t to ssize_t (or just int).

Body:
I have this code where I am trying to take the diagonal elements from a matrix stored in a vector from the top right, but I get a "vector out of range" error

     const int size_rows = 3;
     const int size_cols = 3;

    vector< vector<int> > matrixs(size_rows, vector<int>(size_cols)); //multidimensional vector
    for (size_t i = size_rows - 1; i >= 0; )
        {
            for (size_t j = 0; j < size_cols; j++)
            {
                cout << matrixs[i][j] << " ";

                i--;
            }
            cout << endl;
        }

if my input is this matrix

4 9 2
3 5 7
8 1 5

I should get this output:

2,5,8

But I get an error stating vector subscript out of range!
how can I fix this ?

Body:
for (size_t i = size_rows - 1; i >= 0; )

Your loop runs forever, because an unsigned value is always greater than or equal to 0, and size_t is unsigned. Once you reach 0 and subtract, you'll wrap around to the highest possible value of size_t, which is well out of range of your vector.

Running your program in a debugger would have revealed this.

Iterating towards zero with an unsigned value is tricky business. You might be better off iterating upwards but adjusting your counter for use:

for (size_t i = 0; i < size_rows; ) {
   const size_t real_i = size_rows - 1 - i;
   // now use real_i instead
   i--;
}

Alternatively you could switch from size_t to ssize_t (or just int).


问:
How to maintain login session in ios?
I would like to know where I need to change the root view controller in the app programming. Below is my code

```<code>class NavigationViewController: UINavigationController {

var window: UIWindow?

override func viewDidLoad() {
    super.viewDidLoad()

    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let newRootView = storyBoard.instantiateViewController(withIdentifier: "WelcomeViewController") as! WelcomeViewController
    let userStatus = UserDefaults.standard.bool(forKey: "isLoggedIn")
    if userStatus {
        self.window?.rootViewController = newRootView
    }

  }
}
</code>```

I am setting the value for isLoggedIn key as true when user logged in and false when the user logged out so that I can retrieve the value in this navigation controller subclass, based on that I can choose the root view controller. But its not working fine it remains the same whenever I am launching the app I am getting the login page only though I already logged in, also please don't suggest me to change the root view controller inside of didfinishlaunchingwithoptions method. Could someone help me to solve it? Thanks in advance.

答:
First set user login bool true in NSUserDefults. when User is login Successfully.

```<code>UserDefaults.standard.set(true, forKey: "USERISLOGIN")
</code>```

Now Open Appdelegate.swift -> didFinishLaunchingWithOptions Method:-

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    if(UserDefaults.standard.bool(forKey: "USERISLOGIN")){

                let storyboard = UIStoryboard(name: "Main", bundle: nil)

                let objLogoutVC = storyboard.instantiateViewController(withIdentifier: "LogoutVC") as! LogoutVC
                let navigationController = UINavigationController(rootViewController: objLogoutVC)

                navigationController.navigationBar.isTranslucent = false
                navigationController.navigationBar.isHidden = true
                self.window?.rootViewController = navigationController
                self.window?.makeKeyAndVisible()
            }
     return true
}
</code>```

Let me know if you needed any thing more.

Title: How to maintain login session in ios?

Body:
I would like to know where I need to change the root view controller in the app programming. Below is my code

class NavigationViewController: UINavigationController {

var window: UIWindow?

override func viewDidLoad() {
    super.viewDidLoad()

    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let newRootView = storyBoard.instantiateViewController(withIdentifier: "WelcomeViewController") as! WelcomeViewController
    let userStatus = UserDefaults.standard.bool(forKey: "isLoggedIn")
    if userStatus {
        self.window?.rootViewController = newRootView
    }

  }
}

I am setting the value for isLoggedIn key as true when user logged in and false when the user logged out so that I can retrieve the value in this navigation controller subclass, based on that I can choose the root view controller. But its not working fine it remains the same whenever I am launching the app I am getting the login page only though I already logged in, also please don't suggest me to change the root view controller inside of didfinishlaunchingwithoptions method. Could someone help me to solve it? Thanks in advance.

Body:
First set user login bool true in NSUserDefults. when User is login Successfully.

UserDefaults.standard.set(true, forKey: "USERISLOGIN")

Now Open Appdelegate.swift -> didFinishLaunchingWithOptions Method:-

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    if(UserDefaults.standard.bool(forKey: "USERISLOGIN")){

                let storyboard = UIStoryboard(name: "Main", bundle: nil)

                let objLogoutVC = storyboard.instantiateViewController(withIdentifier: "LogoutVC") as! LogoutVC
                let navigationController = UINavigationController(rootViewController: objLogoutVC)

                navigationController.navigationBar.isTranslucent = false
                navigationController.navigationBar.isHidden = true
                self.window?.rootViewController = navigationController
                self.window?.makeKeyAndVisible()
            }
     return true
}

Let me know if you needed any thing more.


问:
time picker showing time like 5:7 instead of 05:07
I have a time picker function which sets time in an EditText but the format it shows is not suitable. For example for 04:07pm is shown as 4:7. Whenever the digit in time is less than 10 it removes the 0 automatically.

Please help me out. My code is

```<code>$("#startTime").kendoTimePicker();
var timepicker = $("#startTime").data("kendoTimePicker");
timepicker.enable(true);
StartTimeVal = $('#startTime').val("");
</code>```

答:
use format you can format the time using format option like this

```<code>$("##startTime").kendoTimePicker({
        format: "hh:mm tt"
    });
</code>```

Body:
I have a time picker function which sets time in an EditText but the format it shows is not suitable. For example for 04:07pm is shown as 4:7. Whenever the digit in time is less than 10 it removes the 0 automatically.

Please help me out. My code is

$("#startTime").kendoTimePicker();
var timepicker = $("#startTime").data("kendoTimePicker");
timepicker.enable(true);
StartTimeVal = $('#startTime').val("");

Body:
use format you can format the time using format option like this

$("##startTime").kendoTimePicker({
        format: "hh:mm tt"
    });


问:
Multiprocessing Pipe send() blocks
According to Python documentation, only recv() blocks but not send(). I wrote the following code trying to make a GUI sudoku game. I made it in such a way that I can update the game board even if the tkinter is executing its mainloop. However, during a test run, I found that if I close the window while the game is updating, the pipe.send() starts to block (I found that out using CPython profiler.) Can anyone please tell me why and, if possible, how to fix this issue?

To produce the issue: close the poped up window while the script is updating. That is, close the window while some numbers are printed to console.

My system: macOS Sierra 10.12.5

```<code>import multiprocessing as mp
import threading
import random
import time
try:
    import tkinter as tk  # Python3
except ImportError:
    import Tkinter as tk  # Python2

class VisualizedBoard:
    def __init__(self,input_string,pipe):
        '''input_string: a string has a length of at least 81 that represent the board from top-left to bottom right.
        empty cell is 0'''

        self.update_scheduled=False
        self.pipe=pipe

        # create board
        self.root = tk.Tk()
        self.canvas = tk.Canvas(self.root, width=500, height=500)
        self.canvas.create_rectangle(50, 50, 500, 500, width=2)
        for i in range(1, 10):
            self.canvas.create_text(25 + 50 * i, 30, text=str(i))
            self.canvas.create_text(30, 25 + 50 * i, text=str(i))
            self.canvas.create_line(50 + 50 * i, 50, 50 + 50 * i, 500, width=2 if i % 3 == 0 else 1)
            self.canvas.create_line(50, 50 + 50 * i, 500, 50 + 50 * i, width=2 if i % 3 == 0 else 1)

        for i in range(81):
            if input_string[i] != '0':
                self.canvas.create_text(75 + 50 * (i // 9), 75 + 50 * (i % 9), tags=str((i//9+1,i%9+1)).replace(' ',''),text=input_string[i], fill='black')

        self.canvas.pack()
        self.root.attributes('-topmost', True)

        self.root.geometry('550x550+%d+%d' % ((self.root.winfo_screenwidth() - 550) // 2, (self.root.winfo_screenheight() - 550) // 2))
        self.root.wm_protocol('WM_DELETE_WINDOW',lambda :(self.root.destroy()))
        threading.Thread(target=self.listen, args=()).start()
        self.root.mainloop()

    def update(self,coordinate,value,color='magenta'):
        """
                :parameter coordinate: a tuple (x,y)
                :parameter value: single digit
                :returns: None
        """
        try:
            assert isinstance(coordinate,tuple)
        except AssertionError:
            print('Update Failed. Coordinate should be a tuple (x,y)')

        coordinate_tag=str(coordinate).replace(' ','')
        self.canvas.delete(coordinate_tag)
        if value != 0 and value != '0':
            self.canvas.create_text(25+50*coordinate[0],25+50*coordinate[1],tags=coordinate_tag,text=str(value),fill=color)

        self.postponed_update()

        #self.canvas.update()

    def postponed_update(self):
        if not self.update_scheduled:
            self.canvas.after(50,self.scheduled_update)
            self.update_scheduled=True

    def scheduled_update(self):
        self.canvas.update()
        self.update_scheduled=False

    def new_board(self,input_string):
        self.root.destroy()
        return VisualizedBoard(input_string,self.pipe)

    def listen(self):
        try:
            while True:
                msg=self.pipe.recv()
                self.update(*msg)
        except EOFError:
            self.pipe.close()
            tk.Label(self.root,text='Connection to the main script has been closed.\nIt is safe to close this window now.').pack()
        except Exception as m:
            self.pipe.close()
            print('Error during listing:',m)

class BoardConnection:
    def __init__(self,input_string):
        ctx = mp.get_context('spawn')
        self.receive,self.pipe=ctx.Pipe(False)
        self.process=ctx.Process(target=VisualizedBoard,args=(input_string,self.receive))
        self.process.start()

    def update(self,coordinate,value,color='magenta'):
        """
        :parameter coordinate: a tuple (x,y)
        :parameter value: single digit
        :returns: None
        """
        self.pipe.send((coordinate,value,color))

    def close(self):
        self.pipe.close()
        self.process.terminate()

if __name__ == "__main__":
    b=BoardConnection('000000000302540000050301070000000004409006005023054790000000050700810000080060009')
    start = time.time()
    for i in range(5000): #test updating using random numbers
        b.update((random.randint(1, 9), random.randint(1, 9)), random.randrange(10))
        print(i)
    print(time.time() - start)
</code>```

答:
Python Pipe is an abstractions on top of OS nameless pipes.

An OS pipe is generally implemented as a memory buffer of a certain size within the kernel. By default, if the buffer fills up the next call to send/write will block.

If you want to be able to continue publishing data even if no consumer is consuming it, you should either use a multiprocessing.Queue or asyncio facilities.

The multiprocessing.Queue employs a "limitless" buffer and a thread to push the data into the OS pipe. If the pipe gets full the caller will continue running as the published data will be piled up in the Queue buffer.

IIRC, asyncio sets the pipe O_NONBLOCK flag and waits for the pipe to be consumed. Additional messages are stored within a "limitless" buffer as for the multiprocessing.Queue.

Title: Multiprocessing Pipe send() blocks

Body:
According to Python documentation, only recv() blocks but not send(). I wrote the following code trying to make a GUI sudoku game. I made it in such a way that I can update the game board even if the tkinter is executing its mainloop. However, during a test run, I found that if I close the window while the game is updating, the pipe.send() starts to block (I found that out using CPython profiler.) Can anyone please tell me why and, if possible, how to fix this issue?

To produce the issue: close the poped up window while the script is updating. That is, close the window while some numbers are printed to console.

My system: macOS Sierra 10.12.5

import multiprocessing as mp
import threading
import random
import time
try:
    import tkinter as tk  # Python3
except ImportError:
    import Tkinter as tk  # Python2

class VisualizedBoard:
    def __init__(self,input_string,pipe):
        '''input_string: a string has a length of at least 81 that represent the board from top-left to bottom right.
        empty cell is 0'''

        self.update_scheduled=False
        self.pipe=pipe

        # create board
        self.root = tk.Tk()
        self.canvas = tk.Canvas(self.root, width=500, height=500)
        self.canvas.create_rectangle(50, 50, 500, 500, width=2)
        for i in range(1, 10):
            self.canvas.create_text(25 + 50 * i, 30, text=str(i))
            self.canvas.create_text(30, 25 + 50 * i, text=str(i))
            self.canvas.create_line(50 + 50 * i, 50, 50 + 50 * i, 500, width=2 if i % 3 == 0 else 1)
            self.canvas.create_line(50, 50 + 50 * i, 500, 50 + 50 * i, width=2 if i % 3 == 0 else 1)

        for i in range(81):
            if input_string[i] != '0':
                self.canvas.create_text(75 + 50 * (i // 9), 75 + 50 * (i % 9), tags=str((i//9+1,i%9+1)).replace(' ',''),text=input_string[i], fill='black')

        self.canvas.pack()
        self.root.attributes('-topmost', True)

        self.root.geometry('550x550+%d+%d' % ((self.root.winfo_screenwidth() - 550) // 2, (self.root.winfo_screenheight() - 550) // 2))
        self.root.wm_protocol('WM_DELETE_WINDOW',lambda :(self.root.destroy()))
        threading.Thread(target=self.listen, args=()).start()
        self.root.mainloop()

    def update(self,coordinate,value,color='magenta'):
        """
                :parameter coordinate: a tuple (x,y)
                :parameter value: single digit
                :returns: None
        """
        try:
            assert isinstance(coordinate,tuple)
        except AssertionError:
            print('Update Failed. Coordinate should be a tuple (x,y)')

        coordinate_tag=str(coordinate).replace(' ','')
        self.canvas.delete(coordinate_tag)
        if value != 0 and value != '0':
            self.canvas.create_text(25+50*coordinate[0],25+50*coordinate[1],tags=coordinate_tag,text=str(value),fill=color)

        self.postponed_update()

        #self.canvas.update()

    def postponed_update(self):
        if not self.update_scheduled:
            self.canvas.after(50,self.scheduled_update)
            self.update_scheduled=True

    def scheduled_update(self):
        self.canvas.update()
        self.update_scheduled=False

    def new_board(self,input_string):
        self.root.destroy()
        return VisualizedBoard(input_string,self.pipe)

    def listen(self):
        try:
            while True:
                msg=self.pipe.recv()
                self.update(*msg)
        except EOFError:
            self.pipe.close()
            tk.Label(self.root,text='Connection to the main script has been closed.\nIt is safe to close this window now.').pack()
        except Exception as m:
            self.pipe.close()
            print('Error during listing:',m)

class BoardConnection:
    def __init__(self,input_string):
        ctx = mp.get_context('spawn')
        self.receive,self.pipe=ctx.Pipe(False)
        self.process=ctx.Process(target=VisualizedBoard,args=(input_string,self.receive))
        self.process.start()

    def update(self,coordinate,value,color='magenta'):
        """
        :parameter coordinate: a tuple (x,y)
        :parameter value: single digit
        :returns: None
        """
        self.pipe.send((coordinate,value,color))

    def close(self):
        self.pipe.close()
        self.process.terminate()

if __name__ == "__main__":
    b=BoardConnection('000000000302540000050301070000000004409006005023054790000000050700810000080060009')
    start = time.time()
    for i in range(5000): #test updating using random numbers
        b.update((random.randint(1, 9), random.randint(1, 9)), random.randrange(10))
        print(i)
    print(time.time() - start)


问:
Is it "better" to have an update field or COUNT query?
In a Django App I'm working on I've got this going on:

```<code>class Parent(models.Model):
    name = models.CharField(...)

    def num_children(self):
        return Children.objects.filter(parent=self).count()

    def avg_child_rating(self):
        return Child.objects.filter(parent=self).aggregate(Avg('rating'))

class Child(models.Model):
    name = models.CharField(...)
    parent = models.ForeignKey(Parent)
    rating = models.IntegerField(default=0)
</code>```

I plan on accessing avg_child_rating  often.  Would it be optimizing if I did the following:

```<code>class Parent(models.Model):
    ...
    num_children = models.IntegerField(default=0)
    avg_child_rating = models.FloatField(default=0.0)

def update_parent_child_stats(sender, instance, **kwargs):
    num_children = Child.objects.filter(parent=instance.parent)
    if instance.parent.num_children != num_children:
        instance.parent.num_children = num_children
        instance.parent.avg_child_rating = Child.objects.filter(instance.parent=self).aggregate(Avg('rating'))

post_save.connect(update_parent_child_stats, sender=Child)
post_delete.connect(update_parent_child_stats, sender=Child)
</code>```

The difference now is that every time a child is created/rated/deleted, the Parent object is updated.  I know that the created/rating will be done often.

What's more expensive?

答:
Depends on the scale of the problem.
If you anticipate a lot of write traffic, this might be an issue. It's much harder to scale writes than reads (replicate, caching etc.) That said, you can probably going a long way without this extra query causing you any problems.

Depending on how up-to-date your stats must be you could have some other process (non-web session) come through and update these stats nightly.

OwnerDisplayName: jobscry

Body:
In a Django App I'm working on I've got this going on:

class Parent(models.Model):
    name = models.CharField(...)

    def num_children(self):
        return Children.objects.filter(parent=self).count()

    def avg_child_rating(self):
        return Child.objects.filter(parent=self).aggregate(Avg('rating'))

class Child(models.Model):
    name = models.CharField(...)
    parent = models.ForeignKey(Parent)
    rating = models.IntegerField(default=0)

I plan on accessing avg_child_rating  often.  Would it be optimizing if I did the following:

class Parent(models.Model):
    ...
    num_children = models.IntegerField(default=0)
    avg_child_rating = models.FloatField(default=0.0)

def update_parent_child_stats(sender, instance, **kwargs):
    num_children = Child.objects.filter(parent=instance.parent)
    if instance.parent.num_children != num_children:
        instance.parent.num_children = num_children
        instance.parent.avg_child_rating = Child.objects.filter(instance.parent=self).aggregate(Avg('rating'))

post_save.connect(update_parent_child_stats, sender=Child)
post_delete.connect(update_parent_child_stats, sender=Child)

The difference now is that every time a child is created/rated/deleted, the Parent object is updated.  I know that the created/rating will be done often.

What's more expensive?

OwnerDisplayName: rhettg


问:
How to create a simple draggable marker in OpenLayers
Very simple question, how can I create a draggable marker in an OpenLayers map, and get the latlon when its been dragged. From google, it seems that you can have draggable vectors, but not draggable markers.

I've seen some references to OpenLayers.Control.DragMarker, but this doesn't seem to be in the "core" library. It's used in this example but that seems to be using a custom OpenLayers JS file, so I have no idea how to go about including that in my code.

Code thus far (to add a simple marker):

```<code>var layer = new OpenLayers.Layer.TMS( "TMS The Layer","",
    {  url: '', serviceVersion: '.', layername: '.', alpha: true,
        type: 'png', getURL: overlay_getTileURL
    });

map.addLayers([layer]);

    var markers = new OpenLayers.Layer.Markers( "Markers" );
    map.addLayer(markers);
    var lonLat = new OpenLayers.LonLat( -100 ,100 );
    markers.addMarker(new OpenLayers.Marker(lonLat));
</code>```

答:
I've done that, but I can't find that code now. Take a look at this OpenLayers Example:

Drag Feature

Body:
Very simple question, how can I create a draggable marker in an OpenLayers map, and get the latlon when its been dragged. From google, it seems that you can have draggable vectors, but not draggable markers.

I've seen some references to OpenLayers.Control.DragMarker, but this doesn't seem to be in the "core" library. It's used in this example but that seems to be using a custom OpenLayers JS file, so I have no idea how to go about including that in my code.

Code thus far (to add a simple marker):

var layer = new OpenLayers.Layer.TMS( "TMS The Layer","",
    {  url: '', serviceVersion: '.', layername: '.', alpha: true,
        type: 'png', getURL: overlay_getTileURL
    });

map.addLayers([layer]);

    var markers = new OpenLayers.Layer.Markers( "Markers" );
    map.addLayer(markers);
    var lonLat = new OpenLayers.LonLat( -100 ,100 );
    markers.addMarker(new OpenLayers.Marker(lonLat));


问:
java.lang.illegalstateexception could not find a method (view) in the activity class android fragment
In my program, I am using a gridview with some images. I want to show a menu when user tapped on an image in gridview and then select an action to do from the menu showed.

Here is my code:

```<code>package Kazemi.Alireza.scada;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("NewApi")
public class CitiesTab extends Fragment {

AnimationDrawable[] frameAnimation;
ImageAdapter ia;
GridView gridView;
int in;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return (LinearLayout)inflater.inflate(R.layout.citytab, container, false);
}

public void onStart()
{
    super.onStart();
    ia = new ImageAdapter(getActivity());
    gridView = (GridView) getActivity().findViewById(R.id.gridview);
    gridView.setAdapter(ia);
    gridView.post(new Starter());
    gridView.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {
            dialog = new Dialog(getActivity(), android.R.style.Theme_InputMethod);
            dialog.setContentView(R.layout.pump_menu);
        }});
    /*Button btn = (Button) getActivity().findViewById(R.id.Button_pumpInfo);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(getActivity(), "You clicked on Item 1",
                    Toast.LENGTH_LONG).show();
        }
    });*/
}

public void Btn_pumpInfo_Clicked(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(getActivity(), "You clicked on Item 1",
            Toast.LENGTH_LONG).show();
}
</code>```

}

here is my pump_menu.xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#a5c5f0"
    android:orientation="vertical" >

<Button
    android:id="@+id/Button_pumpInfo"
    android:layout_height="40dp"
    android:text="@string/menu_pumpinfo_item1"
    android:textSize="11sp"
    android:layout_width="125dp"
    android:background="#a5c5f0"
    android:onClick="Btn_pumpInfo_Clicked"/>
</code>```

and citytab.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />

<ImageView
    android:id="@+id/gifViewer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"/>

</LinearLayout>
</code>```

When I use this code an error occured:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{Kazemi.Alireza.scada/Kazemi.Alireza.scada.MainMenu}: java.lang.NullPointerException
</code>```

And when i comment the Btn_pumpInfo_Clicked() method and uncomment the button listener in onStart() the following error occurs:

```<code>java.lang.IllegalStateException: Could not find a method Btn_pumpInfo_Clicked(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'Button_pumpInfo'
</code>```

Where is the problem?

答:
This can also happen when the method to call on onClick of the View(Button) isn't accessible or isn't available in the respective activity.
Steps to check:

Check the method name in the value for android:onClick attribute matches the method actually written.

Check the access modifier of the method is public so as to be available to the
execute.

Body:
In my program, I am using a gridview with some images. I want to show a menu when user tapped on an image in gridview and then select an action to do from the menu showed.

Here is my code:

package Kazemi.Alireza.scada;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("NewApi")
public class CitiesTab extends Fragment {

AnimationDrawable[] frameAnimation;
ImageAdapter ia;
GridView gridView;
int in;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return (LinearLayout)inflater.inflate(R.layout.citytab, container, false);
}

public void onStart()
{
    super.onStart();
    ia = new ImageAdapter(getActivity());
    gridView = (GridView) getActivity().findViewById(R.id.gridview);
    gridView.setAdapter(ia);
    gridView.post(new Starter());
    gridView.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {
            dialog = new Dialog(getActivity(), android.R.style.Theme_InputMethod);
            dialog.setContentView(R.layout.pump_menu);
        }});
    /*Button btn = (Button) getActivity().findViewById(R.id.Button_pumpInfo);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(getActivity(), "You clicked on Item 1",
                    Toast.LENGTH_LONG).show();
        }
    });*/
}

public void Btn_pumpInfo_Clicked(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(getActivity(), "You clicked on Item 1",
            Toast.LENGTH_LONG).show();
}

}

here is my pump_menu.xml code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#a5c5f0"
    android:orientation="vertical" >

<Button
    android:id="@+id/Button_pumpInfo"
    android:layout_height="40dp"
    android:text="@string/menu_pumpinfo_item1"
    android:textSize="11sp"
    android:layout_width="125dp"
    android:background="#a5c5f0"
    android:onClick="Btn_pumpInfo_Clicked"/>

and citytab.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />

<ImageView
    android:id="@+id/gifViewer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"/>

</LinearLayout>

When I use this code an error occured:

java.lang.RuntimeException: Unable to start activity ComponentInfo{Kazemi.Alireza.scada/Kazemi.Alireza.scada.MainMenu}: java.lang.NullPointerException

And when i comment the Btn_pumpInfo_Clicked() method and uncomment the button listener in onStart() the following error occurs:

java.lang.IllegalStateException: Could not find a method Btn_pumpInfo_Clicked(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'Button_pumpInfo'

Where is the problem?


问:
Web.config rewrite http + www and http non www and https non-www to to https://www
I have recently switched my asp.net MVC website to https and want all existing traffic to get redirected to https://www.example.com using web.config rewrite.

I have tried various combinations but not yet successful.

need to handle following three scenarios :

```
http://
http://www
https://
```

答:
You can redirect your traffic to use the https using the Global.asax as well.

Method name:  Application_BeginRequest

Your code to redirect will look something like this

```<code>strProtocol = "https";

if (HttpContext.Current.Request.Url.ToString().ToLower().StartsWith("http:") == true)
{
    Response.Redirect(strProtocol + "://" + strYourHostName + strYourRemainingURL, false);
}
</code>```

you can keep the protocol and hostname in the web.config and pick from there.

Body:
I have recently switched my asp.net MVC website to https and want all existing traffic to get redirected to https://www.example.com using web.config rewrite.

I have tried various combinations but not yet successful.

need to handle following three scenarios :

http://
http://www
https://

Body:
You can redirect your traffic to use the https using the Global.asax as well.

Method name:  Application_BeginRequest

Your code to redirect will look something like this

strProtocol = "https";

if (HttpContext.Current.Request.Url.ToString().ToLower().StartsWith("http:") == true)
{
    Response.Redirect(strProtocol + "://" + strYourHostName + strYourRemainingURL, false);
}

you can keep the protocol and hostname in the web.config and pick from there.


问:
MVc 5 - validation german date with unobtrusiv js - a simple approach
The question: How get the unobtrusiv validation of a german date running in MVC?

Because I can't find a running example of using globalize 1.x with MVC 5 to validate a german date I needed two days to get it running.

The problems are the order of the js-files, getting the cldr-data and putting it all together in an way it can be reused.

In the answer I will show my current solution.

答:
In this zip-file (https://www.dropbox.com/sh/75dx6alck7itwia/AABFkcgOQVc1bUXFE_jYfR_da?dl=0) you find all files you need.

It includes

an short todo.txt (de and en)

the cldr-data (jsons) in sub-directories

a custom HTML-Helper-class wich writes the needed HTML/js-Scripts to the view.

It seems, that rendering by the helper not allways works. So if there are problems with that, copy the code to every (edit / new) view.

```<code><script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<script src="~/Scripts/cldr/unresolved.js"></script>

<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/currency.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<script src="~/Scripts/globalize/plural.js"></script>
<script src="~/Scripts/globalize/relative-time.js"></script>
<script src="~/Scripts/globalize/unit.js"></script>
<script src="~/Scripts/jquery.validate.globalize.js"></script>

<script>
    $(document).ready(function () {
        // Use $.getJSON instead of $.get if your server is not configured to return the
        // right MIME type for .json files.
        $.when(
            $.get("/Scripts/cldr/main/de/ca-gregorian.json"),
            $.get("/Scripts/cldr/main/de/numbers.json"),
            $.get("/Scripts/cldr/supplemental/likelySubtags.json"),
            $.get("/Scripts/cldr/supplemental/timeData.json"),
            $.get("/Scripts/cldr/supplemental/weekData.json")
        ).then(function () {
            // Normalize $.get results, we only need the JSON, not the request statuses.
            return [].slice.apply(arguments, [0]).map(function (result) {
                return result[0];
            });
        }).then(Globalize.load)
    .then(function () {
        Globalize.locale("de-DE");
    });
    });
</script>
</code>```

I hope it helps.

This solution based on the answer to MVC 5 - can not get globalisation running.
If you want to use a bündle, see MVC 5, globalize, validate german date: How to bundle the js-scripts?

Body:
In this zip-file (https://www.dropbox.com/sh/75dx6alck7itwia/AABFkcgOQVc1bUXFE_jYfR_da?dl=0) you find all files you need.

It includes

an short todo.txt (de and en)

the cldr-data (jsons) in sub-directories

a custom HTML-Helper-class wich writes the needed HTML/js-Scripts to the view.

It seems, that rendering by the helper not allways works. So if there are problems with that, copy the code to every (edit / new) view.

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<script src="~/Scripts/cldr/unresolved.js"></script>

<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/currency.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<script src="~/Scripts/globalize/plural.js"></script>
<script src="~/Scripts/globalize/relative-time.js"></script>
<script src="~/Scripts/globalize/unit.js"></script>
<script src="~/Scripts/jquery.validate.globalize.js"></script>

<script>
    $(document).ready(function () {
        // Use $.getJSON instead of $.get if your server is not configured to return the
        // right MIME type for .json files.
        $.when(
            $.get("/Scripts/cldr/main/de/ca-gregorian.json"),
            $.get("/Scripts/cldr/main/de/numbers.json"),
            $.get("/Scripts/cldr/supplemental/likelySubtags.json"),
            $.get("/Scripts/cldr/supplemental/timeData.json"),
            $.get("/Scripts/cldr/supplemental/weekData.json")
        ).then(function () {
            // Normalize $.get results, we only need the JSON, not the request statuses.
            return [].slice.apply(arguments, [0]).map(function (result) {
                return result[0];
            });
        }).then(Globalize.load)
    .then(function () {
        Globalize.locale("de-DE");
    });
    });
</script>

I hope it helps.

This solution based on the answer to MVC 5 - can not get globalisation running.
If you want to use a bündle, see MVC 5, globalize, validate german date: How to bundle the js-scripts?


问:
Facebook bot with multiple senders
Is it possible to make a Facebook bot look like there are multiple senders from the bot side? I couldn't see anything obvious in the Facebook docs. Even if the icon for the bot could be changed on the fly that may work

I'm trying to make a Facebook chat bot where a different 'person' will reply based on user input

EDIT:

As an alternative approach, could it be possible to use two separate facebook bots to have a semi simultaneous conversation with a single user. Take an example scenario where user starts a conversation with Bot A, then midway through the conversation, Bot B in a separate Facebook messenger chat, messages the user?

答:
There is no way to do it currently;

For each Facebook Page, Facebook generates a unique id for the user(User#X has different id for PageA and PageB).

For each App(Bot) Facebook creates a unique id for the User#X(User#X will have different id for App#1 and App#1 for the same Facebook page)

Title: Facebook bot with multiple senders


问:
add click event to Jquery UI accordian Header
When you create a Jquery UI accordian you get a bunch of headers, that when you click them a div opens. However, I would like to preform an additional action upon clicking the header.

How do i do this?

Any ideas?

Thanks!

答:
You need to wrap your code in ready handler:

```<code>$(function(){
  $("#CreateNewUserHeader").click(function() {
    alert("test");
  });
});
</code>```

Also make sure that you do not assign same id to more than one elements.

Body:
You need to wrap your code in ready handler:

$(function(){
  $("#CreateNewUserHeader").click(function() {
    alert("test");
  });
});

Also make sure that you do not assign same id to more than one elements.


问:
Why is it better to choose Struts 2 than Struts 1?
1) What are the major advantages of preferring Struts 2 over the Struts 1?  What are all the advantages in Struts 1?

2) What is the use of having filter dispatcher in Struts 2?

3) Is it good to use filter dispatcher over servlet(Struts 1 uses servlet)?

As i am new to Struts can anyone give an elaborated description for these questions?

答:
You can find Pros and Cons comparing Struts 1 and Struts 2.

To add to these features I'd say that Struts 2 not only bigger but
  heavier  than Struts 1. Struts 2 in the default configuration
  intercepts and runs a lot of stuff to simplify the development process,
  write less code, use recent technologies, but the cost for it is a
  complexity of framework. You will have more time to learn a framework itself to be
  able to modify it to suit your needs.


问:
Arithmetic bit-shift on a signed integer
I am trying to figure out how exactly arithmetic bit-shift operators work in C, and how it will affect signed 32-bit integers.

To make things simple, let's say we work within one byte (8 bits):

```<code>x = 1101.0101
MSB[ 1101.0101 ]LSB
</code>```

Reading other posts on Stack Overflow and some websites, I found that:
<< will shift toward MSB (to the left, in my case), and fill "empty" LSB bits with 0s.

And >> will shift toward LSB (to the right, in my case) and fill "empty" bits with MS bit

So, x = x << 7 will result in moving LSB to MSB, and setting everything to 0s.

```<code>1000.0000
</code>```

Now, let's say I would >> 7, last result. This would result in [0000.0010]? Am I right?

Am I right about my assumptions about shift operators?

I just tested on my machine, **

```<code>int x = 1;   //000000000......01

x = x << 31; //100000000......00

x = x >> 31; //111111111......11 (Everything is filled with 1s !!!!!)
</code>```

Why?

答:
In the 32 bit compiler

x = x >> 31;

here x is the signed integer so 32nd bit is  sign bit.

final x value is 100000...000. and 32nd bit indicate -ive value.

here x value implement to 1's compliment.

then final x is -32768

Body:
I am trying to figure out how exactly arithmetic bit-shift operators work in C, and how it will affect signed 32-bit integers.

To make things simple, let's say we work within one byte (8 bits):

x = 1101.0101
MSB[ 1101.0101 ]LSB

Reading other posts on Stack Overflow and some websites, I found that:
<< will shift toward MSB (to the left, in my case), and fill "empty" LSB bits with 0s.

And >> will shift toward LSB (to the right, in my case) and fill "empty" bits with MS bit

So, x = x << 7 will result in moving LSB to MSB, and setting everything to 0s.

1000.0000

Now, let's say I would >> 7, last result. This would result in [0000.0010]? Am I right?

Am I right about my assumptions about shift operators?

I just tested on my machine, **

int x = 1;   //000000000......01

x = x << 31; //100000000......00

x = x >> 31; //111111111......11 (Everything is filled with 1s !!!!!)

Why?


问:
Writing a Scheduled Windows Service in .NET
I want to write a windows service which the user can schedule. i.e, the user can choose to run the service from 9:00 AM to 6 PM daily, or he could run it every night, starting from night 12 o clock at night to next day morning 6, etc. Is there any out of the box .NET API that will help me do this? I know I can do this using the Scheduled tasks, but is there any way to do this programmatically?</p>

答:
I implemented some unattended services (Windows Services written in c#), using crontab algorithm to manage the scheduling. The pattern is powerful, and flexible. We can create schedules to any time we want, only using the cron expression. Maybe I am wrong, but the only schedule that I think cron doesn't cover is if we want the last day of the month, but this was never a requirement for all services.

I copied the cron algorithm from an article in the internet (open source by Atif Aziz), and implemented in my utility class, working beautifully for years.

See more details in my blog:
CronTab schedule parser algorithm

Cheers!

Roberto


问:
React isn't rendering an array of objects with map() in a stateless component
I've just started exploring React.js and I can't figure out why there are errors when I try to map over all of the days in the StudyDayList Component:

1) Warning: React.createElement: type is invalid --
  expected a string (for built-in components) or a class/function (for
  composite components) but got: undefined. You likely forgot to export
  your component from the file it's defined in. Check the render method
  of StudyDayList.
      in StudyDayList

2) Uncaught Error: Element type is invalid: expected a string (for
  built-in components) or a class/function (for composite components)
  but got: undefined. You likely forgot to export your component from
  the file it's defined in. Check the render method of StudyDayList.

```<code>// index.js

import React from 'react';
import {render} from 'react-dom';
import {StudyDayList} from '../src/components/StudyDayList';

window.React = React;

render(
<StudyDayList days={
    [
        {
            study: "React Essentials",
            date: new Date("4/7/2017"),
            practice: true
        },
        {
            study: "Web Security",
            date: new Date("3/7/2017"),
            practice: false
        }
    ]
} />,
document.getElementById('react-container')
);
</code>```

What I've tried

This particular part of the code doesn't work. All displays well if I am removing this part of the code in StudyDayList.js:

```<code>{days.map((day, i) =>
      <StudyDayRow key={i}
               study={day.study}
               date={day.date}
               practice={day.practice} />
)}
</code>```

Also, I've tried to change syntaxis:

```<code>{days.map(day, i => (
      <StudyDayRow key={i}
               study={day.study}
               date={day.date}
               practice={day.practice} />
))}
</code>```

and it gives another error:

Uncaught ReferenceError: day is not defined

I've checked the value of days from index.js by propTypes and days: PropTypes.array is true and the length is not null.

StudyDayList Component

```<code>// StudyDayList.js

import Terrain from 'react-icons/lib/md/terrain';
import StudyDayRow from './StudyDayRow';

export const StudyDayList = ({days}) => (
<table>
    <thead>
        <tr>
            <th>Date</th>
            <th>Study</th>
            <th>Practice</th>
        </tr>
    </thead>
    <tbody>

        // The part of code which I was removing

        {days.map((day, i) =>
            <StudyDayRow key={i}
                        study={day.study}
                        date={day.date}
                        practice={day.practice} />
        )}

    </tbody>
</table>
)
</code>```

StudyDayRow Component

I'm not sure if StudyDayRow Component could cause the errors. I think it couldn't, but I've attached it in case it could.

```<code>// StudyDayRow.js

import Terrain from 'react-icons/lib/md/terrain';

export const StudyDayRow = ({study, date, practice}) => (
<tr>
    <td>
        {date.getMonth()+1}/{date.getDate()}/{date.getFullYear()}
    </td>
    <td>
        {study}
    </td>
    <td>
        {(practice) ? <Terrain /> : null}
    </td>
</tr>
)
</code>```

答:
I guess you are not exporting default StudyDayRow;

so, do something like that-

```<code>import {StudyDayRow} from './StudyDayRow';
</code>```

or may edit-

```<code>export default const StudyDayRow = ({study, date, practice}) => (
....
)
</code>```

Body:
I've just started exploring React.js and I can't figure out why there are errors when I try to map over all of the days in the StudyDayList Component:

1) Warning: React.createElement: type is invalid --
  expected a string (for built-in components) or a class/function (for
  composite components) but got: undefined. You likely forgot to export
  your component from the file it's defined in. Check the render method
  of StudyDayList.
      in StudyDayList

2) Uncaught Error: Element type is invalid: expected a string (for
  built-in components) or a class/function (for composite components)
  but got: undefined. You likely forgot to export your component from
  the file it's defined in. Check the render method of StudyDayList.

// index.js

import React from 'react';
import {render} from 'react-dom';
import {StudyDayList} from '../src/components/StudyDayList';

window.React = React;

render(
<StudyDayList days={
    [
        {
            study: "React Essentials",
            date: new Date("4/7/2017"),
            practice: true
        },
        {
            study: "Web Security",
            date: new Date("3/7/2017"),
            practice: false
        }
    ]
} />,
document.getElementById('react-container')
);

What I've tried

This particular part of the code doesn't work. All displays well if I am removing this part of the code in StudyDayList.js:

{days.map((day, i) =>
      <StudyDayRow key={i}
               study={day.study}
               date={day.date}
               practice={day.practice} />
)}

Also, I've tried to change syntaxis:

{days.map(day, i => (
      <StudyDayRow key={i}
               study={day.study}
               date={day.date}
               practice={day.practice} />
))}

and it gives another error:

Uncaught ReferenceError: day is not defined

I've checked the value of days from index.js by propTypes and days: PropTypes.array is true and the length is not null.

StudyDayList Component

// StudyDayList.js

import Terrain from 'react-icons/lib/md/terrain';
import StudyDayRow from './StudyDayRow';

export const StudyDayList = ({days}) => (

            Date
            Study
            Practice

        // The part of code which I was removing

        {days.map((day, i) =>
            <StudyDayRow key={i}
                        study={day.study}
                        date={day.date}
                        practice={day.practice} />
        )}

)

StudyDayRow Component

I'm not sure if StudyDayRow Component could cause the errors. I think it couldn't, but I've attached it in case it could.

// StudyDayRow.js

import Terrain from 'react-icons/lib/md/terrain';

export const StudyDayRow = ({study, date, practice}) => (

        {date.getMonth()+1}/{date.getDate()}/{date.getFullYear()}

        {study}

        {(practice) ? <Terrain /> : null}

)

Body:
I guess you are not exporting default StudyDayRow;

so, do something like that-

import {StudyDayRow} from './StudyDayRow';

or may edit-

export default const StudyDayRow = ({study, date, practice}) => (
....
)


问:
WooCommerce shipping methods not working for logged-in users?
I have developed a custom build on woocommerce.

All is fine except for the checkout page.

The site ships to UK only, and i have Flat Rate shipping enabled.

However, on the checkout page there are two issues. The first is an invalid argument in a foreach loop:

Warning: Invalid argument supplied for foreach() in /home/****/public_html/wp-content/plugins/woocommerce/includes/class-wc-shipping.php on line 291

And the second problem is:

There doesn‘t seem to be any available shipping methods. Please double check your address, or contact us if you need any help.

I am bashing my head against a wall here. I have a shipping method enabled, so why is it continuing to tell me there is no method available?

All i want it to do there is simply list all the shipping methods i have enabled so the user can select one.

I also noticed that the shipping methods display when user is not logged in, but when they are logged in it shows Flat Rate - then a random price that isn't entered anywhere in admin.

To elaborate a little. This problem does not occur if i add a variable product to the art using the ?add-to-cart url, but as soon as i use the add_to_cart function it causes those errors.

```<code>woocommerce->cart->add_to_cart(522,1, 523,array("attribute_colour" => "colour","attribute_size" => "a3", "attribute_invoice-numbering" => "yes", "attribute_quantity-column" => "yes", "attribute_cc-type" => "duplicate"));
</code>```

The above code works fine if it is used in a URL, but i want to call it via ajax with the function.

答:
Go to woo commerce settings and add a shipping zone. See here.

On existing products and when adding new products always ensure u set the shipping location. See here

Body:
I have developed a custom build on woocommerce.

All is fine except for the checkout page.

The site ships to UK only, and i have Flat Rate shipping enabled.

However, on the checkout page there are two issues. The first is an invalid argument in a foreach loop:

Warning: Invalid argument supplied for foreach() in /home/****/public_html/wp-content/plugins/woocommerce/includes/class-wc-shipping.php on line 291

And the second problem is:

There doesn‘t seem to be any available shipping methods. Please double check your address, or contact us if you need any help.

I am bashing my head against a wall here. I have a shipping method enabled, so why is it continuing to tell me there is no method available?

All i want it to do there is simply list all the shipping methods i have enabled so the user can select one.

I also noticed that the shipping methods display when user is not logged in, but when they are logged in it shows Flat Rate - then a random price that isn't entered anywhere in admin.

To elaborate a little. This problem does not occur if i add a variable product to the art using the ?add-to-cart url, but as soon as i use the add_to_cart function it causes those errors.

woocommerce->cart->add_to_cart(522,1, 523,array("attribute_colour" => "colour","attribute_size" => "a3", "attribute_invoice-numbering" => "yes", "attribute_quantity-column" => "yes", "attribute_cc-type" => "duplicate"));

The above code works fine if it is used in a URL, but i want to call it via ajax with the function.


问:
How to use the type of an object's property in flow?
How do you use the type of an object's property in flow? e.g.</p>

```<code>type A = {
  someproperty: string
}

// throws error
const b: A.someproperty = "hello"
</code>```

答:
You can use the $PropertyType<T,x> utility type.

```<code>type A = {
  someproperty: string
}

// this works fine
const b: $PropertyType<A, 'someproperty'> = "hello"
</code>```

Body:
How do you use the type of an object's property in flow? e.g.

type A = {
  someproperty: string
}

// throws error
const b: A.someproperty = "hello"

Body:
You can use the $PropertyType<T,x> utility type.

type A = {
  someproperty: string
}

// this works fine
const b: $PropertyType<A, 'someproperty'> = "hello"


问:
Remove file from git repo, but not from server
At some point in the past, a symlink media file has been added to a git repo I'm working on.  I want to remove it from the repo, delete the file locally, but not on the server the repo is deployed to (I would also not want to have to re-make the symlink).  git update-index --assume-unchanged does not appear to be persistent, and git rm --cached would kill the files on deploy.

Is there a way of doing this?

答:
The closest thing to what you want I found in deployhq config files. This is good for any non-repo text file, but unfortunately this won't work for symlinks.

This may work:

first remove the symlink from the repo (git rm, commit, push/deploy).

ssh to the server where you deployed. Create the symbolic link there. If it's something in the repo you can add it to .gitignore, but you don't have to - it won't matter.

Now the server has the link, and it's unconnected to the repository so it will not exist in github or whatever you're using, or your local machine. It will only be a file on the server. The point is the link should not be at all in the repo anywhere, and you need to create it manually on the server.


问:
google cloud platform pricing - delete account
I just sign in to google cloud platform, and I got a message that I earn 300$ free trial. Can anyone please answer me if I got charge for anything.
I did it by mistake and I can't able to delete it.

Please help me.

答:
As a First time Signup Bonus google will give you 1 Year of Free Subscription. for signup you should link your Credit card. (i think you too linked it. thats why you fear about it.)  as per google said, you have been given 300$ worth paid service for the period of 1 year. till that you will not charged until this,

For example, only the portion of your Google App Engine usage above
  the App Engine free daily usage limits is charged against your $300
  credit. In addition, if your App Engine usage is below the free daily
  usage limits, your app will continue to run even after the free trial
  ends.

also you can use that credit in paid google API's

You can use the $300 credits to call any paid Google APIs or for any
  Google Cloud Platform services.

Charging: Google will charge only after your subscription was expired or if you reached your 300$ benefits. Google won't charge without your permission. so, your card was secured. dont fear about it.

About cancellation:

If you want to leave the free trial, there's nothing to do. Your trial
  automatically expires after 12 months, and you will not be charged
  during the free trial period unless you upgrade to a paid account.

Please Note

Your credit card is not charged unless you upgrade to a paid account.


问:
Laravel: Notify admin when user do something
I will explain my idea. When a default user does an action, I want the admin to be notified about this action. To do this, I use notifications in Laravel that are saved in the database (I don't know if this is the better way).

My problem is that i can't show the notifications with an admin user.

When a user does a specific action, I want all the admins to be notified:

```<code>$admins = Admin::all();<p>
foreach ($admins as $admin) {
    <p>$admin->notify(new RepliedToThread($acao));<p>
}
</code>```

Next, I want to show the notifications on a navbar in my dashboard (only admins have access).

I did that with:

```<code><li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
        Notificações <span class="badge"> {{Auth::admin()->unreadNotifications() }}</span>
    </a>

    <ul class="dropdown-menu" role="menu"><p>
        <li>
            @foreach (Auth::admin()->unreadNotifications as $notification)
                {{$notification->type}}
            @endforeach
        </li>
    </ul>
</li>
</code>```

I don't know if I did this in the best way or if it will work. For now I have this error:

Method admin does not exist

But I want help with the entire process, not just this error because I don't know if I'm doing it the right way.

答:
Regarding that error, within your blade template you are calling Auth::admin() and there isn't an admin method on the Auth facade. If notifications are common to all users, then you should be able to do Auth::user()->unreadNotifications() instead (providing an unreadNotifications method exists on your user model).

Regarding listening for changes and notifying admins, I would recommend you look into Events, an explanation of which can be found on the Laravel website: https://laravel.com/docs/5.4/events

Body:
I will explain my idea. When a default user does an action, I want the admin to be notified about this action. To do this, I use notifications in Laravel that are saved in the database (I don't know if this is the better way).

My problem is that i can't show the notifications with an admin user.

When a user does a specific action, I want all the admins to be notified:

$admins = Admin::all();

foreach ($admins as $admin) {

$admin->notify(new RepliedToThread($acao));

}

Next, I want to show the notifications on a navbar in my dashboard (only admins have access).

I did that with:

        Notificações  {{Auth::admin()->unreadNotifications() }}

            @foreach (Auth::admin()->unreadNotifications as $notification)
                {{$notification->type}}
            @endforeach

I don't know if I did this in the best way or if it will work. For now I have this error:

Method admin does not exist

But I want help with the entire process, not just this error because I don't know if I'm doing it the right way.


问:
Can not convert html to png using phantomjs or wkhtmltoimage
I want to convert html to png.

Here is my html

```<code><!DOCTYPE html>
<html>
<head>
  <style type="text/css">* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  main {
    width: 600px;
    margin: 100px auto;
  }

  header {
    width: 100%;
    height: auto;
    background-color: red;
    background-size: cover;
    background-repeat: no-repeat;
  }

  header .content {
    width: 80%;
    margin-left: 10%;
    margin-right: 10%;
    display: flex;
    padding: 40px 0;
  }

  .content .column {
    width: 25%;
    margin: auto;
    text-align: center;
  }

  .content .column.lfp-logo {
    width: 30%;
  }

  .content .column img {
    width: 80%;
    height: auto;
  }
  </style>
</head>
<body>
<main>
  <header>
    <div class="content">
      <div class="column"><img
        src="https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg"></div>
      <div class="column lfp-logo"><img
        src="https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg"></div>
      <div class="column"><img
        src="https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg"></div>
    </div>
  </header>
</main>
</body>
</html>
</code>```

Here is jsfiddle example. this is actually what i need to get in my png file jsfiddle

I tried to use wkhtmltoimage and I get this image

Also I tried to use phantomjs and get this image

I use phantomjs with nodejs module webshot.

Can anyone suggest me way I can render html to png image.
I dont need dynamic html. All I want to render is static.

UPDATE. Added code for generating images

```<code>const pug = require('pug');
const child_process = require('child_process');
const fs = require('fs');
const webshot = require('webshot');

const options = {
    data: {
        images: {
            header: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg',
            team1: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg',
            team2: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg',
            competition: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg'
        }
    }
};

const html = pug.renderFile('./template/next.pug', options);

console.log(html); // this is html

// webshot with wkhtmltoimage
child_process.exec(`echo "${html}" | wkhtmltoimage --width 600 --disable-smart-width - export/out.png`, (err) => {
    console.log(err);
});

// webshot with phantomjs
webshot(html, 'hello_world.png', {siteType:'html'}, function(err) {
    console.log(err);
});
</code>```

答:
I would say to make something like this. Working with html2canvas you can do it easy and fast.

```<code>    convert_to_img = function (do_download) {
  html2canvas(document.getElementById("contenedor_chimichangas"), {
    //onrender devuelve el canvas para hacerle los retoques necesarios
    onrendered: function (canvas) {//sombra aqui, sombra allí!!
      var context = canvas.getContext('2d');//context from originalCanvas
      var data_image = canvas.toDataURL("image/png"); //cogemos la url de la imagen sin tratar
      //añadimos la url en una imagen para poder tratarla y redimensionarla
      var image_edicion = $("<img/>", {
        id: "image",
        src: data_image
      }).appendTo($("#show_img").empty());
        //if we click download:
        if(do_download === true){
          Canvas2Image.saveAsPNG(new_canvas);
        }
      });

    },

  });
}
</code>```

The js are documented line at line. ;D

Body:
I want to convert html to png.

Here is my html

<!DOCTYPE html>

Here is jsfiddle example. this is actually what i need to get in my png file jsfiddle

I tried to use wkhtmltoimage and I get this image

Also I tried to use phantomjs and get this image

I use phantomjs with nodejs module webshot.

Can anyone suggest me way I can render html to png image.
I dont need dynamic html. All I want to render is static.

UPDATE. Added code for generating images

const pug = require('pug');
const child_process = require('child_process');
const fs = require('fs');
const webshot = require('webshot');

const options = {
    data: {
        images: {
            header: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg',
            team1: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg',
            team2: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg',
            competition: 'https://cdn.shopify.com/s/files/1/1237/5652/products/spiderman_3_compression_shirt_3_small.jpg'
        }
    }
};

const html = pug.renderFile('./template/next.pug', options);

console.log(html); // this is html

// webshot with wkhtmltoimage
child_process.exec(`echo "${html}" | wkhtmltoimage --width 600 --disable-smart-width - export/out.png`, (err) => {
    console.log(err);
});

// webshot with phantomjs
webshot(html, 'hello_world.png', {siteType:'html'}, function(err) {
    console.log(err);
});

Body:
I would say to make something like this. Working with html2canvas you can do it easy and fast.

    convert_to_img = function (do_download) {
  html2canvas(document.getElementById("contenedor_chimichangas"), {
    //onrender devuelve el canvas para hacerle los retoques necesarios
    onrendered: function (canvas) {//sombra aqui, sombra allí!!
      var context = canvas.getContext('2d');//context from originalCanvas
      var data_image = canvas.toDataURL("image/png"); //cogemos la url de la imagen sin tratar
      //añadimos la url en una imagen para poder tratarla y redimensionarla
      var image_edicion = $("<img/>", {
        id: "image",
        src: data_image
      }).appendTo($("#show_img").empty());
        //if we click download:
        if(do_download === true){
          Canvas2Image.saveAsPNG(new_canvas);
        }
      });

    },

  });
}

The js are documented line at line. ;D


问:
Show music control after minimising application Cordova Ionic1
How can we force show Music-Control in notification tray when Music is playing even after minimising application. I'm using Cordova-plugin-background-mode to show notification when app is in background but it is not fulfilling my requirement.</p>

答:
use this in your js file:</p>

```<code>cordova.plugins.backgroundMode.enable();
     // or
cordova.plugins.backgroundMode.setEnabled(true);
</code>```

Body:
use this in your js file:

cordova.plugins.backgroundMode.enable();
     // or
cordova.plugins.backgroundMode.setEnabled(true);


问:
String manipulation in C#. Inserting "+" between words
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

```<code>    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }
</code>```

Desired output

```<code>word1+word2+word3
</code>```

where the number of words are not fixed.

答:
You're looking for String.Join("+", searchTermArray)

You're trying to write searchTerm.Replace(' ', '+')

You probably should be writing Uri.EscapeDataString(searchTerm)

Body:
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }

Desired output

word1+word2+word3

where the number of words are not fixed.


问:
JAVA SimpleDateFormat on ArrayList changes Date
I'm populating a 'ListView' with an 'ArrayList' using an Adapter.
The 'ArrayList' contains objects with date and time.
When i send the data as it is to the ListView, there is no problem, and the list shows the relevant objects as desired :

```<code>public View getView(int position, View convertView, ViewGroup parent) {

  TimePeriod freeSlot = (TimePeriod)getItem(position);

  if (convertView == null) {
      convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
    }

    TextView start = (TextView) convertView.findViewById(R.id.start);
    TextView end = (TextView) convertView.findViewById(R.id.end);

    startTime = freeSlot.getStart().toString()
    endTime = freeSlot.getEnd().toString();
    start.setText(startTime);
    end.setText(endTime);

    return convertView;
}
</code>```

2017-07-05T10:30:00.000Z 2017-07-05T11:30:00.000Z

But when i use SimpleDateFormat to change the output as i want, it somehow sets the dates of all objects to the same one (01/01) :

```<code>startTime = freeSlot.getStart().toString();
endTime = freeSlot.getEnd().toString();

try {
            SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ss.SSS'Z'");
            Date newDate = formatter.parse(startTime);
            Date newDate2 = formatter.parse(endTime);

            SimpleDateFormat format = new SimpleDateFormat("dd/MM hh:mm");
            startTime = format.format(newDate);
            SimpleDateFormat format1 = new SimpleDateFormat("hh:mm");
            endTime = format1.format(newDate2);

        } catch (ParseException pe) {
            pe.printStackTrace();
        }

        start.setText(startTime);
        end.setText(endTime);
</code>```

for start - 01/01 10:30, for end - 11:30

As iv'e mentioned earlier, all objects get this date even though dates & hours are different.

Any ideas? What am i doing wrong?
Thanks a lot!

答:
```<code>SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ss.SSS'Z'");
</code>```

change it to :

```<code>SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'");
</code>```

you need to

You need to use either HH:mm or hh:mm a THis is difference between 24 and 12 hour format.

Body:
I'm populating a 'ListView' with an 'ArrayList' using an Adapter.
The 'ArrayList' contains objects with date and time.
When i send the data as it is to the ListView, there is no problem, and the list shows the relevant objects as desired :

public View getView(int position, View convertView, ViewGroup parent) {

  TimePeriod freeSlot = (TimePeriod)getItem(position);

  if (convertView == null) {
      convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
    }

    TextView start = (TextView) convertView.findViewById(R.id.start);
    TextView end = (TextView) convertView.findViewById(R.id.end);

    startTime = freeSlot.getStart().toString()
    endTime = freeSlot.getEnd().toString();
    start.setText(startTime);
    end.setText(endTime);

    return convertView;
}

2017-07-05T10:30:00.000Z 2017-07-05T11:30:00.000Z

But when i use SimpleDateFormat to change the output as i want, it somehow sets the dates of all objects to the same one (01/01) :

startTime = freeSlot.getStart().toString();
endTime = freeSlot.getEnd().toString();

try {
            SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ss.SSS'Z'");
            Date newDate = formatter.parse(startTime);
            Date newDate2 = formatter.parse(endTime);

            SimpleDateFormat format = new SimpleDateFormat("dd/MM hh:mm");
            startTime = format.format(newDate);
            SimpleDateFormat format1 = new SimpleDateFormat("hh:mm");
            endTime = format1.format(newDate2);

        } catch (ParseException pe) {
            pe.printStackTrace();
        }

        start.setText(startTime);
        end.setText(endTime);

for start - 01/01 10:30, for end - 11:30

As iv'e mentioned earlier, all objects get this date even though dates & hours are different.

Any ideas? What am i doing wrong?
Thanks a lot!

Body:
SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ss.SSS'Z'");

change it to :

SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'");

you need to

You need to use either HH:mm or hh:mm a THis is difference between 24 and 12 hour format.


问:
Is there a Java class that is a cross between a Map and a List?
I am looking for a Java class that offers both Map (fast lookup) and List (determinate order) characteristics.  Any advice?

Thanks!

答: LinkedHashMap preserves the order elements are added into collection.</p>


问:
html appending url for form action
on my html page I do form action after a button has been pressed:

```<code><form action="/example.php" method="POST">
</code>```

how do I append that url so I can use input from a textbox as well?
what I want to do is redirect user to a specific url

```<code>/example.php?id=inputfromtextbox
</code>```

答:
With php you can directly interpret the value from the textbox that you have just by accessing it with post:

```<code>$textVal = $_POST["someInput"];
</code>```

And even redirect to another page with a constructed url:

```<code>header("Location:example2.php?id=$textVal");
</code>```

But it's not a very good idea, because if you already have the value just use it.

With Javascript you can directly navigate to the url you want when the user submits the form. First you must handle the form submission with the onsubmit event:

```<code><form id="form1" action="/example.php" method="POST" onsubmit="return submitFunc()">
</code>```

Then in the function you would do:

```<code>function submitFunc(){
     var textVal = document.getElementById("someInput").value;
     var formAction = document.getElementById("form1").getAttribute("action");
     window.location.href= formAction + "?id=" + textVal;
     return false;
}
</code>```

The simplest of all would actually be to change the method type to GET which would already encode the form values in the url itself.

Title: html appending url for form action

Body:
on my html page I do form action after a button has been pressed:

<form action="/example.php" method="POST">

how do I append that url so I can use input from a textbox as well?
what I want to do is redirect user to a specific url

/example.php?id=inputfromtextbox

Body:
With php you can directly interpret the value from the textbox that you have just by accessing it with post:

$textVal = $_POST["someInput"];

And even redirect to another page with a constructed url:

header("Location:example2.php?id=$textVal");

But it's not a very good idea, because if you already have the value just use it.

With Javascript you can directly navigate to the url you want when the user submits the form. First you must handle the form submission with the onsubmit event:

<form id="form1" action="/example.php" method="POST" onsubmit="return submitFunc()">

Then in the function you would do:

function submitFunc(){
     var textVal = document.getElementById("someInput").value;
     var formAction = document.getElementById("form1").getAttribute("action");
     window.location.href= formAction + "?id=" + textVal;
     return false;
}

The simplest of all would actually be to change the method type to GET which would already encode the form values in the url itself.


问:
add zero after single number if needed
i want to add zero after number if number is single

e.g $a = 2 then 20
if $a = 20 then 20
if $a = 12 then '12'

like this. I some things but it didn't work for me.
How to do it ?

答:
That shouldn't be too hard.</p>

```<code>$number = intval($number)
if ($number > 0 && $number < 10) {
    $number *= 10;
}
</code>```

Title: add zero after single number if needed

Body:
That shouldn't be too hard.

$number = intval($number)
if ($number > 0 && $number < 10) {
    $number *= 10;
}


答:
Use if-statements:

```<code>if ($a < 10) $a *= 10;
</code>```

Title: add zero after single number if needed

Body:
i want to add zero after number if number is single

e.g $a = 2 then 20
if $a = 20 then 20
if $a = 12 then '12'

like this. I some things but it didn't work for me.
How to do it ?

Body:
Use if-statements:

if ($a < 10) $a *= 10;


答: See java.text.SimpleDateFormat API, pattern letter y: For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits.

Title: JAVA SimpleDateFormat on ArrayList changes Date