问:
How to randomize a generator output in JavaScript?
Let's pretend I have a generator which eventually stops

function* letters () {
  let offset = 0
  while (offset < 26)
    yield String.fromCharCode(65 + offset++)
}

console.log(Array.from(letters()))
// => [ "A", "B", "C", ..., "X", "Y", "Z" ]```
</div>
</div>
</p>

<p>Using that generator as an input, I want to create another generator, but for this one I would like the values to come out in a randomized order</p>

```function* randomizeGen (gen) {
  // ...
}

Array.from(randomizeGen(letters()))
// => [ "X", "T", "L", "P", "A", ..., "G", "S", "B" ] (all 26 letters)
```

<p>The new generator should be lazy, like the first one, but I cannot figure out how to write it in a smart way</p>

```function shuffleArray (arr) {
  // return shuffled array
}

function* randomizeGen (gen) {
   const all = Array.from(gen) // help!
   for (const one of shuffleArray(all))
     yield one
}
```

This would work, but it does so by completely exhausting gen first. In reality, my initial generator outputs millions of values, so I don't think collecting them all in an array first is a good idea. The whole point of using a generator is that I can process the values one at a time

I honestly have no idea how to randomize the generator output but keep it lazy at the same time. Can someone please help?

答:
You can't, by definition. A generator produces a single value in a specific order every time it is invoked. So if you want some other value rather than the next one in line, you will have to consume multiple values from the generator, and then select one to return. Which is eager evaluation rather then lazy.

However you could simulate the intended behaviour like this. It will remain lazy for about 50% of the time. So its kinda-lazy.

Note that this is far from an actually random order. The first half of the elements in the generator will each have a 50% chance of being put in the right order (and 50% chance of being put in the cache). While the second half of elements will have a 2/n chance of being put in the right order (where n is the current number of elements in the cache, aka n will go from N/2 to 0 (where N is the number of elements in the generator in total)).

TL:DR the first half of the "random" result will be in order but missing a couple of elements here and there (they show up in the other half).

Math.random.between = (min, max) => Math.floor(Math.random()*(max-min+1)+min);

function* letters () {
  let offset = 0
  while (offset < 26)
    yield String.fromCharCode(65 + offset++)
}

function* randomizeGen (gen) {
   let cache = [];
   let current = gen.next();

   while (!current.done) {
    if (Math.random.between(0, 1) > 0.5) {
      yield current.value;
    } else {
      cache.push(current);
    }
    current = gen.next();
   }

   while (cache.length > 0) {
    const index = Math.random.between(0, cache.length-1);
    const v = cache[index];
    cache = cache.filter((_,i) => i !== index);
    yield v.value;
   }
}

const randomOrder = Array.from(randomizeGen(letters()));
console.log(randomOrder);```

Body:
Let's pretend I have a generator which eventually stops

function* letters () {
  let offset = 0
  while (offset < 26)
    yield String.fromCharCode(65 + offset++)
}

console.log(Array.from(letters()))
// => [ "A", "B", "C", ..., "X", "Y", "Z" ]

Using that generator as an input, I want to create another generator, but for this one I would like the values to come out in a randomized order

function* randomizeGen (gen) {
  // ...
}

Array.from(randomizeGen(letters()))
// => [ "X", "T", "L", "P", "A", ..., "G", "S", "B" ] (all 26 letters)

The new generator should be lazy, like the first one, but I cannot figure out how to write it in a smart way

function shuffleArray (arr) {
  // return shuffled array
}

function* randomizeGen (gen) {
   const all = Array.from(gen) // help!
   for (const one of shuffleArray(all))
     yield one
}

This would work, but it does so by completely exhausting gen first. In reality, my initial generator outputs millions of values, so I don't think collecting them all in an array first is a good idea. The whole point of using a generator is that I can process the values one at a time

I honestly have no idea how to randomize the generator output but keep it lazy at the same time. Can someone please help?


来源: stackexchange

问:
How can I insert and join from three tables?
I have to combine two tables and replace a value within a table with values from a 3rd column.

the tables look like this
order

```<code>order   date    product_type    quantity    cost
1      1/1/19   tops             2          49.99
2      1/2/19   bottom           3          190
3      1/2/19   jewelry          1          30

product
order   date    product type    product name
1       1/1/19  tops            sophia tank
2       1/2/19  bottom          boyfriend jeans
3       1/2/19  jewelry         alex necklace

 type
ascin_product      ascin
tops               0081112
bottom             121412
jewelry            12412415
</code>```

The output should look like this

```<code>order   date    quantity    cost    product name    ascin
1      1/1/19     2        49.99    sophia tank     0001112
2      1/2/19     3        190      boyfriend jeans 121412
3      1/2/19     1        30       alex necklace   12412415
</code>```

[enter image description here][2]

I can join order and product easily, I just don't know how to join the 3rd table based off of ascin product and then replace product type with ascin in the overall table

```<code>select order, date, product_type,product_name from product
inner join on order
product.product_type=order.product type
inner join on type
product.product_type=order.product type=type=ascin_product
</code>```

I don't know how to replace product type in my table with ascin

答:
Start from Order and then join the other tables</p>

```<code>SELECT o.order, o.date, o.quantity, o.cost, p.product_name, t.ascin
FROM order o
JOIN product p ON p.order = o.order
JOIN type t ON t.ascin_product = o.product_type
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have to combine two tables and replace a value within a table with values from a 3rd column.

the tables look like this
order

order   date    product_type    quantity    cost
1      1/1/19   tops             2          49.99
2      1/2/19   bottom           3          190
3      1/2/19   jewelry          1          30

product
order   date    product type    product name
1       1/1/19  tops            sophia tank
2       1/2/19  bottom          boyfriend jeans
3       1/2/19  jewelry         alex necklace

 type
ascin_product      ascin
tops               0081112
bottom             121412
jewelry            12412415

The output should look like this

order   date    quantity    cost    product name    ascin
1      1/1/19     2        49.99    sophia tank     0001112
2      1/2/19     3        190      boyfriend jeans 121412
3      1/2/19     1        30       alex necklace   12412415

[enter image description here][2]

I can join order and product easily, I just don't know how to join the 3rd table based off of ascin product and then replace product type with ascin in the overall table

select order, date, product_type,product_name from product
inner join on order
product.product_type=order.product type
inner join on type
product.product_type=order.product type=type=ascin_product

I don't know how to replace product type in my table with ascin

Body:
Start from Order and then join the other tables

SELECT o.order, o.date, o.quantity, o.cost, p.product_name, t.ascin
FROM order o
JOIN product p ON p.order = o.order
JOIN type t ON t.ascin_product = o.product_type


问:
Applying a Synth Look and Feel to Sliders?
I have a bunch of sliders that I am trying to apply a custom thumb to. The dimensions of it are 12x20, and I am applying it using a synth look and feel with the code below. This displays the thumb correctly for horizontal sliders, but once I make a vertical one the thumb gets distorted on the edges. Is there any better way to do this? Also, The thumb pressed code doesn't do anything, I would assume the reason for that is that sliderThumbs don't have a "pressed state"? Is there a way to make the L&F change on a slider when it is pressed? Thanks beforehand!!!

Cheers,
Lukas

```<code><!-- Make and Bind a SliderThumb style -->
<style id="sliderStyle">

    <state>
      <property key="Slider.paintValue" type="boolean" value="false"/>
      <property key="Slider.thumbWidth" type="integer" value="12"/>
      <property key="Slider.thumbHeight" type="integer" value="21"/>
    </state>

</style>

<bind style="sliderStyle" type="region" key="slider" />

<style id="SliderTrackStyle">
    <opaque value="FALSE"/>
</style>
<bind style="SliderTrackStyle" type="region" key="sliderTrack" />

<style id="sliderThumbStyle">

    <state>
       <imagePainter method="sliderThumbBackground" path="Images/SliderThumb.png"
         sourceInsets="0 0 0 0"/>
    </state>

   <state value="PRESSED">
       <imagePainter method="sliderThumbBackground" path="Images/SliderThumbPressed.png"
         sourceInsets="0 0 0 0"/>
   </state>

</style>

<bind style="sliderThumbStyle" type="region" key="sliderThumb" />
</code>```

答: Use Vector graphics. On one of my apps, I originally used png files, the same as you. When I switched to Vector graphics, the edges didn't tear when used on smaller buttons.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a bunch of sliders that I am trying to apply a custom thumb to. The dimensions of it are 12x20, and I am applying it using a synth look and feel with the code below. This displays the thumb correctly for horizontal sliders, but once I make a vertical one the thumb gets distorted on the edges. Is there any better way to do this? Also, The thumb pressed code doesn't do anything, I would assume the reason for that is that sliderThumbs don't have a "pressed state"? Is there a way to make the L&F change on a slider when it is pressed? Thanks beforehand!!!

Cheers,
Lukas

<bind style="sliderStyle" type="region" key="slider" />

<bind style="SliderTrackStyle" type="region" key="sliderTrack" />

<bind style="sliderThumbStyle" type="region" key="sliderThumb" />

ContentLicense: CC BY-SA 3.0


问:
why output is null at select translate(' @',' ','') from dual; and why resulit is @ at select replace(' @',' ','') from dual;
Basically  translate will change character to character and Replace string to string , and  here i have tried to remove spaces using translate to count the number words . </p>

```<code>select translate('  @',' ','') from dual;

select replace('  @',' ','') from dual;

select ename , nvl(length(replace(TRANSLATE(upper(trim(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @ '),' ',''))+1,1) NOOFWORDs
from emp;
</code>```

答:
```<code>select translate('  @',' ','') from dual;
</code>```

Returns NULL because in Oracle empty strings unfortunately yield NULLs. Therefore it's equivalent to

```<code>SELECT translate('  @', ' ', NULL)
       FROM dual;
</code>```

and translate() returns NULL when an argument is null. Actually this is well documented in "TRANSLATE":

(...)

You cannot use an empty string for to_string to remove all characters in from_string from the return value. Oracle Database interprets the empty string as null, and if this function has a null argument, then it returns null.

If you want to replace one character, use replace() as you already did. For a few but more than one characters you can nest the replace()s.

This however gets unhandy, when you want to replace quite a lot of characters. In such a situation, if the replacement character is only one character or the empty string regexp_replace() using a character class or alternates may come in handy.

