问:
jQuery Filter with multiple Checkboxes
we have a Multiple Checkbox Filter:

Image from Checkbox Filter

The DIV containers have several classes, depending on the assigned category, there must always be at least one class checked so that they are displayed. But on loading the page should be all displayed.

Unfortunately, my script does not work properly, hope you can help me.

Best regards

$(".filter-menu :checkbox").click(function () {

 $(".grid-sort-container").fadeOut();

 if ($(this).not(':checked')) {
  $("." + $(this).val()).fadeOut();
 }

 $(".filter-menu :checkbox:checked").each(function () {
  $("." + $(this).val()).fadeIn();
 });

 $(".grid-sort-container").fadeIn();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid-sort-container {
padding: 20px 0;
}

.grid-entry {
height:20px;
width: 20px;
display: inline-block;
margin: 0 10px;
background-color: #CCCCCC;
}</code>```

Branche / Industrie

        <input type="checkbox" value="bau-bergbau_sort" id="filter-bau-bergbau_sort">
           Bau & Bergbau

        <input type="checkbox" value="energie-und-umwelt_sort" id="filter-energie-und-umwelt_sort">
         Energie & Umwelt

        <input type="checkbox" value="finanzwesen_sort" id="filter-finanzwesen_sort">
         Finanzwesen

        <input type="checkbox" value="oeffentlicher-sektor-non-profit_sort" id="filter-oeffentlicher-sektor-non-profit_sort">
         Öffentlicher Sektor & Non-Profit

        <input type="checkbox" value="gesundheit-pharma-biotechnologie_sort" id="filter-gesundheit-pharma-biotechnologie_sort">
         Gesundheit, Pharma & Biotechnologie

        <input type="checkbox" value="fertigung-elektronik_sort" id="filter-fertigung-elektronik_sort">
         Fertigung & Elektronik

        <input type="checkbox" value="dienstleistungen_sort" id="filter-dienstleistungen_sort">
         Dienstleistungen

```

答:
Use loop and check one by one:

$(".filter-menu :checkbox").change(function() {
  $(".grid-sort-container").fadeOut();

  $('.filter-menu input:checkbox').each(function() {

    if ($(this).is(':checked')) {
      //console.log($(this).val());
      $("." + $(this).val()).fadeIn();
    } else {
      $("." + $(this).val()).fadeOut();
    }
  });

  $(".grid-sort-container").fadeIn();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid-sort-container {
  padding: 20px 0;
}

.grid-entry {
  height: 20px;
  width: 20px;
  display: inline-block;
  margin: 0 10px;
  background-color: #CCCCCC;
}</code>```

Branche / Industrie

    <input type="checkbox" value="bau-bergbau_sort" id="filter-bau-bergbau_sort">
     Bau & Bergbau

    <input type="checkbox" value="energie-und-umwelt_sort" id="filter-energie-und-umwelt_sort">
     Energie & Umwelt

    <input type="checkbox" value="finanzwesen_sort" id="filter-finanzwesen_sort">
     Finanzwesen

    <input type="checkbox" value="oeffentlicher-sektor-non-profit_sort" id="filter-oeffentlicher-sektor-non-profit_sort">
     Öffentlicher Sektor & Non-Profit

    <input type="checkbox" value="gesundheit-pharma-biotechnologie_sort" id="filter-gesundheit-pharma-biotechnologie_sort">
     Gesundheit, Pharma & Biotechnologie

    <input type="checkbox" value="fertigung-elektronik_sort" id="filter-fertigung-elektronik_sort">
     Fertigung & Elektronik

    <input type="checkbox" value="dienstleistungen_sort" id="filter-dienstleistungen_sort">
     Dienstleistungen

```

Title: jQuery Filter with multiple Checkboxes

Body:
we have a Multiple Checkbox Filter:

Image from Checkbox Filter

The DIV containers have several classes, depending on the assigned category, there must always be at least one class checked so that they are displayed. But on loading the page should be all displayed.

Unfortunately, my script does not work properly, hope you can help me.

Best regards

$(".filter-menu :checkbox").click(function () {

 $(".grid-sort-container").fadeOut();

 if ($(this).not(':checked')) {
  $("." + $(this).val()).fadeOut();
 }

 $(".filter-menu :checkbox:checked").each(function () {
  $("." + $(this).val()).fadeIn();
 });

 $(".grid-sort-container").fadeIn();
});

.grid-sort-container {
padding: 20px 0;
}

.grid-entry {
height:20px;
width: 20px;
display: inline-block;
margin: 0 10px;
background-color: #CCCCCC;
}

Branche / Industrie

        <input type="checkbox" value="bau-bergbau_sort" id="filter-bau-bergbau_sort">
           Bau & Bergbau

        <input type="checkbox" value="energie-und-umwelt_sort" id="filter-energie-und-umwelt_sort">
         Energie & Umwelt

        <input type="checkbox" value="finanzwesen_sort" id="filter-finanzwesen_sort">
         Finanzwesen

        <input type="checkbox" value="oeffentlicher-sektor-non-profit_sort" id="filter-oeffentlicher-sektor-non-profit_sort">
         Öffentlicher Sektor & Non-Profit

        <input type="checkbox" value="gesundheit-pharma-biotechnologie_sort" id="filter-gesundheit-pharma-biotechnologie_sort">
         Gesundheit, Pharma & Biotechnologie

        <input type="checkbox" value="fertigung-elektronik_sort" id="filter-fertigung-elektronik_sort">
         Fertigung & Elektronik

        <input type="checkbox" value="dienstleistungen_sort" id="filter-dienstleistungen_sort">
         Dienstleistungen

Body:
Use loop and check one by one:

$(".filter-menu :checkbox").change(function() {
  $(".grid-sort-container").fadeOut();

  $('.filter-menu input:checkbox').each(function() {

    if ($(this).is(':checked')) {
      //console.log($(this).val());
      $("." + $(this).val()).fadeIn();
    } else {
      $("." + $(this).val()).fadeOut();
    }
  });

  $(".grid-sort-container").fadeIn();
});

.grid-sort-container {
  padding: 20px 0;
}

.grid-entry {
  height: 20px;
  width: 20px;
  display: inline-block;
  margin: 0 10px;
  background-color: #CCCCCC;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="filter-menu">
  <h4>Branche / Industrie</h4>
  <div>
    <input type="checkbox" value="bau-bergbau_sort" id="filter-bau-bergbau_sort">
    <label for="filter-bau-bergbau_sort"> Bau &amp; Bergbau</label>
  </div>
  <div>
    <input type="checkbox" value="energie-und-umwelt_sort" id="filter-energie-und-umwelt_sort">
    <label for="filter-energie-und-umwelt_sort"> Energie &amp; Umwelt</label>
  </div>
  <div>
    <input type="checkbox" value="finanzwesen_sort" id="filter-finanzwesen_sort">
    <label for="filter-finanzwesen_sort"> Finanzwesen</label>
  </div>
  <div>
    <input type="checkbox" value="oeffentlicher-sektor-non-profit_sort" id="filter-oeffentlicher-sektor-non-profit_sort">
    <label for="filter-oeffentlicher-sektor-non-profit_sort"> Öffentlicher Sektor &amp; Non-Profit</label>
  </div>
  <div>
    <input type="checkbox" value="gesundheit-pharma-biotechnologie_sort" id="filter-gesundheit-pharma-biotechnologie_sort">
    <label for="filter-gesundheit-pharma-biotechnologie_sort"> Gesundheit, Pharma &amp; Biotechnologie</label>
  </div>
  <div>
    <input type="checkbox" value="fertigung-elektronik_sort" id="filter-fertigung-elektronik_sort">
    <label for="filter-fertigung-elektronik_sort"> Fertigung &amp; Elektronik</label>
  </div>
  <div>
    <input type="checkbox" value="dienstleistungen_sort" id="filter-dienstleistungen_sort">
    <label for="filter-dienstleistungen_sort"> Dienstleistungen</label>
  </div>
</div>

<div class="grid-sort-container">
  <div class="grid-entry all_sort fertigung-elektronik_sort operations-management_sort"></div>
  <div class="grid-entry all_sort dienstleistungen_sort operations-management_sort"></div>
  <div class="grid-entry all_sort fertigung-elektronik_sort gesundheit-pharma-biotechnologie_sort"></div>
  <div class="grid-entry all_sort fertigung-elektronik_sort finanzwesen_sort"></div>
  <div class="grid-entry all_sort energie-und-umwelt_sort bau-bergbau_sort"></div>
  <div class="grid-entry all_sort oeffentlicher-sektor-non-profit_sort operations-management_sort"></div>
</div>


来源: stackexchange

问:
how to set custom marker for my current marker?
how to set custom marker for my current marker?

i tried this link but this doesn't work for me How do you create a Marker with a custom icon for google maps API v3?

here my code

```<code>      var markers = [
       {
           "lat": '3.214608',
           "lng": '101.639114',
       },
       {
           "lat": '3.214790',
           "lng": '101.640928',
       }
       ];

       window.onload = function () {
           LoadMap();
       }

       function LoadMap() {
           var mapOptions = {
               center: { lat: 3.214608, lng: 101.639114},
               zoom: 16,
               mapTypeId: google.maps.MapTypeId.ROADMAP
           };
           var map = new google.maps.Map(document.getElementById("map"), mapOptions);

           var infoWindow = new google.maps.InfoWindow();

           for (var i = 0; i < markers.length; i++) {
               var data = markers[i];
               var myLatlng = new google.maps.LatLng(data.lat, data.lng);
               var marker = new google.maps.Marker({
                   position: myLatlng,
                   map: map,

               });
           }

       }
</code>```

答:
add a global variable with a link to the image:

```<code>var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
</code>```

To change the size / scale etc modify the code to include:

```<code>  var icon = {
    url: image,
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0, 0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
  }
</code>```

When adding the marker use the icon variable, and assign to the icon variable

```<code> marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: simplerweb,
    icon: icon// assign image here
  });
</code>```

JSFiddle: https://jsfiddle.net/cmjcs5eL/18/

ContentLicense: CC BY-SA 3.0

Body:
how to set custom marker for my current marker?

i tried this link but this doesn't work for me How do you create a Marker with a custom icon for google maps API v3?

here my code

      var markers = [
       {
           "lat": '3.214608',
           "lng": '101.639114',
       },
       {
           "lat": '3.214790',
           "lng": '101.640928',
       }
       ];

       window.onload = function () {
           LoadMap();
       }

       function LoadMap() {
           var mapOptions = {
               center: { lat: 3.214608, lng: 101.639114},
               zoom: 16,
               mapTypeId: google.maps.MapTypeId.ROADMAP
           };
           var map = new google.maps.Map(document.getElementById("map"), mapOptions);

           var infoWindow = new google.maps.InfoWindow();

           for (var i = 0; i < markers.length; i++) {
               var data = markers[i];
               var myLatlng = new google.maps.LatLng(data.lat, data.lng);
               var marker = new google.maps.Marker({
                   position: myLatlng,
                   map: map,

               });
           }

       }

Body:
add a global variable with a link to the image:

var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';

To change the size / scale etc modify the code to include:

  var icon = {
    url: image,
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0, 0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
  }

When adding the marker use the icon variable, and assign to the icon variable

 marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: simplerweb,
    icon: icon// assign image here
  });

JSFiddle: https://jsfiddle.net/cmjcs5eL/18/


问:
How do I select an element with special characters in the ID?
I have a page with a grid containing a lot if input with "strange names" to simulate an array:

```<code> <input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />
</code>```

How can I set the value of these inputs with jQuery, specifically, how would I select them? I tried in a lot of ways but nothing works.

答:
The problem is that brackets have special meaning in CSS (as attribute selectors) and dots do too, as class selectors. Try $.escapeSelector:

```<code>$('#' + $.escapeSelector('Punteggi[@counter].Descrizione'))
</code>```

This will escape the selector so the special characters don't affect the selection. You could also try using an attribute selector and wrapping that in quotes:

```<code>$('[id="Punteggi[@counter].Descrizione"]')
</code>```

This will literally match that ID and won't treat any of the special characters as special characters.

Body:
I have a page with a grid containing a lot if input with "strange names" to simulate an array:

 <input type="text" id="Punteggi[@counter].Descrizione" readonly="readonly" tabindex="-1" name="Punteggi[@counter].Descrizione" class="{validate: {required:true}}" value="@item.Descrizione" />

How can I set the value of these inputs with jQuery, specifically, how would I select them? I tried in a lot of ways but nothing works.

Body:
The problem is that brackets have special meaning in CSS (as attribute selectors) and dots do too, as class selectors. Try $.escapeSelector:

$('#' + $.escapeSelector('Punteggi[@counter].Descrizione'))

This will escape the selector so the special characters don't affect the selection. You could also try using an attribute selector and wrapping that in quotes:

$('[id="Punteggi[@counter].Descrizione"]')

This will literally match that ID and won't treat any of the special characters as special characters.


问:
Create loadbalancer inside a vnet with azure
I want to create a load balancer for all my agents.
In the official docs I found a guide for an external load balancer, but I want to connect it with the api management so it has to be only visible in the vnet.

This post works if you only have one agent (you enter the private ip of the agent in your api route). But it does not handle the second agent.
Is it possible to use Azure API Management and Azure ACS (kubernetes) as frontend and backend?

So in my case I need to create a load balancer that handles all agents for the service and has a private ip in a vnet in that the api management service also is.

答:
As 4c74356b41 said, we can't add a VM to two backend pools (if your k8s create via azure portal, the agents in a VMSS.)

In your scenario, I think we can create a VM in ACS resource group, and install load balance software on it, make this VM work as a load balancer.

For example, we can use Haproxy to load balance the network traffic to agents.


问:
Flexbox and Internet Explorer 11 (display:flex in ?)
I am planning to move away from "floaty" layouts and use CSS flexbox for future projects. I was delighted to see that all major browsers in their current versions seem to support (in one way or another) flexbox.

I headed over to "Solved by Flexbox" to look at some examples. However the "Sticky Footer" example does not seem to work in Internet Explorer 11. I played around a bit and got it to work by adding display:flex to the  and width:100% to the

So my first question is: Can anybody explain that logic to me? I just fiddled around and it worked, but I don't quite understand why it worked that way...

Then there is the "Media Object" example that works in all browsers except for - you guessed it - Internet Explorer. I fiddled around with that, too, but without any success.

My second question therefore is: Is there a "clean" possibility to get the "Media Object" example working in Internet Explorer?

答:
Here is an example of using flex that also works in Internet Explorer 11 and Chrome.

HTML

<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Flex Test</title>

            test test test

```

ContentLicense: CC BY-SA 4.0

Title: Flexbox and Internet Explorer 11 (display:flex in <html>?)

Body:
Here is an example of using flex that also works in Internet Explorer 11 and Chrome.

HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Flex Test</title>
<style>
html, body {
    margin: 0px;
    padding: 0px;
    height: 100vh;
}
.main {
    display: -webkit-flex;
    display: flex;
    -ms-flex-direction: row;
    flex-direction: row;
    align-items: stretch;
    min-height: 100vh;
}

.main::after {
  content: '';
  height: 100vh;
  width: 0;
  overflow: hidden;
  visibility: hidden;
  float: left;
}

.left {
    width: 200px;
    background: #F0F0F0;
    flex-shrink: 0;
}

.right {
    flex-grow: 1;
    background: yellow;
}
</style>
</head>

<body>
<div class="main">
    <div class="left">
        <div style="height: 300px;">
        </div>
    </div>

    <div class="right">
        <div style="height: 1000px;">
            test test test
        </div>
    </div>
</div>
</body>
</html>


问:
Add-Computer adds VM to domain then WMI fails
I am currently trying to add a Windows Server 2016 Vm to our domain using the following command.

```<code>Add-Computer -ComputerName $ServerName -NewName $ServerName -LocalCredential $localCreds -Credential $adcreds -DomainName mydomain.net -OUPath $ou -Force
</code>```

The command creates the AD computer object and renames the server pending its reboot.

However, the cmdlet runs for about 15 minutes then gives us the following error:

```<code>Add-Computer : Cannot establish the WMI connection to the computer 'SERVER' with the following error message: The remote procedure call failed. (Exception from HRESULT: 0x800706BE).
</code>```

We are not experiencing this issue at all with our Windows Server 2012 R2 Build.

答:
Looks like failed authentication. You can try to connect to the remote computer by the following code example:

```<code>Net use \$servername\IPC$ /User:Administrator $LocalCreds.GetNetworkcredential().password
</code>```

After that, try your command again.

Body:
I am currently trying to add a Windows Server 2016 Vm to our domain using the following command.

Add-Computer -ComputerName $ServerName -NewName $ServerName -LocalCredential $localCreds -Credential $adcreds -DomainName mydomain.net -OUPath $ou -Force

The command creates the AD computer object and renames the server pending its reboot.

However, the cmdlet runs for about 15 minutes then gives us the following error:

Add-Computer : Cannot establish the WMI connection to the computer 'SERVER' with the following error message: The remote procedure call failed. (Exception from HRESULT: 0x800706BE).

We are not experiencing this issue at all with our Windows Server 2012 R2 Build.

Body:
Looks like failed authentication. You can try to connect to the remote computer by the following code example:

Net use \$servername\IPC$ /User:Administrator $LocalCreds.GetNetworkcredential().password

After that, try your command again.


问:
Scanning multiple files and printing them alphabetically
I'm reading multiple text files using Java and printing their directories and I wonder why the output is not alphabetically arranged?

Code Snippet (got it from the internet also)

```<code>File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
    System.out.println(path);
}
</code>```

Output:

```<code>dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$
</code>```

Can I do it with the output being:

```<code>a.txt
b.txt
c.txt
</code>```

Thank you in advance!

答:
To quote File#listDir's documentation:

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

If you want to print them in a specific order, you'll have to do so yourself. Java 8 streams git you an elegant way of combining the extraction of the file's name from the patch and sorting them in a single statement:

```<code>Arrays.stream(listOfFiles)
      .map(File::getName)
      .sorted()
      .forEach(System.out::println);
</code>```

Body:
I'm reading multiple text files using Java and printing their directories and I wonder why the output is not alphabetically arranged?

Code Snippet (got it from the internet also)

File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
    System.out.println(path);
}

Output:

dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$

Can I do it with the output being:

a.txt
b.txt
c.txt

Thank you in advance!

Body:
To quote File#listDir's documentation:

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

If you want to print them in a specific order, you'll have to do so yourself. Java 8 streams git you an elegant way of combining the extraction of the file's name from the patch and sorting them in a single statement:

Arrays.stream(listOfFiles)
      .map(File::getName)
      .sorted()
      .forEach(System.out::println);


问:
Select from multiple tables with same condition, avoid ambiguity error
How can I do something like this but avoid the error column common_reference is ambiguous? I know it's ambiguous, I want to select from table_one all the results for common_reference there, and table_two the same.

SELECT * FROM table_one, table_two WHERE common_reference = 42

This is obviously not going to work, so how do I use subqueries to achieve what I need?

答:
```<code>SELECT table_one.* FROM table_one, table_two WHERE table_one.common_reference = 42
</code>```

ContentLicense: CC BY-SA 2.5


问:
Is it possible the knockout ignores 'data-bind=with..." ?
Please take a look at the following code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
    <form data-bind="with: selectedMerchant">
        <h1 data-bind="text: name"></h1>
        <button data-bind="click: show"> SHOW </button>
    </form>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-debug.js" type="text/javascript"></script>
    <script>
        function PartnersViewModel() {
            self.selectedMerchant = ko.observable({'name': 'John'});
            self.show = function() {
                alert(JSON.stringify(self.selectedMerchant()));
            }
        }
        ko.applyBindings(new PartnersViewModel());
    </script>
</body>
</html>
</code>```

As you can see, the line:

```<code><form data-bind="with: selectedMerchant">
</code>```

makes the object 'selectedMerchant' the binding context of the form. That's why inside the 'h1'-tag, we'll see the name 'John'.

However, the line:

```<code><button data-bind="click: show"> SHOW </button>
</code>```

says (as I understand) that once the button is clicked, the method "show" inside the object 'selectedMerchant' will be invoked. Of course this method doesn't exist inside selectedMerchant, so I expect to see an Error.

To my surprise, it works correctly and I get a pop-up window saying:

{'name': 'John'}

I don't understand why knockout.js invokes a method which is outside the object 'selectedMerchant'. Does anyone have a good explanation?

答:
You are missing the var self = this; from the beginning of your view model declaration.

Without declaring self the line self.show = function() { ... declares a global show function on the window object that is why KO can find this handler.

So with properly declaring self your code will give the expected error: Message: show is not defined

```<code><script>
    function PartnersViewModel() {
        var self = this;
        self.selectedMerchant = ko.observable({'name': 'John'});
        self.show = function() {
            alert(JSON.stringify(self.selectedMerchant()));
        }
    }
    ko.applyBindings(new PartnersViewModel());
</script>
</code>```

Body:
Please take a look at the following code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <form data-bind="with: selectedMerchant">

        <button data-bind="click: show"> SHOW </button>
    </form>

As you can see, the line:

<form data-bind="with: selectedMerchant">

makes the object 'selectedMerchant' the binding context of the form. That's why inside the 'h1'-tag, we'll see the name 'John'.

However, the line:

<button data-bind="click: show"> SHOW </button>

says (as I understand) that once the button is clicked, the method "show" inside the object 'selectedMerchant' will be invoked. Of course this method doesn't exist inside selectedMerchant, so I expect to see an Error.

To my surprise, it works correctly and I get a pop-up window saying:

{'name': 'John'}

I don't understand why knockout.js invokes a method which is outside the object 'selectedMerchant'. Does anyone have a good explanation?

Body:
You are missing the var self = this; from the beginning of your view model declaration.

Without declaring self the line self.show = function() { ... declares a global show function on the window object that is why KO can find this handler.

So with properly declaring self your code will give the expected error: Message: show is not defined

<script>
    function PartnersViewModel() {
        var self = this;
        self.selectedMerchant = ko.observable({'name': 'John'});
        self.show = function() {
            alert(JSON.stringify(self.selectedMerchant()));
        }
    }
    ko.applyBindings(new PartnersViewModel());
</script>


问:
Force entity framework to add identity column
This issue is solved for me in this thread
How can I force entity framework to insert identity columns?

But what I need to know that if I set

```<code>dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
</code>```

before I call the SaveChanges() method will it have the same effect?, I mean why should I turn Identity to off after I call SaveChanges().

答:
I was doing this exact thing a few days ago. Using

```<code>dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Table] ON");
</code>```

and

```<code>dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Table] OFF");
</code>```

did nothing.

I had to use a SQL Command that turned it on, did what I wanted to do, and then turned it off within the same command.

Body:
This issue is solved for me in this thread
How can I force entity framework to insert identity columns?

But what I need to know that if I set

dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");

before I call the SaveChanges() method will it have the same effect?, I mean why should I turn Identity to off after I call SaveChanges().

Body:
I was doing this exact thing a few days ago. Using

dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Table] ON");

and

dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Table] OFF");

did nothing.

I had to use a SQL Command that turned it on, did what I wanted to do, and then turned it off within the same command.


问:
SQL Alchemy query multiple tables
I am trying to make a query using SQL alchemy which would otherwise been very simple if  I wasn't using ORM, so I am thinking to myself surely there must be a straightforward way. I have gone through most of the questions on this topic but don't seem to answer my question. I have these two tables

```<code>class Artisan(Base):
    __tablename__ = 'artisan'
    name = Column(String(80), nullable=False)
    skill = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    bio = Column(String(300))
    category = Column(Integer, ForeignKey(Category.id))
    user = Column(Integer, ForeignKey(Users.id))
    id_no = Column(Integer, nullable=False)
    users = relationship(Users)
</code>```

and

```<code>class Address(Base):
    __tablename__ = 'address'
    building = Column(String(80), nullable=False)
    floor = Column(String(80), nullable=False)
    house_no = Column(String(80), nullable=False)
    telephone = Column(String(80), nullable=False)
    kwetu_address = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    lat = Column(String(25))
    lng = Column(String(25))
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)
</code>```

I would like to filter the Artisans by a category, then filter the addresses by the filtered artisans, and present the results in a way that associates the artisan with respective addresses hopefully getting sqlachemy to do the filtering

The best I can come up with involves two queries and post processing which I feel is very inefficient

```<code>my_artisans = (session.query(Artisan).filter_by(category=cat_id))
my_addresses = (session.query(Address)
                        .join(Artisan, Artisan.id ==Address.artisan).filter_by(category=cat_id))
return jsonify(artisans =[art.serialize for art in my_artisans], addresses=[add.serialize for add in my_addresses])
</code>```

Thanks

Add on - all related classes

```<code>import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Users(Base):
    __tablename__ = 'users'
    name = Column(String(80), nullable=False)
    email = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    bio = Column(String(300))
    picture = Column(String(80))

class Category(Base):
    __tablename__ = 'category'
    name = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'name': self.name
        }

class Artisan(Base):
    __tablename__ = 'artisan'
    name = Column(String(80), nullable=False)
    skill = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    bio = Column(String(300))
    category = Column(Integer, ForeignKey(Category.id))
    user = Column(Integer, ForeignKey(Users.id))
    id_no = Column(Integer, nullable=False)
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'name': self.name,
            'skill': self.skill,
            'category': self.category,
            'bio': self.bio,
            'id_no': self.id_no

        }

class Portfolio(Base):
    __tablename__ = 'portfolio'
    title = Column(String(80), nullable=False)
    details = Column(String(300), nullable=False)
    id = Column(Integer, primary_key=True)
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'title': self.title,
            'details': self.details
        }

class Endorsements(Base):
    __tablename__ = 'endorsements'
    title = Column(String(80), nullable=False)
    details = Column(String(300), nullable=False)
    id = Column(Integer, primary_key=True)
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'title': self.title,
            'details': self.details
        }

class Address(Base):
    __tablename__ = 'address'
    building = Column(String(80), nullable=False)
    floor = Column(String(80), nullable=False)
    house_no = Column(String(80), nullable=False)
    telephone = Column(String(80), nullable=False)
    kwetu_address = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    lat = Column(String(25))
    lng = Column(String(25))
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'lat': self.lat,
            'lng': self.lng,
            'kwetu_address': self.kwetu_address,
            'artisan': self.artisan
        }

engine = create_engine('sqlite:///mycatalog.db')

Base.metadata.create_all(engine)
</code>```

答:
This gave me what I needed in terms of associating my artisan with respective addresses, though still using two queries</p>

```<code>my_artisans = (session.query(Artisan).filter_by(category=cat_id))
my_addresses = (session.query(Address)
                        .join(Artisan, Artisan.id ==Address.artisan).filter_by(category=cat_id))
these_addresses = []
for art in my_artisans:
   art_id = art.id
   for add in my_addresses:
       if art_id == add.artisan:
           grouped_address = {"Artisan Id" : art.id, "name" : art.name, "skill" : art.skill, "Lat" : add.lat, "lng" : add.lng}
                these_addresses.append(grouped_address)

    return jsonify({'Addresses': these_addresses })
</code>```

Title: SQL Alchemy query multiple tables

Body:
I am trying to make a query using SQL alchemy which would otherwise been very simple if  I wasn't using ORM, so I am thinking to myself surely there must be a straightforward way. I have gone through most of the questions on this topic but don't seem to answer my question. I have these two tables

class Artisan(Base):
    __tablename__ = 'artisan'
    name = Column(String(80), nullable=False)
    skill = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    bio = Column(String(300))
    category = Column(Integer, ForeignKey(Category.id))
    user = Column(Integer, ForeignKey(Users.id))
    id_no = Column(Integer, nullable=False)
    users = relationship(Users)

and

class Address(Base):
    __tablename__ = 'address'
    building = Column(String(80), nullable=False)
    floor = Column(String(80), nullable=False)
    house_no = Column(String(80), nullable=False)
    telephone = Column(String(80), nullable=False)
    kwetu_address = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    lat = Column(String(25))
    lng = Column(String(25))
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

I would like to filter the Artisans by a category, then filter the addresses by the filtered artisans, and present the results in a way that associates the artisan with respective addresses hopefully getting sqlachemy to do the filtering

The best I can come up with involves two queries and post processing which I feel is very inefficient

my_artisans = (session.query(Artisan).filter_by(category=cat_id))
my_addresses = (session.query(Address)
                        .join(Artisan, Artisan.id ==Address.artisan).filter_by(category=cat_id))
return jsonify(artisans =[art.serialize for art in my_artisans], addresses=[add.serialize for add in my_addresses])

Thanks

Add on - all related classes

import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Users(Base):
    __tablename__ = 'users'
    name = Column(String(80), nullable=False)
    email = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    bio = Column(String(300))
    picture = Column(String(80))

class Category(Base):
    __tablename__ = 'category'
    name = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'name': self.name
        }

class Artisan(Base):
    __tablename__ = 'artisan'
    name = Column(String(80), nullable=False)
    skill = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    bio = Column(String(300))
    category = Column(Integer, ForeignKey(Category.id))
    user = Column(Integer, ForeignKey(Users.id))
    id_no = Column(Integer, nullable=False)
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'name': self.name,
            'skill': self.skill,
            'category': self.category,
            'bio': self.bio,
            'id_no': self.id_no

        }

