问:
Filter element if checkboxes are check or not JavaScript
I got a problem with my code. I coded a search bar which filter checkboxes by their name and I coded a function which only display the checkboxes selected. But there is a conflict.

Everytime I click on "Selected" everything is passing to a display : none;

So I tried to wrap my search bar into some div but it's not working as I imagined. I know that .parent() is the problem because it impacts the parent of my search bar, but I need it to hide the elements not selected so I don't succeed in solving it.

Here is the snippet to understand what I mean. Update it in your answer to let me see what was wrong.

Hope you guys will be able to help me.

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}

updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  width: 100vw;
  white-space: normal;
  height: 75px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}</code>```

All | Selected | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>

</form>
<textarea id="t" style="display: none;"></textarea>```

答:
rather than only hide all your unchecked input, I would prefer to show all input first. that way, even after I searched something, then if I click "selected", it would still show all the selected input

```<code>function OnlySelecteds() {
  $("input").parent().show();
  $("input:not(:checked)").parent('label').hide();
}
</code>```

demo : https://jsfiddle.net/Lzw1xg2n/1/

Body:
I got a problem with my code. I coded a search bar which filter checkboxes by their name and I coded a function which only display the checkboxes selected. But there is a conflict.

Everytime I click on "Selected" everything is passing to a display : none;

So I tried to wrap my search bar into some div but it's not working as I imagined. I know that .parent() is the problem because it impacts the parent of my search bar, but I need it to hide the elements not selected so I don't succeed in solving it.

Here is the snippet to understand what I mean. Update it in your answer to let me see what was wrong.

Hope you guys will be able to help me.

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}

updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
  }
}

* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  width: 100vw;
  white-space: normal;
  height: 75px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}

All | Selected | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>

</form>
<textarea id="t" style="display: none;"></textarea>

Body:
rather than only hide all your unchecked input, I would prefer to show all input first. that way, even after I searched something, then if I click "selected", it would still show all the selected input

function OnlySelecteds() {
  $("input").parent().show();
  $("input:not(:checked)").parent('label').hide();
}

demo : https://jsfiddle.net/Lzw1xg2n/1/


来源: stackexchange

问:
How to add ssl cipher to ssl_ciphers in nginx
I am using Let's Encrypt to install a free TLS/SSL certificate in my server. I followed the suggestion of Mozilla SSL Configuration Generator and configured nginx like this:

```<code>ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
</code>```

The problem is that I need Java 7 to communicate with the server and it doesn't work with the configuration above.

When I submit my site to ssllabs I get the following message:

```<code>Java 7u25   Server sent fatal alert: handshake_failure
</code>```

If I just comment the ssl_ciphers line in nginx configuration, than the communication with Java 7 starts to work.

```<code># After commenting the line below it works
# ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
</code>```

So I get the following message from ssllabs:

```<code>Java 7u25   RSA 2048 (SHA256)   TLS 1.0 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
</code>```

I would not like to let the ssl_ciphers line commented, because nginx would use its default configuration, which is less secure.

I would like just to add the cipher TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA to the ssl_ciphers list.

Is it possible? How to do it?

答:
From OpenSSL's cipher list or this nice table from testssl.sh, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA corresponds to ECDHE-RSA-AES128-SHA. So you'd set your ssl_ciphers directive to

ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-RSA-AES128-SHA";

ContentLicense: CC BY-SA 3.0

Body:
I am using Let's Encrypt to install a free TLS/SSL certificate in my server. I followed the suggestion of Mozilla SSL Configuration Generator and configured nginx like this:

ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";

The problem is that I need Java 7 to communicate with the server and it doesn't work with the configuration above.

When I submit my site to ssllabs I get the following message:

Java 7u25   Server sent fatal alert: handshake_failure

If I just comment the ssl_ciphers line in nginx configuration, than the communication with Java 7 starts to work.

# After commenting the line below it works
# ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";

So I get the following message from ssllabs:

Java 7u25   RSA 2048 (SHA256)   TLS 1.0 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

I would not like to let the ssl_ciphers line commented, because nginx would use its default configuration, which is less secure.

I would like just to add the cipher TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA to the ssl_ciphers list.

Is it possible? How to do it?


问:
Click anywhere remove class jQuery
I am trying to take a mobile open menu and close it by clicking anywhere except for the actual navigation items.

Here is my HTML

```<code><nav class="site-nav">
  <ul>
    <li><a title="About Riad Kilani - Front End Developer" href="#">About</a></li>
    <li><a title="Portfolio of Riad Kilani - Front End Developer" href="#">Portfolio</a></li>
    <li><a title="Front End Development News and Tutorials from Riad Kilani" href="#">Blog</a></li>
    <li><a title="Contact Riad Kilani" href="#">Contact</a></li>
  </ul>
</nav>

<div id="content">
  <section id="featured">
    <a href="#" class="mobile-button"><i class="fa fa-bars"> Site Name</i></a>
  </section>
</div>
</code>```

And Here is my JS

```<code>$(document).ready(function(e) {
  $(".mobile-button").click(function() {
    $("#content").addClass("mobile-open");
  });

  $(document).click(function(event){
    if (event.target.id === 'site-nav') {
    } else {
        $("#content").removeClass("mobile-open");
    }
  });
});
</code>```

What am I doing wrong??

答:
First of all I will add to your links class, e.g. class="link":

```<code><nav class="site-nav">
  <ul>
    <li><a class="link" title="About Riad Kilani - Front End Developer" href="#">About</a></li>
    <li><a class="link" title="Portfolio of Riad Kilani - Front End Developer" href="#">Portfolio</a></li>
    <li><a class="link" title="Front End Development News and Tutorials from Riad Kilani" href="#">Blog</a></li>
    <li><a class="link" title="Contact Riad Kilani" href="#">Contact</a></li>
  </ul>
</nav>

<div id="content">
  <section id="featured">
    <a href="#" class="mobile-button"><i class="fa fa-bars"> Site Name</i></a>
  </section>
</div>
</code>```

After that, try below jQuery code:

```<code>$(document).ready(function(e) {
    $(".mobile-button").click(function(event) {
        $("#content").addClass("mobile-open");
        event.stopPropagation();
    });

    $(document).click(function(event){
        if (!$(event.target).hasClass('link')) {
            $("#content").removeClass("mobile-open");
        }
    });
});
</code>```

I made jsFiddler for that so you can check if that is what you want - https://jsfiddle.net/o2gxgz9r/8261/.

Title: Click anywhere remove class jQuery

Body:
I am trying to take a mobile open menu and close it by clicking anywhere except for the actual navigation items.

Here is my HTML

About

Portfolio

Blog

Contact

     Site Name

And Here is my JS

$(document).ready(function(e) {
  $(".mobile-button").click(function() {
    $("#content").addClass("mobile-open");
  });

  $(document).click(function(event){
    if (event.target.id === 'site-nav') {
    } else {
        $("#content").removeClass("mobile-open");
    }
  });
});

What am I doing wrong??

Body:
First of all I will add to your links class, e.g. class="link":

<nav class="site-nav">
  <ul>
    <li><a class="link" title="About Riad Kilani - Front End Developer" href="#">About</a></li>
    <li><a class="link" title="Portfolio of Riad Kilani - Front End Developer" href="#">Portfolio</a></li>
    <li><a class="link" title="Front End Development News and Tutorials from Riad Kilani" href="#">Blog</a></li>
    <li><a class="link" title="Contact Riad Kilani" href="#">Contact</a></li>
  </ul>
</nav>

<div id="content">
  <section id="featured">
    <a href="#" class="mobile-button"><i class="fa fa-bars">&nbsp;Site Name</i></a>
  </section>
</div>

After that, try below jQuery code:

$(document).ready(function(e) {
    $(".mobile-button").click(function(event) {
        $("#content").addClass("mobile-open");
        event.stopPropagation();
    });

    $(document).click(function(event){
        if (!$(event.target).hasClass('link')) {
            $("#content").removeClass("mobile-open");
        }
    });
});

I made jsFiddler for that so you can check if that is what you want - https://jsfiddle.net/o2gxgz9r/8261/.


问:
Is it possible to have a dictionary with a mutable array as the value in Swift
I am trying to do this:

```<code>var dictArray = [String:[String]]()
dictArray["test"] = [String]()
dictArray["test"]! += "hello"
</code>```

But I am getting the weird error NSString is not a subtype of 'DictionaryIndex<String, [(String)]>'.

I just want to be able to add objects to an array inside a dictionary.

Update: Looks like Apple considers this a "known issue" in Swift, implying it will work as expected eventually. From the Xcode 6 Beta 4 release notes:

...Similarly, you cannot modify the underlying value of a mutable
  optional value, either  conditionally or within a force-unwrap:

```<code>tableView.sortDescriptors! += NSSortDescriptor(key: "creditName", ascending: true)
</code>```

Workaround: Test the optional value explicitly and then assign the
  result back:

```<code>if let window = NSApplication.sharedApplication.mainWindow {
    window.title = "Currently experiencing problems"
}
tableView.sortDescriptors = tableView.sortDescriptors!
</code>```

答:
The problem is that we want class semantics here but have to use structs. If you put class objects into the dictionary, you get what you want!

So, if you have¹ to have mutable values, you can wrap them in a class and perform updates with a closure:

```<code>class MutableWrapper<T> {
    var rawValue: T

    init(_ val: T) {
        self.rawValue = val
    }

    func update(_ with: (inout T) -> Void) {
        with(&self.rawValue)
    }
}
</code>```

Example:

```<code>func foo() {
    var dict = [String: MutableWrapper<[String]>]()

    dict["bar"] = MutableWrapper(["rum"])
    dict["bar"]?.update({$0.append("gin")})

    print(dict["bar"]!.rawValue)
    // > ["rum", "gin"]
}
</code>```

For what it's worth, I do not see a way to keep caller and wrapper in sync. Even if we declare init(_ val: inout T) we will end up with a copy in rawValue.

Performance is not necessarily an issue since the compiler optimizes structs heavily. I'd benchmark any mutable solution against what looks like lots of copy-updates in the code.

Body:
I am trying to do this:

var dictArray = [String:[String]]()
dictArray["test"] = [String]()
dictArray["test"]! += "hello"

But I am getting the weird error NSString is not a subtype of 'DictionaryIndex<String, [(String)]>'.