For example

```<code>SELECT regexp_replace('a12b478c01', '[0-9]', '')
       FROM dual;
</code>```

replaces all the digits so just 'abc' remains and

```<code>SELECT regexp_replace('ABcc1233', 'c|3', '')
       FROM dual;
</code>```

removes any '3' or 'c' and results in 'AB12'. In your very example

```<code>SELECT regexp_replace('  @', ' ', '')
       FROM dual;
</code>```

would also work and give you '@'. Though in the simple case of your example a simple replace() is enough.

Body:
Basically  translate will change character to character and Replace string to string , and  here i have tried to remove spaces using translate to count the number words .

select translate('  @',' ','') from dual;

select replace('  @',' ','') from dual;

select ename , nvl(length(replace(TRANSLATE(upper(trim(ename)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ'' ','                           @ '),' ',''))+1,1) NOOFWORDs
from emp;

Body:
select translate('  @',' ','') from dual;

Returns NULL because in Oracle empty strings unfortunately yield NULLs. Therefore it's equivalent to

SELECT translate('  @', ' ', NULL)
       FROM dual;

and translate() returns NULL when an argument is null. Actually this is well documented in "TRANSLATE":

(...)

You cannot use an empty string for to_string to remove all characters in from_string from the return value. Oracle Database interprets the empty string as null, and if this function has a null argument, then it returns null.

If you want to replace one character, use replace() as you already did. For a few but more than one characters you can nest the replace()s.

This however gets unhandy, when you want to replace quite a lot of characters. In such a situation, if the replacement character is only one character or the empty string regexp_replace() using a character class or alternates may come in handy.

For example

SELECT regexp_replace('a12b478c01', '[0-9]', '')
       FROM dual;

replaces all the digits so just 'abc' remains and

SELECT regexp_replace('ABcc1233', 'c|3', '')
       FROM dual;

removes any '3' or 'c' and results in 'AB12'. In your very example

SELECT regexp_replace('  @', ' ', '')
       FROM dual;

would also work and give you '@'. Though in the simple case of your example a simple replace() is enough.


问:
react.ga: how to get the data created in the 'set' API
I am trying to integrate Google Analytics into my react app. And currently I'm using the react-ga library.

It's a little confusing or unclear to understand the API set.

```<code>ReactGA.set({ userId: 123 })
</code>```

There is not too much explanation about its functionalities. So what's the purpose of this API, and how to get the data set in the API?

答:
This API is used to set the userId in the user explorer tab in your google analytics account. so that you can view the events, page views with respect to that user ID.

This is basically to track the users based on their userID.

Body:
I am trying to integrate Google Analytics into my react app. And currently I'm using the react-ga library.

It's a little confusing or unclear to understand the API set.

ReactGA.set({ userId: 123 })

There is not too much explanation about its functionalities. So what's the purpose of this API, and how to get the data set in the API?


问:
.Count not supported when doing a find on child collection complex object field value
I have a find query that when from this

```<code>!CurrentUser.SentMatchRequest.Contains(OtherProfile.userId)
</code>```

To this

```<code>CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0
</code>```

However, the query fails by stating .count is not supported.
Before the collection used to be a simple string array and now it changed to a complex object

```<code>public class info
{
 public string Id {get;set;}
 public DateTime TimeStamp {get;set;}
}
</code>```

答:
If you want to test if your query's result contains at least one element, better use Any(), like so:

Instead of...

```<code>CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0
</code>```

better use...

```<code>!CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Any()
</code>```

If you really need the count, you can get it like this:

```<code>CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).ToList().Count==0
</code>```

The reason is, that IEnumerable<T> can be used to iterate through a collection, but the number of elements in the collection remains unknown until you reach the end.
T get the count of elements, you must iterate through the whole collection, that's what happens with the ToList() method, it forces LINQ to exactly do this.
If you only need to know, if the collection contains elements at all, this apporach is inefficient. Any() however, does what you need: It checks, if the collection contains at least one element, so this operation does not have t iterate through the whole collection.

Body:
I have a find query that when from this

!CurrentUser.SentMatchRequest.Contains(OtherProfile.userId)

To this

CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0

However, the query fails by stating .count is not supported.
Before the collection used to be a simple string array and now it changed to a complex object

public class info
{
 public string Id {get;set;}
 public DateTime TimeStamp {get;set;}
}

Body:
If you want to test if your query's result contains at least one element, better use Any(), like so:

Instead of...

CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Count==0

better use...

!CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).Any()

If you really need the count, you can get it like this:

CurrentUser.SentMatchRequest.FindAll(x => x.Id==OtherProfile.userId).ToList().Count==0

The reason is, that IEnumerable<T> can be used to iterate through a collection, but the number of elements in the collection remains unknown until you reach the end.
T get the count of elements, you must iterate through the whole collection, that's what happens with the ToList() method, it forces LINQ to exactly do this.
If you only need to know, if the collection contains elements at all, this apporach is inefficient. Any() however, does what you need: It checks, if the collection contains at least one element, so this operation does not have t iterate through the whole collection.


问:
How to fix: "Database Cant be imported" in C# using Visual Studio
I'm making a program for a C# project using Visual studio, and whenever I tried to insert the data into the database, it succeeded. But whenever I tried to refresh the db, it gives "The Database cannot be Imported. It's either an Unsupported SQL Server Version or an unsupported database compatibility" error.

The form i used is Windows Forms App (.NET Framework) and the database is SQL Server Database Project

Tried changing the Copy to Output directory to copy if newer, didn't work.

The code to save the input in registration form

```<code>using (DatabaseProjectEntities db = new DatabaseProjectEntities())
{
    db.MsUser.Add(usertemp);// msuser is name of the table &
                            // usertemp type is MsUser
    db.SaveChanges(); // saves

    MessageBox.Show("Success!");
    this.Close(); // form closes
}
</code>```

After I used the registration form, it shows MessageBox "Success!".

It saves into the current running program, but when I tried to refresh the database, it shows the error.

But when I tried to login in login form

```<code>
using (DatabaseProjectEntities db = new DatabaseProjectEntities())
{

    var peperesult = (...
        // selecting required data
        }
    );
...
//if else statement checking data is available in the database or not
    else
    {
        MessageBox.Show("Login Success");
        this.Close();
    }
</code>```

It shows "Login success", meaning the data already inserted.

If I close the running program, the data doesn't get inserted.

Update #1, I managed to make it work by simply use the database in bin/debug, however, since i have to submit it to other person, i have to use the database inside the project instead of using the visual studio one.

答:
Apparently, When my colleague made the first part of the project, he used an outdated Visual Studio to make it. Creating an older version of the Database.

After using the same version of Visual Studio. Change the Database behavior to Copy If Newer. It doesn't have any problem at all.

Guess next time I'm going to make sure we are all using the same version. :/

Body:
I'm making a program for a C# project using Visual studio, and whenever I tried to insert the data into the database, it succeeded. But whenever I tried to refresh the db, it gives "The Database cannot be Imported. It's either an Unsupported SQL Server Version or an unsupported database compatibility" error.

The form i used is Windows Forms App (.NET Framework) and the database is SQL Server Database Project

Tried changing the Copy to Output directory to copy if newer, didn't work.

The code to save the input in registration form

using (DatabaseProjectEntities db = new DatabaseProjectEntities())
{
    db.MsUser.Add(usertemp);// msuser is name of the table &
                            // usertemp type is MsUser
    db.SaveChanges(); // saves

    MessageBox.Show("Success!");
    this.Close(); // form closes
}

After I used the registration form, it shows MessageBox "Success!".

It saves into the current running program, but when I tried to refresh the database, it shows the error.

But when I tried to login in login form

using (DatabaseProjectEntities db = new DatabaseProjectEntities())
{

    var peperesult = (...
        // selecting required data
        }
    );
...
//if else statement checking data is available in the database or not
    else
    {
        MessageBox.Show("Login Success");
        this.Close();
    }

It shows "Login success", meaning the data already inserted.

If I close the running program, the data doesn't get inserted.

Update #1, I managed to make it work by simply use the database in bin/debug, however, since i have to submit it to other person, i have to use the database inside the project instead of using the visual studio one.


问:
cannot implicitly convert type 'string' to 'ConsoleApp3.Program.Status'
I'm practising doing code, I'm a beginner, and for some reason it's not working.

I've searched for some solutions, but I have found nothing in this matter.

```<code>namespace ConsoleApp3
{
    class Program
    {
        public enum Status { single, taken };

        public class Person
        {
            public string name;
            public int age;

            public string status;

             public Person(string _name, int _age, Status _status)
            {
                _name = name;
                _age = age;
                _status = status;

            }
            public void Print()
            {
                Console.WriteLine("Name: " + name );
                Console.WriteLine("Age: " + age );
                Console.WriteLine("Status: " + status);
            }
        }
        static void Main(string[] args)
        {

            Person Jackk = new Person("Jack", 20, Status.single);
            Jackk.Print();

            }
        }
    }
}
</code>```

I expect it would write all the information about the person, but it outputs the stuff in the Print void, but it doesn't use any of the variables, it will just print for example- Age : 0, even though it's set to 20.

I've got some messages about this. It says about the _age, _name, etc. that the value assigned to them is never used. But why?

Sorry if it's obvious, I'm still a beginner.

(the error says: cannot implicitly convert type 'string' to 'ConsoleApp3.Program.Status'), but if I removed the status thing completely, it would still not assign the variables to the output.

答: Your constructor has the assignments mirrored. You are assigning the input to the constructor to what is the default values of your instance variables, swap age = _age etc and you should be fine.

Body:
I'm practising doing code, I'm a beginner, and for some reason it's not working.

I've searched for some solutions, but I have found nothing in this matter.

namespace ConsoleApp3
{
    class Program
    {
        public enum Status { single, taken };

        public class Person
        {
            public string name;
            public int age;

            public string status;

             public Person(string _name, int _age, Status _status)
            {
                _name = name;
                _age = age;
                _status = status;

            }
            public void Print()
            {
                Console.WriteLine("Name: " + name );
                Console.WriteLine("Age: " + age );
                Console.WriteLine("Status: " + status);
            }
        }
        static void Main(string[] args)
        {

            Person Jackk = new Person("Jack", 20, Status.single);
            Jackk.Print();

            }
        }
    }
}

I expect it would write all the information about the person, but it outputs the stuff in the Print void, but it doesn't use any of the variables, it will just print for example- Age : 0, even though it's set to 20.

I've got some messages about this. It says about the _age, _name, etc. that the value assigned to them is never used. But why?

Sorry if it's obvious, I'm still a beginner.

(the error says: cannot implicitly convert type 'string' to 'ConsoleApp3.Program.Status'), but if I removed the status thing completely, it would still not assign the variables to the output.


答:
Because assigment operator takes value from variable on left of = and assigns it to the variable at the right of =

Change constructor to:

```<code>public Person(string _name, int _age, Status _status)
        {
            name = _name;
            age = _age;
            status = _status;

        }
</code>```

You pass Status enum that is why your field should be as well of type Status

Change status field to:

```<code>public Status status;
</code>```

Title: cannot implicitly convert type 'string' to 'ConsoleApp3.Program.Status'

Body:
Because assigment operator takes value from variable on left of = and assigns it to the variable at the right of =

Change constructor to:

public Person(string _name, int _age, Status _status)
        {
            name = _name;
            age = _age;
            status = _status;

        }

You pass Status enum that is why your field should be as well of type Status

Change status field to:

public Status status;


答:
Except for the array handling this is a duplicate of Measuring the distance between two coordinates in PHP (to calculate the distance). I would suggest something like:</p>

```<code>$dist=0;
$alen=count($latitude);

for ($i=1;$i<$alen;$i++) {
   $lat=$latitude[$i];
   $lon=$longotude[$i];
   $frlat=$latitude[$i-1];
   $frlon=$longotude[$i-1]
  // calculate distance according to the link above
  // pass in $frlat, $frlon and $lat, $lon to determine a single
  // segment distance. store in $calcdist)
  $dist+=$caldist;
  $llat=$lat;
  $
}
</code>```

Title: How to calculate the distance from multiple latitude and longitude coordinates?

Body:
I have the following arrays:

$latitude = ['9.9663755','10.1883153','9.9689272','10.1109653' ,'10.1883153','10.1883153']
$longitude = ['76.288569','76.4512288','76.2890601','76.3541268','76.4512288','76.4512288']

How do I get the total distance travelled  with these points.

Body:
Except for the array handling this is a duplicate of Measuring the distance between two coordinates in PHP (to calculate the distance). I would suggest something like:

$dist=0;
$alen=count($latitude);

for ($i=1;$i<$alen;$i++) {
   $lat=$latitude[$i];
   $lon=$longotude[$i];
   $frlat=$latitude[$i-1];
   $frlon=$longotude[$i-1]
  // calculate distance according to the link above
  // pass in $frlat, $frlon and $lat, $lon to determine a single
  // segment distance. store in $calcdist)
  $dist+=$caldist;
  $llat=$lat;
  $
}


问:
Switch between different types of buttons
So I used a codepen to implement buttons into my homepage here. The buttons work, but the issue is now the ToDo (+) button on the right, and the ToDo (x) button which appears after adding one, also have the effect of the button ToDo(+). Specifically, hovering over them has two parallel lines swing in from opposite ends. How do I separate them from each other so one doesn't affect the other? The specific css code is here:

```<code>button{
  background:#00000088;
  color:#fff;
  border:none;
  position:relative;
  height:40px;
  font-size:1.2em;
  padding:0 1em;
  cursor:pointer;
  margin: 0 0.25em;
  transition:800ms ease all;
  outline:none;
}
button:hover{
  background:#ffffff;
  color:#000;
}
button:before,button:after{
  content:'';
  position:absolute;
  top:0;
  right:0;
  height:3px;
  width:0;
  background: #bd818d;
  transition:400ms ease all;
}
button:after{
  right: inherit;
  top: 47px;
  left: -5px;
  bottom: 0;
}
button:hover:before,button:hover:after{
  width:100%;
  transition:800ms ease all;
}
</code>```

答:
Instead of applying styles to button, you can make use of classnames to give specific styles to separate buttons.
The classname containing common styles can be given to both, and the specific ones can be in their respective classnames.

Body:
So I used a codepen to implement buttons into my homepage here. The buttons work, but the issue is now the ToDo (+) button on the right, and the ToDo (x) button which appears after adding one, also have the effect of the button ToDo(+). Specifically, hovering over them has two parallel lines swing in from opposite ends. How do I separate them from each other so one doesn't affect the other? The specific css code is here:

button{
  background:#00000088;
  color:#fff;
  border:none;
  position:relative;
  height:40px;
  font-size:1.2em;
  padding:0 1em;
  cursor:pointer;
  margin: 0 0.25em;
  transition:800ms ease all;
  outline:none;
}
button:hover{
  background:#ffffff;
  color:#000;
}
button:before,button:after{
  content:'';
  position:absolute;
  top:0;
  right:0;
  height:3px;
  width:0;
  background: #bd818d;
  transition:400ms ease all;
}
button:after{
  right: inherit;
  top: 47px;
  left: -5px;
  bottom: 0;
}
button:hover:before,button:hover:after{
  width:100%;
  transition:800ms ease all;
}


问:
print output only if real boolean is passed to the function
What is an elegant way for debug function to print only if the value passed is an actual boolean value. If an object or string is passed as the second parameter, it should NOT print the output message. If I can avoid comparison of real boolean within the debug function, it would be an elegant solution to me.

```<code>function debug(msg, enable) {
       this.msg = msg;
       if (Boolean(enable))
         console.log(this.msg);
}
</code>```

debug("message", true) //should output message

debug("message", "random")// should not output the console message.

答:
I can't tell from the question whether you want to output the message if enable is a boolean (whether it's true or false) (the way I originally read it) or only if it's true (the way I read it the second time).

If only for booleans (whether true or false)

If for either true or false, then:

```<code>if (typeof enable === "boolean")
    console.log(this.msg);
</code>```

or

```<code>if (enable === true || enable === false)
    console.log(this.msg);
</code>```

or (but I think you said you didn't like this one):

```<code>if (Boolean(enable) === enable)
    console.log(this.msg);
</code>```

Live Example:

function debug(msg, enable) {
       this.msg = msg;
       if (enable === true)
         console.log(this.msg);
}

debug("one", true);      // prints
debug("two", "random");  // doesn't, it's not boolean, even though "random" is truthy```
</div>
</div>
</p>

<h3>If only for <code>true</code></h3>

<p>If you want to print the message only for <code>true</code>, then just use strict equality, since you want <code>false</code> to also not print the message:</p>

```if (enable === true)
    console.log(this.msg);
```

<p>With <code>===</code>, the expression will be false if:</p>

<ul>
<li><code>enable</code> isn't a boolean (because <code>===</code> requires the operand types to match), or</li>
<li><code>enable</code> is <code>false</code> (because although the types match, the values don't)</li>
</ul>

<p>Live Example:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function debug(msg, enable) {
       this.msg = msg;
       if (enable === true)
         console.log(this.msg);
}

debug("one", true);       // prints
debug("two", false);      // doesn't, it's false
debug("three", "random"); // doesn't, it's not boolean, even though "random" is truthy</code>```

Body:
What is an elegant way for debug function to print only if the value passed is an actual boolean value. If an object or string is passed as the second parameter, it should NOT print the output message. If I can avoid comparison of real boolean within the debug function, it would be an elegant solution to me.

function debug(msg, enable) {
       this.msg = msg;
       if (Boolean(enable))
         console.log(this.msg);
}

debug("message", true) //should output message

debug("message", "random")// should not output the console message.

Body:
I can't tell from the question whether you want to output the message if enable is a boolean (whether it's true or false) (the way I originally read it) or only if it's true (the way I read it the second time).

If only for booleans (whether true or false)

If for either true or false, then:

if (typeof enable === "boolean")
    console.log(this.msg);

or

if (enable === true || enable === false)
    console.log(this.msg);

or (but I think you said you didn't like this one):

if (Boolean(enable) === enable)
    console.log(this.msg);

Live Example:

function debug(msg, enable) {
       this.msg = msg;
       if (enable === true)
         console.log(this.msg);
}

debug("one", true);      // prints
debug("two", "random");  // doesn't, it's not boolean, even though "random" is truthy

If only for true

If you want to print the message only for true, then just use strict equality, since you want false to also not print the message:

if (enable === true)
    console.log(this.msg);

With ===, the expression will be false if:

enable isn't a boolean (because === requires the operand types to match), or

enable is false (because although the types match, the values don't)

Live Example:

function debug(msg, enable) {
       this.msg = msg;
       if (enable === true)
         console.log(this.msg);
}

debug("one", true);       // prints
debug("two", false);      // doesn't, it's false
debug("three", "random"); // doesn't, it's not boolean, even though "random" is truthy


问:
Always enter credentials without "prompt=login" in IdentityServer4
This is similar to IdentityServer4 Force User to re-enter credentials, but the solution there says to use prompt=login query string in the /authorize URL, which works, but also allows for sneaky users to remove it. Also, seeing as I'm not using .AddOpenIdConnect() the suggestion to use OnRedirectToIdentityProvider doesn't apply to me.

So how can we force the user to always enter credentials without relying on the prompt=login in the query string?

Here's my basic IdentityServer4 setup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var builder = services.AddIdentityServer()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApis())
        .AddInMemoryClients(Config.GetClients());

    builder.AddDeveloperSigningCredential();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseFileServer();
    app.UseIdentityServer();
    app.UseMvc();
}
```

<p>Where my login page only has an "OK" and "Cancel" button (I don't care which user logs on yet, only that authentication was OK or not), and the controller does the following when it is authenticating the user:</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<IActionResult> Post(AuthenticateViewModel model, string button)
{
    var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

    if (button == "authCancel")
    {
        if (context != null)
        {
            await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
            return Redirect(model.ReturnUrl);
        }

        return Redirect("~/");
    }

    if (button == "authOk" && ModelState.IsValid)
    {
        if (context != null)
        {
            await _events.RaiseAsync(new UserLoginSuccessEvent("provider", "userId", "subjectId", "name"));
            await HttpContext.SignInAsync("subject", "name", new AuthenticationProperties());
            return Redirect(model.ReturnUrl);
        }
    }

    return Redirect("~/");
}
</code>```

答:
You should be able to achieve desired behaviour by overriding the default cookie scheme that AddIdentityServer() registers internally:

```<code>services.AddIdentityServer()...

services.AddAuthentication("CustomScheme")
    .AddCookie("CustomScheme", options =>
    {
        options.ExpireTimeSpan = ...;
    });
</code>```

Make sure you add the override scheme after AddIdentityServer(), the sequence here is important due to the way ASP.Net Core DI works.

Body:
This is similar to IdentityServer4 Force User to re-enter credentials, but the solution there says to use prompt=login query string in the /authorize URL, which works, but also allows for sneaky users to remove it. Also, seeing as I'm not using .AddOpenIdConnect() the suggestion to use OnRedirectToIdentityProvider doesn't apply to me.

So how can we force the user to always enter credentials without relying on the prompt=login in the query string?

Here's my basic IdentityServer4 setup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var builder = services.AddIdentityServer()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApis())
        .AddInMemoryClients(Config.GetClients());

    builder.AddDeveloperSigningCredential();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseFileServer();
    app.UseIdentityServer();
    app.UseMvc();
}

Where my login page only has an "OK" and "Cancel" button (I don't care which user logs on yet, only that authentication was OK or not), and the controller does the following when it is authenticating the user:

public async Task<IActionResult> Post(AuthenticateViewModel model, string button)
{
    var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

    if (button == "authCancel")
    {
        if (context != null)
        {
            await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
            return Redirect(model.ReturnUrl);
        }

        return Redirect("~/");
    }

    if (button == "authOk" && ModelState.IsValid)
    {
        if (context != null)
        {
            await _events.RaiseAsync(new UserLoginSuccessEvent("provider", "userId", "subjectId", "name"));
            await HttpContext.SignInAsync("subject", "name", new AuthenticationProperties());
            return Redirect(model.ReturnUrl);
        }
    }

    return Redirect("~/");
}

Body:
You should be able to achieve desired behaviour by overriding the default cookie scheme that AddIdentityServer() registers internally:

services.AddIdentityServer()...

services.AddAuthentication("CustomScheme")
    .AddCookie("CustomScheme", options =>
    {
        options.ExpireTimeSpan = ...;
    });

Make sure you add the override scheme after AddIdentityServer(), the sequence here is important due to the way ASP.Net Core DI works.


问:
Kotlin domain class casting to subclass
I have a domain class

```<code>@Entity
@Table(name = "user")
open class User(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    open var id: Long = 0L,

    @Column(nullable = false)
    var name: String? = null)
</code>```

And I have a subclass of this domain class that I would like to add a JsonIgnore annotation:

```<code>open class UserFiltered(
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    override var id: Long = 0L
): User()
</code>```

But when I try to cast the User to UserFiltered:

```<code>return ResponseModel<UserFiltered>(true, userModified as UserFiltered)
</code>```

I get the following error:

java.lang.ClassCastException:
  com.example.platform.database.domain.User cannot be cast to
  com.example.platform.model.UserFiltered   at
  com.example.platform.controller.UserController.modifyUser(UserController.kt:71)
  ~[classes/:na]

Is there a way to achieve this in Kotlin, or I will have to do the full cast, setting up every parameter on User?

答:
I had to modify the child class to the following form:

```<code>open class UserFiltered(
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    override var id: Long = 0L
): User(){
    constructor(user: User): this(user.id)
}
</code>```

And creating the instance of UserFiltered

```<code>return ResponseModel<UserFiltered>(true, UserFiltered(userModified))
</code>```

Title: Kotlin domain class casting to subclass

Body:
I have a domain class

@Entity
@Table(name = "user")
open class User(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    open var id: Long = 0L,

    @Column(nullable = false)
    var name: String? = null)

And I have a subclass of this domain class that I would like to add a JsonIgnore annotation:

open class UserFiltered(
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    override var id: Long = 0L
): User()

But when I try to cast the User to UserFiltered:

return ResponseModel<UserFiltered>(true, userModified as UserFiltered)

I get the following error:

java.lang.ClassCastException:
  com.example.platform.database.domain.User cannot be cast to
  com.example.platform.model.UserFiltered   at
  com.example.platform.controller.UserController.modifyUser(UserController.kt:71)
  ~[classes/:na]

Is there a way to achieve this in Kotlin, or I will have to do the full cast, setting up every parameter on User?

Body:
I had to modify the child class to the following form:

open class UserFiltered(
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    override var id: Long = 0L
): User(){
    constructor(user: User): this(user.id)
}

And creating the instance of UserFiltered

return ResponseModel<UserFiltered>(true, UserFiltered(userModified))


问:
Jquery UI, "dead area" with sortable portlets
I'm trying to make a portlet based page where the portlets have different sizes.

The problem is to work around the "dead area" to the left of the "2.2 portlet", a “1.1 portlet” or a “2.1 portlet” would fit into the space, but is it possible to accomplice and how ?

The width of the page is fixed and should remain like that, http://www.jsfiddle.net/XF2pV/

I'm open for suggestions on other frameworks if jQuery UI can't accomplice this.

答:
Unfortunately the method is flawed. Using jquery sortable with a grid layout of differing sized items will result in this behaviour. The reason is that in the html and css, you are creating a list of items floated left, which when allowed to wrap in a fixed width container, will leave gaps which are effectively unusable.

The fact that your container width is fixed, and your boxes are fixed size means it would be easy to try another way of positioning them. Try using absolute positioning using just css and html to get all the spaces filled exactly as you initially want them, then experiment with the javascript to move the boxes around.

However, I doubt that the 'sortable' jQuery library would work when using absolute positioning (I must admit I've never used it) With absolute positioning, it is likely that getting items to 'move out of the way' when you drag something over them will be problematic. You may need to define on set of hidden divs which act as your 'grid' - or places you can drop stuff, and another set of divs which contain the visible stuff you want to move around. The jQuery draggable and dropable api will help, but you will need to do a lot more coding to ensure the items you move 'snap' into position, moving others out of the way when you drop them.

This looks related https://stackoverflow.com/questions/2133677/jquery-sortable-divs-replicate-bbc-home-page maybe you could check the source code of the BBC homepage. http://bbc.co.uk


问:
layout of the screen moves up when keyboard is displayed
Let say I have the following layout:

when I click on the edit text at the bottom I get this:

As you can notice the image from the top goes upper and the whole layout moves.
 This is my xml for this layout:

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

   <LinearLayout
       android:id="@+id/header"
       android:layout_width="fill_parent"
       android:layout_height="75dp"
       android:layout_alignParentLeft="true"
       android:layout_alignParentRight="true"
       android:layout_alignParentTop="true"
       android:isScrollContainer="true"
       android:background="@drawable/header" >
   </LinearLayout>

   <ScrollView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:id="@+id/scrollauthentication"
       android:layout_below="@+id/header"
       android:background="#FFFFFF"
       android:fillViewport="true" >

       <RelativeLayout
           xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:background="#FFFFFF"
           android:id="@+id/authenticationrelativelayout">

           <TextView
               android:id="@+id/login"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignParentLeft="true"
               android:layout_below="@+id/header"
               android:layout_marginLeft="30dp"
               android:layout_marginTop="20dp"
               android:text="login"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/lighter_orange"
               android:textSize="28dp" />

           <TextView
               android:id="@+id/usernameTextView"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignLeft="@+id/login"
               android:layout_below="@+id/login"
               android:layout_marginTop="16dp"
               android:text="username"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/dark_gray" />

           <EditText
               android:id="@+id/user"
               android:layout_width="260dp"
               android:layout_height="42dp"
               android:layout_alignLeft="@+id/usernameTextView"
               android:layout_below="@+id/usernameTextView"
               android:background="@drawable/edittext_selector"
               android:imeOptions="actionDone"
               android:lines="1"
               android:paddingLeft="10dp" />

           <TextView
               android:id="@+id/passwordTextView"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignLeft="@+id/user"
               android:layout_below="@+id/user"
               android:text="password"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/dark_gray" />

           <EditText
               android:id="@+id/password"
               android:layout_width="260dp"
               android:layout_height="42dp"
               android:layout_alignLeft="@+id/passwordTextView"
               android:layout_below="@+id/passwordTextView"
               android:background="@drawable/edittext_selector"
               android:imeOptions="actionDone"
               android:inputType="textPassword"
               android:lines="1"
               android:paddingLeft="10dp" >

               <requestFocus />
           </EditText>

           <CheckBox
               android:id="@+id/remembercheckBox"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignLeft="@+id/password"
               android:layout_below="@+id/password"
               android:layout_marginTop="37dp"
               android:button="@drawable/checkbox_selector"
               android:focusable="true" />

           <TextView
               android:id="@+id/rememberText"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignBaseline="@+id/remembercheckBox"
               android:layout_alignBottom="@+id/remembercheckBox"
               android:layout_toRightOf="@+id/remembercheckBox"
               android:text="Remember me"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/dark_gray" />
       </RelativeLayout>
   </ScrollView>

   <LinearLayout
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_marginLeft="30dp"
       android:layout_below="@+id/scrollauthentication"
       android:orientation="horizontal" >

       <Button
           android:id="@+id/loginButton"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:background="@color/button_selected"
           android:text="log in"
           android:textColor="@drawable/textblack_selected"
           android:textStyle="bold" >
       </Button>

       <Button
           android:id="@+id/forgotten"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginLeft="10dp"
           android:background="@color/button_selected"
           android:text="forgotten password"
           android:textColor="@drawable/textblack_selected"
           android:textStyle="bold" />
   </LinearLayout>

</RelativeLayout>
</code>```

And I have also set this in manifest file for this activity:

```<code>android:windowSoftInputMode="adjustPan"
</code>```

So is there a way to stop my layout from moving when the keyboard is displayed?
Thank you!!!!

答:
Try this, for me it worked...</p>

```<code><CoordinatorLayout
android:fitsSystemWindows="true">
<AppBarLayout>
    <Toobar>
        <!--...-->
    </Toobar>
</AppBarLayout>
<include layout="@layout/content_main_message" /> <!--EditText here-->
</CoordinatorLayout>
</code>```

Body:
Let say I have the following layout:

when I click on the edit text at the bottom I get this:

As you can notice the image from the top goes upper and the whole layout moves.
 This is my xml for this layout:

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

   <LinearLayout
       android:id="@+id/header"
       android:layout_width="fill_parent"
       android:layout_height="75dp"
       android:layout_alignParentLeft="true"
       android:layout_alignParentRight="true"
       android:layout_alignParentTop="true"
       android:isScrollContainer="true"
       android:background="@drawable/header" >
   </LinearLayout>

   <ScrollView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:id="@+id/scrollauthentication"
       android:layout_below="@+id/header"
       android:background="#FFFFFF"
       android:fillViewport="true" >

       <RelativeLayout
           xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:background="#FFFFFF"
           android:id="@+id/authenticationrelativelayout">

           <TextView
               android:id="@+id/login"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignParentLeft="true"
               android:layout_below="@+id/header"
               android:layout_marginLeft="30dp"
               android:layout_marginTop="20dp"
               android:text="login"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/lighter_orange"
               android:textSize="28dp" />

           <TextView
               android:id="@+id/usernameTextView"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignLeft="@+id/login"
               android:layout_below="@+id/login"
               android:layout_marginTop="16dp"
               android:text="username"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/dark_gray" />

           <EditText
               android:id="@+id/user"
               android:layout_width="260dp"
               android:layout_height="42dp"
               android:layout_alignLeft="@+id/usernameTextView"
               android:layout_below="@+id/usernameTextView"
               android:background="@drawable/edittext_selector"
               android:imeOptions="actionDone"
               android:lines="1"
               android:paddingLeft="10dp" />

           <TextView
               android:id="@+id/passwordTextView"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignLeft="@+id/user"
               android:layout_below="@+id/user"
               android:text="password"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/dark_gray" />

           <EditText
               android:id="@+id/password"
               android:layout_width="260dp"
               android:layout_height="42dp"
               android:layout_alignLeft="@+id/passwordTextView"
               android:layout_below="@+id/passwordTextView"
               android:background="@drawable/edittext_selector"
               android:imeOptions="actionDone"
               android:inputType="textPassword"
               android:lines="1"
               android:paddingLeft="10dp" >

               <requestFocus />
           </EditText>

           <CheckBox
               android:id="@+id/remembercheckBox"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignLeft="@+id/password"
               android:layout_below="@+id/password"
               android:layout_marginTop="37dp"
               android:button="@drawable/checkbox_selector"
               android:focusable="true" />

           <TextView
               android:id="@+id/rememberText"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_alignBaseline="@+id/remembercheckBox"
               android:layout_alignBottom="@+id/remembercheckBox"
               android:layout_toRightOf="@+id/remembercheckBox"
               android:text="Remember me"
               android:textAppearance="?android:attr/textAppearanceMedium"
               android:textColor="@color/dark_gray" />
       </RelativeLayout>
   </ScrollView>

   <LinearLayout
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_marginLeft="30dp"
       android:layout_below="@+id/scrollauthentication"
       android:orientation="horizontal" >

       <Button
           android:id="@+id/loginButton"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:background="@color/button_selected"
           android:text="log in"
           android:textColor="@drawable/textblack_selected"
           android:textStyle="bold" >
       </Button>

       <Button
           android:id="@+id/forgotten"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginLeft="10dp"
           android:background="@color/button_selected"
           android:text="forgotten password"
           android:textColor="@drawable/textblack_selected"
           android:textStyle="bold" />
   </LinearLayout>

</RelativeLayout>

And I have also set this in manifest file for this activity:

android:windowSoftInputMode="adjustPan"

So is there a way to stop my layout from moving when the keyboard is displayed?
Thank you!!!!

Body:
Try this, for me it worked...

<CoordinatorLayout
android:fitsSystemWindows="true">
<AppBarLayout>
    <Toobar>
        <!--...-->
    </Toobar>
</AppBarLayout>
<include layout="@layout/content_main_message" /> <!--EditText here-->
</CoordinatorLayout>


答:
You can check typeof enable

function debug(msg, enable) {
    this.msg = msg;
    if (typeof enable === 'boolean')
      console.log(this.msg);
}

debug("message", true) //should output message
debug("message", "random")```
</div>
</div>
</p>

<p>If you wish to show message only when enable is boolean and truthy than you can extend above code </p>

```if (typeof enable === 'boolean' && enable)
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function debug(msg, enable) {
    this.msg = msg;
    if (typeof enable === 'boolean' && enable)
      console.log(this.msg);
}

debug("message", true) //should output message
debug("message", "random")
debug("message", false)</code>```

Title: print output only if real boolean is passed to the function

Body:
You can check typeof enable

function debug(msg, enable) {
    this.msg = msg;
    if (typeof enable === 'boolean')
      console.log(this.msg);
}

debug("message", true) //should output message
debug("message", "random")

If you wish to show message only when enable is boolean and truthy than you can extend above code

if (typeof enable === 'boolean' && enable)

function debug(msg, enable) {
    this.msg = msg;
    if (typeof enable === 'boolean' && enable)
      console.log(this.msg);
}

debug("message", true) //should output message
debug("message", "random")
debug("message", false)


答:
You can use ===.

```<code>function debug(msg, enable) {
    this.msg = msg;
    if (enable === true)
        console.log(this.msg);
}
</code>```

Body:
You can use ===.

function debug(msg, enable) {
    this.msg = msg;
    if (enable === true)
        console.log(this.msg);
}


问:
Java: Why internal class has to be static?
I know that internal class has to be static because will link between public and internal classes and internal class will be created all times that created public classes.
And my question how to check it?
I mean write some simple application and make some loop for creating objects and see that objects do not deleted by GC in some profiler, Can I to do something like that nad some one done it?
Thanks.</p>

答: This can be done using static analysis. If you are using Eclipse check out the FindBugs plugin, it can detect the lack of static inner classes and a bunch of other useful problems.


问:
Summation iterated over a variable length
I have written an optimization problem in pyomo and need a constraint, which contains a summation that has a variable length:
u_i_t[i, t]*T_min_run - sum (tnewnew in (t-T_min_run+1)..t-1) u_i_t[i,tnewnew] <= sum (tnew in t..(t+T_min_run-1)) u_i_t[i,tnew]

T is my actual timeline and N my machines
usually I iterate over t, but I need to guarantee the machines are turned on for certain amount of time.

```<code>def HP_on_rule(model, i, t):
    return model.u_i_t[i, t]*T_min_run - sum(model.u_i_t[i, tnewnew] for tnewnew in range((t-T_min_run+1), (t-1))) <= sum(model.u_i_t[i, tnew] for tnew in range(t, (t+T_min_run-1)))
model.HP_on_rule = Constraint(N, rule=HP_on_rule)
</code>```

I hope you can provide me with the correct formulation in pyomo/python.

The problem is that t is a running variable and I do not know how to implement this in Python. tnew is only a help variable. E.g. t=6 (variable), T_min_run=3 (constant) and u_i_t is binary [00001111100000...] then I get:
1*3 - 1 <= 3
As I said, I do not know how to implement this in my code and the current version is not running.
TypeError: HP_on_rule() missing 1 required positional argument: 't'

答:
It seems like you didn't provide all your arguments to the function rule.

Since t is a parameter of your function, I assume that it corresponds to an element of set T (your timeline).

Then, your last line of your code example should include not only the set N, but also the set T. Try this:

```<code>model.HP_on_rule = Constraint(N, T, rule=HP_on_rule)
</code>```

Please note: Building a Constraint with a "for each" part, you must provide the Pyomo Sets that you want to iterate over at the begining of the call for Constraint construction. As a rule of thumb, your constraint rule function should have 1 more argument than the number of Pyomo Sets specified in the Constraint initilization line.

Body:
I have written an optimization problem in pyomo and need a constraint, which contains a summation that has a variable length:
u_i_t[i, t]*T_min_run - sum (tnewnew in (t-T_min_run+1)..t-1) u_i_t[i,tnewnew] <= sum (tnew in t..(t+T_min_run-1)) u_i_t[i,tnew]

T is my actual timeline and N my machines
usually I iterate over t, but I need to guarantee the machines are turned on for certain amount of time.

def HP_on_rule(model, i, t):
    return model.u_i_t[i, t]*T_min_run - sum(model.u_i_t[i, tnewnew] for tnewnew in range((t-T_min_run+1), (t-1))) <= sum(model.u_i_t[i, tnew] for tnew in range(t, (t+T_min_run-1)))
model.HP_on_rule = Constraint(N, rule=HP_on_rule)

I hope you can provide me with the correct formulation in pyomo/python.

The problem is that t is a running variable and I do not know how to implement this in Python. tnew is only a help variable. E.g. t=6 (variable), T_min_run=3 (constant) and u_i_t is binary [00001111100000...] then I get:
1*3 - 1 <= 3
As I said, I do not know how to implement this in my code and the current version is not running.
TypeError: HP_on_rule() missing 1 required positional argument: 't'

Body:
It seems like you didn't provide all your arguments to the function rule.

Since t is a parameter of your function, I assume that it corresponds to an element of set T (your timeline).

Then, your last line of your code example should include not only the set N, but also the set T. Try this:

model.HP_on_rule = Constraint(N, T, rule=HP_on_rule)

Please note: Building a Constraint with a "for each" part, you must provide the Pyomo Sets that you want to iterate over at the begining of the call for Constraint construction. As a rule of thumb, your constraint rule function should have 1 more argument than the number of Pyomo Sets specified in the Constraint initilization line.


问:
How to View Saved WiFi Passwords on Windows 7, 8, & 10
Can I get the wifi password of my windows pc when it is successful connected? Can I get it from a file or is there another way to do that?</p>

答:
Get windows wifi password

Go to the toolbar and select the Show Hide Icons button and select the connected wifi

Right click on the yellow coloured area and select Open network & Internet Settings

Select the Change adapter option

Then will list all the connections then select the wifi connection which you want to get the password then right click and select the Status

Then will open a status window and then select the Wireless Properties

after that select the Security tab and check the Show characters Then you will get the password from the red marked area.


问:
Putting RUN commands in one line make build faster?
In my docker file, does it really matter if I put RUN commands in one line or not? Does putting them in one line make build time faster?

```<code>RUN apt-get update
RUN apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools
</code>```

vs.

```<code>RUN apt-get update && apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools
</code>```

答:
By minimizing the number of layers you're reducing the size of your image and yes, also build time. This is also recommended in best practices section "Minimize number of layers".

In older versions of Docker, it was important that you minimized the number of layers in your images to ensure they were performant. The following features were added to reduce this limitation.

Only the instructions RUN, COPY, ADD create layers. Other instructions create temporary intermediate images, and do not increase the size of the build.

...

Body:
In my docker file, does it really matter if I put RUN commands in one line or not? Does putting them in one line make build time faster?

RUN apt-get update
RUN apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools

vs.

RUN apt-get update && apt-get -y install --no-install-recommends python3
RUN apt-get -y install --no-install-recommends open-vm-tools


答:
Just replace this line:

```<code>new MorphingBG(document.querySelector('.svg-morph'));
</code>```

With this code:

```<code>// get all elements that you want to morph (not only one)
let toBeMorphed = document.querySelectorAll('.svg-morph');

// apply the MorphingOperator on each of these elements
toBeMorphed.forEach(function(svg) {
    new MorphingBG(svg);
});
</code>```

Title: How to anime EACH svg

Body:
Now my code anime only one SVG with many path in my page, but I would like anime each SVG in my page. If I have many SVG in my page, only first SVG anime.

I work on my localhost for the moment

''script

{
    class MorphingBG {
        constructor(el) {
            this.DOM = {};
            this.DOM.el = el;
            this.DOM.paths = Array.from(this.DOM.el.querySelectorAll('path'));
            this.animate();
        }
        animate() {
            this.DOM.paths.forEach((path) => {
                setTimeout(() => {
                    anime({
                        targets: path,
                        duration: anime.random(3000,5000),
                        easing: [0.5,0,0.5,1],
                        d: path.getAttribute('pathdata:id'),
                        loop: true,
                        direction: 'alternate'
                    });
                }, anime.random(0,1000));
            });
        }
    };

    new MorphingBG(document.querySelector('.svg-morph'));
};

''html

<svg class="svg-morph morph-1" viewBox="0 0 963 754">
<path d="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,56.6,133.8,61,201.5c15.1,233.2-6.4,205.1-49.5,314 C-69,811,459,815,457.4,632c2.2-161.1,601.7-37.1,635.9-382.5C1124.6-66.8,915.2-218.7,739.8-218.7 Z" pathdata:id="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,18,28,20,170c3,228-3,125-8.5,345.5C8,763,379.34,770,551.34,622 c140-157,502.46,60.4,536.66-285C1119.3,20.7,915.2-218.7,739.8-218.7 Z"></path>
</svg>

<svg class="svg-morph morph-2" version="1.1" viewBox="0 0 735.6 807">
    <path d="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,56.6,133.8,61,201.5c15.1,233.2-6.4,205.1-49.5,314 C-69,811,459,815,457.4,632c2.2-161.1,601.7-37.1,635.9-382.5C1124.6-66.8,915.2-218.7,739.8-218.7 Z" pathdata:id="M 739.8-218.7C456-218,480-70,209.9-85.9C39-85,18,28,20,170c3,228-3,125-8.5,345.5C8,763,379.34,770,551.34,622 c140-157,502.46,60.4,536.66-285C1119.3,20.7,915.2-218.7,739.8-218.7 Z"></path>
</svg>

For the moment only svg class="svg-morph morph-1" it's animate

Body:
Just replace this line:

new MorphingBG(document.querySelector('.svg-morph'));

With this code:

// get all elements that you want to morph (not only one)
let toBeMorphed = document.querySelectorAll('.svg-morph');

// apply the MorphingOperator on each of these elements
toBeMorphed.forEach(function(svg) {
    new MorphingBG(svg);
});


问:
How can I find the position of an object (not an int) inside a c++ 2d vector?
I need to track the position of objects (Boxes) in a grid for a candycrush-like game I am developing.

The easiest way I found to keep track of their positions in the grid would be to add them to a 2d vector, move them inside the vector according to the game logic. That is easy.

The hard part, and where I’m actually stuck is to get their current position on the grid at any given time, or in this case, the position inside the 2d vector.
In short, if I had and easy way to periodically check the position of my Box object inside its 2d array, that would solve the problem.

I've been messing around with std:find and std: count, but I am a bit of a newbie and I’m having a hard time. Same of the code below:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

struct position
{
    int x;
    int y;
};

class Box
{
public:
    position currentPosition;

};

int main(int argc, const char * argv[])
{

    Box box1 = Box();
    Box box2 = Box();
    Box box3 = Box();
    Box box4 = Box();
    Box box5 = Box();
    Box box6 = Box();
    Box box7 = Box();
    Box box8 = Box();
    Box box9 = Box();

   // vector<vector<Box>> boxes2dVector;
//
    vector<vector<Box>> boxes2dVector =
    {
        {box1, box2,box3},
        {box4, box5,box6},
        {box7, box8,box9}

    };

    return 0;
}

position getPositionOfBox (Box box, vector<vector<Box>> vct)
{
    position resultPositon;

    /*
     This is what I need...some code that finds the position in the of a Box object in side a 2d array
     */

    return resultPositon;
};
</code>```

Any ideas or help, anyone?

Many thanks!

答:
I think what you are looking for is here : How to use std::find/std::find_if with a vector of custom class objects?

with that in place it's quite easy use this : How to get position of a certain element in strings vector, to use it as an index in ints vector?

Body:
I need to track the position of objects (Boxes) in a grid for a candycrush-like game I am developing.

The easiest way I found to keep track of their positions in the grid would be to add them to a 2d vector, move them inside the vector according to the game logic. That is easy.

The hard part, and where I’m actually stuck is to get their current position on the grid at any given time, or in this case, the position inside the 2d vector.
In short, if I had and easy way to periodically check the position of my Box object inside its 2d array, that would solve the problem.

I've been messing around with std:find and std: count, but I am a bit of a newbie and I’m having a hard time. Same of the code below:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

struct position
{
    int x;
    int y;
};

class Box
{
public:
    position currentPosition;

};

int main(int argc, const char * argv[])
{

    Box box1 = Box();
    Box box2 = Box();
    Box box3 = Box();
    Box box4 = Box();
    Box box5 = Box();
    Box box6 = Box();
    Box box7 = Box();
    Box box8 = Box();
    Box box9 = Box();

   // vector<vector<Box>> boxes2dVector;
//
    vector<vector<Box>> boxes2dVector =
    {
        {box1, box2,box3},
        {box4, box5,box6},
        {box7, box8,box9}

    };

    return 0;
}

position getPositionOfBox (Box box, vector<vector<Box>> vct)
{
    position resultPositon;

    /*
     This is what I need...some code that finds the position in the of a Box object in side a 2d array
     */

    return resultPositon;
};

Any ideas or help, anyone?

Many thanks!


问:
How to properly frame a collate command in T-SQL?
I'm trying to write a query across two linked servers. Having set up the link with an appropriate logon, I'm getting this collate error:

Cannot resolve the collation conflict
  between "SQL_Latin1_General_CP1_CI_AS"
  and "Latin1_General_CI_AS" in the
  equal to operation.

This is new to me, but it looks like a charset conflict, so I googled it and discovered the collate command which can be added to my join. However I've tried both

```<code>va ON V_ID1 = c1.strData COLLATE Latin1_General_CI_AS
</code>```

and

```<code>va ON V_ID1 = c1.strData COLLATE SQL_Latin1_General_CP1_CI_AS
</code>```

And neither seems to resolve the error. What am I doing wrong?

EDIT: The entire query is too big to post and expect people to filter through, but here's the relevant bit:

```<code>   select
        rel.intParentAttributeId as intItemId,
        case va.type
        when 'SM' then 120000000
        when 'FB' then 110000000
        when 'RO' then 100000000
        when 'SP' then 90000000
        when 'A' then 80000000
        when 'D' then 70000000
        when 'P' then 60000000
        when 'SR' then 50000000
        when 'FN' then 40000000
        when 'RL' then 30000000
        when 'VO' then 20000000
        when 'RE' then 10000000
        end
        +

        rel.intParentAttributeId
        as fltStrength
        from
        AttributeMap ky

        join Catalogue c1 on c1.intRowId=ky.intChildAttributeId and c1.intAttributeTypeId=@intsimilarAtt

        join

        [SQLSERVERNAME].[SchemaName].dbo.VidAssc
         va on V_ID1 COLLATE SQL_Latin1_General_CP1_CI_AS = c1.strData COLLATE SQL_Latin1_General_CP1_CI_AS

        join Catalogue c2 on c2.strData=V_ID2 and c2.intAttributeTypeId=@intsimilarAtt

        join AttributeMap rel on rel.intChildAttributeId = c2.intRowId

        join @tmpSeeds s on s.intItemId = ky.intParentAttributeId

        group by rel.intParentAttributeId,va.Type

        )sqi
</code>```

Cheers,
Matt

答:
OK, finally found a fix. Here's what you have to do:

In sql server manager to to Server Objects > Linked Servers > and find the problematic linked server.

Right Click > Properties

Under Server Options set "Use Remote Collation" to "False"
and "Collation Name" to "Latin1_General_CI_AS"

Body:
I'm trying to write a query across two linked servers. Having set up the link with an appropriate logon, I'm getting this collate error:

Cannot resolve the collation conflict
  between "SQL_Latin1_General_CP1_CI_AS"
  and "Latin1_General_CI_AS" in the
  equal to operation.

This is new to me, but it looks like a charset conflict, so I googled it and discovered the collate command which can be added to my join. However I've tried both

va ON V_ID1 = c1.strData COLLATE Latin1_General_CI_AS

and

va ON V_ID1 = c1.strData COLLATE SQL_Latin1_General_CP1_CI_AS

And neither seems to resolve the error. What am I doing wrong?

EDIT: The entire query is too big to post and expect people to filter through, but here's the relevant bit:

   select
        rel.intParentAttributeId as intItemId,
        case va.type
        when 'SM' then 120000000
        when 'FB' then 110000000
        when 'RO' then 100000000
        when 'SP' then 90000000
        when 'A' then 80000000
        when 'D' then 70000000
        when 'P' then 60000000
        when 'SR' then 50000000
        when 'FN' then 40000000
        when 'RL' then 30000000
        when 'VO' then 20000000
        when 'RE' then 10000000
        end
        +

        rel.intParentAttributeId
        as fltStrength
        from
        AttributeMap ky

        join Catalogue c1 on c1.intRowId=ky.intChildAttributeId and c1.intAttributeTypeId=@intsimilarAtt

        join

        [SQLSERVERNAME].[SchemaName].dbo.VidAssc
         va on V_ID1 COLLATE SQL_Latin1_General_CP1_CI_AS = c1.strData COLLATE SQL_Latin1_General_CP1_CI_AS

        join Catalogue c2 on c2.strData=V_ID2 and c2.intAttributeTypeId=@intsimilarAtt

        join AttributeMap rel on rel.intChildAttributeId = c2.intRowId

        join @tmpSeeds s on s.intItemId = ky.intParentAttributeId

        group by rel.intParentAttributeId,va.Type

        )sqi

Cheers,
Matt


问:
Default interface methods are only supported starting with Android 7.0 (Nougat)
I upgraded to Android Studio 3.1 and I'm getting the following error:

Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner)

Message{kind=ERROR, text=Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner), sources=[Unknown source file], tool name=Optional.of(D8)}

Here is my Gradle configuration:

```<code>compileSdkVersion 27
//buildToolsVersion '27.0.3'
defaultConfig {
    minSdkVersion 16
    targetSdkVersion 27
     multiDexEnabled true
     //...
   }
</code>```

As you can see, I am targeting 27 which is already ahead of 24 that it's complaining about. What exactly should I do to fix this? If I change to 1.8 Java, won't I be missing a lot of customers? Why was I not getting this error before I upgraded Android Studio?

I do not know if this is about the LifecycleObserver class I recently put in. It was in Kotlin and now I changed it to Java, but I still get the same error after cleaning the project:

public class LifeCycleAwareObserver implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void  onAppBackgrounded() {
        AnalyticsUtils.trackStartSession(true);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        AnalyticsUtils.trackStartSession(false);
    }
}
```
<p>How can I trace where the error is coming from so I can fix it?</p>
<p>Here are my version dependencies:</p>
```project.ext {

        firebase_version = '12.0.0'

        supportlib_version = '27.0.2'

        room_version = '1.0.0'

        espresso_version = '3.0.1'

        archLifecycleVersion = '1.1.1'
    }
```

答:
Use this code in your build.gradle file:

```<code>android {
    compileOptions {
        incremental true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
</code>```

Body:
I upgraded to Android Studio 3.1 and I'm getting the following error:

Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner)

Message{kind=ERROR, text=Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner), sources=[Unknown source file], tool name=Optional.of(D8)}

Here is my Gradle configuration:

compileSdkVersion 27
//buildToolsVersion '27.0.3'
defaultConfig {
    minSdkVersion 16
    targetSdkVersion 27
     multiDexEnabled true
     //...
   }

As you can see, I am targeting 27 which is already ahead of 24 that it's complaining about. What exactly should I do to fix this? If I change to 1.8 Java, won't I be missing a lot of customers? Why was I not getting this error before I upgraded Android Studio?

I do not know if this is about the LifecycleObserver class I recently put in. It was in Kotlin and now I changed it to Java, but I still get the same error after cleaning the project:

public class LifeCycleAwareObserver implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void  onAppBackgrounded() {
        AnalyticsUtils.trackStartSession(true);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        AnalyticsUtils.trackStartSession(false);
    }
}

How can I trace where the error is coming from so I can fix it?

Here are my version dependencies:

project.ext {

        firebase_version = '12.0.0'

        supportlib_version = '27.0.2'

        room_version = '1.0.0'

        espresso_version = '3.0.1'

        archLifecycleVersion = '1.1.1'
    }

Body:
Use this code in your build.gradle file:

android {
    compileOptions {
        incremental true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}


问:
TensorFlow/Keras: Why do I get "ValueError: Incompatible conversion from float32 to uint8" when calling fit?
I use TensorFlow 1.12 with eager execution. When I call

```<code>model.fit(train, steps_per_epoch=int(np.ceil(num_train_samples / BATCH_SIZE)), epochs=NUM_EPOCHS, batch_size=BATCH_SIZE, validation_data=val, validation_steps=int(np.ceil(num_val_samples / BATCH_SIZE)))
</code>```

I get the following error:

```<code>ValueError: Incompatible type conversion requested to type 'uint8' for variable of type 'float32'
</code>```

As far as I know, I am not converting from uint8 to float32 anywhere, at least not explicitly.

My datasets are generated as follows:

```<code>train = tf.data.Dataset.from_generator(generator=train_sample_fetcher, output_types=(tf.uint8, tf.float32))
train = train.repeat()
train = train.batch(BATCH_SIZE)
train = train.shuffle(10)
val = tf.data.Dataset.from_generator(generator=val_sample_fetcher, output_types=(tf.uint8, tf.float32))
</code>```

employing the following generator functions:

```<code>def train_sample_fetcher():
    return sample_fetcher()

def val_sample_fetcher():
    return sample_fetcher(is_validations=True)

def sample_fetcher(is_validations=False):
    sample_names = [filename[:-4] for filename in os.listdir(DIR_DATASET + "ndarrays/")]
    if not is_validations: sample_names = sample_names[:int(len(sample_names) * TRAIN_VAL_SPLIT)]
    else: sample_names = sample_names[int(len(sample_names) * TRAIN_VAL_SPLIT):]
    for sample_name in sample_names:
        rgb = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + sample_name + ".jpg"))
        rgb = tf.image.resize_images(rgb, (HEIGHT, WIDTH))
        #d = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + "depth/" + sample_name + ".jpg"))
        #d = tf.image.resize_images(d, (HEIGHT, WIDTH))
        #rgbd = tf.concat([rgb,d], axis=2)
        onehots = tf.convert_to_tensor(np.load(DIR_DATASET + "ndarrays/" + sample_name + ".npy"), dtype=tf.float32)
        yield rgb, onehots
</code>```

---------------------------------------------------------------------------------

For reference, the full stacktrace:

```<code>Traceback (most recent call last):
  File "tensorflow/python/ops/gen_nn_ops.py", line 976, in conv2d
    "data_format", data_format, "dilations", dilations)
tensorflow.python.eager.core._FallbackException: Expecting int64_t value for attr strides, got numpy.int32

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "dir/to/my_script.py", line 100, in <module>
    history = model.fit(train, steps_per_epoch=int(np.ceil(num_train_samples / BATCH_SIZE)), epochs=NUM_EPOCHS, batch_size=BATCH_SIZE, validation_data=val, validation_steps=int(np.ceil(num_val_samples / BATCH_SIZE)))
  File "/tensorflow/python/keras/engine/training.py", line 1614, in fit
    validation_steps=validation_steps)
  File "/tensorflow/python/keras/engine/training_eager.py", line 705, in fit_loop
    batch_size=batch_size)
  File "/tensorflow/python/keras/engine/training_eager.py", line 251, in iterator_fit_loop
    model, x, y, sample_weights=sample_weights, training=True)
  File "/tensorflow/python/keras/engine/training_eager.py", line 511, in _process_single_batch
    training=training)
  File "/tensorflow/python/keras/engine/training_eager.py", line 90, in _model_loss
    outs, masks = model._call_and_compute_mask(inputs, **kwargs)
  File "/tensorflow/python/keras/engine/network.py", line 856, in _call_and_compute_mask
    mask=masks)
  File "/tensorflow/python/keras/engine/network.py", line 1029, in _run_internal_graph
    computed_tensor, **kwargs)
  File "/tensorflow/python/keras/engine/network.py", line 856, in _call_and_compute_mask
    mask=masks)
  File "/tensorflow/python/keras/engine/network.py", line 1031, in _run_internal_graph
    output_tensors = layer.call(computed_tensor, **kwargs)
  File "/tensorflow/python/keras/layers/convolutional.py", line 194, in call
    outputs = self._convolution_op(inputs, self.kernel)
  File "/tensorflow/python/ops/nn_ops.py", line 868, in __call__
    return self.conv_op(inp, filter)
  File "/tensorflow/python/ops/nn_ops.py", line 520, in __call__
    return self.call(inp, filter)
  File "/tensorflow/python/ops/nn_ops.py", line 204, in __call__
    name=self.name)
  File "/tensorflow/python/ops/gen_nn_ops.py", line 982, in conv2d
    name=name, ctx=_ctx)
  File "/tensorflow/python/ops/gen_nn_ops.py", line 1015, in conv2d_eager_fallback
    _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], _ctx)
  File "/tensorflow/python/eager/execute.py", line 195, in args_to_matching_eager
    ret = [internal_convert_to_tensor(t, dtype, ctx=ctx) for t in l]
  File "/tensorflow/python/eager/execute.py", line 195, in <listcomp>
    ret = [internal_convert_to_tensor(t, dtype, ctx=ctx) for t in l]
  File "/tensorflow/python/framework/ops.py", line 1146, in internal_convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/tensorflow/python/ops/variables.py", line 828, in _TensorConversionFunction
    "of type '%s'" % (dtype.name, v.dtype.name))
ValueError: Incompatible type conversion requested to type 'uint8' for variable of type 'float32'
</code>```

The first thrown error is about NumPy ndarrays, but I convert those to TensorFlow tensors right after I import them. Any suggestions are greatly appreciated! I checked for any np.int32 types, but was not able to find any.

答: The output of tf.image.resize_images is a tensor of type float and therefore the rgb tensor returned from sample_fetcher() is a tensor of type float. However, when calling the Dataset.from_generator() method, you are specifying the output type of the first generated element as tf.uint8 (i.e. output_types=(tf.uint8, tf.float32)). Therefore, a conversion needs to be done which actually could not be done. Change it to tf.float32 (i.e. output_types=(tf.float32, tf.float32)) for both train and validation generators and the problem would be fixed.

Body:
I use TensorFlow 1.12 with eager execution. When I call

model.fit(train, steps_per_epoch=int(np.ceil(num_train_samples / BATCH_SIZE)), epochs=NUM_EPOCHS, batch_size=BATCH_SIZE, validation_data=val, validation_steps=int(np.ceil(num_val_samples / BATCH_SIZE)))

I get the following error:

ValueError: Incompatible type conversion requested to type 'uint8' for variable of type 'float32'

As far as I know, I am not converting from uint8 to float32 anywhere, at least not explicitly.

My datasets are generated as follows:

train = tf.data.Dataset.from_generator(generator=train_sample_fetcher, output_types=(tf.uint8, tf.float32))
train = train.repeat()
train = train.batch(BATCH_SIZE)
train = train.shuffle(10)
val = tf.data.Dataset.from_generator(generator=val_sample_fetcher, output_types=(tf.uint8, tf.float32))

employing the following generator functions:

def train_sample_fetcher():
    return sample_fetcher()

def val_sample_fetcher():
    return sample_fetcher(is_validations=True)

def sample_fetcher(is_validations=False):
    sample_names = [filename[:-4] for filename in os.listdir(DIR_DATASET + "ndarrays/")]
    if not is_validations: sample_names = sample_names[:int(len(sample_names) * TRAIN_VAL_SPLIT)]
    else: sample_names = sample_names[int(len(sample_names) * TRAIN_VAL_SPLIT):]
    for sample_name in sample_names:
        rgb = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + sample_name + ".jpg"))
        rgb = tf.image.resize_images(rgb, (HEIGHT, WIDTH))
        #d = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + "depth/" + sample_name + ".jpg"))
        #d = tf.image.resize_images(d, (HEIGHT, WIDTH))
        #rgbd = tf.concat([rgb,d], axis=2)
        onehots = tf.convert_to_tensor(np.load(DIR_DATASET + "ndarrays/" + sample_name + ".npy"), dtype=tf.float32)
        yield rgb, onehots