class Portfolio(Base):
    __tablename__ = 'portfolio'
    title = Column(String(80), nullable=False)
    details = Column(String(300), nullable=False)
    id = Column(Integer, primary_key=True)
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'title': self.title,
            'details': self.details
        }

class Endorsements(Base):
    __tablename__ = 'endorsements'
    title = Column(String(80), nullable=False)
    details = Column(String(300), nullable=False)
    id = Column(Integer, primary_key=True)
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'title': self.title,
            'details': self.details
        }

class Address(Base):
    __tablename__ = 'address'
    building = Column(String(80), nullable=False)
    floor = Column(String(80), nullable=False)
    house_no = Column(String(80), nullable=False)
    telephone = Column(String(80), nullable=False)
    kwetu_address = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    lat = Column(String(25))
    lng = Column(String(25))
    artisan = Column(Integer, ForeignKey(Artisan.id))
    user = Column(Integer, ForeignKey(Users.id))
    users = relationship(Users)

    @property
    def serialize(self):
        return{
            'id': self.id,
            'lat': self.lat,
            'lng': self.lng,
            'kwetu_address': self.kwetu_address,
            'artisan': self.artisan
        }

engine = create_engine('sqlite:///mycatalog.db')

Base.metadata.create_all(engine)

Body:
This gave me what I needed in terms of associating my artisan with respective addresses, though still using two queries

