问:
Why AVD Manager options are not showing in Android Studio
Why i'm unable to see Android Virtual Device (AVD)

I'm facing problem to create AVD in android studio, the problem is i'm unable to see any of this option Tools —> Android —> AVD Manager

below screen shot  where i'm not finding  Tools —> Android —> AVD Manager

in the above screen shot you cannot find Android --> AVD Manager,Why it is not showing.

Below is my installed packages:

1. SDK Manager

2. SDK Tools

i'm following this link:http://www.dev2qa.com/how-to-create-android-virtual-device-avd-in-android-studio/

答:
After updating Android Studio to the latest version I finally found the AVD Manager:

(Update Android Studio)

Create a new project

Click on the device config dropdown:


来源: stackexchange

问:
Session Id's, UUID's and GUID's and just ID's in general
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

```<code>14th of May 2011 04:36:05PM
</code>```

If used as an identifier, could be changed to:

```<code>14052011163605
</code>```

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?

答:
UUIDs are already generated based on nanosecond intervals of time (see this wikipeida article). If you are using PHP, I'd suggest this page to take a look at how to generate the different versions, depending on your use:

http://php.net/manual/en/function.uniqid.php

The reason you can't guarantee uniqueness is that you have to eventually pick a size limit for the actual string/variable containing your UUID, so there is always the potential for a duplicate. Given the number of possibilities for a UUID, though, this should be practically impossible.

I agree with the other posters... this probably shouldn't ever happen. How are you actually generating unique IDs? Are you sure your code is properly creating them?

ContentLicense: CC BY-SA 3.0

Body:
I have an idea. It might be bad, for reasons not known by me, but I would really appreciate your feedback on this!

We've been using Session ID's in a PHP project. And for the first time in 4 years, a duplicate sessionid was generated. Luckily enough I randomly decided to go looking through the Customers Table because I was bored and noticed there was a duplicate entry in the sessionid column and changed it, and references to it, before any real problems occured.

Which led (or lead?) me to ask myself this question:

Basically, any type of ID, be it a session id, uuid or guid can eventually be duplicated because the length of them is not infinite. So then I got thinking, because we never want this to happen again.

I thought, What if we use a combination of date and time, as an identifier? This wouldn't be "random", but it would solve the duplication issue. For example:

14th of May 2011 04:36:05PM

If used as an identifier, could be changed to:

14052011163605

The reason this form of ID will never become duplicated is because no date, combined with time in the future will ever be the same as one in the past, or present.

And since, in our case, these ID's are not meant to be seen by anybody, there's no reason for it to be random, is there?

I'd love to hear your thoughts on this, and, how you approach situations like this. What's your best method of generating [practically] unique ID'S?


问:
Change fontcolor onclick
I try to change my fontcolor onclick but it doesn't work :D

My js function:

```<code>    function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }
</code>```

The first div is a img-file. I want to press on the image and change the color of the 2nd div "txt_raum_ein"

```<code>    <div id="but_bel_raum_ein" onclick="changeColor("txt_raum_ein", "green")"></div>
    <div id="txt_raum_ein"><font size = "+2" face="Arial">RAUM EIN</font></div>
</code>```

答:
Check this when you click on image word the below name color will be change

 function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="but_bel_raum_ein" onclick="changeColor('txt_raum_ein', 'green')">image</div>
   <div id="txt_raum_ein"><font size = "+2" face="Arial">RAUM EIN</font></div></code>```

ContentLicense: CC BY-SA 4.0

Title: Change fontcolor onclick

Body:
I try to change my fontcolor onclick but it doesn't work :D

My js function:

    function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }

The first div is a img-file. I want to press on the image and change the color of the 2nd div "txt_raum_ein"

RAUM EIN

Body:
Check this when you click on image word the below name color will be change

 function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }

<div id="but_bel_raum_ein" onclick="changeColor('txt_raum_ein', 'green')">image</div>
   <div id="txt_raum_ein"><font size = "+2" face="Arial">RAUM EIN</font></div>


问:
Add value of the already existing key in dict in a form of container in Python
Is there any built-in function that would do the following?

```<code>dictionary = {‘a’:1, ‘b’:2, ‘c’:3}

dictionary.update(c=10)

# what happens
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:10}

# what I want to happen:
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:(3, 10)}
</code>```

By default if keys are the same, later key would override earlier one.
If the key is already present in dict, the value of the new key: value pair would be added to already existing value in a form of container, like tuple, or list or set.

I can write a helper function to do so but I believe it should be something built-in for this matter.

答:
Your desired solution is not very elegant, so I am going to propose an alternative one.

Tuples are immutable. Let's use lists instead, because we can easily append to them.

The data type of the values should be consistent. Use lists in any case, even for single values.

Let's use a defaultdict such that we don't have to initialize lists manually.

Putting it together:

```<code>>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for v, k in enumerate('abc', 1):
...     d[k].append(v)
...
>>> d
defaultdict(<class 'list'>, {'a': [1], 'b': [2], 'c': [3]})
>>> d['c'].append(10)
>>> d
defaultdict(<class 'list'>, {'a': [1], 'b': [2], 'c': [3, 10]})
</code>```

Body:
Is there any built-in function that would do the following?

dictionary = {‘a’:1, ‘b’:2, ‘c’:3}

dictionary.update(c=10)

# what happens
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:10}

# what I want to happen:
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:(3, 10)}

By default if keys are the same, later key would override earlier one.
If the key is already present in dict, the value of the new key: value pair would be added to already existing value in a form of container, like tuple, or list or set.

I can write a helper function to do so but I believe it should be something built-in for this matter.

Body:
Your desired solution is not very elegant, so I am going to propose an alternative one.

Tuples are immutable. Let's use lists instead, because we can easily append to them.

The data type of the values should be consistent. Use lists in any case, even for single values.

Let's use a defaultdict such that we don't have to initialize lists manually.

Putting it together:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for v, k in enumerate('abc', 1):
...     d[k].append(v)
...
>>> d
defaultdict(<class 'list'>, {'a': [1], 'b': [2], 'c': [3]})
>>> d['c'].append(10)
>>> d
defaultdict(<class 'list'>, {'a': [1], 'b': [2], 'c': [3, 10]})


问:
Get data with firebase
I am making a kids app on iOS. When I released it, I had a problem with advertising because of the IDFA fence, and I had to remove it from the application. I also use Firebase / analytics. Will I have the same problems as with advertising through a data collection, or can firebase / analytics be used in children's applications?</p>

答:
As per the apple new guidelines for Kids category, you are allowed to use third-party analytics with limited permissions in kid's application.

In limited cases, third-party analytics may be permitted provided that the services do not collect or transmit the IDFA or any identifiable information about children (such as name, date of birth, email address), their location, or their devices.

Yes, you can customize your app requirements following Apple's guidelines more strictly.

Go through this in detail - https://developer.apple.com/app-store/review/guidelines/#kids-category

Title: Get data with firebase


问:
javascript regular expressions for password
i have to create a regular expression for password in java script with the following criteria
1. The password should contain atleast one alphabet either upper case or lower case
2. It should contain atleast one number
3. It should contain atlease one special character(`,~,!,@,#,$,%,^,&,*,_,+,=)</p>

答:
These posts were helpfull here is a bit of code some of you may want to use at some point. This forces the user to input an Uppercase, Lowercase, Special character, and minimum of 8 characters in length. It also breaks it up and lets them know what exactly it is they are doing wrong.</p>