---------------------------------------------------------------------------------

For reference, the full stacktrace:

Traceback (most recent call last):
  File "tensorflow/python/ops/gen_nn_ops.py", line 976, in conv2d
    "data_format", data_format, "dilations", dilations)
tensorflow.python.eager.core._FallbackException: Expecting int64_t value for attr strides, got numpy.int32

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "dir/to/my_script.py", line 100, in <module>
    history = model.fit(train, steps_per_epoch=int(np.ceil(num_train_samples / BATCH_SIZE)), epochs=NUM_EPOCHS, batch_size=BATCH_SIZE, validation_data=val, validation_steps=int(np.ceil(num_val_samples / BATCH_SIZE)))
  File "/tensorflow/python/keras/engine/training.py", line 1614, in fit
    validation_steps=validation_steps)
  File "/tensorflow/python/keras/engine/training_eager.py", line 705, in fit_loop
    batch_size=batch_size)
  File "/tensorflow/python/keras/engine/training_eager.py", line 251, in iterator_fit_loop
    model, x, y, sample_weights=sample_weights, training=True)
  File "/tensorflow/python/keras/engine/training_eager.py", line 511, in _process_single_batch
    training=training)
  File "/tensorflow/python/keras/engine/training_eager.py", line 90, in _model_loss
    outs, masks = model._call_and_compute_mask(inputs, **kwargs)
  File "/tensorflow/python/keras/engine/network.py", line 856, in _call_and_compute_mask
    mask=masks)
  File "/tensorflow/python/keras/engine/network.py", line 1029, in _run_internal_graph
    computed_tensor, **kwargs)
  File "/tensorflow/python/keras/engine/network.py", line 856, in _call_and_compute_mask
    mask=masks)
  File "/tensorflow/python/keras/engine/network.py", line 1031, in _run_internal_graph
    output_tensors = layer.call(computed_tensor, **kwargs)
  File "/tensorflow/python/keras/layers/convolutional.py", line 194, in call
    outputs = self._convolution_op(inputs, self.kernel)
  File "/tensorflow/python/ops/nn_ops.py", line 868, in __call__
    return self.conv_op(inp, filter)
  File "/tensorflow/python/ops/nn_ops.py", line 520, in __call__
    return self.call(inp, filter)
  File "/tensorflow/python/ops/nn_ops.py", line 204, in __call__
    name=self.name)
  File "/tensorflow/python/ops/gen_nn_ops.py", line 982, in conv2d
    name=name, ctx=_ctx)
  File "/tensorflow/python/ops/gen_nn_ops.py", line 1015, in conv2d_eager_fallback
    _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], _ctx)
  File "/tensorflow/python/eager/execute.py", line 195, in args_to_matching_eager
    ret = [internal_convert_to_tensor(t, dtype, ctx=ctx) for t in l]
  File "/tensorflow/python/eager/execute.py", line 195, in <listcomp>
    ret = [internal_convert_to_tensor(t, dtype, ctx=ctx) for t in l]
  File "/tensorflow/python/framework/ops.py", line 1146, in internal_convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/tensorflow/python/ops/variables.py", line 828, in _TensorConversionFunction
    "of type '%s'" % (dtype.name, v.dtype.name))