my_artisans = (session.query(Artisan).filter_by(category=cat_id))
my_addresses = (session.query(Address)
                        .join(Artisan, Artisan.id ==Address.artisan).filter_by(category=cat_id))
these_addresses = []
for art in my_artisans:
   art_id = art.id
   for add in my_addresses:
       if art_id == add.artisan:
           grouped_address = {"Artisan Id" : art.id, "name" : art.name, "skill" : art.skill, "Lat" : add.lat, "lng" : add.lng}
                these_addresses.append(grouped_address)

    return jsonify({'Addresses': these_addresses })


问:
Using Apache POI - Zip Bomb detected
When I am trying to write data to an Excel sheet, using Apache POI which contains more than 64000 records, where SXSSF is used, I am getting the below error:

Zip bomb detected! The file would exceed the max. ratio of compressed file size to the size of the expanded data. This may indicate that the file is used to inflate memory usage and thus could pose a security risk. You can adjust this limit via ZipSecureFile.setMinInflateRatio() if you need to work with files which exceed this limit. Counter: 820224, cis.counter: 8192, ratio: 0.009987515605493134Limits: MIN_INFLATE_RATIO: 0.01

I found a solution stating by adding ZipSecureFile.setMinInflateRatio(0.009), but why is it happening and what is the limit I need to provide for the above error? And where should I add the solution?