```<code>    <script type="text/javascript" language="javascript">
    function validate() {

        if (document.aspnetForm.PasswordValue.value == '') {
            alert('Current Password is a required field!');
            document.aspnetForm.PasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value == '') {
            alert('New Password is a required field!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/\d/) == null) {
            alert('Your new password must have a number!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/[a-z]/) == null) {
            alert('Your new password must have an Upper and lower case letter!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/[A-Z]/) == null) {
            alert('Your new password must have an Upper and lower case letter!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/['~!@#$%&*_+=]/) == null) {
            alert('Your new password must have a special character i.e.(!@#$%&*)');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.length < 8) {
            alert('Your new password must have a minimum of 8 characters!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewConfirmPassword.value == '') {
            alert('Confirm New Password is a required field!');
            document.aspnetForm.NewConfirmPassword.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value != document.aspnetForm.NewConfirmPassword.value)
        {
            alert('New password and Confirm New Password do not match!');
            document.aspnetForm.NewConfirmPassword.focus()
            return false;
        }
        if (document.aspnetForm.PasswordValue.value == document.aspnetForm.NewPasswordValue.value) {
            alert('Your current password and new password are the same!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
    }
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
These posts were helpfull here is a bit of code some of you may want to use at some point. This forces the user to input an Uppercase, Lowercase, Special character, and minimum of 8 characters in length. It also breaks it up and lets them know what exactly it is they are doing wrong.

    <script type="text/javascript" language="javascript">
    function validate() {

        if (document.aspnetForm.PasswordValue.value == '') {
            alert('Current Password is a required field!');
            document.aspnetForm.PasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value == '') {
            alert('New Password is a required field!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/\d/) == null) {
            alert('Your new password must have a number!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/[a-z]/) == null) {
            alert('Your new password must have an Upper and lower case letter!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/[A-Z]/) == null) {
            alert('Your new password must have an Upper and lower case letter!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.match(/['~!@#$%&*_+=]/) == null) {
            alert('Your new password must have a special character i.e.(!@#$%&*)');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value.length < 8) {
            alert('Your new password must have a minimum of 8 characters!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
        if (document.aspnetForm.NewConfirmPassword.value == '') {
            alert('Confirm New Password is a required field!');
            document.aspnetForm.NewConfirmPassword.focus()
            return false;
        }
        if (document.aspnetForm.NewPasswordValue.value != document.aspnetForm.NewConfirmPassword.value)
        {
            alert('New password and Confirm New Password do not match!');
            document.aspnetForm.NewConfirmPassword.focus()
            return false;
        }
        if (document.aspnetForm.PasswordValue.value == document.aspnetForm.NewPasswordValue.value) {
            alert('Your current password and new password are the same!');
            document.aspnetForm.NewPasswordValue.focus()
            return false;
        }
    }
</script>


问:
Is generating random numbers from hardware performance cryptographically secure?
Suppose I have a program that needs an RNG.

If I were to run arbitrary operations and check the ∆t it takes to do said operations, I could generate random numbers from that

For example:

```<code>double start = device.time();
for(int i=0;i<100;i++);//assume compiler doesn't optimize this away
double end = device.time();
double dt = end-start;
</code>```

dt will be more or less random based on many variables on the device such as battery level, transistor age, room temperature, other processes running, etc.

Now, suppose I keep generating dts and multiply them together as I go, hundreds of times, thousands of times, millions of times, eventually I am left with a very arbitrary number based on values that were more or less randomly calculated by hardware performance benchmarking.

Every time I multiply these dts together, the possible outputs increases exponentially, so determining what possible outputs may be becomes perhaps an impossible task after millions of iterations of this, even if each individual dt value is going to be within a similar range.

A thought then occurs, if you have a very consistent device, you may have dt always in the range of say 0.000000011, 0.000000012, 0.000000013, 0.000000014, then the final output number, no matter how many times I iterate and multiply, will be a number of the form 0.000000011^a * 0.000000012^b * 0.000000013^c * 0.000000014^d, that's probably easy to crack.

But then I turn to hashing, suppose rather than multiplying each dt, I concatenate it in string form to the previous values and hash them, so every time I generate a new dt based on hardware performance's random environmental values, I hash. Then at the end I digest the hash to whatever form I need, now the final output number can't be written in a general algebraic form.

Will numbers generated in this form be cryptographically secure?

答:
Using a clock potentially leaks information to an adversary.  Using a microphone also -- the adversary may have planted a bug and is hearing the same input.  Best not to rely on any single source but to combine entropy inputs from multiple sources, both external to your computer and internal.  By all means use internal OS entropy sources, such as dev/urandom, but use other sources as well.

It might be worth reading the description of the Fortuna CSPRNG for ideas.

Body:
Suppose I have a program that needs an RNG.

If I were to run arbitrary operations and check the ∆t it takes to do said operations, I could generate random numbers from that

For example:

double start = device.time();
for(int i=0;i<100;i++);//assume compiler doesn't optimize this away
double end = device.time();
double dt = end-start;

dt will be more or less random based on many variables on the device such as battery level, transistor age, room temperature, other processes running, etc.

Now, suppose I keep generating dts and multiply them together as I go, hundreds of times, thousands of times, millions of times, eventually I am left with a very arbitrary number based on values that were more or less randomly calculated by hardware performance benchmarking.

Every time I multiply these dts together, the possible outputs increases exponentially, so determining what possible outputs may be becomes perhaps an impossible task after millions of iterations of this, even if each individual dt value is going to be within a similar range.

A thought then occurs, if you have a very consistent device, you may have dt always in the range of say 0.000000011, 0.000000012, 0.000000013, 0.000000014, then the final output number, no matter how many times I iterate and multiply, will be a number of the form 0.000000011^a * 0.000000012^b * 0.000000013^c * 0.000000014^d, that's probably easy to crack.

But then I turn to hashing, suppose rather than multiplying each dt, I concatenate it in string form to the previous values and hash them, so every time I generate a new dt based on hardware performance's random environmental values, I hash. Then at the end I digest the hash to whatever form I need, now the final output number can't be written in a general algebraic form.

Will numbers generated in this form be cryptographically secure?


问:
AudioTrack, SoundPool or MediaPlayer, which should I use?
Should I use AudioTrack, SoundPool or MediaPlayer if I need to be able to:

play multiple audio files, with different duration, like 5 to 30 seconds.

set the volume independently for right / left channel.

apply sound effects, like reverb / distortion.

So, which API should I use?

Also, I can't find too much doc on AudioTrack API.

Does anyone know where can I find examples?

答:
Playing Audio

If you want to play audio in your Android apps, there are three APIs to choose from

MediaPlayer - Streams and decodes in real-time for local or remote files. Good for long clips and applications such as background music. More CPU and resource-intensive. Relatively long initialization time. MediaPlayer is a state machine!

SoundPool - Good for short audio effects or clips. Stored uncompressed in memory, 1MB limit. Clips must be fully loaded before playing. Supports volume and speed control, looping, simultaneous sounds, priorities.

AudioTrack - Lowest-level audio API on Android. It provides a channel you can configure. Push and pull byte data to the channel. Configure rate, samples, audio format, etc. You can decode audio in unsupported formats.

In summary, MediaPlayer is the good general-purpose class to play a file, SoundPool is well suited for short audio effects, and AudioTrack lets you get into the low-level audio configurations.

Reference - https://en.proft.me/2018/05/8/how-play-audio-file-android/


问:
Why does decodeURIComponent('%') lock up my browser?
I was just testing something with AJAX and I found that on success if I alert

```<code>alert(decodeURI('%'));
</code>```

or

```<code>alert(encodeURIComponent('%'));
</code>```

the browser errors out with the following code.

```<code>$.ajax({
   type: "POST",
   url: "some.php",
   data: "",
   success: function(html){
         alert(decodeURIComponent('%'));
//           alert(decodeURI('%'));
   }
 });
</code>```

If I use any other string it works just fine.

Is it something that I missed?

答:
I had the same issue as OP and found this useful topic.
Had to find a way to check if URI string contained percent sign before using decodeURIComponent().

The piece of code from Ilia Rostovtsev works great except for URI which contains encoded characters like %C3 (where percent sign is starting by [A-F]) because the regex used doesn't handle them (only % followed by a decimal).

I replaced the following line:

```<code>   x = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];
</code>```

by

```<code>   x = mod ? arr[i].replace(/%(?!\d|[ABCDEF]+)/g, '%25') : arr[i];
</code>```

Now, it is working as the regex will reject %1A to %9F and also %A1 to %F9

Body:
I was just testing something with AJAX and I found that on success if I alert

alert(decodeURI('%'));

or

alert(encodeURIComponent('%'));

the browser errors out with the following code.

$.ajax({
   type: "POST",
   url: "some.php",
   data: "",
   success: function(html){
         alert(decodeURIComponent('%'));
//           alert(decodeURI('%'));
   }
 });

If I use any other string it works just fine.

Is it something that I missed?

Body:
I had the same issue as OP and found this useful topic.
Had to find a way to check if URI string contained percent sign before using decodeURIComponent().

The piece of code from Ilia Rostovtsev works great except for URI which contains encoded characters like %C3 (where percent sign is starting by [A-F]) because the regex used doesn't handle them (only % followed by a decimal).

I replaced the following line:

   x = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];

by

   x = mod ? arr[i].replace(/%(?!\d|[ABCDEF]+)/g, '%25') : arr[i];

Now, it is working as the regex will reject %1A to %9F and also %A1 to %F9


问:
Delay Javascript effect by 500 ms
I want to delay slideOutItem by 500 millisecond. Canno't get that working.</p>

```<code>if(current === idx) {
    slideOutItem($menuItems.eq(current), false, 250, 'easeOutQuint', true);
    current = -1;
}
</code>```

答:
```<code>function delayed_one  ()
{
   if(current === idx) {
      slideOutItem($menuItems.eq(current), false, 250, 'easeOutQuint', true);
      current = -1;
   }
}

setTimeout ( delayed_one, 500 );
</code>```

Title: Delay Javascript effect by 500 ms

Body:
I want to delay slideOutItem by 500 millisecond. Canno't get that working.

if(current === idx) {
    slideOutItem($menuItems.eq(current), false, 250, 'easeOutQuint', true);
    current = -1;
}


问:
React TypeError: Cannot read property 'map' of undefined
Updated

I am learning react so using omdbapi api want to fetch data but getting TypeError: Cannot read property 'map' of undefined

Kindly help how to solve this issue

```<code>class App extends React.Component {
  constructor(){
    super()
    this.state={
      data:[],
    }
  }
  componentDidMount(){
    fetch('http://www.omdbapi.com/?i=tt3896198&apikey=key123')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
     this.setState({
       data:findresponse.movie
     })
      })
  }
  render() {
  return (
    <div>
      {this.state.data.map((dynamicData)=>
      <div>
        <img src={dynamicData.Poster} alt=""/>
        <p>{dynamicData.title} </p>
        <p>{dynamicData.Released} </p>
      </div>
      )}
    </div>
  )
}
}
</code>```

After below answer i have updated the source code now in html output is blank but in console.log showing the output

I want to loop 20 movies

```<code>componentDidMount(){
    fetch('http://www.omdbapi.com/?apikey=mykey&s=batman')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
      console.log(findresponse)
     this.setState({
      data:[findresponse]
     })
      })
  }
  render() {
  return (
    <div>
      {this.state.data && this.state.data.map((dynamicData , key)=>
      <div key={key}>
        <img src={dynamicData.Poster} alt=""/>
        <p>{dynamicData.Title} </p>
        <p>{dynamicData.Released} </p>
      </div>
      )}
    </div>
  )
}
}
</code>```

答:
Try to check if data is not undefined first:</p>

```<code>{this.state.data && this.state.data.map((dynamicData)=>
  <div>
    <img src={dynamicData.Poster} alt=""/>
    <p>{dynamicData.title} </p>
    <p>{dynamicData.Released} </p>
  </div>
  )}