ValueError: Incompatible type conversion requested to type 'uint8' for variable of type 'float32'

The first thrown error is about NumPy ndarrays, but I convert those to TensorFlow tensors right after I import them. Any suggestions are greatly appreciated! I checked for any np.int32 types, but was not able to find any.


问:
Autoprefixer generically adds prefixes to browser-specific extensions
how to block autoprefixer from adding -webkit prefixes to a Mozilla specific extension ?

Here are some examples to make my point :

```<code>.custom-range::-moz-range-thumb {
    -webkit-transition: none;
    transition: none
}
</code>```

-webkit-transition has nothing to do here as it is a Mozilla specific selector (::-moz-range-thumb).

Another crazy output happens with keyframes and transitions, as Autoprefixer creates useless variants

```<code>  -webkit-transition: -webkit-box-shadow 0.1s ease-out;
  transition: -webkit-box-shadow 0.1s ease-out;
  transition: box-shadow 0.1s ease-out;
  transition: box-shadow 0.1s ease-out, -webkit-box-shadow 0.1s ease-out;
</code>```

Instead of just

```<code>-webkit-transition: -webkit-box-shadow 0.1s ease-out;
      transition: box-shadow 0.1s ease-out;
</code>```

How to fix this ?
Thanks for your help.

答:
You can force Autoprefixer to ignore specific blocks of CSS by using "Control Comments" (their words). It looks pretty flexible.