I just want to be able to add objects to an array inside a dictionary.

Update: Looks like Apple considers this a "known issue" in Swift, implying it will work as expected eventually. From the Xcode 6 Beta 4 release notes:

...Similarly, you cannot modify the underlying value of a mutable
  optional value, either  conditionally or within a force-unwrap:

tableView.sortDescriptors! += NSSortDescriptor(key: "creditName", ascending: true)

Workaround: Test the optional value explicitly and then assign the
  result back:

if let window = NSApplication.sharedApplication.mainWindow {
    window.title = "Currently experiencing problems"
}
tableView.sortDescriptors = tableView.sortDescriptors!

Body:
The problem is that we want class semantics here but have to use structs. If you put class objects into the dictionary, you get what you want!

So, if you have¹ to have mutable values, you can wrap them in a class and perform updates with a closure:

class MutableWrapper<T> {
    var rawValue: T

    init(_ val: T) {
        self.rawValue = val
    }

    func update(_ with: (inout T) -> Void) {
        with(&self.rawValue)
    }
}

Example:

func foo() {
    var dict = [String: MutableWrapper<[String]>]()

    dict["bar"] = MutableWrapper(["rum"])
    dict["bar"]?.update({$0.append("gin")})

    print(dict["bar"]!.rawValue)
    // > ["rum", "gin"]
}

For what it's worth, I do not see a way to keep caller and wrapper in sync. Even if we declare init(_ val: inout T) we will end up with a copy in rawValue.

Performance is not necessarily an issue since the compiler optimizes structs heavily. I'd benchmark any mutable solution against what looks like lots of copy-updates in the code.


问:
How do I append '-f' flag to each items in a file and save to variable?
in ksh, I am trying to add some option flag (-f) to each item which I read from a file
For ex.

```<code>ls > fileList.txt

// fileList.txt contains
// test1.out
// test2.out
// test3.out

// I tried this but I get this error
// error :  -f: not found [No such file or directory]
files=`cat fileList.txt | sed 's/^/-f /'`

// What I want to see is $files show
// -f test1.out -f test2.out -f test3.out
// so I can call another script with this new argument
processFile $files
</code>```

How can I do this??

答:
you need to loop in each file with a variable as below to get desired output:</p>

```<code>for i in `cat fileList.txt`
do
        echo -n " -f $i"
done
echo
</code>```

Body:
in ksh, I am trying to add some option flag (-f) to each item which I read from a file
For ex.

ls > fileList.txt

// fileList.txt contains
// test1.out
// test2.out
// test3.out

// I tried this but I get this error
// error :  -f: not found [No such file or directory]
files=`cat fileList.txt | sed 's/^/-f /'`

// What I want to see is $files show
// -f test1.out -f test2.out -f test3.out
// so I can call another script with this new argument
processFile $files

How can I do this??

Body:
you need to loop in each file with a variable as below to get desired output:

for i in `cat fileList.txt`
do
        echo -n " -f $i"
done
echo


问:
How can I make my icon
s show up next to each other, rather than underneath each other?
I have this

```<code><a href="#"><div class="iconFriends"></div></a>
<a href="#"><div class="iconFavorite"></div></a>
<a href="#"><div class="iconPM"></div></a>
<a href="#"><div class="iconShield"></div></a>
</code>```

and the css for the icons class looks all similiar to this:

```<code>.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}
</code>```

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

答:
In your CSS:</p>

```<code>.iconFriends{
 background: url(../images/icons/friends_16x16.png) no-repeat;
 width: 16px;
 height: 16px;
 border: none;
 float: left /* or right, depending on the desired outcome */
 }
</code>```

ContentLicense: CC BY-SA 2.5

Title: How can I make my icon <div>s show up next to each other, rather than underneath each other?

Body:
I have this

and the css for the icons class looks all similiar to this:

.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

Body:
In your CSS:

.iconFriends{
 background: url(../images/icons/friends_16x16.png) no-repeat;
 width: 16px;
 height: 16px;
 border: none;
 float: left /* or right, depending on the desired outcome */
 }


问:
In IOS how to auto save the state when the app is in background
we are developing a fitness app in IOS and there is requirement like we have to save state or activity every 1 min. So my query is how is it possible when the app is in background. is there any functionality for this ?</p>

答:
When your app is go in background than applicationDidEnterBackground called after in this you can start your activity

```<code> - (void)applicationDidEnterBackground:(UIApplication *)application {

    UIBackgroundTaskIdentifier backgroundTaskIdentifire = 0;
     backgroundTaskIdentifire = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:backgroundTaskIdentifire];
    }];
    [self TimerMethod];
}

-(void)TimerMethod
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateMethod:) userInfo:self repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer: timer forMode:NSRunLoopCommonModes];
}
</code>```

Body:
When your app is go in background than applicationDidEnterBackground called after in this you can start your activity

 - (void)applicationDidEnterBackground:(UIApplication *)application {

    UIBackgroundTaskIdentifier backgroundTaskIdentifire = 0;
     backgroundTaskIdentifire = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:backgroundTaskIdentifire];
    }];
    [self TimerMethod];
}

-(void)TimerMethod
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateMethod:) userInfo:self repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer: timer forMode:NSRunLoopCommonModes];
}


问:
jQuery toggle with active class
I have a menu with "yes / no" options just like this.

The red color box containing word "yes" is my active button. I just want to show another options when users click yes. So I used jQuery toggle function.

When page load, it showing menu with options just like this.

But I don't want to show it until users click yes. I figured out the problem. It happened because yes button has an active class activated. That's why it showing its options. And also I need to hide that toggle menu options when click no.

I tried with jquery hide functions adding another class to no. It seems ok but expert advice needed.

```<code>$(".remove-toggle").click(function(){
 $(".wrap").hide();
});
</code>```

Working jsfiddle here.

答:
Is this what you need?

- the active class was removed from the HTML element. So white will be the starting background color for both buttons.

- the element with the .wrap class is hidden by default.