</code>```

Body:
Updated

I am learning react so using omdbapi api want to fetch data but getting TypeError: Cannot read property 'map' of undefined

Kindly help how to solve this issue

class App extends React.Component {
  constructor(){
    super()
    this.state={
      data:[],
    }
  }
  componentDidMount(){
    fetch('http://www.omdbapi.com/?i=tt3896198&apikey=key123')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
     this.setState({
       data:findresponse.movie
     })
      })
  }
  render() {
  return (

      {this.state.data.map((dynamicData)=>

{dynamicData.title}

{dynamicData.Released}

      )}

  )
}
}

After below answer i have updated the source code now in html output is blank but in console.log showing the output

I want to loop 20 movies

componentDidMount(){
    fetch('http://www.omdbapi.com/?apikey=mykey&s=batman')
    .then((Response)=>Response.json())
    .then((findresponse)=>
    {
      console.log(findresponse)
     this.setState({
      data:[findresponse]
     })
      })
  }
  render() {
  return (

      {this.state.data && this.state.data.map((dynamicData , key)=>

{dynamicData.Title}

{dynamicData.Released}

      )}

  )
}
}

Body:
Try to check if data is not undefined first:

{this.state.data && this.state.data.map((dynamicData)=>
  <div>
    <img src={dynamicData.Poster} alt=""/>
    <p>{dynamicData.title} </p>
    <p>{dynamicData.Released} </p>
  </div>
  )}


问:
How to make HTML container flex easier / scale navbar on mobile
This is currently what I have in my HTML code:

I have 3 of the "col-md-4" div's in the row, along with container--wrap in each of those, so that it fills the webpage with 3 equally sized containers. (div row is inside another div with class = container-fluid). When I adjust the window, the containers will stack on top of each other, but only after I make it much smaller (like 2/3). Also, on mobile, it does not stack at all and the containers are all really small. How can I make it so that these containers are able to stack (flex?) easier, and have them stack on mobile automatically? I also have a navbar that looks fine on mobile, but it remains small on mobile, just collapsed. How can I make it larger on mobile? Here is the navbar code:

cov19.cc (website) is an example of what I would like my site to do. The navbar is enlarged on mobile, and the container are stacked on top of each other rather than side by side. Thanks

答:
For the First Problem, use display:flex for the row.I have also used media query so that when the user is on mobile screen or the size of screen is less than 991px, the containers will be on the top of each other.Please run it full screen and shrink the browser window to see the effect.

@media all and (max-width:991px){

.row{

flex-direction:column;

}
.container--wrap{
width:98vw!important;

}

}

.row{

display:flex;

}

.container--wrap{

width:33vw;
text-align:center;
border:1px solid;
transition:all 0.3s;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
        <div class="col-md-4">
              <div class="container--wrap">
              This is one
              </div>
              </div>
        <div class="col-md-4">
              <div class="container--wrap">
              This is two
              </div>
              </div>
        <div class="col-md-4">
              <div class="container--wrap">
              This is three
              </div>
              </div>

</div></code>```

Body:
For the First Problem, use display:flex for the row.I have also used media query so that when the user is on mobile screen or the size of screen is less than 991px, the containers will be on the top of each other.Please run it full screen and shrink the browser window to see the effect.

@media all and (max-width:991px){

.row{

flex-direction:column;

}
.container--wrap{
width:98vw!important;

}

}

.row{

display:flex;

}

.container--wrap{

width:33vw;
text-align:center;
border:1px solid;
transition:all 0.3s;

}

<div class="row">
        <div class="col-md-4">
              <div class="container--wrap">
              This is one
              </div>
              </div>
        <div class="col-md-4">
              <div class="container--wrap">
              This is two
              </div>
              </div>
        <div class="col-md-4">
              <div class="container--wrap">
              This is three
              </div>
              </div>

</div>


问:
getProjectMetadata does not exist when adding custom webpack
I'm following this tutorial and I'm trying to get brotli working with angular projectI created a ```custom-webpack.config.js file and put in the root directory where angular.json is located. (also tried src folder, but that didn't work) As soon as I update the angular.json file to</p>

```"architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./custom-webpack.config.js"
             },
            ...
```

<p>I get the error <code>An unhandled exception occurred: Job name "..getProjectMetadata" does not exist.</code></p>

<p>I also ran <code>npm i -D compression-webpack-plugin brotli-webpack-plugin</code>
and made my <code>custom-webpack.config.js</code> file look like</p>

```const CompressionPlugin = require(`compression-webpack-plugin`);
const BrotliPlugin = require(`brotli-webpack-plugin`);
const path = require(`path`);
module.exports = {
    plugins:[
        new BrotliPlugin({
            asset: '[fileWithoutExt].[ext].br',
            test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif)$/
        }),
        new CompressionPlugin({
            test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif)$/,
            filename(info){
                let opFile= info.path.split('.'),
                opFileType =  opFile.pop(),
                opFileName = opFile.join('.');
                return `${opFileName}.${opFileType}.gzip`;
            }
        })
    ],
}
```

<p>package.json</p>

```{
  "name": "mean-course",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "start:server": "nodemon backend/server.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^8.2.13",
    "@angular/cdk": "~8.2.2",
    "@angular/common": "~8.2.4",
    "@angular/compiler": "~8.2.4",
    "@angular/core": "~8.2.4",
    "@angular/forms": "~8.2.4",
    "@angular/material": "^8.2.2",
    "@angular/platform-browser": "~8.2.4",
    "@angular/platform-browser-dynamic": "~8.2.4",
    "@angular/router": "~8.2.4",
    "@azure/storage-blob": "^12.1.0",
    "@ng-bootstrap/ng-bootstrap": "^5.1.5",
    "@ngrx/store": "^8.6.0",
    "ably": "^1.1.22",
    "angular-doka": "file:src/angular-doka",
    "angular-filepond": "^1.0.5",
    "azure-arm-rediscache": "^3.0.0",
    "bcrypt": "^3.0.6",
    "bootstrap": "^4.4.1",
    "classlist.js": "^1.1.20150312",
    "countdown": "^2.6.0",
    "crypto-js": "^4.0.0",
    "dependency-check": "^4.1.0",
    "dotenv": "^8.2.0",
    "filepond": "^4.13.4",
    "filepond-plugin-file-encode": "^2.1.5",
    "filepond-plugin-file-validate-size": "^2.2.0",
    "filepond-plugin-file-validate-type": "^1.2.5",
    "filepond-plugin-image-crop": "^2.0.3",
    "filepond-plugin-image-edit": "^1.6.0",
    "filepond-plugin-image-exif-orientation": "^1.0.7",
    "filepond-plugin-image-preview": "^4.6.1",
    "filepond-plugin-image-resize": "^2.0.4",
    "filepond-plugin-image-transform": "^3.7.2",
    "jquery": "^3.5.1",
    "jsonwebtoken": "^8.5.1",
    "lib-storage-service": "^1.0.2",
    "material": "^0.4.1",
    "moment-mini": "^2.24.0",
    "ng-starrating": "^1.0.11",
    "ngx-clipboard": "^12.3.0",
    "ngx-device-detector": "^1.3.20",
    "ngx-filepond": "^5.0.1",
    "ngx-light-carousel": "^1.0.37-beta.8",
    "ngx-pagination": "^5.0.0",
    "ngx-simple-countdown": "^1.0.2",
    "ngx-spinner": "^8.0.3",
    "ngx-toastr": "^11.2.1",
    "ngx-ui-carousel": "^1.3.2",
    "nodemon": "^2.0.2",
    "numeral": "^2.0.6",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "tsoa": "^2.5.7",
    "uid": "0.0.2",
    "web-animations-js": "^2.3.2",
    "yamljs": "^0.3.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "^9.1.0",
    "@angular-devkit/build-angular": "^0.803.26",
    "@angular/cli": "~8.3.2",
    "@angular/compiler-cli": "~8.2.4",
    "@angular/language-service": "~8.2.4",
    "@types/crypto-js": "^3.1.43",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^8.10.59",
    "brotli-gzip-webpack-plugin": "^0.5.0",
    "brotli-webpack-plugin": "^1.1.0",
    "codelyzer": "^5.0.0",
    "compression-webpack-plugin": "^4.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  },
  "browser": {
    "crypto": false
  }
}
```

but when I run ng build --prod I get the error. Is there something I missing? I appreciate any help!

答: Downgrade your @angular-builders/custom-webpack, try this 8.4.1

Body:
I'm following this tutorial and I'm trying to get brotli working with angular projectI created a ```custom-webpack.config.js file and put in the root directory where angular.json is located. (also tried src folder, but that didn't work) As soon as I update the angular.json file to

"architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./custom-webpack.config.js"
             },
            ...