```<code>.className {
  /* autoprefixer: off */
  something: not-prefixed;
}
</code>```

Here's the documentation.

But you might also want to submit a bug as what you're seeing could be filtered out.

Body:
how to block autoprefixer from adding -webkit prefixes to a Mozilla specific extension ?

Here are some examples to make my point :

.custom-range::-moz-range-thumb {
    -webkit-transition: none;
    transition: none
}

-webkit-transition has nothing to do here as it is a Mozilla specific selector (::-moz-range-thumb).

Another crazy output happens with keyframes and transitions, as Autoprefixer creates useless variants

  -webkit-transition: -webkit-box-shadow 0.1s ease-out;
  transition: -webkit-box-shadow 0.1s ease-out;
  transition: box-shadow 0.1s ease-out;
  transition: box-shadow 0.1s ease-out, -webkit-box-shadow 0.1s ease-out;

Instead of just

-webkit-transition: -webkit-box-shadow 0.1s ease-out;
      transition: box-shadow 0.1s ease-out;

How to fix this ?
Thanks for your help.

Body:
You can force Autoprefixer to ignore specific blocks of CSS by using "Control Comments" (their words). It looks pretty flexible.

.className {
  /* autoprefixer: off */
  something: not-prefixed;
}

Here's the documentation.

But you might also want to submit a bug as what you're seeing could be filtered out.