- Instead of making .wrap visible via jQuery, I defined a class with animation and use jQuery to add and remove the class when necessary.

  $('.btn-switch').click(function() {
    var $group = $(this).closest('.form-group');
    $('.btn-switch', $group).removeClass("active");
    $(this).addClass("active");
  });

  $(".activate-toggle").click(function() {
    $(".wrap").addClass('animate-wrap-show');
  });

  $(".remove-toggle").click(function() {
    $(".wrap").removeClass('animate-wrap-show');
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap {
  opacity: 0;
  transition: all 1s ease;
}
.btn-switch.active {
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}
.animate-wrap-show {
  opacity: 1;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Do you have the car right now?

      <button type="button" class="btn btn-default btn-switch activate-toggle"> Yes
      </button>

        <button type="button" class="btn btn-default btn-switch remove-toggle">No
        </button>

    Qualification type

      <input type="text" class="form-control input-std" id="qualification-type">

```

Title: jQuery toggle with active class

Body:
I have a menu with "yes / no" options just like this.

The red color box containing word "yes" is my active button. I just want to show another options when users click yes. So I used jQuery toggle function.

When page load, it showing menu with options just like this.

But I don't want to show it until users click yes. I figured out the problem. It happened because yes button has an active class activated. That's why it showing its options. And also I need to hide that toggle menu options when click no.

I tried with jquery hide functions adding another class to no. It seems ok but expert advice needed.

$(".remove-toggle").click(function(){
 $(".wrap").hide();
});

Working jsfiddle here.

Body:
Is this what you need?

- the active class was removed from the HTML element. So white will be the starting background color for both buttons.

- the element with the .wrap class is hidden by default.

- Instead of making .wrap visible via jQuery, I defined a class with animation and use jQuery to add and remove the class when necessary.

  $('.btn-switch').click(function() {
    var $group = $(this).closest('.form-group');
    $('.btn-switch', $group).removeClass("active");
    $(this).addClass("active");
  });

  $(".activate-toggle").click(function() {
    $(".wrap").addClass('animate-wrap-show');
  });

  $(".remove-toggle").click(function() {
    $(".wrap").removeClass('animate-wrap-show');
  });

.wrap {
  opacity: 0;
  transition: all 1s ease;
}
.btn-switch.active {
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}
.animate-wrap-show {
  opacity: 1;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="member" class="col-md-5 col-sm-12 control-label">
    Do you have the car right now?
  </label>
  <div class="col-lg-10">
    <div class="btn-group">
      <button type="button" class="btn btn-default btn-switch activate-toggle"> <span class="goods">Yes</span>
      </button>
      <div class="btn-group">
        <button type="button" class="btn btn-default btn-switch remove-toggle"><span class="services">No</span>
        </button>
      </div>
    </div>
  </div>
</div>

<div class="wrap">
  <div class="form-group">
    <label for="lastname" class="col-md-5 col-sm-12 control-label">Qualification type</label>
    <div class="col-lg-7 col-md-7 col-sm-12 form-input">
      <input type="text" class="form-control input-std" id="qualification-type">
    </div>
  </div>
</div>


问:
how to download video in ionic 2 from server to the mobile file system
want to download a video in ionic 2 project which is placed on the server, also what other plugin need to install for this. Need help.</p>

答:
import {Component} from '@angular/core';
import {NavController, Platform, AlertController} from 'ionic-angular';
import {Transfer, TransferObject} from '@ionic-native/transfer';
import {File} from '@ionic-native/file';

declare let cordova: any;

@Component({
  selector: 'page-about',
  templateUrl: 'about.html',
  providers: [Transfer, TransferObject, File]
})
export class AboutPage {

  storageDirectory: string = '';

  constructor(public navCtrl: NavController, public platform: Platform, private transfer: Transfer, private file: File, public alertCtrl: AlertController) {
    this.platform.ready().then(() => {
      // make sure this is on a device, not an emulation (e.g. chrome tools device mode)
      if(!this.platform.is('cordova')) {
        return false;
      }

      if (this.platform.is('ios')) {
        this.storageDirectory = cordova.file.documentsDirectory;
      }
      else if(this.platform.is('android')) {

  file.createDir(file.externalDataDirectory, 'newDir', true).then((result)=>{

    console.log("Directory created"+result);
    });

        this.storageDirectory = cordova.file.externalDataDirectory+ 'newDir/';
  console.log(this.storageDirectory);
      }
      else {
        // exit otherwise, but you could add further types here e.g. Windows
        return false;
      }
    });
  }

   download() {

    this.platform.ready().then(() => {

 /*file.checkDir(file.externalDataDirectory, 'newDir').then( => console.log('Directory exists')).catch(err =>
 console.log('Directory doesnt exist'));
 console.log('new Directory is created');
 */
 });

 const fileTransfer: TransferObject = this.transfer.create();
 const imageLocation = 'http://html5demos.com/assets/dizzy.mp4';
 fileTransfer.download(imageLocation, this.storageDirectory + 'dizzy.mp4').then((entry) => {

 const alertSuccess = this.alertCtrl.create({
    title: `Download Succeeded!`,
    subTitle: `successfully downloaded to: ${entry.toURL()}`,
    buttons: ['Ok']
    });

        alertSuccess.present();

      }, (error) => {

        const alertFailure = this.alertCtrl.create({
          title: `Download Failed!`,
          subTitle: `was not downloaded. Error code: ${error}`,
          buttons: ['Ok']
        });

        alertFailure.present();

      });

}
  }```

Here I got the solution.

Body:
import {Component} from '@angular/core';
import {NavController, Platform, AlertController} from 'ionic-angular';
import {Transfer, TransferObject} from '@ionic-native/transfer';
import {File} from '@ionic-native/file';

declare let cordova: any;

@Component({
  selector: 'page-about',
  templateUrl: 'about.html',
  providers: [Transfer, TransferObject, File]
})
export class AboutPage {

  storageDirectory: string = '';

  constructor(public navCtrl: NavController, public platform: Platform, private transfer: Transfer, private file: File, public alertCtrl: AlertController) {
    this.platform.ready().then(() => {
      // make sure this is on a device, not an emulation (e.g. chrome tools device mode)
      if(!this.platform.is('cordova')) {
        return false;
      }

      if (this.platform.is('ios')) {
        this.storageDirectory = cordova.file.documentsDirectory;
      }
      else if(this.platform.is('android')) {

  file.createDir(file.externalDataDirectory, 'newDir', true).then((result)=>{

    console.log("Directory created"+result);
    });

        this.storageDirectory = cordova.file.externalDataDirectory+ 'newDir/';
  console.log(this.storageDirectory);
      }
      else {
        // exit otherwise, but you could add further types here e.g. Windows
        return false;
      }
    });
  }

   download() {

    this.platform.ready().then(() => {

 /*file.checkDir(file.externalDataDirectory, 'newDir').then( => console.log('Directory exists')).catch(err =>
 console.log('Directory doesnt exist'));
 console.log('new Directory is created');
 */
 });

 const fileTransfer: TransferObject = this.transfer.create();
 const imageLocation = 'http://html5demos.com/assets/dizzy.mp4';
 fileTransfer.download(imageLocation, this.storageDirectory + 'dizzy.mp4').then((entry) => {

 const alertSuccess = this.alertCtrl.create({
    title: `Download Succeeded!`,
    subTitle: `successfully downloaded to: ${entry.toURL()}`,
    buttons: ['Ok']
    });

        alertSuccess.present();

      }, (error) => {

        const alertFailure = this.alertCtrl.create({
          title: `Download Failed!`,
          subTitle: `was not downloaded. Error code: ${error}`,
          buttons: ['Ok']
        });

        alertFailure.present();

      });

}
  }

Here I got the solution.


问:
What is the difference between a map and a dictionary?
I know a map is a data structure that maps keys to values. Isn't a dictionary the same? What is the difference between a map and a dictionary1?

1. I am not asking for how they are defined in language X or Y (which seems to be what generally people are asking here on SO), I want to know what is their difference in theory.

答:
The main difference is that a Map, requires that all entries(value & key pair) have a unique key. If collisions occur, i.e. when a new entry has the same key as an entry already in the collection, then collision handling is required.

Usually, we handle collisions using either Separate Chaining. Or Linear Probing.

A Dictionary allows for multiple entries to be linked to the same key.

When a Map has implemented Separate Chaining, then it tends to resemble a Dictionary.


问:
Python functions and array parameters
I am trying to build a program that can produce (x,y,z) 10x10x10 arrays (unit cells) on a 3D grid. Example: one cube is at point (0,10)x(0,10)x(0,10) while another is at (0,10)x(10,20)x(0,10). So far I have a function that makes 4 of these but how would I automate it to make dozens or even hundreds? </p>

```<code>import math
import numpy as np

def cubeplot():
    count = 0
    count2 = 0
    x = 11
    y = 11
    z = 11
    c = 11
    parameter = np.arange(0,11,1)
    xx, yy, zz = np.meshgrid(parameter, parameter, parameter)
    valuesrange = np.zeros((11, 11, 11))
    parameter2 = np.arange(c, y+10,1)
    xx2, yy2, zz2 = np.meshgrid(parameter2, parameter2, parameter2)
    valuesrange2 = np.zeros((x+10, y+10 , z + 10))
    parameter3 = np.arange(c + 10, y+20,1)
    xx2, yy2, zz2 = np.meshgrid(parameter2, parameter2, parameter2)
    valuesrange2 = np.zeros((x+20, y+20 , z +20))

    print('POINT 1')
    while (count < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
            xint = np.random.randint(10,c, 22)
            x = 10
        else:
            xint = np.random.randint(0,1, 22)
            x = 0
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y = 10
        else:
            yint = np.random.randint(0,1, 22)
            y = 0
        if zint > 0:
            zint = np.random.randint(10,c, 22)
            z = 10
        else:
            zint = np.random.randint(0,1, 22)
            z = 0
        count = count + 1
        print('x = ' + str(x))
        print('y = ' + str(y))
        print('z = ' + str(z))
    #       print('Distance = ' + str(zint))

    print('POINT 2')

    while (count2 < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
            xint = np.random.randint(20,c + 10, 22)
            x2 = 20
        else:
            xint = np.random.randint(10,11, 22)
            x2 = 10
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y2 = 10
        else:
            yint = np.random.randint(0,1, 22)
            y2 = 0
        if zint > 0:
            zint = np.random.randint(10,c, 22)
            z2 = 10
        else:
            zint = np.random.randint(0,1, 22)
            z2 = 0
        count2 = count2 + 1
        print('x = ' + str(x2))
        print('y = ' + str(y2))
        print('z = ' + str(z2))

    distance = ((x2-x)**2 + (y2 - y)**2 + (z2 - z)**2)**.5
    print ('POINT 1: x,y,z: ' + str(x) +',' + str(y) + ','+ str(z))
    print ('POINT 2: x,y,z: ' + str(x2) +',' + str(y2)+ ',' + str(z2))
    print('Distance = ' + str(distance))

    print('POINT 3')
    count3 = 0
    while (count3 < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
           xint = np.random.randint(10,c, 22)
           x3 = 10
        else:
            xint = np.random.randint(0,1, 22)
            x3 = 0
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y3 = 10
        else:
            yint = np.random.randint(0,1, 22)
            y3 = 0
        if zint > 0:
            zint = np.random.randint(20,c + 10, 22)
            z3 = 20
        else:
            zint = np.random.randint(10,c, 22)
            z3 = 10
        count3 = count3 + 1
        print('x = ' + str(x3))
        print('y = ' + str(y3))
        print('z = ' + str(z3))

    print('POINT 4')
    count4 = 0
    while (count4 < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
            xint = np.random.randint(20,c+10, 22)
            x4 = 20
        else:
            xint = np.random.randint(10,c, 22)
            x4 = 10
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y4 = 10
        else:
            yint = np.random.randint(0,1, 22)
            y4 = 0
        if zint > 0:
            zint = np.random.randint(20,c + 10, 22)
            z4 = 20
        else:
            zint = np.random.randint(10,c, 22)
            z4 = 10
        count4 = count4 + 1
        print('x = ' + str(x4))
        print('y = ' + str(y4))
        print('z = ' + str(z4))
        print ('POINT 3: x,y,z: ' + str(x3) +',' + str(y3) + ','+ str(z3))
        print ('POINT 4: x,y,z: ' + str(x4) +',' + str(y4)+ ',' + str(z4))
        print('SET END')
        print('')
        print('')
        print('')

runtime = int (input("How many times would you like to run the program?: "))
maincount = 0
print ('The program will run', runtime, 'times')

while (maincount < runtime):
    cubeplot()
    maincount = maincount + 1
</code>```

答:
numpy arrays are a bit more powerful than you might think. If you want each cell of your 3D grid to have another 3D grid, what you are looking for is a 6D grid. Check the following example:

```<code>import numpy as np

# Lets make a 3D grid in which each cell has 3 dimensions
# (making it a 6D grid)
grid = np.zeros((3, 2, 4, 10, 10, 10))

# So for every arbitrary 3D coordinate of the grid I have
# another 3D grid (result: (10, 10, 10))
print(grid[2, 1, 3].shape)

# If a make a grid for a single cell:
# the randint function is creating a (10, 10, 10) grid
local_grid = np.random.randint(0, 10, (10, 10, 10))

# I can put it inside my big grid:
grid[2, 1, 3] = local_grid

# If I need to this for all (3, 2, 4) shape of my big grid
# (meaning its first 3 dimensions) I can loop each of those
# dimensions:
for x in range(grid.shape[0]):
    for y in range(grid.shape[1]):
        for z in range(grid.shape[2]):
            grid[x, y, z] = np.random.randint(0, 10, (10, 10, 10))
</code>```

There are other ways to fill a grid (possibly more optimal) depending on your needs but there is little need for you to play with indexation numbers unless you really need to. Is this what you are looking for (logic wise)?

EDIT: So if you really want just a 3D grid you can multiply your cell dimensions by grid dimension and loop it to index some content inside. For example:

```<code>target = (3, 2, 4)
cell = (3, 3, 3)
grid = np.zeros((target[0]*cell[0], target[1]*cell[1], target[2]*cell[2]))
counter = 1
for x in range(target[0]):
    for y in range(target[1]):
        for z in range(target[2]):
            grid[x*cell[0]:x*cell[0]+cell[0], y*cell[0]:y*cell[1]+cell[1], z*cell[2]:z*cell[2]+cell[2]] = counter
            counter += 1
</code>```

In this case grid[0:cell[0], 0:cell[1], 0:cell[2]] will be equal to a grid of cell dimensions whose content is 1.

Title: Python functions and array parameters

Body:
I am trying to build a program that can produce (x,y,z) 10x10x10 arrays (unit cells) on a 3D grid. Example: one cube is at point (0,10)x(0,10)x(0,10) while another is at (0,10)x(10,20)x(0,10). So far I have a function that makes 4 of these but how would I automate it to make dozens or even hundreds?

import math
import numpy as np

def cubeplot():
    count = 0
    count2 = 0
    x = 11
    y = 11
    z = 11
    c = 11
    parameter = np.arange(0,11,1)
    xx, yy, zz = np.meshgrid(parameter, parameter, parameter)
    valuesrange = np.zeros((11, 11, 11))
    parameter2 = np.arange(c, y+10,1)
    xx2, yy2, zz2 = np.meshgrid(parameter2, parameter2, parameter2)
    valuesrange2 = np.zeros((x+10, y+10 , z + 10))
    parameter3 = np.arange(c + 10, y+20,1)
    xx2, yy2, zz2 = np.meshgrid(parameter2, parameter2, parameter2)
    valuesrange2 = np.zeros((x+20, y+20 , z +20))

    print('POINT 1')
    while (count < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
            xint = np.random.randint(10,c, 22)
            x = 10
        else:
            xint = np.random.randint(0,1, 22)
            x = 0
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y = 10
        else:
            yint = np.random.randint(0,1, 22)
            y = 0
        if zint > 0:
            zint = np.random.randint(10,c, 22)
            z = 10
        else:
            zint = np.random.randint(0,1, 22)
            z = 0
        count = count + 1
        print('x = ' + str(x))
        print('y = ' + str(y))
        print('z = ' + str(z))
    #       print('Distance = ' + str(zint))

    print('POINT 2')

    while (count2 < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
            xint = np.random.randint(20,c + 10, 22)
            x2 = 20
        else:
            xint = np.random.randint(10,11, 22)
            x2 = 10
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y2 = 10
        else:
            yint = np.random.randint(0,1, 22)
            y2 = 0
        if zint > 0:
            zint = np.random.randint(10,c, 22)
            z2 = 10
        else:
            zint = np.random.randint(0,1, 22)
            z2 = 0
        count2 = count2 + 1
        print('x = ' + str(x2))
        print('y = ' + str(y2))
        print('z = ' + str(z2))

    distance = ((x2-x)**2 + (y2 - y)**2 + (z2 - z)**2)**.5
    print ('POINT 1: x,y,z: ' + str(x) +',' + str(y) + ','+ str(z))
    print ('POINT 2: x,y,z: ' + str(x2) +',' + str(y2)+ ',' + str(z2))
    print('Distance = ' + str(distance))

    print('POINT 3')
    count3 = 0
    while (count3 < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
           xint = np.random.randint(10,c, 22)
           x3 = 10
        else:
            xint = np.random.randint(0,1, 22)
            x3 = 0
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y3 = 10
        else:
            yint = np.random.randint(0,1, 22)
            y3 = 0
        if zint > 0:
            zint = np.random.randint(20,c + 10, 22)
            z3 = 20
        else:
            zint = np.random.randint(10,c, 22)
            z3 = 10
        count3 = count3 + 1
        print('x = ' + str(x3))
        print('y = ' + str(y3))
        print('z = ' + str(z3))

    print('POINT 4')
    count4 = 0
    while (count4 < 1):
        xint = np.random.randint(0,2)
        yint = np.random.randint(0,2)
        zint = np.random.randint(0,2)

        if xint > 0:
            xint = np.random.randint(20,c+10, 22)
            x4 = 20
        else:
            xint = np.random.randint(10,c, 22)
            x4 = 10
        if yint >0:
            yint = np.random.randint(10,c, 22)
            y4 = 10
        else:
            yint = np.random.randint(0,1, 22)
            y4 = 0
        if zint > 0:
            zint = np.random.randint(20,c + 10, 22)
            z4 = 20
        else:
            zint = np.random.randint(10,c, 22)
            z4 = 10
        count4 = count4 + 1
        print('x = ' + str(x4))
        print('y = ' + str(y4))
        print('z = ' + str(z4))
        print ('POINT 3: x,y,z: ' + str(x3) +',' + str(y3) + ','+ str(z3))
        print ('POINT 4: x,y,z: ' + str(x4) +',' + str(y4)+ ',' + str(z4))
        print('SET END')
        print('')
        print('')
        print('')

runtime = int (input("How many times would you like to run the program?: "))
maincount = 0
print ('The program will run', runtime, 'times')

while (maincount < runtime):
    cubeplot()
    maincount = maincount + 1

Body:
numpy arrays are a bit more powerful than you might think. If you want each cell of your 3D grid to have another 3D grid, what you are looking for is a 6D grid. Check the following example:

import numpy as np

# Lets make a 3D grid in which each cell has 3 dimensions
# (making it a 6D grid)
grid = np.zeros((3, 2, 4, 10, 10, 10))

# So for every arbitrary 3D coordinate of the grid I have
# another 3D grid (result: (10, 10, 10))
print(grid[2, 1, 3].shape)

# If a make a grid for a single cell:
# the randint function is creating a (10, 10, 10) grid
local_grid = np.random.randint(0, 10, (10, 10, 10))

# I can put it inside my big grid:
grid[2, 1, 3] = local_grid

# If I need to this for all (3, 2, 4) shape of my big grid
# (meaning its first 3 dimensions) I can loop each of those
# dimensions:
for x in range(grid.shape[0]):
    for y in range(grid.shape[1]):
        for z in range(grid.shape[2]):
            grid[x, y, z] = np.random.randint(0, 10, (10, 10, 10))

There are other ways to fill a grid (possibly more optimal) depending on your needs but there is little need for you to play with indexation numbers unless you really need to. Is this what you are looking for (logic wise)?

EDIT: So if you really want just a 3D grid you can multiply your cell dimensions by grid dimension and loop it to index some content inside. For example:

target = (3, 2, 4)
cell = (3, 3, 3)
grid = np.zeros((target[0]*cell[0], target[1]*cell[1], target[2]*cell[2]))
counter = 1
for x in range(target[0]):
    for y in range(target[1]):
        for z in range(target[2]):
            grid[x*cell[0]:x*cell[0]+cell[0], y*cell[0]:y*cell[1]+cell[1], z*cell[2]:z*cell[2]+cell[2]] = counter
            counter += 1

In this case grid[0:cell[0], 0:cell[1], 0:cell[2]] will be equal to a grid of cell dimensions whose content is 1.


问:
Launch modal from controller
i'm trying to show a modal window (using jquery ui dialog) to the user from my controller.

For example :

```<code>def create
  if params[:id]
    #do something
  else
    #show a modal window with a partial as content
end
</code>```

Thx for your help =)

答: You can't show a jQuery dialog from a controller, because you can't execute JavaScript on server side. The closest you could come to this is sending back a JavaScript string to be evaluated on the client side, but this is very bad practice. Your best bet is to key off something on the server side and do your dialog code on the client side. If you don't want a bunch of JavaScript in your erb templates, you can call a function from there, or you can do your submit via AJAX and either have your handler do the dialog or render a js.erb template that can both render partials and do JavaScript. Let me know if you want an example of any of the above and I'll see if I can provide one.</p>

Title: Launch modal from controller

Body:
i'm trying to show a modal window (using jquery ui dialog) to the user from my controller.

For example :

def create
  if params[:id]
    #do something
  else
    #show a modal window with a partial as content
end

Thx for your help =)


问:
how to know what version exists for a specific npm package?
I am a noob. So I don't know where to find what is a valid version number.

For example, for code push, I only find this table in their readme:

```<code>React Native version(s) Supporting CodePush version(s)
<0.14   Unsupported
v0.14   v1.3 (introduced Android support)
v0.15-v0.18 v1.4-v1.6 (introduced iOS asset support)
v0.19-v0.28 v1.7-v1.17 (introduced Android asset support)
v0.29-v0.30 v1.13-v1.17 (RN refactored native hosting code)
v0.31-v0.33 v1.14.6-v1.17 (RN refactored native hosting code)
v0.34-v0.35 v1.15-v1.17 (RN refactored native hosting code)
v0.36-v0.39 v1.16-v1.17 (RN refactored resume handler)
v0.40-v0.42 v1.17 (RN refactored iOS header files)
v0.43-v0.44 v2.0+ (RN refactored uimanager dependencies)
v0.45+  TBD :) We work hard to respond to new RN releases, but they do occasionally break us. We will update this chart with each RN release, so that users can check to see what our "official" support is.
</code>```

They mentioned v1.17, so I try

```<code>"react-native-code-push": "^1.17",
</code>```

but then got error:

```<code>notarget No matching version found for react-native-code-push@^1.17
</code>```

So from where do I know what previous versions number are valid for a package?

答:
See last version of the package in the right column on package page at npmjs.com:

To list all available versions run npm view:

```<code>npm view react-native-code-push versions
</code>```

returns

```<code>[ '1.0.0-beta',
  '1.0.1-beta',
   …
  '2.0.3-beta',
  '2.1.0-beta' ]
</code>```

Body:
I am a noob. So I don't know where to find what is a valid version number.

For example, for code push, I only find this table in their readme:

React Native version(s) Supporting CodePush version(s)
<0.14   Unsupported
v0.14   v1.3 (introduced Android support)
v0.15-v0.18 v1.4-v1.6 (introduced iOS asset support)
v0.19-v0.28 v1.7-v1.17 (introduced Android asset support)
v0.29-v0.30 v1.13-v1.17 (RN refactored native hosting code)
v0.31-v0.33 v1.14.6-v1.17 (RN refactored native hosting code)
v0.34-v0.35 v1.15-v1.17 (RN refactored native hosting code)
v0.36-v0.39 v1.16-v1.17 (RN refactored resume handler)
v0.40-v0.42 v1.17 (RN refactored iOS header files)
v0.43-v0.44 v2.0+ (RN refactored uimanager dependencies)
v0.45+  TBD :) We work hard to respond to new RN releases, but they do occasionally break us. We will update this chart with each RN release, so that users can check to see what our "official" support is.

They mentioned v1.17, so I try

"react-native-code-push": "^1.17",

but then got error:

notarget No matching version found for react-native-code-push@^1.17

So from where do I know what previous versions number are valid for a package?

Body:
See last version of the package in the right column on package page at npmjs.com:

To list all available versions run npm view:

npm view react-native-code-push versions

returns

[ '1.0.0-beta',
  '1.0.1-beta',
   …
  '2.0.3-beta',
  '2.1.0-beta' ]


问:
iOS build disappears from iTunes Connect
I'm using Xcode 8.3.3 to upload an App on itunes connect. Xcode shows me that the uploading is successful. In Activity tab of iTunesConnect I see that my build is appears and it's marked as "processing...". But after a few minutes this build disappears and I cannot find it anywhere. I tried to upload it, but it says the build is already uploaded to iTunesConnect. So when I tried to upload build with increased version it says OK, but I still cannot see the build in iTunesConnect. There isn't a way for know error code of the processing? I have no information.
Thanks in advance.</p>

答: Check your mail. Your build might get rejected so Apple sent rejection reason to mail. You might have received Invalid swift support error in mail</p>


问:
Serialise empty strings as nulls so they are not output
I've got an XSD which has been supplied by a third party and I've then converted this into classes using xsd.exe.

Due to the fact we do not own this XSD, I'm trying to not alter the generated classes in any way.

Without manually applying a blank string check to every single field we are mapping, e.g.:

```<code>!String.IsNullOrWhiteSpace(field) ? field : null;
</code>```

I can't think of an easy way to serialise the blank strings in a way which means they are not output at all (no tag is produced).

The reason we cannot output blank strings is because the XSD has pattern constraints such as StringM50m1 which I believe means a minimum length of 1 is required (however, they are happy to not receive the tag if there is no content) which fail post-output validation with the following message:

The 'field' element is invalid - The value '' is invalid according to its datatype 'StringM50m1' - The Pattern constraint failed.

Any thoughts would be appreciated.

答:
If you use XmlSerializer you can add XmlDefaultValue for required properties:</p>

```<code>private static void Serialize()
{
    XsdClass xc = new XsdClass();
    xc.SomeString1 = string.Empty;
    xc.SomeString2 = "value";
    xc.SomeString3 = null;

    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attribs = new XmlAttributes();
    attribs.XmlDefaultValue = string.Empty;
    foreach (var prop in TypeDescriptor.GetProperties(typeof(XsdClass)).Cast<PropertyDescriptor>().Where(x => !x.IsReadOnly && x.PropertyType == typeof(string)))
        overrides.Add(typeof(XsdClass), prop.Name, attribs);

    XmlSerializer serializer = new XmlSerializer(typeof(XsdClass), overrides);
    string result;
    using (StringWriter textWriter = new StringWriter())
    {
        serializer.Serialize(textWriter, xc);
        result = textWriter.ToString();
    }
}

public class XsdClass
{
    public string SomeString1 { get; set; }
    public string SomeString2 { get; set; }
    public string SomeString3 { get; set; }
}
</code>```

Body:
I've got an XSD which has been supplied by a third party and I've then converted this into classes using xsd.exe.

Due to the fact we do not own this XSD, I'm trying to not alter the generated classes in any way.

Without manually applying a blank string check to every single field we are mapping, e.g.:

!String.IsNullOrWhiteSpace(field) ? field : null;

I can't think of an easy way to serialise the blank strings in a way which means they are not output at all (no tag is produced).

The reason we cannot output blank strings is because the XSD has pattern constraints such as StringM50m1 which I believe means a minimum length of 1 is required (however, they are happy to not receive the tag if there is no content) which fail post-output validation with the following message:

The 'field' element is invalid - The value '' is invalid according to its datatype 'StringM50m1' - The Pattern constraint failed.

Any thoughts would be appreciated.

Body:
If you use XmlSerializer you can add XmlDefaultValue for required properties:

private static void Serialize()
{
    XsdClass xc = new XsdClass();
    xc.SomeString1 = string.Empty;
    xc.SomeString2 = "value";
    xc.SomeString3 = null;

    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attribs = new XmlAttributes();
    attribs.XmlDefaultValue = string.Empty;
    foreach (var prop in TypeDescriptor.GetProperties(typeof(XsdClass)).Cast<PropertyDescriptor>().Where(x => !x.IsReadOnly && x.PropertyType == typeof(string)))
        overrides.Add(typeof(XsdClass), prop.Name, attribs);

    XmlSerializer serializer = new XmlSerializer(typeof(XsdClass), overrides);
    string result;
    using (StringWriter textWriter = new StringWriter())
    {
        serializer.Serialize(textWriter, xc);
        result = textWriter.ToString();
    }
}

public class XsdClass
{
    public string SomeString1 { get; set; }
    public string SomeString2 { get; set; }
    public string SomeString3 { get; set; }
}


问:
Python Selenium Chrome Not Running Headless
I'm currently writing a program in which I'm connecting to chrome. I would like to make this process without a new chrome window popping up every time. I know that --headless makes chrome run silently, but my current code is not working; it is still opening up chrome tabs.

Current Code:

```<code>chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options = chrome_options)
</code>```

What am I doing wrong or what do I need to add?

答:
If you are using linux one alternate solution to run the browser in headless mode is to use pyvirtual display.
First install xvfb and pyvirtual display:

```<code>sudo apt-get install xvfb xserver-xephyr

sudo pip install pyvirtualdisplay
</code>```

The code will be:

```<code>from pyvirtualdisplay import Display
import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
browser = webdriver.Chrome()
</code>```

Body:
I'm currently writing a program in which I'm connecting to chrome. I would like to make this process without a new chrome window popping up every time. I know that --headless makes chrome run silently, but my current code is not working; it is still opening up chrome tabs.

Current Code:

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options = chrome_options)

What am I doing wrong or what do I need to add?

Body:
If you are using linux one alternate solution to run the browser in headless mode is to use pyvirtual display.
First install xvfb and pyvirtual display:

sudo apt-get install xvfb xserver-xephyr

sudo pip install pyvirtualdisplay

The code will be:

from pyvirtualdisplay import Display
import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
browser = webdriver.Chrome()


问:
CardView Strange Behaviour
I have a simple layout with CardView

```<code><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cv_tag"
android:layout_width="wrap_content"
android:layout_height="@dimen/tag_height"
android:layout_margin="4dp"
android:clickable="true"
app:cardCornerRadius="20dp"
app:cardElevation="2dp">

<FrameLayout
    android:id="@+id/fl_selection_indicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="8dp"
        android:textAppearance="@style/PrimaryWhiteText.Tiny"
        tools:text="Hard"/>

</FrameLayout>

</android.support.v7.widget.CardView>
</code>```

And it's rendering not as I expect it to. It looks like system wraps this layout into FrameLayout with elevation and white background. Interesting thing is if I wrap this layout into FrameLayout by myself elevation goes away but white background is still there (Background of frame layout not CardView)

How to remove elevation and white background and why is it happening?

Thanks in advance!

答:
Might be a quirk of pre-API 21 implementation.

In the mean time, you probably don't need the CardView altogether. Consider using DrawableResource.

Refer to How do I set the rounded corner radius of a color drawable using xml?

Old answer:

By default CardView has a background color set depending on your theme.
Here's an exempt from styles

```<code><color name="cardview_dark_background">#FF424242</color>
<color name="cardview_light_background">#FFFFFFFF</color>
</code>```

And from the initialization of the view

```<code>if (a.hasValue(R.styleable.CardView_cardBackgroundColor)) {
            backgroundColor = a.getColorStateList(R.styleable.CardView_cardBackgroundColor);
} else {
     // There isn't one set, so we'll compute one based on the theme
     final TypedArray aa = getContext().obtainStyledAttributes(COLOR_BACKGROUND_ATTR);
     final int themeColorBackground = aa.getColor(0, 0);
     aa.recycle();

     // If the theme colorBackground is light, use our own light color, otherwise dark
     final float[] hsv = new float[3];
     Color.colorToHSV(themeColorBackground, hsv);
     backgroundColor = ColorStateList.valueOf(hsv[2] > 0.5f
                    ? getResources().getColor(R.color.cardview_light_background)
                    : getResources().getColor(R.color.cardview_dark_background));
 }
</code>```

To change the color, use the app:cardBackgroundColor attribute

Title: CardView Strange Behaviour

Body:
I have a simple layout with CardView

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cv_tag"
android:layout_width="wrap_content"
android:layout_height="@dimen/tag_height"
android:layout_margin="4dp"
android:clickable="true"
app:cardCornerRadius="20dp"
app:cardElevation="2dp">

<FrameLayout
    android:id="@+id/fl_selection_indicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="8dp"
        android:textAppearance="@style/PrimaryWhiteText.Tiny"
        tools:text="Hard"/>

</FrameLayout>

</android.support.v7.widget.CardView>

And it's rendering not as I expect it to. It looks like system wraps this layout into FrameLayout with elevation and white background. Interesting thing is if I wrap this layout into FrameLayout by myself elevation goes away but white background is still there (Background of frame layout not CardView)

How to remove elevation and white background and why is it happening?

Thanks in advance!

Body:
Might be a quirk of pre-API 21 implementation.

In the mean time, you probably don't need the CardView altogether. Consider using DrawableResource.

Refer to How do I set the rounded corner radius of a color drawable using xml?

Old answer:

By default CardView has a background color set depending on your theme.
Here's an exempt from styles

<color name="cardview_dark_background">#FF424242</color>
<color name="cardview_light_background">#FFFFFFFF</color>

And from the initialization of the view

if (a.hasValue(R.styleable.CardView_cardBackgroundColor)) {
            backgroundColor = a.getColorStateList(R.styleable.CardView_cardBackgroundColor);
} else {
     // There isn't one set, so we'll compute one based on the theme
     final TypedArray aa = getContext().obtainStyledAttributes(COLOR_BACKGROUND_ATTR);
     final int themeColorBackground = aa.getColor(0, 0);
     aa.recycle();

     // If the theme colorBackground is light, use our own light color, otherwise dark
     final float[] hsv = new float[3];
     Color.colorToHSV(themeColorBackground, hsv);
     backgroundColor = ColorStateList.valueOf(hsv[2] > 0.5f
                    ? getResources().getColor(R.color.cardview_light_background)
                    : getResources().getColor(R.color.cardview_dark_background));
 }

To change the color, use the app:cardBackgroundColor attribute


问:
How to get list of files in use when installing MSI file with ExternalUI
I am writing program witch runs msi installations silent on background. Using MsiSetExternalUI and MsiSetInternalUI with INSTALLUILEVEL_NONE I can show my progress dialog and catch errors during install:

```<code>INT CALLBACK ProgressHandler(LPVOID pvContext, UINT uiMessageType, LPCTSTR szMessage)
{
    INSTALLMESSAGE iMessage = (INSTALLMESSAGE)(0xFF000000 & uiMessageType);
    if( INSTALLMESSAGE_PROGRESS == iMessage )
        ShowProgress(...);
    if( INSTALLMESSAGE_FILESINUSE == iMessage )
        MessageBox(NULL, szMessage, _T("Files in use"), MB_OK);
}
...
DWORD dwMessageFilter = INSTALLLOGMODE_PROGRESS | INSTALLLOGMODE_FILESINUSE;
MsiSetExternalUI(&ProgressHandler, dwMessageFilter, NULL);
INSTALLUILEVEL pervousUILevel = MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
UINT res = MsiInstallProduct(sPath, NULL);
</code>```

The problem is that when some files is in use my callback receives INSTALLMESSAGE_FILESINUSE message, but szMessage parameter contains only this text - "The following applications should be closed before continuing the installation:". If I run msi file with full interface there is dialog wit list of programs witch must be closed before installation can continue.

How can I get this list and display it to user when running setup without UI?

答: This thread in the wix-users mailing list suggests using MsiSetExternalUIRecord instead of MsiSetExternalUI allows you to retrieve the file names in the fields of the record (corresponding to  [1], [2], and so forth). Just watch out for empty ones in the middle. This suggests that these values should be available in szMessage, so I'm unclear why they wouldn't be visible already, unless perhaps they contain a NUL and end the string that way.

Body:
I am writing program witch runs msi installations silent on background. Using MsiSetExternalUI and MsiSetInternalUI with INSTALLUILEVEL_NONE I can show my progress dialog and catch errors during install:

INT CALLBACK ProgressHandler(LPVOID pvContext, UINT uiMessageType, LPCTSTR szMessage)
{
    INSTALLMESSAGE iMessage = (INSTALLMESSAGE)(0xFF000000 & uiMessageType);
    if( INSTALLMESSAGE_PROGRESS == iMessage )
        ShowProgress(...);
    if( INSTALLMESSAGE_FILESINUSE == iMessage )
        MessageBox(NULL, szMessage, _T("Files in use"), MB_OK);
}
...
DWORD dwMessageFilter = INSTALLLOGMODE_PROGRESS | INSTALLLOGMODE_FILESINUSE;
MsiSetExternalUI(&ProgressHandler, dwMessageFilter, NULL);
INSTALLUILEVEL pervousUILevel = MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
UINT res = MsiInstallProduct(sPath, NULL);

The problem is that when some files is in use my callback receives INSTALLMESSAGE_FILESINUSE message, but szMessage parameter contains only this text - "The following applications should be closed before continuing the installation:". If I run msi file with full interface there is dialog wit list of programs witch must be closed before installation can continue.

How can I get this list and display it to user when running setup without UI?


问:
Ajax function not being called on form submit
I am a beginner in this so excuse me if I'm just dumb.

So basically I'm trying to get a div to reload with information from a php file after submitting a form using ajax and this is what I have.

index.php

```<code><script type="text/javascript">
$('#searchForm').submit(function(event){
  $.ajax({
    url: 'result.php',
    type: 'post',
    dataType:'html',   //expect return data as html from server
    data: $('#searchForm').serialize(),
    success: function(response, textStatus, jqXHR){
      $('#underInput').html(response);
     },
  error: function(jqXHR, textStatus, errorThrown){
  console.log('error(s):'+textStatus, errorThrown);
  }
 });
 });
</script>

    <form class="form-group" id="searchForm" onsubmit="return false">
        <div class="input-group">
            <input id="search" class="form-control" name="user" type="text" placeholder="Enter instagram username">
            <span class="input-group-btn">
            <button class="btn btn-primary" id="submit" type="submit">Sök</button>
            </span>
        </div>
    </form>
        <div id="underInput"/>
</code>```

result.php

```<code>//dont want to show calculation for therate here
echo '<h2><?php echo $_POST["user"]?> can charge <?php echo $therate?>€ per
post</h2>';
</code>```

Nothing happens when i click submit, why?

答:
Use on click instead of submit

Example-

```<code> $(document).ready(function(){
    $('#submit').on("click", function(event){
      $.ajax({
        url: 'result.php',
        type: 'post',
        dataType:'html',   //expect return data as html from server
        data: $('#searchForm').serialize(),
        success: function(response, textStatus, jqXHR){
          $('#underInput').html(response);
         },
      error: function(jqXHR, textStatus, errorThrown){
      console.log('error(s):'+textStatus, errorThrown);
      }
     });
     });
});
</code>```

Then replace your php code with this code

```<code><?php
echo '<h2>'.$_POST["user"].' can charge '.$therate.' € per
post</h2>';
?>
</code>```

Body:
I am a beginner in this so excuse me if I'm just dumb.

So basically I'm trying to get a div to reload with information from a php file after submitting a form using ajax and this is what I have.

index.php

    <form class="form-group" id="searchForm" onsubmit="return false">

            <input id="search" class="form-control" name="user" type="text" placeholder="Enter instagram username">

            <button class="btn btn-primary" id="submit" type="submit">Sök</button>

    </form>

result.php

//dont want to show calculation for therate here
echo '
<?php echo $_POST["user"]?> can charge <?php echo $therate?>€ per
post
';

Nothing happens when i click submit, why?

Body:
Use on click instead of submit

Example-

 $(document).ready(function(){
    $('#submit').on("click", function(event){
      $.ajax({
        url: 'result.php',
        type: 'post',
        dataType:'html',   //expect return data as html from server
        data: $('#searchForm').serialize(),
        success: function(response, textStatus, jqXHR){
          $('#underInput').html(response);
         },
      error: function(jqXHR, textStatus, errorThrown){
      console.log('error(s):'+textStatus, errorThrown);
      }
     });
     });
});

Then replace your php code with this code

<?php
echo '<h2>'.$_POST["user"].' can charge '.$therate.' € per
post</h2>';
?>


问:
Optimize the for loop in python
Good, I currently have the following code:

```<code>n = 0
with open('/home/user/test.filter') as f:

    lines = f.readlines()

    for l in lines:
        if lines[n].startswith('-A vlan_8'):
            if "-o bond1.8" in lines[n]:
                    f = open('vlan8.filter_in', 'a')
                    f.write(l)
            else:
                f = open('vlan8.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_10'):
            if "-o bond1.10" in lines[n]:
                f = open('vlan10.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan10.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_15'):
            if "-o bond1.15" in lines[n]:
                f = open('vlan15.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan15.filter_out', 'a')
                f.write(l)

        # [...]

        n = n + 1
</code>```

I thought about optimizing it with some accumulator or list to not make the script so extensive. Any suggestions?

答:
I think you want to make the code cleaner, not faster. If that is so maybe this would work:

```<code>import re

parameter_re = re.compile(r'^-A vla_(\d+).*')

with open('data.csv') as f:
    lines = f.readlines()

for line in lines:
    # Match required parameter
    match = parameter_re.match(line)

    # Skip line if it doesn't match the required parameter
    if not match:
        continue

    # Extract number from parameter
    number = int(match.group(1))

    # Create output parameter string
    output_str = '-o bond1.%d' % number

    # Select correct filename to save the line
    if output_str in line:
        output_filename = 'vlan%d.filter_in' % number
    else:
        output_filename = 'vlan%d.filter_out' % number

    # Write the line to the correct file
    with open(output_filename, 'a') as f:
        f.write(line)
</code>```

And if you want to make it shorter (which I don't recommend, better for it to be readable):

```<code>import re

with open('data.csv') as f:
    lines = f.readlines()

for line in lines:
    match = re.match(r'^-A vla_(\d+).*', line)
    if not match:
        continue
    number = int(match.group(1))
    if '-o bond1.%d' % number in line:
        output_filename = 'vlan%d.filter_in' % number
    else:
        output_filename = 'vlan%d.filter_out' % number
    with open(output_filename, 'a') as f:
        f.write(line)
</code>```

Title: Optimize the for loop in python

Body:
Good, I currently have the following code:

n = 0
with open('/home/user/test.filter') as f:

    lines = f.readlines()

    for l in lines:
        if lines[n].startswith('-A vlan_8'):
            if "-o bond1.8" in lines[n]:
                    f = open('vlan8.filter_in', 'a')
                    f.write(l)
            else:
                f = open('vlan8.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_10'):
            if "-o bond1.10" in lines[n]:
                f = open('vlan10.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan10.filter_out', 'a')
                f.write(l)
        if lines[n].startswith('-A vlan_15'):
            if "-o bond1.15" in lines[n]:
                f = open('vlan15.filter_in', 'a')
                f.write(l)
            else:
                f = open('vlan15.filter_out', 'a')
                f.write(l)

        # [...]

        n = n + 1

I thought about optimizing it with some accumulator or list to not make the script so extensive. Any suggestions?

Body:
I think you want to make the code cleaner, not faster. If that is so maybe this would work:

import re

parameter_re = re.compile(r'^-A vla_(\d+).*')

with open('data.csv') as f:
    lines = f.readlines()

for line in lines:
    # Match required parameter
    match = parameter_re.match(line)

    # Skip line if it doesn't match the required parameter
    if not match:
        continue

    # Extract number from parameter
    number = int(match.group(1))

    # Create output parameter string
    output_str = '-o bond1.%d' % number

    # Select correct filename to save the line
    if output_str in line:
        output_filename = 'vlan%d.filter_in' % number
    else:
        output_filename = 'vlan%d.filter_out' % number

    # Write the line to the correct file
    with open(output_filename, 'a') as f:
        f.write(line)

And if you want to make it shorter (which I don't recommend, better for it to be readable):

import re

with open('data.csv') as f:
    lines = f.readlines()

for line in lines:
    match = re.match(r'^-A vla_(\d+).*', line)
    if not match:
        continue
    number = int(match.group(1))
    if '-o bond1.%d' % number in line:
        output_filename = 'vlan%d.filter_in' % number
    else:
        output_filename = 'vlan%d.filter_out' % number
    with open(output_filename, 'a') as f:
        f.write(line)


问:
kotlin alias property delegation throws Exception
i want to add aliases property to some class in kotlin which just delegate themselves to some existed properties

then i invent a method called alias to do so, which unfortunately results in an Exception

```<code>val <T> Array<T>.length by alias(Array<T>::size)

val <T> Collection<T>.length by alias(Collection<T>::size)

fun <R, T> alias(alias: KProperty1<R, T>) = object : ReadOnlyProperty<R, T> {
    override operator fun getValue(thisRef: R, property: KProperty<*>): T {
        return alias.get(thisRef)
    }
}
</code>```

following the exception stack

```<code>java.lang.NoSuchMethodError: [Ljava.lang.Object;.getSize()I
at kt.ruby.ArrayKt$length$2.get(Array.kt:34)
at kt.ruby.ArrayKt$alias$1.getValue(Array.kt:40)
at kt.ruby.ArrayKt.getLength(Array.kt)
</code>```

答:
It seems to be a bug. The following program crashes as well:

```<code>fun main(args: Array<String>) {
    val a: KProperty1<Array<String>, Int> = Array<String>::size
    a.get(args)
}
</code>```

The problem here is that the generated KProperty1<Array<String>> references getSize() instead of length on Object[].

```<code>final class MainKt$main$a$1 extends PropertyReference1 {
   public static final KProperty1 INSTANCE = new MainKt$main$a$1();

   public String getName() {
      return "size";
   }

   public String getSignature() {
      return "getSize()I";
   }

   public KDeclarationContainer getOwner() {
      return Reflection.getOrCreateKotlinClass(Object[].class);
   }

   @Nullable
   public Object get(@Nullable Object receiver) {
      return Integer.valueOf(((String[])receiver).getSize());
   }
}
</code>```

See KT-15618 for this.

Body:
i want to add aliases property to some class in kotlin which just delegate themselves to some existed properties

then i invent a method called alias to do so, which unfortunately results in an Exception

val <T> Array<T>.length by alias(Array<T>::size)

val <T> Collection<T>.length by alias(Collection<T>::size)

fun <R, T> alias(alias: KProperty1<R, T>) = object : ReadOnlyProperty<R, T> {
    override operator fun getValue(thisRef: R, property: KProperty<*>): T {
        return alias.get(thisRef)
    }
}

following the exception stack

java.lang.NoSuchMethodError: [Ljava.lang.Object;.getSize()I
at kt.ruby.ArrayKt$length$2.get(Array.kt:34)
at kt.ruby.ArrayKt$alias$1.getValue(Array.kt:40)
at kt.ruby.ArrayKt.getLength(Array.kt)

Body:
It seems to be a bug. The following program crashes as well:

fun main(args: Array<String>) {
    val a: KProperty1<Array<String>, Int> = Array<String>::size
    a.get(args)
}

The problem here is that the generated KProperty1<Array<String>> references getSize() instead of length on Object[].

final class MainKt$main$a$1 extends PropertyReference1 {
   public static final KProperty1 INSTANCE = new MainKt$main$a$1();

   public String getName() {
      return "size";
   }

   public String getSignature() {
      return "getSize()I";
   }

   public KDeclarationContainer getOwner() {
      return Reflection.getOrCreateKotlinClass(Object[].class);
   }

   @Nullable
   public Object get(@Nullable Object receiver) {
      return Integer.valueOf(((String[])receiver).getSize());
   }
}

See KT-15618 for this.


问:
JPA transaction rollback is not working
Hi all
   I have done an application configuration using hybernate + JPA ,and atomikos for XA transcation management and spring 3.0 and mysql is my backend,here every thing is working fine however insert operation, when exception is throwing the transcation should rollback,but it is not happening!!
   here is a small flow for our application, in our manager level we are  calling the businesss (here we are using Spring IOC)
 my

```<code>Manager.java
        insertuser()
         {
         //here we are getting transcation support from spring.

          business.insertuser();
         }
</code>```

business.java we are using one method insertuser()

```<code>insertuser()
  {
    Tauser taUser=new Tauser();
    taUser.setUsername("Maya");
    taUser.setPassword("*****")
    Dao.insertDetails(taUser);
    throw new NullPointerException("checking transcation management");
    // because  of this exception throwing,it should rollback right,
    but its not happening.The property's are commiting in to the table.

 }
</code>```

and our dao.java class we are using one method insertuser(Object entity)

```<code> void insertDetails(Object entity)
       {
        this.getJpaTemplate().persist(entity);
       }
</code>```

and our     orm.xml

```<code>       <entity class="TaUser" name="TaUser">
<table name="ta_user" />
<attributes>
    <id name="userId">
        <column name="USER_ID" />
        <generated-value strategy="AUTO" />
    </id>
    <basic name="userName">
        <column name="USER_NAME" length="50" />
    </basic>
    </attributes>
</code>```

and my persistence.xml file is

```<code><persistence-unit name="shop" transaction-type="JTA">
       <provider>org.hibernate.ejb.HibernatePersistence</provider>
         <jta-data-source>java:comp/env/jdbc/shobWeb</jta-data-source>
           <mapping-file>META-INF/orm.xml</mapping-file>
           <class>TaUser</class>
           ---------
           ---------
           ---------
           <properties>
            <property name="hibernate.transaction.manager_lookup_class"
            value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"/>
            </properties>
    </persistence-unit>
  </persistence>
</code>```

and i configured my jndi in  application/meta_inf/context.xml

```<code>  <Resource name="jdbc/shobWeb" auth="Container"
                      driverClassName="com.mysql.jdbc.Driver"
                      user="root"
                      password="root"
                      type="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"
                      factory="com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory"
                      url="jdbc:mysql://localhost:3306/shobWebSample"
                      explicitUrl="true"
                      pinGlobalTxToPhysicalConnection="true"
                      ></Resource>
</code>```

and my config file is config.xml

```<code><beans:bean id="Manager"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <beans:property name="transactionManager">
        <beans:ref bean="transactionManager" />
    </beans:property>
    <beans:property name="target">
        <beans:ref local=" ManagerTarget" />
    </beans:property>
    <beans:property name="transactionAttributes">
        <beans:props>
            <beans:prop key="*">PROPAGATION_REQUIRED</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<beans:bean id="ManagerTarget"
    class="Manager">
    <beans:property name="Business" ref="Business" />
</beans:bean>
<beans:bean id="Business" class="PaymentsBusiness">
    <beans:property name="Dao" ref=" Dao" />
</beans:bean>

<beans:bean id="Dao"
    class=" Dao">
    <beans:property name="jpaTemplate">
        <beans:ref bean="jpaTemplate" />
    </beans:property>
</beans:bean>

<beans:bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
    <beans:property name="entityManagerFactory">
        <beans:ref bean="entityManagerFactory" />
    </beans:property>
</beans:bean>

<beans:bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
 <beans:property name="persistenceUnitName" value="shop" />
    <beans:property name="jpaVendorAdapter">
        <beans:bean
            class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <beans:property name="generateDdl" value="false" />
            <beans:property name="showSql" value="true" />
         </beans:bean>
    </beans:property>
    <beans:property name="persistenceXmlLocation">
        <bean:value>classpath:META-INF/persistence.xml</beans:value>
    </beans:property>
</beans:bean>
</code>```

where is the issue? Actually when i am trying to update some property in table then transcation is working fine (rollback and commit is  happening ),but when i am trying to do insert operation rollback is not happening.

答:
The more I look at this, the more confused it looks.

First, how does the AOP config relate to your actual methods? The way it is configured, it will only create transactions around methods starting with "save" or "remove", and read-only transactions around everything else. Your method is called insertDetails, so that won't work.

Second, do you have a Spring PlatformTransactionManager configured? I don't see the configuration.

Third: Looks like you're using the default package for your classes, but defined the pointcut for classes in a package com.live.webAppl. Is that where your classes really are?

Fourth: Is there an open transaction at the point where the exception is thrown, and did the inserting method participate in that transaction? If not, then it cannot rollback. Use the debugger together with the log output to see where which transaction is created and if the insert method participates. Try raising Atomikos' log level to debug, too.

Fourth, are you stuck in a Java 1.4 codebase? Otherwise, go for annotational transaction declaration. (A lot of the ways things are done in your config and code look a little dated.)

Fifth, the convention is to use all lowercase package names. Classes start with a capital letter, members and locals lowercase. This will help the readability of your code. (For example, Dao.insertUser() looks like a static method call to anyone who can read Java. Not good.)

Title: JPA transaction rollback is not working

Body:
Hi all
   I have done an application configuration using hybernate + JPA ,and atomikos for XA transcation management and spring 3.0 and mysql is my backend,here every thing is working fine however insert operation, when exception is throwing the transcation should rollback,but it is not happening!!
   here is a small flow for our application, in our manager level we are  calling the businesss (here we are using Spring IOC)
 my

Manager.java
        insertuser()
         {
         //here we are getting transcation support from spring.

          business.insertuser();
         }

business.java we are using one method insertuser()

insertuser()
  {
    Tauser taUser=new Tauser();
    taUser.setUsername("Maya");
    taUser.setPassword("*****")
    Dao.insertDetails(taUser);
    throw new NullPointerException("checking transcation management");
    // because  of this exception throwing,it should rollback right,
    but its not happening.The property's are commiting in to the table.

 }

and our dao.java class we are using one method insertuser(Object entity)

 void insertDetails(Object entity)
       {
        this.getJpaTemplate().persist(entity);
       }

and our     orm.xml

       <entity class="TaUser" name="TaUser">

<attributes>
    <id name="userId">
        <column name="USER_ID" />
        <generated-value strategy="AUTO" />
    </id>
    <basic name="userName">
        <column name="USER_NAME" length="50" />
    </basic>
    </attributes>

and my persistence.xml file is

<persistence-unit name="shop" transaction-type="JTA">
       <provider>org.hibernate.ejb.HibernatePersistence</provider>
         <jta-data-source>java:comp/env/jdbc/shobWeb</jta-data-source>
           <mapping-file>META-INF/orm.xml</mapping-file>
           <class>TaUser</class>
           ---------
           ---------
           ---------
           <properties>
            <property name="hibernate.transaction.manager_lookup_class"
            value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"/>
            </properties>
    </persistence-unit>
  </persistence>

and i configured my jndi in  application/meta_inf/context.xml

  <Resource name="jdbc/shobWeb" auth="Container"
                      driverClassName="com.mysql.jdbc.Driver"
                      user="root"
                      password="root"
                      type="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"
                      factory="com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory"
                      url="jdbc:mysql://localhost:3306/shobWebSample"
                      explicitUrl="true"
                      pinGlobalTxToPhysicalConnection="true"
                      ></Resource>

and my config file is config.xml

<beans:bean id="Manager"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <beans:property name="transactionManager">
        <beans:ref bean="transactionManager" />
    </beans:property>
    <beans:property name="target">
        <beans:ref local=" ManagerTarget" />
    </beans:property>
    <beans:property name="transactionAttributes">
        <beans:props>
            <beans:prop key="*">PROPAGATION_REQUIRED</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<beans:bean id="ManagerTarget"
    class="Manager">
    <beans:property name="Business" ref="Business" />
</beans:bean>
<beans:bean id="Business" class="PaymentsBusiness">
    <beans:property name="Dao" ref=" Dao" />
</beans:bean>

<beans:bean id="Dao"
    class=" Dao">
    <beans:property name="jpaTemplate">
        <beans:ref bean="jpaTemplate" />
    </beans:property>
</beans:bean>

<beans:bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
    <beans:property name="entityManagerFactory">
        <beans:ref bean="entityManagerFactory" />
    </beans:property>
</beans:bean>

<beans:bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
 <beans:property name="persistenceUnitName" value="shop" />
    <beans:property name="jpaVendorAdapter">
        <beans:bean
            class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <beans:property name="generateDdl" value="false" />
            <beans:property name="showSql" value="true" />
         </beans:bean>
    </beans:property>
    <beans:property name="persistenceXmlLocation">
        <bean:value>classpath:META-INF/persistence.xml</beans:value>
    </beans:property>
</beans:bean>

where is the issue? Actually when i am trying to update some property in table then transcation is working fine (rollback and commit is  happening ),but when i am trying to do insert operation rollback is not happening.


问:
Retention Rate with MySQL
I try to calculate the retention rate with mysql and start with this one:

```<code>SELECT
    s_order.ordertime,
    DATE_SUB(future_orders.ordertime, INTERVAL 90 DAY),
    count(distinct s_order.userID) as active_users,
    count(distinct future_orders.userID) as retained_users
FROM s_order
LEFT JOIN s_order as future_orders on
      s_order.userID = future_orders.userID
      AND s_order.ordertime = DATE_SUB(future_orders.ordertime, INTERVAL 90 DAY);
</code>```

This does not work - I get all users are active and therefore I added DATE_SUB(future_orders.ordertime, INTERVAL 90 DAY), to the selection criteria to see what is going on. However it returns NULL - but why?

As a reference I did take a look at this explanation:
https://www.periscopedata.com/blog/how-to-calculate-cohort-retention-in-sql.html

My table has a structure like

```<code>s_orders:
ID | userID | ordertime
</code>```

I would expect a result how many different users have ordered something in general and how many have ordered something again in the last 90 days, to get the retention of the customers.

Does anybody know what am I doing wrong in MySQL?

答: DATE_SUB() returns null when the date value is null, so that probably why. Because you are LEFT JOIN-ing, the future_orders record can be null/non-existing</p>

Title: Retention Rate with MySQL

Body:
I try to calculate the retention rate with mysql and start with this one:

SELECT
    s_order.ordertime,
    DATE_SUB(future_orders.ordertime, INTERVAL 90 DAY),
    count(distinct s_order.userID) as active_users,
    count(distinct future_orders.userID) as retained_users
FROM s_order
LEFT JOIN s_order as future_orders on
      s_order.userID = future_orders.userID
      AND s_order.ordertime = DATE_SUB(future_orders.ordertime, INTERVAL 90 DAY);

This does not work - I get all users are active and therefore I added DATE_SUB(future_orders.ordertime, INTERVAL 90 DAY), to the selection criteria to see what is going on. However it returns NULL - but why?

As a reference I did take a look at this explanation:
https://www.periscopedata.com/blog/how-to-calculate-cohort-retention-in-sql.html

My table has a structure like

s_orders:
ID | userID | ordertime

I would expect a result how many different users have ordered something in general and how many have ordered something again in the last 90 days, to get the retention of the customers.

Does anybody know what am I doing wrong in MySQL?


问:
Filter using PrimeFaces menu bar
Is there a possibility to filter data from a JSF rich dataTable(where I use composite attributes) when using a navbar like this in page home.xhtml:

```<code>     <p:menubar>
                <p:submenu label="Categories">
                    <p:submenu label="ANTIQUES">
                        <p:menuitem value="European Antiques"></p:menuitem>
                        <p:menuitem value="Asian Antiques"></p:menuitem>
                    </p:submenu>
               </p:submenu>
    </p:menubar>
</code>```

I want to update the table's values based on the selected item(the selected items are categories from the table). The problem is that the table is in another page(listAuctions.xhtml):

```<code><h:form id="form">
        <rich:dataTable id="auctionsTable" rows="7" value="#{cc.attrs.auctions}" var="auct" border="1" styleClass="flat list auctions" rendered="#{cc.attrs.rendered and not empty cc.attrs.auctions}" filterVar="filterValue" rowClasses="odd-row, even-row">

            <rich:column sortBy="#{auct.name}" sortOrder="ascending" >
                <h:commandLink value="#{auct.name}" action="#{auctionManager.goToDetailsEnglish()}" rendered="#{auct.auctionTypes eq 'ENGLISH'}">
                    <f:param  name="auctionId" value="#{auct.id}"/>
                </h:commandLink>
                <h:commandLink value="#{auct.name}" action="#{auctionManager.goToDetailsDutch()}" rendered="#{auct.auctionTypes eq 'DUTCH'}">
                    <f:param  name="auctionId" value="#{auct.id}"/>
                </h:commandLink>
            </rich:column>
            <rich:column sortBy="#{auct.category}"
                     filterExpression="#{empty filterValue or fn:startsWith(auct.category, filterValue)}"
                     filterValue="#{filterBean.category}">
                    <f:facet name="header">CATEGORY</f:facet>
                    <h:outputText value="#{auct.category}"/>
                 </rich:column>
</code>```

...

```<code>Those 2 pages are connected in whe welcome file like this:

<ui:composition template="templates/home.xhtml">
<ui:param name="activeTab" value="list" />

<ui:define name="content">
    <h2>Auction List</h2>
    <a:listAuctions auctions="#{auctionManager.all}"/>
</ui:define>
</code>```

Thanks!

答:
Try this:

And add widgetVar to your datatable:

Title: Filter using PrimeFaces menu bar

Body:
Is there a possibility to filter data from a JSF rich dataTable(where I use composite attributes) when using a navbar like this in page home.xhtml:

I want to update the table's values based on the selected item(the selected items are categories from the table). The problem is that the table is in another page(listAuctions.xhtml):

<h:form id="form">
        <rich:dataTable id="auctionsTable" rows="7" value="#{cc.attrs.auctions}" var="auct" border="1" styleClass="flat list auctions" rendered="#{cc.attrs.rendered and not empty cc.attrs.auctions}" filterVar="filterValue" rowClasses="odd-row, even-row">

            <rich:column sortBy="#{auct.name}" sortOrder="ascending" >
                <h:commandLink value="#{auct.name}" action="#{auctionManager.goToDetailsEnglish()}" rendered="#{auct.auctionTypes eq 'ENGLISH'}">
                    <f:param  name="auctionId" value="#{auct.id}"/>
                </h:commandLink>
                <h:commandLink value="#{auct.name}" action="#{auctionManager.goToDetailsDutch()}" rendered="#{auct.auctionTypes eq 'DUTCH'}">
                    <f:param  name="auctionId" value="#{auct.id}"/>
                </h:commandLink>
            </rich:column>
            <rich:column sortBy="#{auct.category}"
                     filterExpression="#{empty filterValue or fn:startsWith(auct.category, filterValue)}"
                     filterValue="#{filterBean.category}">
                    <f:facet name="header">CATEGORY</f:facet>
                    <h:outputText value="#{auct.category}"/>
                 </rich:column>

...

Those 2 pages are connected in whe welcome file like this:

<ui:composition template="templates/home.xhtml">
<ui:param name="activeTab" value="list" />

<ui:define name="content">

Auction List

</ui:define>

Thanks!

Body:
Try this: <p:menuItem onclick="PF('dataTableWidgetVarName').filter()" />

And add widgetVar to your datatable: <p:dataTable widgetVar="dataTableWidgetVarName" ... />


问:
TYPO3 v6.2.x Tutorials for beginners
I  decided to learning TYPO3 v6.2.x CMS,I installed CMS on local server  but I can't create some basic  template, after long searching in google and here on stackoverflow, I can't find  any useful tutorials or books for beginners.

I need only tutorials  where explained how to create basic template  with TYPO3 CMS v6.x.x or maybe in "github" is some basic start kit with basic template?.

I hope some kind  people suggest me  how  and where to start.
Please don't be lazy, it`s very important for me :).

答:
First of all, TYPO3 v6.2 isn't supported anymore. I recommend you to start with v8. Not only because of the support but things have become more easy to use and extend in v8.7. Its also way faster while using php 7.1 ;)

There aren't a lot of tutorials. Most of the time learning TYPO3 is reviewing the core code and this site: http://docs.typo3.org/

The site also got an tutorial part (http://docs.typo3.org/typo3cms/GuidesAndTutorials/Index.html) BTW.

But now to some of my recommendations:

EXT:styleguide https://github.com/TYPO3/styleguide

This extension is made by the core team to test everything in the
  backend. Does not contain much of templating. But is definitely worth
  a lot of looks ;)

Next one is more something you are looking for:

EXT:bootstrap_package http://github.com/benjaminkott/bootstrap_package/

Also made by the core team. This extension brings bootstrap css based
  frontend to TYPO3.

Hope you get some inspiration from this ;)
Happy Programming!

Kami Yang

Title: TYPO3 v6.2.x Tutorials for beginners