Reference for the solution: How can I determine if a Zip Bomb error thrown when retrieving an Excel files Styles Table is legitimate?

Is there another solution for this?

答:
"Zip bomb" is a term used for an attack vector where a small zip file expands to a very large uncompressed file and thus can cause issues like exhausting memory or disk space.

Usually such zips are created with the intent of causing a denial of service attack on systems that receive zip files from external sources.

As .xlsx files are actually zipped files which contain XML files, there is a chance of causing such a zip bomb vulnerability in POI.

In order to prevent this from happening, Apache POI has some safeguards built in and enabled by default. So if you create a file with unusual content, e.g. many rows/columns with the same content, you can run into these safeguards and receive the exception as shown above.

If you fully control the creation of the processed files, you can adjust the setting given in the error message to avoid the exception.

See https://bz.apache.org/bugzilla/show_bug.cgi?id=58499 for the related issue and ZIp-bomb exception while writing a large formatted Excel (.xlsx) and How to determine if a Zip Bomb error thrown when retrieving an Excel files Styles Table is legitimate? for similar discussions.

Title: Using Apache POI - Zip Bomb detected


问:
What common database is used with ASP?
I know PHP and how to use MySQL with it but now I am moving onto ASP but which common database is used with ASP (ie. the equivalent to MySQL)?</p>

答: MS SQL server is commonly used with ASP (Classic and .NET). There are many different versions of SQL (SQL Express, Standard Edition, Enterprise etc)</p>

Title: What common database is used with ASP?


问:
How to handle login errors with Ionic custom auth?
I'm trying to implement a user login with Ionic Cloud's Auth Service, and would prefer to no show the Cordova inAppBrowser. In case of an authentication error (e.g. wrong password), I would expect the error handler to fire, but for some reason this never seems to be the case.

The method in my login component contains this:

```<code>let loginData = {
  email: this.email,
  password: this.password
};
let loginOptions: AuthLoginOptions = {
  inAppBrowserOptions: {
    hidden: true
  }
};
this.auth.login('custom', loginData, loginOptions).then(() => {
  console.log('login success');
}, (err) => {
  console.log('login error', err); // <-- this never gets executed.
});
</code>```

I made sure that my authentication server responds with an HTTP status of 401 and a JSON body that contains an error property. This is the code (PHP, Laravel 3):

```<code>  public function get_login()
  {
    try {
      $redirect_uri = CustomAuthentication::process(
        $_GET['token'],
        $_GET['state'],
        $_GET['redirect_uri']
      );
      return Redirect::to($redirect_uri);
    } catch (\Exception $e) {
      return Response::json(array(
        'ok' => false,
        'error' => $e->getMessage(),
        'code' => $e->getCode()
      ), 401);
    }
  }
</code>```

I found two issues on github that seem relevant:

https://github.com/driftyco/ionic-cloud/issues/53

https://github.com/driftyco/ionic-cloud-angular/issues/22

Apparently there is no way to get this to work at the moment, when the inAppBrowser is hidden. Or is there another option?

In case there's no way to achieve this for now, what would be an alternative, in order to provide the users with a nice login flow, that shoes them a meaningful error message for unsuccessful login attempts?

Should I try to implement this with a visible inAppBrowser? If so, where can I find docs or an example?

Unfortunately the official docs don't tell much (http://docs.ionic.io/services/auth/custom-auth.html#login) and the tutorials I found are  outdated.

答:
anyErrors : any;

in the controller.ts file

```<code>this.auth.login('basic', details).then(() => {
    this.isUserLoggedIn = true; // <------ Debug here (1)
   this.currentUserData = this.user;
   console.log(this.currentUserData);
    return this.currentUserData;
}, (err: IDetailedError) => {
this.anyErrors= err; // map the error here

});
</code>```

in the html file

      <ion-row >
        <ion-item  >
          <ion-label text-wrap color=red color="primary" >
    {{anyErrors}}
    </ion-label>
  </ion-item>
      </ion-row>

```

So any error in ionic .ts will flow the the html page I use this for the login page. i.e below the login submit button, i have the above div code. if there is no error the msg will not display, if there is an error msg it will display.

Body:
I'm trying to implement a user login with Ionic Cloud's Auth Service, and would prefer to no show the Cordova inAppBrowser. In case of an authentication error (e.g. wrong password), I would expect the error handler to fire, but for some reason this never seems to be the case.

The method in my login component contains this:

let loginData = {
  email: this.email,
  password: this.password
};
let loginOptions: AuthLoginOptions = {
  inAppBrowserOptions: {
    hidden: true
  }
};
this.auth.login('custom', loginData, loginOptions).then(() => {
  console.log('login success');
}, (err) => {
  console.log('login error', err); // <-- this never gets executed.
});

I made sure that my authentication server responds with an HTTP status of 401 and a JSON body that contains an error property. This is the code (PHP, Laravel 3):

  public function get_login()
  {
    try {
      $redirect_uri = CustomAuthentication::process(
        $_GET['token'],
        $_GET['state'],
        $_GET['redirect_uri']
      );
      return Redirect::to($redirect_uri);
    } catch (\Exception $e) {
      return Response::json(array(
        'ok' => false,
        'error' => $e->getMessage(),
        'code' => $e->getCode()
      ), 401);
    }
  }

I found two issues on github that seem relevant:

https://github.com/driftyco/ionic-cloud/issues/53

https://github.com/driftyco/ionic-cloud-angular/issues/22

Apparently there is no way to get this to work at the moment, when the inAppBrowser is hidden. Or is there another option?

In case there's no way to achieve this for now, what would be an alternative, in order to provide the users with a nice login flow, that shoes them a meaningful error message for unsuccessful login attempts?

Should I try to implement this with a visible inAppBrowser? If so, where can I find docs or an example?

Unfortunately the official docs don't tell much (http://docs.ionic.io/services/auth/custom-auth.html#login) and the tutorials I found are  outdated.

Body:
anyErrors : any;

in the controller.ts file

this.auth.login('basic', details).then(() => {
    this.isUserLoggedIn = true; // <------ Debug here (1)
   this.currentUserData = this.user;
   console.log(this.currentUserData);
    return this.currentUserData;
}, (err: IDetailedError) => {
this.anyErrors= err; // map the error here

});

in the html file

<div >
      <ion-row >
        <ion-item  >
          <ion-label text-wrap color=red color="primary" >
    {{anyErrors}}
    </ion-label>
  </ion-item>
      </ion-row>
    </div>

So any error in ionic .ts will flow the the html page I use this for the login page. i.e below the login submit button, i have the above div code. if there is no error the msg will not display, if there is an error msg it will display.


问:
Setting text on TextView from background thread anomaly
I've just started playing with Android Concurrency/Loopers/Handers, and I have just faced with strange anomaly. The code below doesn't block me from setting text on TextView from different Thread.

```<code>TextView tv;
Handler backgroundHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView) findViewById(R.id.sample_text);
    Runnable run = new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            backgroundHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    String text = (String) msg.obj;
                    tv.setText(Thread.currentThread().getName() + " " + text);
                }
            };
            Looper.loop();
        }
    };

    Thread thread = new Thread(run);
    thread.setName("Background thread");
    thread.start();
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Message message = backgroundHandler.obtainMessage();
    message.obj = "message from UI";
    backgroundHandler.sendMessage(message);
}
</code>```

And guess what happen

But, when I sleep background thread for a while

```<code>backgroundHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String text = (String) msg.obj;
                tv.setText(Thread.currentThread().getName() + " " + text);
            }
        };