I get the error An unhandled exception occurred: Job name "..getProjectMetadata" does not exist.

I also ran npm i -D compression-webpack-plugin brotli-webpack-plugin
and made my custom-webpack.config.js file look like

const CompressionPlugin = require(`compression-webpack-plugin`);
const BrotliPlugin = require(`brotli-webpack-plugin`);
const path = require(`path`);
module.exports = {
    plugins:[
        new BrotliPlugin({
            asset: '[fileWithoutExt].[ext].br',
            test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif)$/
        }),
        new CompressionPlugin({
            test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif)$/,
            filename(info){
                let opFile= info.path.split('.'),
                opFileType =  opFile.pop(),
                opFileName = opFile.join('.');
                return `${opFileName}.${opFileType}.gzip`;
            }
        })
    ],
}

package.json

{
  "name": "mean-course",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "start:server": "nodemon backend/server.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^8.2.13",
    "@angular/cdk": "~8.2.2",
    "@angular/common": "~8.2.4",
    "@angular/compiler": "~8.2.4",
    "@angular/core": "~8.2.4",
    "@angular/forms": "~8.2.4",
    "@angular/material": "^8.2.2",
    "@angular/platform-browser": "~8.2.4",
    "@angular/platform-browser-dynamic": "~8.2.4",
    "@angular/router": "~8.2.4",
    "@azure/storage-blob": "^12.1.0",
    "@ng-bootstrap/ng-bootstrap": "^5.1.5",
    "@ngrx/store": "^8.6.0",
    "ably": "^1.1.22",
    "angular-doka": "file:src/angular-doka",
    "angular-filepond": "^1.0.5",
    "azure-arm-rediscache": "^3.0.0",
    "bcrypt": "^3.0.6",
    "bootstrap": "^4.4.1",
    "classlist.js": "^1.1.20150312",
    "countdown": "^2.6.0",
    "crypto-js": "^4.0.0",
    "dependency-check": "^4.1.0",
    "dotenv": "^8.2.0",
    "filepond": "^4.13.4",
    "filepond-plugin-file-encode": "^2.1.5",
    "filepond-plugin-file-validate-size": "^2.2.0",
    "filepond-plugin-file-validate-type": "^1.2.5",
    "filepond-plugin-image-crop": "^2.0.3",
    "filepond-plugin-image-edit": "^1.6.0",
    "filepond-plugin-image-exif-orientation": "^1.0.7",
    "filepond-plugin-image-preview": "^4.6.1",
    "filepond-plugin-image-resize": "^2.0.4",
    "filepond-plugin-image-transform": "^3.7.2",
    "jquery": "^3.5.1",
    "jsonwebtoken": "^8.5.1",
    "lib-storage-service": "^1.0.2",
    "material": "^0.4.1",
    "moment-mini": "^2.24.0",
    "ng-starrating": "^1.0.11",
    "ngx-clipboard": "^12.3.0",
    "ngx-device-detector": "^1.3.20",
    "ngx-filepond": "^5.0.1",
    "ngx-light-carousel": "^1.0.37-beta.8",
    "ngx-pagination": "^5.0.0",
    "ngx-simple-countdown": "^1.0.2",
    "ngx-spinner": "^8.0.3",
    "ngx-toastr": "^11.2.1",
    "ngx-ui-carousel": "^1.3.2",
    "nodemon": "^2.0.2",
    "numeral": "^2.0.6",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "tsoa": "^2.5.7",
    "uid": "0.0.2",
    "web-animations-js": "^2.3.2",
    "yamljs": "^0.3.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "^9.1.0",
    "@angular-devkit/build-angular": "^0.803.26",
    "@angular/cli": "~8.3.2",
    "@angular/compiler-cli": "~8.2.4",
    "@angular/language-service": "~8.2.4",
    "@types/crypto-js": "^3.1.43",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^8.10.59",
    "brotli-gzip-webpack-plugin": "^0.5.0",
    "brotli-webpack-plugin": "^1.1.0",
    "codelyzer": "^5.0.0",
    "compression-webpack-plugin": "^4.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  },
  "browser": {
    "crypto": false
  }
}

but when I run ng build --prod I get the error. Is there something I missing? I appreciate any help!


问:
Webots simulation: Mobsya's Thymio2 pen doesn't write
I want to simulate a Thymio 2 drawing sewing patterns on fabric. So I created a world and implemented the behavior of the robot. Then I added a Thymio2Pen to the bodySlot but the pen didn't draw at all. The robot did however drive how it is supposed to. I then created a different, very simple world with only the Thymio, the Thymio2Pen and a default floor and added a controller which set both motor velocities to 5. And again the robot did drive but it didn't draw.

So now I don't know why the pen isn't working. Maybe someone has had the same problem or knows why the pen doesn't draw.

I am using a Ubuntu Virtual Machine. The Texture Quality of Webots is medium.
Tank you for your answers

答:
This is because the pen device need a textured floor in order to be able to draw on it. Also, the texture mapping of the floor should be simple. I would recommend you to copy the rectangle arena floor used in the thymio2_pen.wbt example:

```<code>RectangleArena {
  floorTileSize 1 1
  floorAppearance PBRAppearance {
    baseColorMap ImageTexture {
      url [
        "textures/paper.jpg"
      ]
    }
    roughness 1
    metalness 0
  }
}
</code>```

Body:
This is because the pen device need a textured floor in order to be able to draw on it. Also, the texture mapping of the floor should be simple. I would recommend you to copy the rectangle arena floor used in the thymio2_pen.wbt example:

RectangleArena {
  floorTileSize 1 1
  floorAppearance PBRAppearance {
    baseColorMap ImageTexture {
      url [
        "textures/paper.jpg"
      ]
    }
    roughness 1
    metalness 0
  }
}


问:
How to set offset of Basemap in Python?
Here's one example of Basemap:

```<code>fig = plt.figure(figsize=(10,6))

ax = fig.add_subplot(121)
ax.set_title('Default')

# miller projection
map = Basemap(projection='mill',lon_0=180)
# plot coastlines, draw label meridians and parallels.
map.drawcoastlines()
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])

ax = fig.add_subplot(122)
ax.set_title('Add offset')

# miller projection
map = Basemap(projection='mill',lon_0=180)
# plot coastlines, draw label meridians and parallels.
map.drawcoastlines()
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],xoffset=100,yoffset=100)
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],xoffset=100,yoffset=100)
</code>```

I want to add more space between the xlabel/ylabel and axis.
But, the space is smaller when xoffset and yoffset are added.

答:
I think you are not using the correct unit. @Thomas Kühn quoted the basemap doc:

xoffset: label offset from edge of map in x-direction (default is 0.01
  times width of map in map projection coordinates).

yoffset: label offset from edge of map in y-direction (default is 0.01
  times height of map in map projection coordinates).

Note that it is defaulted to 1% of the domain span measured in map projection coordinates.

If you check the span in y-axis of the mill projection you used, the length has 8 digits, so no wonder yoffset=100 gives no visual offset.

So an easier way is to modify the offset using the actual domain span, like:

```<code>map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.01*abs(map.ymax-map.ymin))
</code>```

This gives the same offset as default, i.e. 1% of the domain span (See figure (b) below). Changing 0.01 to 0.03 will be 3x of that (figure (c)).

If you instead use cyl projection which uses degree of latitude/longitude as units, the offsets are also measured in degrees, then yoffset=100 will be an insane offset. Figure (f) uses a yoffset=30, note that is the same distance as the distance from 60S to 90S.

The script to generate the figure:

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
fig = plt.figure(figsize=(12,6))

def drawMap(proj):
    map = Basemap(projection=proj,lon_0=180)
    map.drawcoastlines()
    return map

# miller projection
ax = fig.add_subplot(231)
ax.set_title('(a) Mill, Default')
map=drawMap('mill')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])

ax = fig.add_subplot(232)
ax.set_title('(b) Mill, add same offset as default')
map=drawMap('mill')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.01*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.01*abs(map.ymax-map.ymin))

ax = fig.add_subplot(233)
ax.set_title('(c) Mill, add 3x offset as default')
map=drawMap('mill')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.03*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.03*abs(map.ymax-map.ymin))

ax = fig.add_subplot(234)
ax.set_title('(d) Cyl, Default')
map=drawMap('cyl')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])

ax = fig.add_subplot(235)
ax.set_title('(e) Cyl, add same offset as default')
map=drawMap('cyl')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.01*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.01*abs(map.ymax-map.ymin))

ax = fig.add_subplot(236)
ax.set_title('(f) Cyl, add 30 degree offset')
map=drawMap('cyl')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.03*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=30)