问:
Asp .Net Core 2.2 Razor Pages Ajax Call Post not working
I've done so many ajax in razor pages but i can't figure out why this does not work. It keeps giving me error 400 on dev tools. It does not reach the page handler no matter what.

```<code><script>
     $.ajax({
                    url: "/Account/Users/Index?handler=Delete",
                    type: "POST",
                    data: {
                        id: id
                    },
                    success: function () {
                        swal("Utilizador Desactivado!", {
                            icon: "success",
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        swal("Falha na ligação ao servidor. Tente novamente mais tarde.");
                    }
                });
</script>
</code>```

page handler

```<code>  public async Task<IActionResult> OnPostDeleteAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await _context.Users.FindAsync(id);

        if (user != null)
        {
            user.IsActivo = false;
            _context.Users.Attach(user).Property( u => u.IsActivo).IsModified = true;
            await _context.SaveChangesAsync();
        }

        return RedirectToPage("./Index");
    }
</code>```

I tried many url combinations and none work. I don't see what is wrong in here....

EDIT

It seems like the problem is the anti forgery token not being validated on razor page.

I wrote Ignore Anti forgery Token on the page model and everything works correctly

答:
As you've already found out it's the anti forgery token, that is ruining your day.
Now, if you are inside a form, asp.net core will create a hidden input with that token for you. If you are not working with a form on your page, you'll have to call @Html.AntiForgeryToken(), which will add the token for you.
Still, this will not resolve the Bad Request for you. You have to add it to your ajax call:

```<code>$.ajax({
    url: "/Account/Users/Index?handler=Delete",
    type: "POST",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    data: {
        id: id
    },
});
</code>```

Additionally, add this line to your Startup.cs file:

```<code>services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
</code>```

Body:
I've done so many ajax in razor pages but i can't figure out why this does not work. It keeps giving me error 400 on dev tools. It does not reach the page handler no matter what.

page handler

  public async Task<IActionResult> OnPostDeleteAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await _context.Users.FindAsync(id);

        if (user != null)
        {
            user.IsActivo = false;
            _context.Users.Attach(user).Property( u => u.IsActivo).IsModified = true;
            await _context.SaveChangesAsync();
        }

        return RedirectToPage("./Index");
    }

I tried many url combinations and none work. I don't see what is wrong in here....

EDIT

It seems like the problem is the anti forgery token not being validated on razor page.

I wrote Ignore Anti forgery Token on the page model and everything works correctly

Body:
As you've already found out it's the anti forgery token, that is ruining your day.
Now, if you are inside a form, asp.net core will create a hidden input with that token for you. If you are not working with a form on your page, you'll have to call @Html.AntiForgeryToken(), which will add the token for you.
Still, this will not resolve the Bad Request for you. You have to add it to your ajax call:

$.ajax({
    url: "/Account/Users/Index?handler=Delete",
    type: "POST",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    data: {
        id: id
    },
});

Additionally, add this line to your Startup.cs file:

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");