</code>```

it does throw exception as I expected

```<code>07-03 18:54:40.506 5996-6025/com.stasbar.tests E/AndroidRuntime: FATAL EXCEPTION: Background thread
                                                             Process: com.stasbar.tests, PID: 5996
                                                             android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                                                                 at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7275)
</code>```

Can someone explain me what happened ? Why I was able to set text from different thread ?

答:
From the very first try, your code is wrong because you created Handler on different thread. This leads to looper/handler is run on different thread. Based on your comment, I guess you know this issue and you want to understand why exception doesn't throw on first try but second.

You should beware this: Accessing UI Element on different thread except from UI Thread causes undefined behavior. This means:

Sometime you see it works.

sometime you don't. You will meet exception as you have seen.

That means Accessing UI Element on different thread isn't always 100% reproducible.

Why you should access all UI Elements only on UI Thread? Because processing UI Element (change internal state, draw to screen ...) is a complex process and need to synchronized between related parties. For example, you call TextView#setText(String) on 2 fragments that both visible on screen. Android doesn't do this concurrently but pushing all jobs into an UI message queue and do that sequentially. This is also true not only from your application viewpoint but also from whole Android system perspective. Updating from status bar that called by system, updating from your app that called by your application always push actions to same UI Message queue before processing.

When you access and modify UI elements on different thread, you broke that process. That means maybe two threads might access and modify an element at same state and same time. As the result, you will meet race condition at some time. That when error occurs.

Explaining for your situation is hard because not enough data for analyzing. But there are some few reasons:

At your first try, TextView haven't displayed on screen yet. So different thread was able to make change on TextView. But on your second try, you sleep for 1 second. At this time, all view has rendered and displayed successfully on screen, so exception threw. You can try Thread.sleep(0) and hopefully your code doesn't crash.

This is will happen in some situations but hard to guess why. That by some chance, both your thread and ui thread accesses same lock object, exception threw.

You can read more about thread issue here Android Thread

Explicit references

Many tasks on non-main threads have the end goal
  of updating UI objects. However, if one of these threads accesses an
  object in the view hierarchy, application instability can result: If a
  worker thread changes the properties of that object at the same time
  that any other thread is referencing the object, the results are
  undefined.

Hope this help you.

Body:
I've just started playing with Android Concurrency/Loopers/Handers, and I have just faced with strange anomaly. The code below doesn't block me from setting text on TextView from different Thread.

TextView tv;
Handler backgroundHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView) findViewById(R.id.sample_text);
    Runnable run = new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            backgroundHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    String text = (String) msg.obj;
                    tv.setText(Thread.currentThread().getName() + " " + text);
                }
            };
            Looper.loop();
        }
    };

    Thread thread = new Thread(run);
    thread.setName("Background thread");
    thread.start();
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Message message = backgroundHandler.obtainMessage();
    message.obj = "message from UI";
    backgroundHandler.sendMessage(message);
}

And guess what happen

But, when I sleep background thread for a while

backgroundHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String text = (String) msg.obj;
                tv.setText(Thread.currentThread().getName() + " " + text);
            }
        };

it does throw exception as I expected

07-03 18:54:40.506 5996-6025/com.stasbar.tests E/AndroidRuntime: FATAL EXCEPTION: Background thread
                                                             Process: com.stasbar.tests, PID: 5996
                                                             android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                                                                 at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7275)

Can someone explain me what happened ? Why I was able to set text from different thread ?


问:
why javascript Speech Recognition api is not working without internet?
I was working with javascript speech recognition api(new webkitSpeechRecognition()) and i amazed why it is not working without internet since it is javascript code so it should work offline

I checked the network section of chrome developer tools, it is even not making request to internet

答:
Looking at https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition:

SpeechRecognition.serviceURI
 Specifies the location of the speech recognition service used by the current SpeechRecognition to
  handle the actual recognition. The default is the user agent's default
  speech service.

The actual recognition is done by a 3rd party server.
I assume the task of speech recognition currently is just too much for a browser to cope with on it's own or requires a big database.


问:
Automated string insertion on windows
Normally I'm a mac person, but at my new job I'm finding myself using a PC. I often have to open html files and for every href link insert a target blank argument. Rather then do this manually I was wondering if there was a script that I could use to automate the process. Say:

search for href

find the second double quotation after the href string

insert the string "target = _blank"

Mind you I have never used a shell script on a PC in my life, so much explanation might be needed here.

Thanks,

答:
I don't believe the windows shell is very powerful, so even if it is possible to achieve I can't imagine it'll be easy. I would strongly advise using a real scripting language such as Python or Perl, or bash if that's what you're familiar with. You can install pretty much all of them on Windows (see links).

I presume you can solve the problem from there, as your major concern seemed to be with Windows.

Title: Automated string insertion on windows


问:
When UITableViewCell's accessoryType was inited?
I am using storyboard for UITableView prototype cell and set the accessoryType to Disclosure Indicator. The arrow one ">". I want to know when the arrow image was added or where can i get it correctly?

Here is the UIImageView i want to get.

My test() function below prints [], only when i scroll the tableview then it prints correct.

```<code>[<UIImageView: 0x7fc614766050; frame = (0 0; 8 13); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x618000435f00>> - (null)]
</code>```

I also tried:
cellForRowAt and willDisplay, both can't get the UIImageView only if by scrolling the tableView it works.

My customize UITableViewCell class:

```<code>class TestCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        test()
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        test()
        self.accessoryType
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        test()
    }

    func test() {
        print(subviews[2].subviews)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        test()
        // Configure the view for the selected state
    }
}
</code>```

答:
you override layoutSubviews of the custom cell class and when that is called, delegate to super class first and then check the view hierarchy over and over till you find it.

it is the best you get. not fool proof as you deal with private view hierarchy that isnt yours ;) but it works - we did it for years.

note too that the view hierarchy can change between any iOS releases. it isnt like this is public api. so program extra defensively

Body:
I am using storyboard for UITableView prototype cell and set the accessoryType to Disclosure Indicator. The arrow one ">". I want to know when the arrow image was added or where can i get it correctly?

Here is the UIImageView i want to get.

My test() function below prints [], only when i scroll the tableview then it prints correct.

[<UIImageView: 0x7fc614766050; frame = (0 0; 8 13); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x618000435f00>> - (null)]

I also tried:
cellForRowAt and willDisplay, both can't get the UIImageView only if by scrolling the tableView it works.

My customize UITableViewCell class:

class TestCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        test()
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        test()
        self.accessoryType
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        test()
    }

    func test() {
        print(subviews[2].subviews)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        test()
        // Configure the view for the selected state
    }
}


问:
Use one component in multiple states with different service methods
I want to build a component that I would be able to re-use in different states, because the functions it performs are quite similar. The problem is that it is supposed to use different methods from my service according to the state where it is rendered. Considering I've got these states:

```<code>$stateProvider
    .state('create', {
        url: 'create',
        component: 'myComponent',
        resolve: {
           data: function (myService) {
               return myService.getData();
           }
        }
    })
    .state('edit', {
         url: 'edit',
         component: 'myComponent',
         // another resolve
    })
    // and so on