fig.subplots_adjust(hspace=0.01)
fig.show()
</code>```

Title: How to set offset of Basemap in Python?

Body:
Here's one example of Basemap:

fig = plt.figure(figsize=(10,6))

ax = fig.add_subplot(121)
ax.set_title('Default')

# miller projection
map = Basemap(projection='mill',lon_0=180)
# plot coastlines, draw label meridians and parallels.
map.drawcoastlines()
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])

ax = fig.add_subplot(122)
ax.set_title('Add offset')

# miller projection
map = Basemap(projection='mill',lon_0=180)
# plot coastlines, draw label meridians and parallels.
map.drawcoastlines()
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],xoffset=100,yoffset=100)
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],xoffset=100,yoffset=100)

I want to add more space between the xlabel/ylabel and axis.
But, the space is smaller when xoffset and yoffset are added.

Body:
I think you are not using the correct unit. @Thomas Kühn quoted the basemap doc:

xoffset: label offset from edge of map in x-direction (default is 0.01
  times width of map in map projection coordinates).

yoffset: label offset from edge of map in y-direction (default is 0.01
  times height of map in map projection coordinates).

Note that it is defaulted to 1% of the domain span measured in map projection coordinates.

If you check the span in y-axis of the mill projection you used, the length has 8 digits, so no wonder yoffset=100 gives no visual offset.

So an easier way is to modify the offset using the actual domain span, like:

map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.01*abs(map.ymax-map.ymin))

This gives the same offset as default, i.e. 1% of the domain span (See figure (b) below). Changing 0.01 to 0.03 will be 3x of that (figure (c)).

If you instead use cyl projection which uses degree of latitude/longitude as units, the offsets are also measured in degrees, then yoffset=100 will be an insane offset. Figure (f) uses a yoffset=30, note that is the same distance as the distance from 60S to 90S.

The script to generate the figure:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
fig = plt.figure(figsize=(12,6))

def drawMap(proj):
    map = Basemap(projection=proj,lon_0=180)
    map.drawcoastlines()
    return map

# miller projection
ax = fig.add_subplot(231)
ax.set_title('(a) Mill, Default')
map=drawMap('mill')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])

ax = fig.add_subplot(232)
ax.set_title('(b) Mill, add same offset as default')
map=drawMap('mill')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.01*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.01*abs(map.ymax-map.ymin))

ax = fig.add_subplot(233)
ax.set_title('(c) Mill, add 3x offset as default')
map=drawMap('mill')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.03*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.03*abs(map.ymax-map.ymin))

ax = fig.add_subplot(234)
ax.set_title('(d) Cyl, Default')
map=drawMap('cyl')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])

ax = fig.add_subplot(235)
ax.set_title('(e) Cyl, add same offset as default')
map=drawMap('cyl')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.01*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=0.01*abs(map.ymax-map.ymin))

ax = fig.add_subplot(236)
ax.set_title('(f) Cyl, add 30 degree offset')
map=drawMap('cyl')
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0],
        xoffset=0.03*abs(map.xmax-map.xmin))
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1],
        yoffset=30)

fig.subplots_adjust(hspace=0.01)
fig.show()


问:
Flutter build_runner fails to build when added third party generator
I wrote a flutter project which working fine and I was able to build it properly, but when I added retrofit_generator the build getting failed, If i remove the generator the code runs fine and the build also succeeds. here is the error,

Unsupported operation: Cannot resolve
file:///C:/Users/User/AndroidStudioProjects/digigad/lib/resources/network/reposi
tory.dart; only "package" and "asset" schemes supported
[SEVERE] retrofit_generator:retrofit on lib/ui/login/login_view.dart:

here is my code of login_view.dart

```<code> class LoginView extends StatefulWidget {
  @override
  _LoginViewState createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  LoginViewModel _loginViewModel;

  @override
  void initState() {
    super.initState();
    _loginViewModel = locator<LoginViewModel>();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LoginViewModel>.nonReactive(
        builder: (context, model, child) {
          return Scaffold(
            backgroundColor: Colors.white,
            body: SafeArea(
              child: Padding(
                padding: const EdgeInsets.all(30.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Container(
                      child: Center(
                        child: Container(
                          child: Image.asset('images/iv_logo.png'),
                          width: 100,
                          height: 100,
                        ),
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            _socialButton(
                                image: 'icons/ic_facebook.png',
                                title: 'Facebook'),
                            SizedBox(
                              width: 30,
                            ),
                            _socialButton(
                                image: 'icons/ic_google.png', title: 'Google'),
                          ],
                        ),
                        SizedBox(
                          height: 30,
                        ),
                        Text(
                          'or',
                          style: TextStyle(
                              fontSize: 15, color: AppConstants.colorHint),
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        StreamBuilder<String>(
                            stream: model.phoneStream,
                            builder: (context, snapshot) {
                              return Column(
                                children: <Widget>[
                                  AppFunctions.getTextInputField(
                                      hintText: 'Mobile Number',
                                      maxLength: 10,
                                      inputType: TextInputType.phone,
                                      onChanged: model.onPhoneChanged,
                                      errorText: snapshot.error),
                                  AppFunctions.getStandardDivider(),
                                  AppFunctions.getBigButton(
                                    title: 'Login',
                                    color: snapshot.hasData
                                        ? AppConstants.colorPrimary
                                        : AppConstants.colorHint,
                                    onClick: snapshot.hasData
                                        ? () => _loginViewModel
                                            .onLoginClicked(snapshot.data)
                                        : () => () {},
                                  )
                                ],
                              );
                            }),
                      ],
                    ),
                    Center(
                      child: Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text('Made with '),
                          Icon(
                            Icons.favorite,
                            color: Colors.red,
                          ),
                          Text(' in Flutter'),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        viewModelBuilder: () => _loginViewModel);
  }

  Expanded _socialButton({String image, String title}) {
    return Expanded(
      child: Container(
        height: 40,
        child: RaisedButton(
          onPressed: () {},
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(
                image,
                width: 16,
                height: 16,
              ),
              SizedBox(
                width: 10,
              ),
              Text(title)
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
I also faced the same error and got to know that there is some direct import statement in my project file.

that import statement was login_page.dart

```<code>import 'file:///D:/Major_Project/connect/lib/api/api.dart';
</code>```

in this case, the same error was thrown in build
Log

so find that statement in the project and change it with the normal import statement

login_page.dart

```<code>import 'package:connect/api/api.dart';
</code>```

Body:
I wrote a flutter project which working fine and I was able to build it properly, but when I added retrofit_generator the build getting failed, If i remove the generator the code runs fine and the build also succeeds. here is the error,

Unsupported operation: Cannot resolve
file:///C:/Users/User/AndroidStudioProjects/digigad/lib/resources/network/reposi
tory.dart; only "package" and "asset" schemes supported
[SEVERE] retrofit_generator:retrofit on lib/ui/login/login_view.dart:

here is my code of login_view.dart

 class LoginView extends StatefulWidget {
  @override
  _LoginViewState createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  LoginViewModel _loginViewModel;

  @override
  void initState() {
    super.initState();
    _loginViewModel = locator<LoginViewModel>();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LoginViewModel>.nonReactive(
        builder: (context, model, child) {
          return Scaffold(
            backgroundColor: Colors.white,
            body: SafeArea(
              child: Padding(
                padding: const EdgeInsets.all(30.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Container(
                      child: Center(
                        child: Container(
                          child: Image.asset('images/iv_logo.png'),
                          width: 100,
                          height: 100,
                        ),
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            _socialButton(
                                image: 'icons/ic_facebook.png',
                                title: 'Facebook'),
                            SizedBox(
                              width: 30,
                            ),
                            _socialButton(
                                image: 'icons/ic_google.png', title: 'Google'),
                          ],
                        ),
                        SizedBox(
                          height: 30,
                        ),
                        Text(
                          'or',
                          style: TextStyle(
                              fontSize: 15, color: AppConstants.colorHint),
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        StreamBuilder<String>(
                            stream: model.phoneStream,
                            builder: (context, snapshot) {
                              return Column(
                                children: <Widget>[
                                  AppFunctions.getTextInputField(
                                      hintText: 'Mobile Number',
                                      maxLength: 10,
                                      inputType: TextInputType.phone,
                                      onChanged: model.onPhoneChanged,
                                      errorText: snapshot.error),
                                  AppFunctions.getStandardDivider(),
                                  AppFunctions.getBigButton(
                                    title: 'Login',
                                    color: snapshot.hasData
                                        ? AppConstants.colorPrimary
                                        : AppConstants.colorHint,
                                    onClick: snapshot.hasData
                                        ? () => _loginViewModel
                                            .onLoginClicked(snapshot.data)
                                        : () => () {},
                                  )
                                ],
                              );
                            }),
                      ],
                    ),
                    Center(
                      child: Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text('Made with '),
                          Icon(
                            Icons.favorite,
                            color: Colors.red,
                          ),
                          Text(' in Flutter'),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        viewModelBuilder: () => _loginViewModel);
  }

  Expanded _socialButton({String image, String title}) {
    return Expanded(
      child: Container(
        height: 40,
        child: RaisedButton(
          onPressed: () {},
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(
                image,
                width: 16,
                height: 16,
              ),
              SizedBox(
                width: 10,
              ),
              Text(title)
            ],
          ),
        ),
      ),
    );
  }
}

Body:
I also faced the same error and got to know that there is some direct import statement in my project file.

that import statement was login_page.dart

import 'file:///D:/Major_Project/connect/lib/api/api.dart';

in this case, the same error was thrown in build
Log

so find that statement in the project and change it with the normal import statement

login_page.dart

import 'package:connect/api/api.dart';


问:
Flutter convert JSON string to multi-level list
I want to convert a string to multi-level list, but I cannot find a efficient way to do.

From String:
[[1,2,3],[1,2]]

To List:
List< List < int>>

答:
```<code>String str = '[[1,2,3],[1,2]]';
  List<List<int>> list=[];
  for(String s in str.split('],[')){
    List<int> l = [];
    String formattedString = s.replaceAll('[','').replaceAll(']','');
    for(String innerS in formattedString.split(',')){
        l.add(int.parse(innerS));
      print(l);
    }
    list.add(l);
  }
</code>```

Output: [[1, 2, 3], [1, 2]]

Body:
String str = '[[1,2,3],[1,2]]';
  List<List<int>> list=[];
  for(String s in str.split('],[')){
    List<int> l = [];
    String formattedString = s.replaceAll('[','').replaceAll(']','');
    for(String innerS in formattedString.split(',')){
        l.add(int.parse(innerS));
      print(l);
    }
    list.add(l);
  }

Output: [[1, 2, 3], [1, 2]]


问:
Unknown File Encoding
I've got a configuration file with some encoding which I'm not sure about. How would I go about decoding it so that it's readable?

Here's a sample:

```<code>xÚ³II,I´ãå´ÉËOIUÈL±U*®,öÌKËW
</code>```

答:
Well, If it is just text encoding problem you should be able to open it in some advance editor, or even a browser.
However, I think this is a configuration files that its data is written in binary format. Unless you know the application and the context, you won't be able to read it.</p>

Title: Unknown File Encoding

Body:
I've got a configuration file with some encoding which I'm not sure about. How would I go about decoding it so that it's readable?

Here's a sample:

xÚ³II,I´ãå´ÉËOIUÈL±U*®,öÌKËW


问:
Add Foreign Key to existing table
I want to add a Foreign Key to a table called "katalog".

```<code>ALTER TABLE katalog
ADD CONSTRAINT `fk_katalog_sprache`
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
</code>```

When I try to do this, I get this error message:

```<code>Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)
</code>```

Error in INNODB Status:

120405 14:02:57 Error in foreign key constraint of table
  mytable.#sql-7fb1_7d3a:

```<code>FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL
</code>```

When i use this query it works, but with wrong "on delete" action:

```<code>ALTER TABLE `katalog`
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )
</code>```

Both tables are InnoDB and both fields are "INT(11) not null". I'm using MySQL 5.1.61. Trying to fire this ALTER Query with MySQL Workbench (newest) on a MacBook Pro.

Table Create Statements:

```<code>CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
 ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$

CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
 `Bezeichnung` varchar(45) NOT NULL,
 PRIMARY KEY (`ID`),
 UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
</code>```

答:
step 1: run this script

```<code>SET FOREIGN_KEY_CHECKS=0;
</code>```

step 2: add column

```<code>ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL
</code>```

step 3: add foreign key to the added column

```<code>ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);
</code>```

step 4: run this script

```<code>SET FOREIGN_KEY_CHECKS=1;
</code>```

Title: Add Foreign Key to existing table

Body:
I want to add a Foreign Key to a table called "katalog".

ALTER TABLE katalog
ADD CONSTRAINT `fk_katalog_sprache`
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;

When I try to do this, I get this error message:

Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)

Error in INNODB Status:

120405 14:02:57 Error in foreign key constraint of table
  mytable.#sql-7fb1_7d3a:

FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL

When i use this query it works, but with wrong "on delete" action:

ALTER TABLE `katalog`
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )

Both tables are InnoDB and both fields are "INT(11) not null". I'm using MySQL 5.1.61. Trying to fire this ALTER Query with MySQL Workbench (newest) on a MacBook Pro.

Table Create Statements:

CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
 ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$

CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
 `Bezeichnung` varchar(45) NOT NULL,
 PRIMARY KEY (`ID`),
 UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

Body:
step 1: run this script

SET FOREIGN_KEY_CHECKS=0;

step 2: add column

ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL

step 3: add foreign key to the added column

ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);

step 4: run this script

SET FOREIGN_KEY_CHECKS=1;


答:
Perhaps you could use something like:

```<code>dictionary = {'a':1, 'b':2, 'c':3}
dictionary.update({'c': 10 if not dictionary.get('c') else tuple([dictionary['c'],] + [10,])})
# {'a': 1, 'b': 2, 'c': (3, 10)}
</code>```

But it should probably be wrapped into a function to make things clean. The general pattern would be (I suppose, based on your question):

```<code>dict = {...}
if 'a' not in dict:
    do_this() # just add it to the dict?
else:
    do_that() # build a tuple or list?
</code>```

In your above question you're mixing types -- I'm not sure if you want that, a more pythonic approach might be to have all the values as list and use a defaultdict.

Title: Add value of the already existing key in dict in a form of container in Python

Body:
Is there any built-in function that would do the following?

dictionary = {‘a’:1, ‘b’:2, ‘c’:3}

dictionary.update(c=10)

# what happens
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:10}

# what I want to happen:
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:(3, 10)}

By default if keys are the same, later key would override earlier one.
If the key is already present in dict, the value of the new key: value pair would be added to already existing value in a form of container, like tuple, or list or set.

I can write a helper function to do so but I believe it should be something built-in for this matter.

Body:
Perhaps you could use something like:

dictionary = {'a':1, 'b':2, 'c':3}
dictionary.update({'c': 10 if not dictionary.get('c') else tuple([dictionary['c'],] + [10,])})
# {'a': 1, 'b': 2, 'c': (3, 10)}

But it should probably be wrapped into a function to make things clean. The general pattern would be (I suppose, based on your question):

dict = {...}
if 'a' not in dict:
    do_this() # just add it to the dict?
else:
    do_that() # build a tuple or list?

In your above question you're mixing types -- I'm not sure if you want that, a more pythonic approach might be to have all the values as list and use a defaultdict.


问:
Change fontcolor onclick
I try to change my fontcolor onclick but it doesn't work :D

My js function:

```<code>    function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }
</code>```

The first div is a img-file. I want to press on the image and change the color of the 2nd div "txt_raum_ein"

```<code>    <div id="but_bel_raum_ein" onclick="changeColor("txt_raum_ein", "green")"></div>
    <div id="txt_raum_ein"><font size = "+2" face="Arial">RAUM EIN</font></div>
</code>```

答:
You need to pass in parameters using single quotes, rather than double quotes. For example:

  function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="but_bel_raum_ein" onclick="changeColor('txt_raum_ein', 'green')">image</div>
   <div id="txt_raum_ein"><font size = "+2" face="Arial">RAUM EIN</font></div></code>```

Title: Change fontcolor onclick

Body:
I try to change my fontcolor onclick but it doesn't work :D

My js function:

    function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }

The first div is a img-file. I want to press on the image and change the color of the 2nd div "txt_raum_ein"

RAUM EIN

Body:
You need to pass in parameters using single quotes, rather than double quotes. For example:

  function changeColor(id, col) {
        document.getElementById(id).style.color = col;
        return false;
    }

<div id="but_bel_raum_ein" onclick="changeColor('txt_raum_ein', 'green')">image</div>
   <div id="txt_raum_ein"><font size = "+2" face="Arial">RAUM EIN</font></div>


问:
Removing outliers based on column variables or multi-index in a dataframe
This is another IQR outlier question. I have a dataframe that looks something like this:

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=('red','yellow','green'))
df.loc[0:49,'Season'] = 'Spring'
df.loc[50:99,'Season'] = 'Fall'
df.loc[0:24,'Treatment'] = 'Placebo'
df.loc[25:49,'Treatment'] = 'Drug'
df.loc[50:74,'Treatment'] = 'Placebo'
df.loc[75:99,'Treatment'] = 'Drug'
df = df[['Season','Treatment','red','yellow','green']]
df
</code>```

I would like to find and remove the outliers for each condition (i.e. Spring Placebo, Spring Drug, etc). Not the whole row, just the cell.  And would like to do it for each of the 'red', 'yellow', 'green' columns.

Is there way to do this without breaking the dataframe into a whole bunch of sub dataframes with all of the conditions broken out separately?  I'm not sure if this would be easier if 'Season' and 'Treatment' were handled as columns or indices. I'm fine with either way.

I've tried a few things with .iloc and .loc but I can't seem to make it work.

答:
If need replace outliers by missing values use GroupBy.transform with DataFrame.quantile, then compare for lower and greater values by DataFrame.lt and DataFrame.gt, chain masks by | for bitwise OR and set missing values in DataFrame.mask, default replacement, so not specified:

```<code>np.random.seed(2020)
df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=('red','yellow','green'))
df.loc[0:49,'Season'] = 'Spring'
df.loc[50:99,'Season'] = 'Fall'
df.loc[0:24,'Treatment'] = 'Placebo'
df.loc[25:49,'Treatment'] = 'Drug'
df.loc[50:74,'Treatment'] = 'Placebo'
df.loc[75:99,'Treatment'] = 'Drug'
df = df[['Season','Treatment','red','yellow','green']]

g = df.groupby(['Season','Treatment'])
df1 = g.transform('quantile', 0.05)
df2 = g.transform('quantile', 0.95)

c = df.columns.difference(['Season','Treatment'])
mask = df[c].lt(df1) | df[c].gt(df2)
df[c] = df[c].mask(mask)

print (df)
    Season Treatment   red  yellow  green
0   Spring   Placebo   NaN     NaN   67.0
1   Spring   Placebo  67.0    91.0    3.0
2   Spring   Placebo  71.0    56.0   29.0
3   Spring   Placebo  48.0    32.0   24.0
4   Spring   Placebo  74.0     9.0   51.0
..     ...       ...   ...     ...    ...
95    Fall      Drug  90.0    35.0   55.0
96    Fall      Drug  40.0    55.0   90.0
97    Fall      Drug   NaN    54.0    NaN
98    Fall      Drug  28.0    50.0   74.0
99    Fall      Drug   NaN    73.0   11.0

[100 rows x 5 columns]
</code>```

Body:
This is another IQR outlier question. I have a dataframe that looks something like this:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=('red','yellow','green'))
df.loc[0:49,'Season'] = 'Spring'
df.loc[50:99,'Season'] = 'Fall'
df.loc[0:24,'Treatment'] = 'Placebo'
df.loc[25:49,'Treatment'] = 'Drug'
df.loc[50:74,'Treatment'] = 'Placebo'
df.loc[75:99,'Treatment'] = 'Drug'
df = df[['Season','Treatment','red','yellow','green']]
df

I would like to find and remove the outliers for each condition (i.e. Spring Placebo, Spring Drug, etc). Not the whole row, just the cell.  And would like to do it for each of the 'red', 'yellow', 'green' columns.

Is there way to do this without breaking the dataframe into a whole bunch of sub dataframes with all of the conditions broken out separately?  I'm not sure if this would be easier if 'Season' and 'Treatment' were handled as columns or indices. I'm fine with either way.

I've tried a few things with .iloc and .loc but I can't seem to make it work.

Body:
If need replace outliers by missing values use GroupBy.transform with DataFrame.quantile, then compare for lower and greater values by DataFrame.lt and DataFrame.gt, chain masks by | for bitwise OR and set missing values in DataFrame.mask, default replacement, so not specified:

np.random.seed(2020)
df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=('red','yellow','green'))
df.loc[0:49,'Season'] = 'Spring'
df.loc[50:99,'Season'] = 'Fall'
df.loc[0:24,'Treatment'] = 'Placebo'
df.loc[25:49,'Treatment'] = 'Drug'
df.loc[50:74,'Treatment'] = 'Placebo'
df.loc[75:99,'Treatment'] = 'Drug'
df = df[['Season','Treatment','red','yellow','green']]

g = df.groupby(['Season','Treatment'])
df1 = g.transform('quantile', 0.05)
df2 = g.transform('quantile', 0.95)

c = df.columns.difference(['Season','Treatment'])
mask = df[c].lt(df1) | df[c].gt(df2)
df[c] = df[c].mask(mask)

print (df)
    Season Treatment   red  yellow  green
0   Spring   Placebo   NaN     NaN   67.0
1   Spring   Placebo  67.0    91.0    3.0
2   Spring   Placebo  71.0    56.0   29.0
3   Spring   Placebo  48.0    32.0   24.0
4   Spring   Placebo  74.0     9.0   51.0
..     ...       ...   ...     ...    ...
95    Fall      Drug  90.0    35.0   55.0
96    Fall      Drug  40.0    55.0   90.0
97    Fall      Drug   NaN    54.0    NaN
98    Fall      Drug  28.0    50.0   74.0
99    Fall      Drug   NaN    73.0   11.0

[100 rows x 5 columns]


问:
?: ?? Operators Instead Of IF|ELSE
```<code>public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}
</code>```

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

```<code>if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}
</code>```

[ 2 ]

```<code>if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}
</code>```

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

答:
Refering to ?: Operator (C# Reference)

The conditional operator (?:) returns
  one of two values depending on the
  value of a Boolean expression.
  Following is the syntax for the
  conditional operator.

Refering to ?? Operator (C# Reference)

The ?? operator is called the
  null-coalescing operator and is used
  to define a default value for a
  nullable value types as well as
  reference types. It returns the
  left-hand operand if it is not null;
  otherwise it returns the right
  operand.

That means:

[Part 1]

```<code>return source ?? String.Empty;
</code>```

[Part 2] is not applicable ...

Title: ?: ?? Operators Instead Of IF|ELSE

Body:
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}

[ 2 ]

if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

Body:
Refering to ?: Operator (C# Reference)

The conditional operator (?:) returns
  one of two values depending on the
  value of a Boolean expression.
  Following is the syntax for the
  conditional operator.

Refering to ?? Operator (C# Reference)

The ?? operator is called the
  null-coalescing operator and is used
  to define a default value for a
  nullable value types as well as
  reference types. It returns the
  left-hand operand if it is not null;
  otherwise it returns the right
  operand.

That means:

[Part 1]

return source ?? String.Empty;

[Part 2] is not applicable ...


问:
htaccess redirects is missing slash and instead appends to domain tld
I am having an issue on a production site. I made a htaccess rule to redirect if the hostname is not "app.example.com". If it is not, I want to redirect to that hostname.

I have done like so:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^app.example.com/$ [NC]
RewriteRule ^(.*)$ https://app.example.com//$1 [R=302,L]
</code>```

It works fine for the root path, however, if I go to an URL like so: https://example.com/something I am redirected to https://example.comsomething

What am I doing wrong?

I have also tried theese combinations, no luck:

```<code>RewriteRule ^(.+[^/])/$ https://app.example.com/$1 [R=302,L]
RewriteRule ^(.*)([^/])$ https://app.example.com/$1$2/ [L,R=302]
RewriteRule ^(.*)$ https://app.example.com//$1 [R=302,L]
</code>```

答:
Instead of playing guessing games you should read the documentation and learn what the tools you use actually do, I suggest. Don't get this wrong, I am not trying to mock you or anything. But this isn't rocket science and there is a documentation of excellent quality that comes with great examples...

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^app\.example\.com/$ [NC]
RewriteRule ^ https://app.example.com%{REQUEST_URI} [R=302,END]
</code>```

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Body:
I am having an issue on a production site. I made a htaccess rule to redirect if the hostname is not "app.example.com". If it is not, I want to redirect to that hostname.

I have done like so:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^app.example.com/$ [NC]
RewriteRule ^(.*)$ https://app.example.com//$1 [R=302,L]

It works fine for the root path, however, if I go to an URL like so: https://example.com/something I am redirected to https://example.comsomething

What am I doing wrong?

I have also tried theese combinations, no luck:

RewriteRule ^(.+[^/])/$ https://app.example.com/$1 [R=302,L]
RewriteRule ^(.*)([^/])$ https://app.example.com/$1$2/ [L,R=302]
RewriteRule ^(.*)$ https://app.example.com//$1 [R=302,L]

Body:
Instead of playing guessing games you should read the documentation and learn what the tools you use actually do, I suggest. Don't get this wrong, I am not trying to mock you or anything. But this isn't rocket science and there is a documentation of excellent quality that comes with great examples...

RewriteEngine On
RewriteCond %{HTTP_HOST} !^app\.example\.com/$ [NC]
RewriteRule ^ https://app.example.com%{REQUEST_URI} [R=302,END]

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


问:
Save image from byte data with python gdal
I'm retrieving a Sentinel-2 image with metadata from an ArcGIS REST API server. It comes as a byte string. I currently first write the data to a tif-file with f.write(). Then I open it with imageio and later save it as a geoTIFF with gdal.

I would like to save the image directly as a geoTIFF with gdal. But I haven't figured out how to extract the image as a numpy array directly from the byte data, or how to use gdal to write the image directly from the byte data. I use Python 3.8 and Windows 10.

```<code>import requests
from imageio import imread
from osgeo import gdal

response = requests.get(im_url, auth=auth)  # call image url
im_binary = response.content  # the image in binary format
im_newpath = 'testimage.tif'
with open(im_newpath, 'wb') as f:
     f.write(im_binary)

print(type(im_binary))

print(im_binary[0:50])
</code>```

returns:

```<code><class 'bytes'>

b'II*\x00\x08\x00\x00\x00\x15\x00\x00\x01\x03\x00\x01\x00\x00\x00X\x02\x00\x00\x01\x01\x03\x00\x01\x00\x00\x00\x90\x01\x00\x00\x02\x01\x03\x00\r\x00\x00\x00\n\x01\x00\x00\x03\x01\x03\x00'
</code>```

My attempts to decode the data has so far given bad results.

```<code>decoded = im_binary.decode('utf_16')

UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 364-365: illegal UTF-16 surrogate
</code>```

Ignoring or replacing the errors gives various non-nunmeric characters. Any advice?

答:
To summary my comments and insights from answers:

Nothing seems wrong with the approach. Since images consist of pure binary data, there is no use of UTF-decoding routines.

I don't understand the necessity for any other decoding. What is received looks like fine TIFF data.

While writing to a temporary file just to be able to pass the file to another library seems clumsy, it is a robust and clean way to proceed. Probably the physical file can be avoided by using a StringIo instance, but since this requires the full image data to be held in memory, it may not work for huge images. (I'm not sure, how the URL to be passed tom imread() has to look like in that case - seems one more argument to use file instead).

Body:
I'm retrieving a Sentinel-2 image with metadata from an ArcGIS REST API server. It comes as a byte string. I currently first write the data to a tif-file with f.write(). Then I open it with imageio and later save it as a geoTIFF with gdal.

I would like to save the image directly as a geoTIFF with gdal. But I haven't figured out how to extract the image as a numpy array directly from the byte data, or how to use gdal to write the image directly from the byte data. I use Python 3.8 and Windows 10.

import requests
from imageio import imread
from osgeo import gdal

response = requests.get(im_url, auth=auth)  # call image url
im_binary = response.content  # the image in binary format
im_newpath = 'testimage.tif'
with open(im_newpath, 'wb') as f:
     f.write(im_binary)

print(type(im_binary))

print(im_binary[0:50])

returns:

<class 'bytes'>

b'II*\x00\x08\x00\x00\x00\x15\x00\x00\x01\x03\x00\x01\x00\x00\x00X\x02\x00\x00\x01\x01\x03\x00\x01\x00\x00\x00\x90\x01\x00\x00\x02\x01\x03\x00\r\x00\x00\x00\n\x01\x00\x00\x03\x01\x03\x00'

My attempts to decode the data has so far given bad results.

decoded = im_binary.decode('utf_16')

UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 364-365: illegal UTF-16 surrogate

Ignoring or replacing the errors gives various non-nunmeric characters. Any advice?


问:
PHP can't write big data to csv file
I'm using the PHP code to export data to CSV file from table (Database).

But unfortunately its writing just 98000 rows and i have total 198000 rows in table.

I think total data upto 34mb in the table.

And second thing how can i download automatically once the file writing finished. Anyone can help thanks.

```<code>$que = "SELECT * FROM campaign";
$query = mysqli_query($connection,$que);
$number_rows = mysqli_num_rows($query);

if ($number_rows >= 1)
{
    $filename = "exported_db_" . date("m-d-Y_hia") . ".csv"; // filenme with date appended
    $fp = fopen($filename, "w"); // open file

    $row = mysqli_fetch_assoc($query);

    $seperator = "";
    $comma = "";

    foreach ($row as $name => $value)
    {
        $seperator .= $comma . $name; // write first value without a comma
        $comma = ","; // add comma in front of each following value
    }
    $seperator .= "\n";

    echo "Database has been exported to $filename";

    fputs($fp, $seperator);

    mysqli_data_seek($query, 0); // use previous query leaving out first row

    while($row = mysqli_fetch_assoc($query))
    {
        $seperator = "";
        $comma = "";

        foreach ($row as $name => $value)
        {
            $seperator .= $comma . $value; // write first value without a comma
            $comma = ","; // add comma in front of each following value
        }

        $seperator .= "\n";

        fputs($fp, $seperator);
    }

    fclose($fp);

}
else {
    echo "There are no records in the database to export.";
}
</code>```

答:
When i put these two line code at the top of file, So i have get correct result.

I think these code increase the size of caches_memory and execution time.

Thanks everyone for commenting and discussion.

```<code>
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');

</code>```

Title: PHP can't write big data to csv file

Body:
I'm using the PHP code to export data to CSV file from table (Database).

But unfortunately its writing just 98000 rows and i have total 198000 rows in table.

I think total data upto 34mb in the table.

And second thing how can i download automatically once the file writing finished. Anyone can help thanks.

$que = "SELECT * FROM campaign";
$query = mysqli_query($connection,$que);
$number_rows = mysqli_num_rows($query);

if ($number_rows >= 1)
{
    $filename = "exported_db_" . date("m-d-Y_hia") . ".csv"; // filenme with date appended
    $fp = fopen($filename, "w"); // open file

    $row = mysqli_fetch_assoc($query);

    $seperator = "";
    $comma = "";

    foreach ($row as $name => $value)
    {
        $seperator .= $comma . $name; // write first value without a comma
        $comma = ","; // add comma in front of each following value
    }
    $seperator .= "\n";

    echo "Database has been exported to $filename";

    fputs($fp, $seperator);

    mysqli_data_seek($query, 0); // use previous query leaving out first row

    while($row = mysqli_fetch_assoc($query))
    {
        $seperator = "";
        $comma = "";

        foreach ($row as $name => $value)
        {
            $seperator .= $comma . $value; // write first value without a comma
            $comma = ","; // add comma in front of each following value
        }

        $seperator .= "\n";

        fputs($fp, $seperator);
    }

    fclose($fp);

}
else {
    echo "There are no records in the database to export.";
}

Body:
When i put these two line code at the top of file, So i have get correct result.

I think these code increase the size of caches_memory and execution time.

Thanks everyone for commenting and discussion.

ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');


问:
MDBDataTable Cannot Sort Column if Cell Contains HTML
I'm trying to generate a sortable and searchable table in reactjs using mdbreact like so

```<code>import React from 'react';
import { MDBDataTable } from 'mdbreact';

const tableData = {
    columns: [
        {
            field: 'first_name',
            label: 'First Name'
        },
        {
            field: 'last_name',
            label: 'Last Name'
        },
        {
            field: 'age',
            label: 'Age'
        }
    ],
    rows: [
        {
            first_name: <a href='/example-route/John'>John</a>,
            last_name: 'Smith',
            age: 29
        },
        {
            first_name: <a href='/example-route/Jane'>Jane</a>,
            last_name: 'Doe',
            age: 34
        }
    ]
};

class Table extends React.Component {
    render() {
        return(
            <MDBDataTable data={tableData} />
        )
    }
}

export default Table;
</code>```

The table renders just fine, but because there are  tags in the body, the relevant column becomes unsortable and unsearchable.

I've thought for a few days now about how to make that column sortable and searchable, but after doing a boatload of reading I've come up blank.

UPDATE

It seems that in Chrome the column is neither searchable nor sortable, but in Firefox the column is sortable but not searchable.

答:
ref: https://mdbootstrap.com/support/react/make-a-mdbdatatable-row-clickable/

I have found a reserved row key called clickEvent that can be used like so:

```<code>import React from 'react';
import { MDBDataTable } from 'mdbreact';

class Table extends React.Component {

    handleClick(name) {
        console.log(name);
    }

    render() {
        return(
            <MDBDataTable data={{
                columns: [
                    {
                        field: 'first_name',
                        label: 'First Name'
                    },
                    {
                        field: 'last_name',
                        label: 'Last Name'
                    },
                    {
                        field: 'age',
                        label: 'Age'
                    }
                ],
                rows: [
                    {
                        first_name: 'John',
                        last_name: 'Smith',
                        age: 29,
                        clickEvent: () => this.handleClick('john')
                    },
                    {
                        first_name: 'Jane',
                        last_name: 'Doe',
                        age: 34,
                        clickEvent: () => this.handleClick('jane')
                    }
                ]
            }} />
        )
    }
}

export default Table;
</code>```

I can then handle the click event in whichever way I'd like, maybe using window.location.href = '/' + name; to simulate the required functionality of an  tag.

Body:
I'm trying to generate a sortable and searchable table in reactjs using mdbreact like so

import React from 'react';
import { MDBDataTable } from 'mdbreact';

const tableData = {
    columns: [
        {
            field: 'first_name',
            label: 'First Name'
        },
        {
            field: 'last_name',
            label: 'Last Name'
        },
        {
            field: 'age',
            label: 'Age'
        }
    ],
    rows: [
        {
            first_name: John,
            last_name: 'Smith',
            age: 29
        },
        {
            first_name: Jane,
            last_name: 'Doe',
            age: 34
        }
    ]
};

class Table extends React.Component {
    render() {
        return(
            <MDBDataTable data={tableData} />
        )
    }
}

export default Table;

The table renders just fine, but because there are  tags in the body, the relevant column becomes unsortable and unsearchable.

I've thought for a few days now about how to make that column sortable and searchable, but after doing a boatload of reading I've come up blank.

UPDATE

It seems that in Chrome the column is neither searchable nor sortable, but in Firefox the column is sortable but not searchable.

Body:
ref: https://mdbootstrap.com/support/react/make-a-mdbdatatable-row-clickable/

I have found a reserved row key called clickEvent that can be used like so:

import React from 'react';
import { MDBDataTable } from 'mdbreact';

class Table extends React.Component {

    handleClick(name) {
        console.log(name);
    }

    render() {
        return(
            <MDBDataTable data={{
                columns: [
                    {
                        field: 'first_name',
                        label: 'First Name'
                    },
                    {
                        field: 'last_name',
                        label: 'Last Name'
                    },
                    {
                        field: 'age',
                        label: 'Age'
                    }
                ],
                rows: [
                    {
                        first_name: 'John',
                        last_name: 'Smith',
                        age: 29,
                        clickEvent: () => this.handleClick('john')
                    },
                    {
                        first_name: 'Jane',
                        last_name: 'Doe',
                        age: 34,
                        clickEvent: () => this.handleClick('jane')
                    }
                ]
            }} />
        )
    }
}

export default Table;

I can then handle the click event in whichever way I'd like, maybe using window.location.href = '/' + name; to simulate the required functionality of an <a> tag.