</code>```

And I have a service with the following methods:

```<code>class myService {
    // constructor($http) { this._$http = $http; }
    create(smth) {
        return this._$http.post(`${apiUrl}/smth`, smth).then(res => res.data);
    }

    edit(smth) {
        return this._$http
            .put(`${apiUrl}/smth/${smth.id}`, smth)
            .then(res => res.data);
    }
}
</code>```

And my component:

```<code>let myComponent = {
    //bindings: {},
    controller: function () {};
    template: myTemplate
}
</code>```

So that if my component is rendered in create state, it would use create() method from myService correspondingly, and the same for edit and other states I would have. How could I design my component to work in a such way?

答:
For example, you can pass binding in one of the cases (like edit):

```<code>bindings: { isEditState: "<?"}
</code>```

Service:

```<code>class myService {
// constructor($http) { this._$http = $http; }
  makeRequest(smth, method) {
    return this._$http[method](smth).then(res => res.data); // because they are pretty similar in your example
  }
}
</code>```

Then in component:

```<code>makeReuest(smth) {
  const reqMethod = isEditState ? "put" : "post";
  this.myService.makeRequest(smth, method);
  // ...
}
</code>```

Finally, in routes, you can pass template instead of component :

```<code>$stateProvider
.state('create', {
    url: 'create',
    template: '<my-component></my-component>',
    resolve: {
       data: function (myService) {
           return myService.getData();
       }
    }
})
.state('edit', {
     url: 'edit',
     template: '<my-component is-edit-state="true"></my-component>',
     // another resolve
});
</code>```

Body:
I want to build a component that I would be able to re-use in different states, because the functions it performs are quite similar. The problem is that it is supposed to use different methods from my service according to the state where it is rendered. Considering I've got these states:

$stateProvider
    .state('create', {
        url: 'create',
        component: 'myComponent',
        resolve: {
           data: function (myService) {
               return myService.getData();
           }
        }
    })
    .state('edit', {
         url: 'edit',
         component: 'myComponent',
         // another resolve
    })
    // and so on

And I have a service with the following methods:

class myService {
    // constructor($http) { this._$http = $http; }
    create(smth) {
        return this._$http.post(`${apiUrl}/smth`, smth).then(res => res.data);
    }

    edit(smth) {
        return this._$http
            .put(`${apiUrl}/smth/${smth.id}`, smth)
            .then(res => res.data);
    }
}

And my component:

let myComponent = {
    //bindings: {},
    controller: function () {};
    template: myTemplate
}

So that if my component is rendered in create state, it would use create() method from myService correspondingly, and the same for edit and other states I would have. How could I design my component to work in a such way?

Body:
For example, you can pass binding in one of the cases (like edit):

bindings: { isEditState: "<?"}

Service:

class myService {
// constructor($http) { this._$http = $http; }
  makeRequest(smth, method) {
    return this._$http[method](smth).then(res => res.data); // because they are pretty similar in your example
  }
}

Then in component:

makeReuest(smth) {
  const reqMethod = isEditState ? "put" : "post";
  this.myService.makeRequest(smth, method);
  // ...
}

Finally, in routes, you can pass template instead of component :

$stateProvider
.state('create', {
    url: 'create',
    template: '<my-component></my-component>',
    resolve: {
       data: function (myService) {
           return myService.getData();
       }
    }
})
.state('edit', {
     url: 'edit',
     template: '<my-component is-edit-state="true"></my-component>',
     // another resolve
});


问:
File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?
I am doing the angular2 tutorial at this address: https://angular.io/docs/ts/latest/tutorial/toh-pt3.html I have put the hero interface in a single file under the app folder, in the console I have this error:

```<code>app/app.component.ts(2,20): error TS2306: File 'app/hero.ts' is not a module.
[0] app/hero-detail.component.ts(2,20): error TS2306: File 'app/hero.ts' is not a module.
</code>```

If I put my interface file in a hero folder the error disappear, this is not mentioned in the documentation, what's wrong with my import?

My import directive (at the beguining of the component files) in both app.components.ts and hero-detail.component.ts:

```<code>import {Component} from 'angular2/core';

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

Must I replace my import directive by: import {Hero} from './'; or simply put the code in a hero folder?

答: Restarting my ng serve process worked for me

Body:
I am doing the angular2 tutorial at this address: https://angular.io/docs/ts/latest/tutorial/toh-pt3.html I have put the hero interface in a single file under the app folder, in the console I have this error:

app/app.component.ts(2,20): error TS2306: File 'app/hero.ts' is not a module.
[0] app/hero-detail.component.ts(2,20): error TS2306: File 'app/hero.ts' is not a module.

If I put my interface file in a hero folder the error disappear, this is not mentioned in the documentation, what's wrong with my import?

My import directive (at the beguining of the component files) in both app.components.ts and hero-detail.component.ts:

import {Component} from 'angular2/core';

import {Hero} from './hero';

Must I replace my import directive by: import {Hero} from './'; or simply put the code in a hero folder?


问:
Override theme text color
My problem

I set my custom theme and it works fine.

But I get black text color on orange( accent) button, but I want to have white color.

My solution

In @material/theme/_variables.scss we have code like this :

```<code>$mdc-theme-primary: #3f51b5 !default; /* Indigo 500 */
$mdc-theme-accent: #ff4081 !default; /* Pink A200 */
$mdc-theme-background: #fff !default; /* White */

/* Which set of text colors to use for each main theme color (light or dark) */
$mdc-theme-primary-tone: mdc-theme-light-or-dark($mdc-theme-primary);
$mdc-theme-accent-tone: mdc-theme-light-or-dark($mdc-theme-accent);
$mdc-theme-background-tone: mdc-theme-light-or-dark($mdc-theme-background);
</code>```

From the above code, we can see first three params have !default which means use this as default , if they are already declared dont override.

For that reason we can specify the custom colors.

But for properties like $mdc-theme-accent-tone we are forced to use the calculated values.
If I change the above code (source code of MDC ) to

```<code>$mdc-theme-accent-tone: mdc-theme-light-or-dark($mdc-theme-accent) !default;
</code>```

and in my styles

```<code>$mdc-theme-accent-tone : "light"
</code>```

It works fine. But obviously I can not change the source code. How to achieve this.

答:
I realized this is according to the material design spec. So, expecting a provision to override is wrong.
But for all practical reasons, to override them do this : </p>

```<code>@import "@material/theme/mdc-theme";

:root {
    --mdc-theme-text-primary-on-accent: white;
}
</code>```

<p>Remember the override style should be written after importing mdc-theme </p>

Title: Override theme text color

Body:
My problem

I set my custom theme and it works fine.

But I get black text color on orange( accent) button, but I want to have white color.

My solution

In @material/theme/_variables.scss we have code like this :

$mdc-theme-primary: #3f51b5 !default; /* Indigo 500 */
$mdc-theme-accent: #ff4081 !default; /* Pink A200 */
$mdc-theme-background: #fff !default; /* White */

/* Which set of text colors to use for each main theme color (light or dark) */
$mdc-theme-primary-tone: mdc-theme-light-or-dark($mdc-theme-primary);
$mdc-theme-accent-tone: mdc-theme-light-or-dark($mdc-theme-accent);
$mdc-theme-background-tone: mdc-theme-light-or-dark($mdc-theme-background);

From the above code, we can see first three params have !default which means use this as default , if they are already declared dont override.

For that reason we can specify the custom colors.

But for properties like $mdc-theme-accent-tone we are forced to use the calculated values.
If I change the above code (source code of MDC ) to

$mdc-theme-accent-tone: mdc-theme-light-or-dark($mdc-theme-accent) !default;

and in my styles

$mdc-theme-accent-tone : "light"

It works fine. But obviously I can not change the source code. How to achieve this.

Body:
I realized this is according to the material design spec. So, expecting a provision to override is wrong.
But for all practical reasons, to override them do this :

@import "@material/theme/mdc-theme";

:root {
    --mdc-theme-text-primary-on-accent: white;
}

Remember the override style should be written after importing mdc-theme


问:
Static variable to change in a child class from a parent
I want to create a child class of Dog, Cat, Lion, etc. I want each animal to create an object of itself. When it creates on object of itself I want it to keep track of how many total types of animals there are. So for example if there are 3 dogs then the dog class knows it has 4 dogs. The same for all the others.

Example code for Dog:

```<code>class Dog {
    static int numberOfDogs = 0;

    public Dog() {
    }

    public void AddDog() {
        numberOfDogs++;
    }

    public void MinusDog() {
        numberOfDogs--;
    }
}
</code>```

Now if I want to do the same thing for a cat I would need to rewrite all that code and replace dog with cat and so on.

What I want to do is create a parent class that has all that repeated code in one spot but as I create a Dog it will add to the dog variable and the same with the cat and so on. My idea of the parent class:

```<code>class Animal {
    public static int NumberOfAnimals;

    public void AddAnimal() {
        NumberOfAnimals++;
    }

    public void MinusAnimal() {
        NumberOfAnimals--;
    }
}
</code>```

If I derive Dog from Animal and call dog.AddAnimal() it will add to all the Animal's static variable. How can I make to so that I have a static variable in Dog that can be changed using the parent class Animal?

Or if I'm asking the wrong question, how can I get the desired result of having many animals with many static variables?

答:
If you want Class Dog to be derived class of Animal so that you can access Class Animal from  Class dog you have to do ->

`class Animal{

public void AddAnimal(int &NumberOfAnimals;)
 { NumberOfAnimals++; }

public void MinusAnimal(int &NumberOfAnimals)
 { NumberOfAnimals--; }
 }

class Dog: public Animal {

int numberOfDogs = 0;

Animal obj;

public void AddDog()
 { obj. AddAnimal(numberOfDogs); }

public void MinusDog() { obj.MinusAnimal(numberOfDogs); } }'

If you want to make numberOfDogs static you won't be able to increase or decrease it's value when you add or minus

Body:
I want to create a child class of Dog, Cat, Lion, etc. I want each animal to create an object of itself. When it creates on object of itself I want it to keep track of how many total types of animals there are. So for example if there are 3 dogs then the dog class knows it has 4 dogs. The same for all the others.

Example code for Dog:

class Dog {
    static int numberOfDogs = 0;

    public Dog() {
    }

    public void AddDog() {
        numberOfDogs++;
    }

    public void MinusDog() {
        numberOfDogs--;
    }
}

Now if I want to do the same thing for a cat I would need to rewrite all that code and replace dog with cat and so on.

What I want to do is create a parent class that has all that repeated code in one spot but as I create a Dog it will add to the dog variable and the same with the cat and so on. My idea of the parent class:

class Animal {
    public static int NumberOfAnimals;

    public void AddAnimal() {
        NumberOfAnimals++;
    }

    public void MinusAnimal() {
        NumberOfAnimals--;
    }
}

If I derive Dog from Animal and call dog.AddAnimal() it will add to all the Animal's static variable. How can I make to so that I have a static variable in Dog that can be changed using the parent class Animal?

Or if I'm asking the wrong question, how can I get the desired result of having many animals with many static variables?


问:
OkHttp 3 IllegalStateException
I customize an interceptor to refresh token when it's expired. When I get response body to detect if the token's expired, it throw java.lang.IllegalStateException: closed.

Here is my code with OkHttp 3

```<code>@Override
public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder requestBuilder = original.newBuilder()
            .header("Content-Type", "application/json")
            .header(Constants.TAG_AUTHORIZATION, "Bearer " + token)
            .method(original.method(), original.body());

    Request request = requestBuilder.build();
    Response response = chain.proceed(request);
    if (response.code() == 200) {
        String json = response.body().string();
        try {
            JSONObject obj = new JSONObject(json);
            int code = obj.getInt(Constants.TAG_CODE);
            if (code == Constants.REQUEST_CODE_TOKEN_EXPIRED) {
                Response r = makeTokenRefreshCall(request, chain);
                return r;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return response;
}
</code>```

Please help me!

答:
Finally, I found a solution to read response body without exception</p>

```<code> ResponseBody body = response.body();
 BufferedSource source = body.source();
 if (source.request(1024)) throw new IOException("Body too long!");
 Buffer bufferedCopy = source.buffer().clone();
 ResponseBody newBody = ResponseBody.create(body.contentType(), body.contentLength(), bufferedCopy);
 String responseBodyString = newBody.string();
</code>```

Title: OkHttp 3 IllegalStateException

Body:
I customize an interceptor to refresh token when it's expired. When I get response body to detect if the token's expired, it throw java.lang.IllegalStateException: closed.

Here is my code with OkHttp 3

@Override
public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder requestBuilder = original.newBuilder()
            .header("Content-Type", "application/json")
            .header(Constants.TAG_AUTHORIZATION, "Bearer " + token)
            .method(original.method(), original.body());

    Request request = requestBuilder.build();
    Response response = chain.proceed(request);
    if (response.code() == 200) {
        String json = response.body().string();
        try {
            JSONObject obj = new JSONObject(json);
            int code = obj.getInt(Constants.TAG_CODE);
            if (code == Constants.REQUEST_CODE_TOKEN_EXPIRED) {
                Response r = makeTokenRefreshCall(request, chain);
                return r;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return response;
}

Please help me!

Body:
Finally, I found a solution to read response body without exception

 ResponseBody body = response.body();
 BufferedSource source = body.source();
 if (source.request(1024)) throw new IOException("Body too long!");
 Buffer bufferedCopy = source.buffer().clone();
 ResponseBody newBody = ResponseBody.create(body.contentType(), body.contentLength(), bufferedCopy);
 String responseBodyString = newBody.string();


问:
RStudio does not see packages after update to R 3.4
I have Ubuntu 16.04 and after update of R to 3.4.1 version it does not see my packages even though they have also been updated:

```<code>> library(dplyr)
Error in library(dplyr) : there is no package called ‘dplyr’
</code>```

Packages are there:

```<code>$ ls ~/R/x86_64-pc-linux-gnu-library/3.4/ | grep plyr
dplyr
plyr
</code>```

My .libPaths:

```<code>> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"       "/usr/lib/R/library"
</code>```

Setting .libPaths to desired path does the thing just for one session. I'd like it to be permanent.

I also tried to set the variables R_LIBS, R_LIBS_SITE and R_LIBS_USER to desired path as indicated here but it worked only in the console (didn't work in RStudio).

答: I had a similar problem with Ubuntu 16.04. Call terminal R and try to install one any package in the terminal. Then use rstudio.</p>

Body:
I have Ubuntu 16.04 and after update of R to 3.4.1 version it does not see my packages even though they have also been updated:

> library(dplyr)
Error in library(dplyr) : there is no package called ‘dplyr’

Packages are there:

$ ls ~/R/x86_64-pc-linux-gnu-library/3.4/ | grep plyr
dplyr
plyr

My .libPaths:

> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"       "/usr/lib/R/library"

Setting .libPaths to desired path does the thing just for one session. I'd like it to be permanent.

I also tried to set the variables R_LIBS, R_LIBS_SITE and R_LIBS_USER to desired path as indicated here but it worked only in the console (didn't work in RStudio).


问:
How to rotate drag/dropped Image using Jquery
I am having an issue in Jquery rotate  below is my HTML code

```<code><div id="frame" style="height:100;width:100;" >
<img alt="" id="Img1" runat="server" src="~/Images/pdfcar.png"
style="height:30px;width:30px;"/>
</code>```

The below code is working fine,

Javascript:Jquery rotate

```<code> var test = 5;
 $(function() {
     $('#Img1').live('mousedown', function(event) {
              test = test + 15;
              **$('#Img1').rotate({ angle: test });**

     });
 });
</code>```

But my scenario is to acheive the rotation of dropped images,when i try the below code its not working

```<code>var test = 5;
 $(function() {
     $('#frame img').live('mousedown', function(event) {
              test = test + 15;
              **$('#frame img').rotate({ angle: test });**

     });
 });
</code>```

What's wrong in the above code or how to achieve it??

Full JQuery code

```<code>var counter = 1;
  $(function() {
  $('#frame img').live('click', function(event) {

          if ((counter > 0) && (counter < 350)) {
              $(this).rotate(counter + 45);
              counter = counter + 45;
          }
          else if ((counter > -1) && (counter > 350)) {

              counter = 1;
          }
      });

  });

  $(function() {

      $('#frame img').live('dblclick', function(ev, ui) {
      // $(this).resizable("destroy")

      $(this).hide();
      var currentId = $(this).attr('id');
      var deleteimage = 1;
      saveCoords(ev.clientX, ev.clientY, currentId, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);

          //$(this).unbind("resizable"); not working
          //$(this).removeclass(); not working
      });
  });

  $(document).ready(function() {
      //Counter
      counter = 0;

      //Make element draggable
      $("#fd img").draggable({
          helper: 'clone',
          containment: '#frame',
          //When first dragged
          stop: function(ev, ui) {

              var pos = $(ui.helper).offset();
              objName = "#clonediv" + counter
              $(objName).css({ "left": pos.left, "top": pos.top });
              $(objName).removeClass("drag");
              //When an existiung object is dragged
              $(objName).draggable({
                  containment: 'parent',
                  stop: function(ev, ui) {
                      var pos = $(ui.helper).offset();
                      //console.log($(this).attr("id"));
                      //console.log(pos.left)
                      //console.log(pos.top)
                  }
              });
          }
      });
      //Make element droppable
      $("#frame").droppable({

      drop: function(ev, ui) {

              if (ui.helper.attr('id').search(/drag[0-9]/) != -1) {
                  var pos = $(ui.helper).offset();
                  counter++;
                  var element = $(ui.helper).clone();
                  //var element = element1.resizable();
                  element.addClass("tempclass");
                  $(this).append(element);
                  var deleteimage = 0;
                  element.attr("id", ui.helper.attr('id') + counter);
                  saveCoords(ui.absolutePosition.left, ui.absolutePosition.top, ui.helper.attr('id') + counter, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);
                  $(".tempclass").attr("id", "clonediv" + counter);
                  $("#clonediv" + counter).removeClass("tempclass");
                  //$(".tempclass").attr("onclick",function(){ $(this).remove(););
                  //$("#clonediv" + counter).removeClass("tempclass");
                  //Get the dynamically item id
                  draggedNumber = ui.helper.attr('id').search(/drag([0-9])/);
                  itemDragged = "dragged" + RegExp.$1;
                  //console.log(itemDragged)
                  //alert('left' + pos.left + ',top' + pos.top + 'of item' + itemDragged);
                  $("#clonediv" + counter).addClass(itemDragged);
              }
          }
      });
      //Make the element resizable

  });
</code>```

答:
If the issue is to target the clicked image you should replace the #frame img with this

```<code>var test = 5;
 $(function() {
     $('#frame img').live('mousedown', function(event) {
              test = test + 15;
              $(this).rotate({ angle: test });

     });
 });
</code>```

If you are using draggables and droppables from the jquery UI, then you will need to show us some code. (The most likely is that you do not actually relocate in the DOM the dropped element to be physically in the droppable area.)

update

The issue is that the plugin replaces the image with a canvas object and wraps it in a span which assumes the id/class of the element..

Solution is to target not the actual img tag but a class on it.

So add a class to your img elements that you want rotatable  and target that with your live method $('#frame .rotatable').live(...).

Keep using the $(this).rotate(...) to apply the rotations.

Body:
I am having an issue in Jquery rotate  below is my HTML code

The below code is working fine,

Javascript:Jquery rotate

 var test = 5;
 $(function() {
     $('#Img1').live('mousedown', function(event) {
              test = test + 15;
              **$('#Img1').rotate({ angle: test });**

     });
 });

But my scenario is to acheive the rotation of dropped images,when i try the below code its not working

var test = 5;
 $(function() {
     $('#frame img').live('mousedown', function(event) {
              test = test + 15;
              **$('#frame img').rotate({ angle: test });**

     });
 });

What's wrong in the above code or how to achieve it??

Full JQuery code

var counter = 1;
  $(function() {
  $('#frame img').live('click', function(event) {

          if ((counter > 0) && (counter < 350)) {
              $(this).rotate(counter + 45);
              counter = counter + 45;
          }
          else if ((counter > -1) && (counter > 350)) {

              counter = 1;
          }
      });

  });

  $(function() {

      $('#frame img').live('dblclick', function(ev, ui) {
      // $(this).resizable("destroy")

      $(this).hide();
      var currentId = $(this).attr('id');
      var deleteimage = 1;
      saveCoords(ev.clientX, ev.clientY, currentId, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);

          //$(this).unbind("resizable"); not working
          //$(this).removeclass(); not working
      });
  });

  $(document).ready(function() {
      //Counter
      counter = 0;

      //Make element draggable
      $("#fd img").draggable({
          helper: 'clone',
          containment: '#frame',
          //When first dragged
          stop: function(ev, ui) {

              var pos = $(ui.helper).offset();
              objName = "#clonediv" + counter
              $(objName).css({ "left": pos.left, "top": pos.top });
              $(objName).removeClass("drag");
              //When an existiung object is dragged
              $(objName).draggable({
                  containment: 'parent',
                  stop: function(ev, ui) {
                      var pos = $(ui.helper).offset();
                      //console.log($(this).attr("id"));
                      //console.log(pos.left)
                      //console.log(pos.top)
                  }
              });
          }
      });
      //Make element droppable
      $("#frame").droppable({

      drop: function(ev, ui) {

              if (ui.helper.attr('id').search(/drag[0-9]/) != -1) {
                  var pos = $(ui.helper).offset();
                  counter++;
                  var element = $(ui.helper).clone();
                  //var element = element1.resizable();
                  element.addClass("tempclass");
                  $(this).append(element);
                  var deleteimage = 0;
                  element.attr("id", ui.helper.attr('id') + counter);
                  saveCoords(ui.absolutePosition.left, ui.absolutePosition.top, ui.helper.attr('id') + counter, document.getElementById("<%=trafficID.ClientID%>").value, deleteimage);
                  $(".tempclass").attr("id", "clonediv" + counter);
                  $("#clonediv" + counter).removeClass("tempclass");
                  //$(".tempclass").attr("onclick",function(){ $(this).remove(););
                  //$("#clonediv" + counter).removeClass("tempclass");
                  //Get the dynamically item id
                  draggedNumber = ui.helper.attr('id').search(/drag([0-9])/);
                  itemDragged = "dragged" + RegExp.$1;
                  //console.log(itemDragged)
                  //alert('left' + pos.left + ',top' + pos.top + 'of item' + itemDragged);
                  $("#clonediv" + counter).addClass(itemDragged);
              }
          }
      });
      //Make the element resizable

  });

Body:
If the issue is to target the clicked image you should replace the #frame img with this

var test = 5;
 $(function() {
     $('#frame img').live('mousedown', function(event) {
              test = test + 15;
              $(this).rotate({ angle: test });

     });
 });

If you are using draggables and droppables from the jquery UI, then you will need to show us some code. (The most likely is that you do not actually relocate in the DOM the dropped element to be physically in the droppable area.)

update

The issue is that the plugin replaces the image with a canvas object and wraps it in a span which assumes the id/class of the element..

Solution is to target not the actual img tag but a class on it.

So add a class to your img elements that you want rotatable <img class="rotatable" alt="" id="Img1" runat="server" src="~/Images/pdfcar.png" style="height:30px;width:30px;"/> and target that with your live method $('#frame .rotatable').live(...).

Keep using the $(this).rotate(...) to apply the rotations.


问:
Remove top line from TabBar
On iOS 10 this code doesn't work in order to remove the tabBar shadow line:

```<code>[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
</code>```

Somebody knows, what must I do to remove it?

On iOS 9.3 with this two lines the line is removed, but iOS 10 ignores setShadowImage command.

答:
If you create your own subclass of UITabBarController, you can set the
 values in viewDidLoad like this

Swift 3

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBar.layer.borderWidth = 0
        self.tabBar.clipsToBounds = true
}
</code>```

Title: Remove top line from TabBar

Body:
On iOS 10 this code doesn't work in order to remove the tabBar shadow line:

[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];

Somebody knows, what must I do to remove it?

On iOS 9.3 with this two lines the line is removed, but iOS 10 ignores setShadowImage command.

Body:
If you create your own subclass of UITabBarController, you can set the
 values in viewDidLoad like this

Swift 3

override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBar.layer.borderWidth = 0
        self.tabBar.clipsToBounds = true
}


问:
SaveToDatabase in TYPO3 8
How to use form finisher SaveToDataBase in TYPO3 8.7.1? I try to add finisher in YAML, but I have an error:

Argument 1 passed to
  TYPO3\CMS\Form\Domain\Finishers\SaveToDatabaseFinisher::process() must
  be of the type integer, string given, called in
  typo3\sysext\form\Classes\Domain\Finishers\SaveToDatabaseFinisher.php
  on line 207

YAML document:

```<code>renderingOptions:
  submitButtonLabel: Submit
type: Form
identifier: form
label: Form
prototypeName: standard
finishers:
  -
    options:
      table: table1
      mode: update
      whereClause:
        uid: '1'
      elements:
        text-1:
          mapOnDatabaseColumn: column1
    identifier: SaveToDatabase
renderables:
  -
    renderingOptions:
      previousButtonLabel: 'previous Page'
      nextButtonLabel: 'next Page'
    type: Page
    identifier: page-1
    label: Page
    renderables:
      -
        defaultValue: ''
        type: Text
        identifier: text-1
        label: Text
</code>```

答:
I had the same TYPO3 exception. Try to write the options as an array, using -. This solved the problem for me.

```<code>renderingOptions:
  submitButtonLabel: Submit
type: Form
identifier: form
label: Form
prototypeName: standard
finishers:
  -
    options:
      -
        table: 'table1'
        mode: update
        whereClause:
          uid: '1'
        elements:
          text-1:
            mapOnDatabaseColumn: column1
    identifier: SaveToDatabase
renderables:
  -
    renderingOptions:
      previousButtonLabel: 'previous Page'
      nextButtonLabel: 'next Page'
    type: Page
    identifier: page-1
    label: Page
    renderables:
      -
        defaultValue: ''
        type: Text
        identifier: text-1
        label: Text
</code>```

Title: SaveToDatabase in TYPO3 8

Body:
How to use form finisher SaveToDataBase in TYPO3 8.7.1? I try to add finisher in YAML, but I have an error:

Argument 1 passed to
  TYPO3\CMS\Form\Domain\Finishers\SaveToDatabaseFinisher::process() must
  be of the type integer, string given, called in
  typo3\sysext\form\Classes\Domain\Finishers\SaveToDatabaseFinisher.php
  on line 207

YAML document:

renderingOptions:
  submitButtonLabel: Submit
type: Form
identifier: form
label: Form
prototypeName: standard
finishers:
  -
    options:
      table: table1
      mode: update
      whereClause:
        uid: '1'
      elements:
        text-1:
          mapOnDatabaseColumn: column1
    identifier: SaveToDatabase
renderables:
  -
    renderingOptions:
      previousButtonLabel: 'previous Page'
      nextButtonLabel: 'next Page'
    type: Page
    identifier: page-1
    label: Page
    renderables:
      -
        defaultValue: ''
        type: Text
        identifier: text-1
        label: Text

Body:
I had the same TYPO3 exception. Try to write the options as an array, using -. This solved the problem for me.

renderingOptions:
  submitButtonLabel: Submit
type: Form
identifier: form
label: Form
prototypeName: standard
finishers:
  -
    options:
      -
        table: 'table1'
        mode: update
        whereClause:
          uid: '1'
        elements:
          text-1:
            mapOnDatabaseColumn: column1
    identifier: SaveToDatabase
renderables:
  -
    renderingOptions:
      previousButtonLabel: 'previous Page'
      nextButtonLabel: 'next Page'
    type: Page
    identifier: page-1
    label: Page
    renderables:
      -
        defaultValue: ''
        type: Text
        identifier: text-1
        label: Text


问:
Dumping lua func with arguments
Is it possibly to dump the Lua table including function arguments?
If so, how can I do it?

I have managed to dump tables and function with addresses, but I haven't been able to figure out a way to get function args, i have tried different methods, but no luck.

So I want to receive them truth dumping tables and function plus args of the function.
Output should be something like this: Function JumpHigh(Player, height)

I don't know if it is even possible, but would be very handy.

答:
Table only stores values.

If there's function stored in a table, then it's just a function body, there's no arguments. If arguments were applied, table would store only final result of that call.

Maybe you're talking about closure - function returned from other function, capturing some arguments from a top level function in a lexical closure? Then see debug.getupvalue() function to check closure's content.

Is this something what you're asking?

```<code>local function do_some_action(x,y)
    return function()
        print(x,y)
    end
end

local t = {
    func = do_some_action(123,478)
}

-- only function value printed
print "Table content:"
for k,v in pairs(t) do
    print(k,v)
end

-- list function's upvalues, where captured arguments may be stored
print "Function's upvalues"
local i = 0
repeat
    i = i + 1
    local name, val = debug.getupvalue(t.func, i)
    if name then
        print(name, val)
    end
until not name
</code>```

Note that upvalues stored is not necessary an argument to a toplevel function. It might be some local variable, storing precomputed value for the inner function.

Also note that if script was precompiled into Lua bytecode with stripping debug info, then you won't get upvalues' names, those will be empty.

Title: Dumping lua func with arguments

Body:
Table only stores values.

If there's function stored in a table, then it's just a function body, there's no arguments. If arguments were applied, table would store only final result of that call.

Maybe you're talking about closure - function returned from other function, capturing some arguments from a top level function in a lexical closure? Then see debug.getupvalue() function to check closure's content.

Is this something what you're asking?

local function do_some_action(x,y)
    return function()
        print(x,y)
    end
end

local t = {
    func = do_some_action(123,478)
}

-- only function value printed
print "Table content:"
for k,v in pairs(t) do
    print(k,v)
end

-- list function's upvalues, where captured arguments may be stored
print "Function's upvalues"
local i = 0
repeat
    i = i + 1
    local name, val = debug.getupvalue(t.func, i)
    if name then
        print(name, val)
    end
until not name

Note that upvalues stored is not necessary an argument to a toplevel function. It might be some local variable, storing precomputed value for the inner function.

Also note that if script was precompiled into Lua bytecode with stripping debug info, then you won't get upvalues' names, those will be empty.