问:
Move div on upside in mobile view using bootstrap
I have two divs with classes col-md-8 and col-md-4 (which contains an image). In dektop view it looks like A  B, but in mobile view I want B upside and A downside.

Here's the code:

```<code><div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class=**"col-md-8"**>
                <div class="card">
                    <div class="header">
                        <h4 class="title">ABC</h4>
                    </div>
                    <div class="content">
                        <form>
                            <div class="row">
                                <div class="col-md-5">
                                    <div class="form-group">
                                        <label>Company</label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="exampleInputEmail1">Email address (disabled)</label>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>First Name</label>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Last Name</label>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                        </form>
                    </div>
                </div>
            </div>
            <div class=**"col-md-4"**>
                <div class="card card-user">
                    <div class="image">
                        <img src="IMG/ABC.HTML" alt="..."/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
You can use order classes in Bootstrap 4 (beta).

To A you'll add the class order-2, and to B (the picture) you'll add the classes order-1 order-sm-3.

The class added to A makes it always be in the "middle". B will move down, or up if the screen size is big enough.

Read more about the classes here. Here's all the responsive breakpoints that can be used.

Body:
I have two divs with classes col-md-8 and col-md-4 (which contains an image). In dektop view it looks like A  B, but in mobile view I want B upside and A downside.

Here's the code:

ABC

                        <form>

                                        Company

                                        Email address (disabled)

                                        First Name

                                        Last Name

                        </form>


来源: stackexchange

问:
Why doesn't C++ support range based for loop for dynamic arrays?
Why doesn't C++ support range based for loop over dynamic arrays?  That is, something like this:

```<code>int* array = new int[len];
for[] (int i : array) {};
</code>```

I just invented the for[] statement to rhyme with new[] and delete[].  As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work) so in theory, range based for loop could also be made to work.  What is the reason that it's not made to work?

答:
array is not an array, but a pointer and there's no information about the size of the "array". So, compiler can not deduce begin and end of this array.

See the syntax of range based for loop:

```<code>{
   auto && __range = range_expression ;
   for (auto __begin = begin_expr, __end = end_expr;
   __begin != __end; ++__begin) {
   range_declaration = *__begin;
   loop_statement
   }
}
</code>```

range_expression - any expression that represents a suitable sequence
  (either an array or an object for which begin and end member functions
  or free functions are defined, see below) or a braced-init-list.

auto works at compile time.So, begin_expr and end_expr doesn't at deduct runtime.

ContentLicense: CC BY-SA 3.0

Body:
Why doesn't C++ support range based for loop over dynamic arrays?  That is, something like this:

int* array = new int[len];
for[] (int i : array) {};

I just invented the for[] statement to rhyme with new[] and delete[].  As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work) so in theory, range based for loop could also be made to work.  What is the reason that it's not made to work?

Body:
array is not an array, but a pointer and there's no information about the size of the "array". So, compiler can not deduce begin and end of this array.

See the syntax of range based for loop:

{
   auto && __range = range_expression ;
   for (auto __begin = begin_expr, __end = end_expr;
   __begin != __end; ++__begin) {
   range_declaration = *__begin;
   loop_statement
   }
}

range_expression - any expression that represents a suitable sequence
  (either an array or an object for which begin and end member functions
  or free functions are defined, see below) or a braced-init-list.

auto works at compile time.So, begin_expr and end_expr doesn't at deduct runtime.


问:
the file type you are attempting to upload is not allowed codeigniter ver 3.0.4
We are getting an error

Error:

Error: The filetype you are attempting to upload is not allowed.

```<code> array(1) { ["csv"]=> array(5) { ["name"]=> string(18) "cod_sp_payment.csv" ["type"]=> string(24) "application/vnd.ms-excel" ["tmp_name"]=> string(24) "C:\xampp\tmp\php5910.tmp" ["error"]=> int(0) ["size"]=> int(155) } }
</code>```

Controller Code:

```<code>$config['upload_path'] = './uploads/excel/';
$config['allowed_types'] = 'text/comma-separated-values|application/csv|application/excel|application/vnd.ms-excel|application/vnd.msexcel|text/anytext|text/plain|text/csv|csv';
$this->load->library('upload', $config);

if(! $this->upload->do_upload('csv')) {

    $error = array('error' => $this->upload->display_errors());

    // $this->load->view('upload_form', $error);

    echo $this->upload->display_errors();
}

$upload_data = $this->upload->data();

exit();
</code>```

答:
This happens because different servers treat files differently. It can be the same file but the mime type won't be seen as the same.

The solution:

On CodeIgniter, open the file system/libraries/Upload.php. On line 199 (in CI ver.3.x), change the line $this->file_size = $_FILES[$field]['size']; to $this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();

Upload the file to the server to test. Run the test. Identify your file type. Copy the file type to be used again later.

Now remove the change in step 1 above and re-upload the file.

Now open the file application/config/mimes.php. Go to line 97. It's the part that has the mime type for 'xlsx'. Include your new mime type by pasting it here. Upload the file to your server.

Done. Now your application/upload should work.

I just found a similar answer to this here: CodeIgniter: "The filetype you are attempting to upload is not allowed."

It seems more detailed.

Body:
We are getting an error

Error:

Error: The filetype you are attempting to upload is not allowed.

 array(1) { ["csv"]=> array(5) { ["name"]=> string(18) "cod_sp_payment.csv" ["type"]=> string(24) "application/vnd.ms-excel" ["tmp_name"]=> string(24) "C:\xampp\tmp\php5910.tmp" ["error"]=> int(0) ["size"]=> int(155) } }

Controller Code:

$config['upload_path'] = './uploads/excel/';
$config['allowed_types'] = 'text/comma-separated-values|application/csv|application/excel|application/vnd.ms-excel|application/vnd.msexcel|text/anytext|text/plain|text/csv|csv';
$this->load->library('upload', $config);

if(! $this->upload->do_upload('csv')) {

    $error = array('error' => $this->upload->display_errors());

    // $this->load->view('upload_form', $error);

    echo $this->upload->display_errors();
}

$upload_data = $this->upload->data();

exit();


问:
installed ffmpeg not detected. Can't convert audio (python 2.7, mac os x)
General information:

I have a project in python that deals with audio classification; the backend is complete but I'm suffering with the front-end. The backend requirement (that I can't change) is that the audio file must be in wav format but I want users to be able to upload mp3 files as well. My front-end is a web server using python 2.7 and flask.

So, I basically want to convert mp3 to wav, but keep on getting errors.

(The complete code is at the bottom in case it is needed to understand the problem more clearly)

My attempts:

1- I used pydub library

I installed homebrew, libav, and ffmpeg

libav installation method: brew install libav --with-libvorbis --with-sdl --with-theora

ffmpeg installation method: brew install ffmpeg --with-libvorbis --with-ffplay --with-theora

Method1

```<code>sound = AudioSegment.from_file(filename[i], format="mp3") #filename[i]=nameOfFile
sound.export("input.wav", format="wav")
</code>```

Method2

```<code>AudioSegment.from_file(filename[i], format="mp3").export("input.wav", format="wav")
</code>```

=> Kept getting "file not found" and "cannot detect ffmpeg or avconv" runtime warning even though I installed ffmpeg and libav

=> Got same error above ("file not found") when I used "from_mp3" instead of "from_file"

=> Tried using "raw" instead of "mp3" and got "key error: sample_width" (couldn't find what this error meant)

Note: I made sure I'm in the right directory

2- Used subprocess

```<code>import subprocess
subprocess.call(["ffmpeg", "-i",filename[i],"inputAudio.wav"])
</code>```

=> Got "OSError: No such file or directory"

I hope you can help me understand what the problem is and how to solve it...

Complete Code:

I have this at the top

```<code>app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
os.chdir(APP_ROOT)
</code>```

Inside the function that deals with the audio files

```<code>data = request.files.getlist('file') #get all uploaded audio files
fsize = len(data) #number of audio files
i = 0 #index counter

filename = ["" for x in range(fsize)] #LIST TO STORE EACH FILE'S NAME
audiofile = ["" for x in range(fsize)] #LIST TO STORE CLASSIFICATION RESULTS OF EACH FILE

#LOOP THROUGH EACH UPLOADED FILE
for file in data:
    filename[i] = file.filename #ADD FILENAME TO LIST ABOVE
    destination = str(APP_ROOT)
</code>```

Problematic Part:

```<code>    if file.filename.endswith(".mp3"):
        from pydub import AudioSegment
        t = destination + "/" + filename[i]
        file.save(t) #SAVE UPLOADED MP3 FILE TO EXTRACT IT USING PYDUB

        sound = AudioSegment.from_file(filename[i], format="mp3")
        sound.export("input.wav", format="wav")
        os.remove(t) #DELETE MP3 FILE, WE ONLY WANT WAV
        destination +=  "/inputAudio.wav"
</code>```

Code Continuation:

```<code>#STORE AUDIO FILE TO PREPARE FOR PROCESSING (CLASSIFICATION)
    else:
        destination +=  "/inputAudio.wav"
        file.save(destination)

#FINAL STEP
    audiofile[i]=Raudio.start() #AUDIO PROCESSING (CLASSIFICATION)
    os.remove(destination) #DELETE AUDIO FILE TO PREVENT CLUTTERING OF FILES
    i += 1 #INCREMENT FILE INDEX
</code>```

答:
Okay so I have found a solution to this problem.

I ended up downloading the FFmpeg binary from this site.

Then I just copy-pasted all of the contents of the downloaded file in the following path:

Macintosh HD/Library/Frameworks/Python.framework/Versions/2.7

This is also where the python exec is and I remember reading somewhere that the problem may be that ffmpeg couldn't be found in the path of python or something.

So.... It finally works! Thought I'd share the solution as this problem has taken up most of my weekend and I hope it can help someone else solve their issues,

Body:
General information:

I have a project in python that deals with audio classification; the backend is complete but I'm suffering with the front-end. The backend requirement (that I can't change) is that the audio file must be in wav format but I want users to be able to upload mp3 files as well. My front-end is a web server using python 2.7 and flask.

So, I basically want to convert mp3 to wav, but keep on getting errors.

(The complete code is at the bottom in case it is needed to understand the problem more clearly)

My attempts:

1- I used pydub library

I installed homebrew, libav, and ffmpeg

libav installation method: brew install libav --with-libvorbis --with-sdl --with-theora

ffmpeg installation method: brew install ffmpeg --with-libvorbis --with-ffplay --with-theora

Method1

sound = AudioSegment.from_file(filename[i], format="mp3") #filename[i]=nameOfFile
sound.export("input.wav", format="wav")

Method2

AudioSegment.from_file(filename[i], format="mp3").export("input.wav", format="wav")

=> Kept getting "file not found" and "cannot detect ffmpeg or avconv" runtime warning even though I installed ffmpeg and libav

=> Got same error above ("file not found") when I used "from_mp3" instead of "from_file"

=> Tried using "raw" instead of "mp3" and got "key error: sample_width" (couldn't find what this error meant)

Note: I made sure I'm in the right directory

2- Used subprocess

import subprocess
subprocess.call(["ffmpeg", "-i",filename[i],"inputAudio.wav"])

=> Got "OSError: No such file or directory"

I hope you can help me understand what the problem is and how to solve it...

Complete Code:

I have this at the top

app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
os.chdir(APP_ROOT)

Inside the function that deals with the audio files

data = request.files.getlist('file') #get all uploaded audio files
fsize = len(data) #number of audio files
i = 0 #index counter

filename = ["" for x in range(fsize)] #LIST TO STORE EACH FILE'S NAME
audiofile = ["" for x in range(fsize)] #LIST TO STORE CLASSIFICATION RESULTS OF EACH FILE

#LOOP THROUGH EACH UPLOADED FILE
for file in data:
    filename[i] = file.filename #ADD FILENAME TO LIST ABOVE
    destination = str(APP_ROOT)

Problematic Part:

    if file.filename.endswith(".mp3"):
        from pydub import AudioSegment
        t = destination + "/" + filename[i]
        file.save(t) #SAVE UPLOADED MP3 FILE TO EXTRACT IT USING PYDUB

        sound = AudioSegment.from_file(filename[i], format="mp3")
        sound.export("input.wav", format="wav")
        os.remove(t) #DELETE MP3 FILE, WE ONLY WANT WAV
        destination +=  "/inputAudio.wav"

Code Continuation:

#STORE AUDIO FILE TO PREPARE FOR PROCESSING (CLASSIFICATION)
    else:
        destination +=  "/inputAudio.wav"
        file.save(destination)

#FINAL STEP
    audiofile[i]=Raudio.start() #AUDIO PROCESSING (CLASSIFICATION)
    os.remove(destination) #DELETE AUDIO FILE TO PREVENT CLUTTERING OF FILES
    i += 1 #INCREMENT FILE INDEX


问:
Java-- characters in list and mapping to uppercase
I am trying to convert everything in a list to uppercase, but I'm having trouble with this. I get an error for the last line:

The method map(Function is not applicable for the
  arguments(Character::toUppercase)

but I'm not sure how to fix it. Also, how would I display all the characters in this list that come after "g"?

```<code> public static void main(String[] args)  {
      List<Character> list = new ArrayList<>();
      String alphabet = "abcdefghijklmnopqrstuvwxyz";
      SecureRandom random = new SecureRandom();

      for (int i = 0; i < 30; ++i)
      {
         list.add(alphabet.charAt(random.nextInt(26)));
      }

     System.out.println("Ascending: ");

     list.stream().sorted().forEach(System.out::print);

     System.out.println("Characters in uppercase: ");

     list.stream().map(Character::toUpperCase).collect(toList());
}
</code>```

答:
you have got misspelled in your code
pls add ")" after args and also use correct method name: toUpperCase

pls check Oracle Character docs

Body:
I am trying to convert everything in a list to uppercase, but I'm having trouble with this. I get an error for the last line:

The method map(Function is not applicable for the
  arguments(Character::toUppercase)

but I'm not sure how to fix it. Also, how would I display all the characters in this list that come after "g"?

 public static void main(String[] args)  {
      List<Character> list = new ArrayList<>();
      String alphabet = "abcdefghijklmnopqrstuvwxyz";
      SecureRandom random = new SecureRandom();

      for (int i = 0; i < 30; ++i)
      {
         list.add(alphabet.charAt(random.nextInt(26)));
      }

     System.out.println("Ascending: ");

     list.stream().sorted().forEach(System.out::print);

     System.out.println("Characters in uppercase: ");

     list.stream().map(Character::toUpperCase).collect(toList());
}


问:
Issue using $_POST with a textarea
I have a simple contact form on a website that has 2 text fields, 1 textarea, and 1 hidden field.

For some reason, all the fields POST to a PHP script except the textarea. I have done this a thousand times before and never had this issue.

Here is my HTML:

```<code><form action="scripts/contactform.php" method="post">
<table width="0" border="0" cellspacing="3" cellpadding="5" class="gpass">
  <tr>
    <td>Name:</td>
    <td><input name="name" type="text" maxlength="50" /></td>
  </tr>
  <tr>
    <td>E-mail:</td>
    <td><input name="email" type="text"/></td>
  </tr>
  <tr>
    <td>Message:</td>
    <td><textarea name="comment" id="comment" cols="30" rows="5"></textarea>
    <input type="hidden" value=" <?php echo $_SERVER['REMOTE_ADDR'];?>" name="address" />
    </td>
  </tr>
  <tr>
    <td colspan="2" align="center"><input name="submit" type="submit" value="Submit" class="noround" id="regbut" /><input name="reset" type="reset" value="Reset" class="noround" id="regbut"/></td>
  </tr>
</table>
</form>
</code>```

And my script looks like this:

```<code>$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
    die('Failed to connect to server: ' . mysql_error());
}

$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
    die("Unable to select database");
}

$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$comment = mysql_real_escape_string($_POST['comment']);
$ipaddress = mysql_real_escape_string($_POST['address']);
</code>```

I have a few things to process the data underneath this, but that doesn't matter since the $comment variable isn't being defined. I've searched the entire script and there are no conflicting variable names.

I am completely stumped on why this is happening. I've successfully processed textarea's on my site multiple times before, so this really is confusing.

答:
You only need to add an ID value to the form and then add the form attribute to the textarea with the form ID value</p>

```<code><form id="sample".....>
<textarea name="aba" form="sample".....></textarea>
</form>
</code>```

Title: Issue using $_POST with a textarea

Body:
I have a simple contact form on a website that has 2 text fields, 1 textarea, and 1 hidden field.

For some reason, all the fields POST to a PHP script except the textarea. I have done this a thousand times before and never had this issue.

Here is my HTML:

<form action="scripts/contactform.php" method="post">

    Name:
    <input name="name" type="text" maxlength="50" />

    E-mail:
    <input name="email" type="text"/>

    Message:
    <textarea name="comment" id="comment" cols="30" rows="5"></textarea>
    <input type="hidden" value=" <?php echo $_SERVER['REMOTE_ADDR'];?>" name="address" />

    <input name="submit" type="submit" value="Submit" class="noround" id="regbut" /><input name="reset" type="reset" value="Reset" class="noround" id="regbut"/>

</form>

And my script looks like this:

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
    die('Failed to connect to server: ' . mysql_error());
}

$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
    die("Unable to select database");
}

$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$comment = mysql_real_escape_string($_POST['comment']);
$ipaddress = mysql_real_escape_string($_POST['address']);

I have a few things to process the data underneath this, but that doesn't matter since the $comment variable isn't being defined. I've searched the entire script and there are no conflicting variable names.

I am completely stumped on why this is happening. I've successfully processed textarea's on my site multiple times before, so this really is confusing.

Body:
You only need to add an ID value to the form and then add the form attribute to the textarea with the form ID value

<form id="sample".....>
<textarea name="aba" form="sample".....></textarea>
</form>


问:
Can't deploy to iPad when I add iCloud entitlement
Using Xcode and Visual Studio for Mac:

In Xcode, I can make, deploy and run an out-of-the-box HelloWorld app to my provisioned iPad.

Also in Xcode, I can add iCloud to the same app (via entitlements), and it deploys and runs on my iPad.

In VS for Mac, I can make and deploy a blank Xamarin Forms HelloWorld app and it runs on my iPad.

However, if I add iCloud to the entitlements.plist for the Xamarin forms app, it won't deploy to my iPad.

I get the following for #4:

ApplicationVerificationFailed: Failed to verify code signature of /private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.tlZMLz/extracted/HelloWorldV.iOS.app : 0xe8008016 (The executable was signed with invalid entitlements.)
error MT1006: Could not install the application '/Users/Huber/Projects/HelloWorldV/iOS/bin/iPhone/Debug/device-builds/ipad5.3-11.1.1/HelloWorldV.iOS.app' on the device 'Denny's iPad': Your code signing/provisioning profiles are not correctly configured. Probably you have an entitlement not supported by your current provisioning profile, or your device is not part of the current provisioning profile. Please check the iOS Device Log for details (error: 0xe8008016).

Application could not be uploaded to the device.

The entitlements.plist file that Xamarin generates is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.icloud-container-identifiers</key>
    <array>
        <string>iCloud.com.DennyHuber.HelloWorldV</string>
    </array>
    <key>com.apple.developer.ubiquity-kvstore-identifier</key>
    <string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
    <key>com.apple.developer.icloud-services</key>
    <array>
        <string>CloudDocuments</string>
    </array>
</dict>
</plist>
</code>```

I have Key-Value Storage and iCloud Documents both checked.

Can anyone help?

Thanks,
Denny Huber

答:
You need to go to developer.apple.com and regenerate provisioning profile with new entitlements. After that, I advise you to manually delete all provisions, because sometimes it still tries to sign with an old one.

The provisions located in ~/Library/MobileDevice/Provisioning Profiles

After that go to Xcode, Setting -> Accounts -> Select your program, and press Download Manual Profiles.

After that clean the project and try to build again.

Body:
Using Xcode and Visual Studio for Mac:

In Xcode, I can make, deploy and run an out-of-the-box HelloWorld app to my provisioned iPad.

Also in Xcode, I can add iCloud to the same app (via entitlements), and it deploys and runs on my iPad.

In VS for Mac, I can make and deploy a blank Xamarin Forms HelloWorld app and it runs on my iPad.

However, if I add iCloud to the entitlements.plist for the Xamarin forms app, it won't deploy to my iPad.

I get the following for #4:

ApplicationVerificationFailed: Failed to verify code signature of /private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.tlZMLz/extracted/HelloWorldV.iOS.app : 0xe8008016 (The executable was signed with invalid entitlements.)
error MT1006: Could not install the application '/Users/Huber/Projects/HelloWorldV/iOS/bin/iPhone/Debug/device-builds/ipad5.3-11.1.1/HelloWorldV.iOS.app' on the device 'Denny's iPad': Your code signing/provisioning profiles are not correctly configured. Probably you have an entitlement not supported by your current provisioning profile, or your device is not part of the current provisioning profile. Please check the iOS Device Log for details (error: 0xe8008016).

Application could not be uploaded to the device.

The entitlements.plist file that Xamarin generates is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.icloud-container-identifiers</key>
    <array>
        <string>iCloud.com.DennyHuber.HelloWorldV</string>
    </array>
    <key>com.apple.developer.ubiquity-kvstore-identifier</key>
    <string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
    <key>com.apple.developer.icloud-services</key>
    <array>
        <string>CloudDocuments</string>
    </array>
</dict>
</plist>

I have Key-Value Storage and iCloud Documents both checked.

Can anyone help?

Thanks,
Denny Huber


问:
javascript: switch statement
I'm trying to learn how to do a switch statement using javascript. Can you guys help me how to convert this one into switch statement?</p>

```<code>        if (x == ix && y == iy){//should be the default
            x.style.backgroundColor = 'white';
        }
        if(x < ix){
            x.style.backgroundColor = 'red';
        }
        else if(x > ix){
            x.style.backgroundColor = 'blue';
        }
        if(y < iy){
            x.style.backgroundColor = 'green';
        }
        else if(y > iy){
            x.style.backgroundColor = 'yellow';
        }
</code>```

答:
Hope this could be helpful to convert your above conditions.</p>

```<code>switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
}
</code>```

Title: javascript: switch statement

Body:
I'm trying to learn how to do a switch statement using javascript. Can you guys help me how to convert this one into switch statement?

        if (x == ix && y == iy){//should be the default
            x.style.backgroundColor = 'white';
        }
        if(x < ix){
            x.style.backgroundColor = 'red';
        }
        else if(x > ix){
            x.style.backgroundColor = 'blue';
        }
        if(y < iy){
            x.style.backgroundColor = 'green';
        }
        else if(y > iy){
            x.style.backgroundColor = 'yellow';
        }

Body:
Hope this could be helpful to convert your above conditions.

switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
}


问:
Finding contiguous ranges in arrays
You are given an array of integers. You have to output the largest range so that all numbers in the range are present in the array. The numbers might be present in any order.  For example, suppose that the array is

```<code>{2, 10, 3, 12, 5, 4, 11, 8, 7, 6, 15}
</code>```

Here we find two (nontrivial) ranges for which all the integers in these ranges are present in the array, namely [2,8] and [10,12].  Out of these [2,8] is the longer one. So we need to output that.

When I was given this question, I was asked to do this in linear time and without using any sorting.  I thought that there might be a hash-based solution, but I couldn't come up with anything.

Here's my attempt at a solution:

```<code>void printRange(int arr[])
{
    int n=sizeof(arr)/sizeof(int);
    int size=2;
    int tempans[2];

    int answer[2];// the range is stored in another array
    for(int i =0;i<n;i++)
    {
        if(arr[0]<arr[1])
        {
             answer[0]=arr[0];
             answer[1]=arr[1];
        }
        if(arr[1]<arr[0])
        {
            answer[0]=arr[1];
            answer[1]=arr[0];
        }

        if(arr[i] < answer[1])
            size += 1;
        else if(arr[i]>answer[1]) {
            initialize tempans to new range;
             size2=2;
        }
        else {
            initialize tempans  to new range
        }
}

//I have to check when the count becomes equal to the diff of the range
</code>```

I am stuck at this part... I can't figure out how many tempanswer[] arrays should be  used.

答:
I read a lot of solutions on multiple platforms to this problem and one got my attention, as it solves the problem very elegantly and it is easy to follow.

The backbone of this method is to create a set/hash which takes O(n) time and from there every access to the set/hash will be O(1). As the O-Notation omit's constant terms, this Algorithm still can be described overall as  O(n)

```<code>def longestConsecutive(self, nums):
    nums = set(nums)                    # Create Hash O(1)
    best = 0
    for x in nums:
        if x - 1 not in nums:           # Optimization
            y = x + 1                   # Get possible next number
            while y in nums:            # If the next number is in set/hash
                y += 1                  # keep counting
            best = max(best, y - x)     # counting done, update best
    return best
</code>```

It's straight forward if you ran over it with simple numbers. The Optimization step is just a short-circuit to make sure you start counting, when that specific number is the beginning of a sequence.

All Credits to Stefan Pochmann.

Title: Finding contiguous ranges in arrays

Body:
You are given an array of integers. You have to output the largest range so that all numbers in the range are present in the array. The numbers might be present in any order.  For example, suppose that the array is

{2, 10, 3, 12, 5, 4, 11, 8, 7, 6, 15}

Here we find two (nontrivial) ranges for which all the integers in these ranges are present in the array, namely [2,8] and [10,12].  Out of these [2,8] is the longer one. So we need to output that.

When I was given this question, I was asked to do this in linear time and without using any sorting.  I thought that there might be a hash-based solution, but I couldn't come up with anything.

Here's my attempt at a solution:

void printRange(int arr[])
{
    int n=sizeof(arr)/sizeof(int);
    int size=2;
    int tempans[2];

    int answer[2];// the range is stored in another array
    for(int i =0;i<n;i++)
    {
        if(arr[0]<arr[1])
        {
             answer[0]=arr[0];
             answer[1]=arr[1];
        }
        if(arr[1]<arr[0])
        {
            answer[0]=arr[1];
            answer[1]=arr[0];
        }

        if(arr[i] < answer[1])
            size += 1;
        else if(arr[i]>answer[1]) {
            initialize tempans to new range;
             size2=2;
        }
        else {
            initialize tempans  to new range
        }
}

//I have to check when the count becomes equal to the diff of the range

I am stuck at this part... I can't figure out how many tempanswer[] arrays should be  used.

Body:
I read a lot of solutions on multiple platforms to this problem and one got my attention, as it solves the problem very elegantly and it is easy to follow.

The backbone of this method is to create a set/hash which takes O(n) time and from there every access to the set/hash will be O(1). As the O-Notation omit's constant terms, this Algorithm still can be described overall as  O(n)

def longestConsecutive(self, nums):
    nums = set(nums)                    # Create Hash O(1)
    best = 0
    for x in nums:
        if x - 1 not in nums:           # Optimization
            y = x + 1                   # Get possible next number
            while y in nums:            # If the next number is in set/hash
                y += 1                  # keep counting
            best = max(best, y - x)     # counting done, update best
    return best

It's straight forward if you ran over it with simple numbers. The Optimization step is just a short-circuit to make sure you start counting, when that specific number is the beginning of a sequence.

All Credits to Stefan Pochmann.


问:
Java: equals check on interface instead of class
I have a case, where I have a Java-Interface representing an entity. This interface is implemented in 2 different classes.
As a consequence, I need a method that tests
- if 2 classes have a common interface
- if all Getter-Values of these 2 classes are the same

if both is true, then they pass as equal, in the case I need.
(note, that I do not know which interface they implement, there are a few possible)

Is that somehow possible, or do I need to give the interface and then check if the two classes implement it?

Thanks for your help,
Michael

答:
```<code> if ( oneClass instanceof Interface1 && secondClass instanceof Interface2)
</code>```

There is a method called isAssignableFrom

Class.isAssignableFrom(interface);

ContentLicense: CC BY-SA 2.5

Body:
 if ( oneClass instanceof Interface1 && secondClass instanceof Interface2)

There is a method called isAssignableFrom

Class.isAssignableFrom(interface);


问:
Should I call the method abstract in Java?
I have a little project to implement different sorting algorithms.

I created the abstract class called Sorter and it's subclasses: BubbleSort, QuickSort, CoctailSort, SelectionSort.

Almost all of the subclasses have method called swap (to change place between two elements), besides MergeSort.

The question is - is it that bad not to define method swap abstract, because one subclass doesn't implement it or I should rework MergeSort code and add swap method to it?

答:
Try an interface that call Swap.
All sorts except MergeSort implement this interface.</p>


问:
Laravel 5.4 Show flash error and success messages in different ways
Method from my PostController

```<code>public function store(PostRequest $request)
    {
        if (Post::create($request->all())) {
            $request->session()->flash('status', 'Post was successfully added!');
        } else {
            $request->session()->flash('status', 'Error!');
        }
        return redirect('/');
    }
</code>```

index view

```<code><?php if(session()->has('status')){
        echo '<div style="text-align: center">';
        echo session()->get('status');
        echo '</div>';
    }?>
</code>```

How to show error and success messages in different ways?

答:
You can display flash messages in this way:

In your controller:

```<code>$request->session()->flash('success', 'Record successfully added!');
//OR
$request->session()->flash('warning', 'Record not added!');
</code>```

In your veiw:

```<code>@foreach (['danger', 'warning', 'success', 'info'] as $key)
 @if(Session::has($key))
     <p class="alert alert-{{ $key }}">{{ Session::get($key) }}</p>
 @endif
@endforeach
</code>```

Body:
Method from my PostController

public function store(PostRequest $request)
    {
        if (Post::create($request->all())) {
            $request->session()->flash('status', 'Post was successfully added!');
        } else {
            $request->session()->flash('status', 'Error!');
        }
        return redirect('/');
    }

index view

<?php if(session()->has('status')){
        echo '
';
        echo session()->get('status');
        echo '
';
    }?>

How to show error and success messages in different ways?

Body:
You can display flash messages in this way:

In your controller:

$request->session()->flash('success', 'Record successfully added!');
//OR
$request->session()->flash('warning', 'Record not added!');

In your veiw:

@foreach (['danger', 'warning', 'success', 'info'] as $key)
 @if(Session::has($key))
     <p class="alert alert-{{ $key }}">{{ Session::get($key) }}</p>
 @endif
@endforeach


问:
xls to csv using POI where excel having other language like japanese ie. UTF-8 characters
xls to csv using POI where excel having other language like japanese ie. UTF-8 characters

```<code> // For storing data into CSV files
        StringBuffer data = new StringBuffer();
        try
        {
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook object for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
        // Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);
        Cell cell;
        Row row;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext())
        {
                row = rowIterator.next();
                // For each row, iterate through each columns
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext())
                {
                        cell = cellIterator.next();

                        switch (cell.getCellType())
                        {
                        case Cell.CELL_TYPE_BOOLEAN:
                                data.append(cell.getBooleanCellValue() + ",");
                                break;

                        case Cell.CELL_TYPE_NUMERIC:
                                data.append(cell.getNumericCellValue() + ",");
                                break;

                        case Cell.CELL_TYPE_STRING:
                                data.append(cell.getStringCellValue() + ",");
                                break;

                        case Cell.CELL_TYPE_BLANK:
                                data.append("" + ",");
                                break;

                        default:
                                data.append(cell + ",");
                        }

                        data.append('\n');
                }
        }

        fos.write(data.toString().getBytes());
        fos.close();
        }
        catch (FileNotFoundException e)
        {
                e.printStackTrace();
        }
        catch (IOException e)
        {
                e.printStackTrace();
        }
        }

        public static void main(String[] args)
        {
                File inputFile = new File("C:\test.xls");
                File outputFile = new File("C:\output.csv");
                xls(inputFile, outputFile);
        }
</code>```

here the issue is i have cell values having other language charaters like テスト,再テスト1,498レッドアップルコート . when i use above code the csv file is getting create but having values as "??????"

i tried with below also

```<code>sValue = cell.getRichStringCellValue().getString();
</code>```

still unable to convert those word

please help me . thanks in advance

答:
OK, because of many misunderstandings about text encoding[see:note1] and because of the inability of Microsoft to provide Unicode support simply usable for CSV in Excel, let's have a concrete example:

Following Excel file:

and following code:

```<code>import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.nio.charset.StandardCharsets;

class ReadExcelWriteCSV {

 public static void main(String[] args) throws Exception {

  Workbook workbook = WorkbookFactory.create(new FileInputStream("inputFile.xls"));

  StringBuffer data = new StringBuffer();

  Sheet sheet = workbook.getSheetAt(0);
  for (Row row : sheet) {
   String delimiter = "";
   for (Cell cell : row) {
    data.append(delimiter);

    switch (cell.getCellTypeEnum()) {
     case STRING:
      data.append(cell.getStringCellValue());
      break;
     //case ...

     default:
      System.out.println("default cell"); //should never occur
    }

    delimiter = ",";
   }
   data.append("\r\n");
  }

  System.out.println(data);

  BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outputFile.csv"), StandardCharsets.UTF_8));

  bwr.write('\ufeff'); //write the UTF-8 BOM to make Excel able to detect UTF-8 encoding
  bwr.write(data.toString());
  bwr.flush();
  bwr.close();

  workbook.close();

 }
}
</code>```

produces a outputFile.csv having text encoding UTF-8. It also has a Byte order mark which makes it easy determinable to be UTF-8 encoded. This is necessary because else Excel cannot properly detect this encoding while simply opening the CSV file by double click.

If we are opening the resulting outputFile.csv using a text editor, it should be shown properly and the editor should be able correct detecting UTF-8 encoding.

If we are opening the resulting outputFile.csv using Text Import Wizard in Excel, then in the step 1 we also should be able correct setting UTF-8 encoding:

The Text Import Wizard looks a little bit different in Office 365:

Note: Images are from German Excel.

And because of the BOM even if simply opened in Excel by double click the file, it should be shown properly because of UTF-8 encoding detected properly.

[note1]: To only talk about one misunderstanding: You are writing about "UTF-8 characters". This is nonsense. There are Unicode characters which may be encoded using UTF-8. UTF-8 is an encoding and not a character set.

Body:
xls to csv using POI where excel having other language like japanese ie. UTF-8 characters

 // For storing data into CSV files
        StringBuffer data = new StringBuffer();
        try
        {
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook object for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
        // Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);
        Cell cell;
        Row row;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext())
        {
                row = rowIterator.next();
                // For each row, iterate through each columns
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext())
                {
                        cell = cellIterator.next();

                        switch (cell.getCellType())
                        {
                        case Cell.CELL_TYPE_BOOLEAN:
                                data.append(cell.getBooleanCellValue() + ",");
                                break;

                        case Cell.CELL_TYPE_NUMERIC:
                                data.append(cell.getNumericCellValue() + ",");
                                break;

                        case Cell.CELL_TYPE_STRING:
                                data.append(cell.getStringCellValue() + ",");
                                break;

                        case Cell.CELL_TYPE_BLANK:
                                data.append("" + ",");
                                break;

                        default:
                                data.append(cell + ",");
                        }

                        data.append('\n');
                }
        }

        fos.write(data.toString().getBytes());
        fos.close();
        }
        catch (FileNotFoundException e)
        {
                e.printStackTrace();
        }
        catch (IOException e)
        {
                e.printStackTrace();
        }
        }

        public static void main(String[] args)
        {
                File inputFile = new File("C:\test.xls");
                File outputFile = new File("C:\output.csv");
                xls(inputFile, outputFile);
        }

here the issue is i have cell values having other language charaters like テスト,再テスト1,498レッドアップルコート . when i use above code the csv file is getting create but having values as "??????"

i tried with below also

sValue = cell.getRichStringCellValue().getString();

still unable to convert those word

please help me . thanks in advance

Body:
OK, because of many misunderstandings about text encoding[see:note1] and because of the inability of Microsoft to provide Unicode support simply usable for CSV in Excel, let's have a concrete example:

Following Excel file:

and following code:

import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.nio.charset.StandardCharsets;

class ReadExcelWriteCSV {

 public static void main(String[] args) throws Exception {

  Workbook workbook = WorkbookFactory.create(new FileInputStream("inputFile.xls"));

  StringBuffer data = new StringBuffer();

  Sheet sheet = workbook.getSheetAt(0);
  for (Row row : sheet) {
   String delimiter = "";
   for (Cell cell : row) {
    data.append(delimiter);

    switch (cell.getCellTypeEnum()) {
     case STRING:
      data.append(cell.getStringCellValue());
      break;
     //case ...

     default:
      System.out.println("default cell"); //should never occur
    }

    delimiter = ",";
   }
   data.append("\r\n");
  }

  System.out.println(data);

  BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outputFile.csv"), StandardCharsets.UTF_8));

  bwr.write('\ufeff'); //write the UTF-8 BOM to make Excel able to detect UTF-8 encoding
  bwr.write(data.toString());
  bwr.flush();
  bwr.close();

  workbook.close();

 }
}

produces a outputFile.csv having text encoding UTF-8. It also has a Byte order mark which makes it easy determinable to be UTF-8 encoded. This is necessary because else Excel cannot properly detect this encoding while simply opening the CSV file by double click.

If we are opening the resulting outputFile.csv using a text editor, it should be shown properly and the editor should be able correct detecting UTF-8 encoding.

If we are opening the resulting outputFile.csv using Text Import Wizard in Excel, then in the step 1 we also should be able correct setting UTF-8 encoding:

The Text Import Wizard looks a little bit different in Office 365:

Note: Images are from German Excel.

And because of the BOM even if simply opened in Excel by double click the file, it should be shown properly because of UTF-8 encoding detected properly.

[note1]: To only talk about one misunderstanding: You are writing about "UTF-8 characters". This is nonsense. There are Unicode characters which may be encoded using UTF-8. UTF-8 is an encoding and not a character set.


问:
how to get Firebase ServerValue.Timestamp in Long using POJO Class
When I am loading TimeStamp value using getDateLastChangedLong method it gives an NullPointerException .How can i convert it into Long.

]4

答:
In order to set a TIMESTAMP in a Firebase database, you need to declare the field as a Map and not as an Object as i see you did and then use ServerValue.TIMESTAMP like this:

```<code>DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map<String, Object> map = new HashMap<>();
map.put("time", ServerValue.TIMESTAMP);
yourRef.child("yourNode").updateChildren(map);
</code>```

Remember, when you are setting the TIMESTAMP in the Firebase database, you are setting it as a Map and when you are retrieving it, you are retrieving it as a long.

Your POJO class should look like this:

```<code>public class ImageUpload {
    private Map<String, String> timeStamp;
    //other fields

    public Map<String, String> getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(Map<String, String> timeStamp) {
        this.timeStamp = timeStamp;
    }

    //other setters and getters.
}
</code>```

In order to get the timestamp using the public getter getTimeStamp(), you need to attach a listener on ImageUpload node and iterate the data from the dataSnapshot object.

If you want also to convert the data back, i suggest you using the following metod:

```<code>public static String getTimeDate(long timeStamp){
    try{
        DateFormat dateFormat = getDateTimeInstance();
        Date netDate = (new Date(timeStamp));
        return dateFormat.format(netDate);
    } catch(Exception e) {
        return "date";
    }
}
</code>```

Body:
In order to set a TIMESTAMP in a Firebase database, you need to declare the field as a Map and not as an Object as i see you did and then use ServerValue.TIMESTAMP like this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map<String, Object> map = new HashMap<>();
map.put("time", ServerValue.TIMESTAMP);
yourRef.child("yourNode").updateChildren(map);

Remember, when you are setting the TIMESTAMP in the Firebase database, you are setting it as a Map and when you are retrieving it, you are retrieving it as a long.

Your POJO class should look like this:

public class ImageUpload {
    private Map<String, String> timeStamp;
    //other fields

    public Map<String, String> getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(Map<String, String> timeStamp) {
        this.timeStamp = timeStamp;
    }

    //other setters and getters.
}

In order to get the timestamp using the public getter getTimeStamp(), you need to attach a listener on ImageUpload node and iterate the data from the dataSnapshot object.

If you want also to convert the data back, i suggest you using the following metod:

public static String getTimeDate(long timeStamp){
    try{
        DateFormat dateFormat = getDateTimeInstance();
        Date netDate = (new Date(timeStamp));
        return dateFormat.format(netDate);
    } catch(Exception e) {
        return "date";
    }
}


问:
How can I remove empty fields from my form in the querystring?
I have a simple form with four inputs. When I submit my form, I want to use the GET http method.

For the example :

```<code>aaa : foo
bbb : ____
ccc : bar
ddd : ____
</code>```

I want to have this query string :

```<code>/?aaa=foo&ccc=bar
</code>```

The problem is I have this query string :

```<code>/?aaa=foo&bbb=&ccc=bar&ddd=
</code>```

How can I remove empty fields from my form in the query string ?

Thanks.

答:
With jQuery:    </p>

```<code>$('form[method="get"]').submit(function(){
    $(this).find(':input').each(function() {
        var inp = $(this);
        if (!inp.val()) {
            inp.remove();
        }
    });
});
</code>```

<p>I use this to remove all empty parameters from all GET forms on my site. The :input pseudo selector covers all inputs, textareas, selects and buttons. </p>

Body:
I have a simple form with four inputs. When I submit my form, I want to use the GET http method.

For the example :

aaa : foo
bbb : ____
ccc : bar
ddd : ____

I want to have this query string :

/?aaa=foo&ccc=bar

The problem is I have this query string :

/?aaa=foo&bbb=&ccc=bar&ddd=

How can I remove empty fields from my form in the query string ?

Thanks.

Body:
With jQuery:

$('form[method="get"]').submit(function(){
    $(this).find(':input').each(function() {
        var inp = $(this);
        if (!inp.val()) {
            inp.remove();
        }
    });
});

I use this to remove all empty parameters from all GET forms on my site. The :input pseudo selector covers all inputs, textareas, selects and buttons.


问:
2D Canvas : specify `arc()` radius units
I have been trying to make a responsive website which includes a canvas.

While drawing a circular progress bar, am invoking the arc() function, but its radius argument, looks like it needs to be in pixels, but I would need it as percents, vw, vh, em or any other unit css proposes.

Of course, I could render it in pixels and stretch it using CSS, but it will either be upscaled and pixelated, downscaled and be a waste of resources, or otherwise distorted.

How should I do it?

答:
I'm working on something right now, where I had to solve the exact same problem (i.e. setting radius values for CanvasRenderingContext2D.arc() in percents or ems).

Here is JavaScript code of my solution:

```<code>function percentToPixelParentBased(percent, element, width_based=true) {
  return percentToPixelElementRelative(percent, element.parentElement, width_based);
}

function emToPixelParentBased(em_value, element) {
  return emToPixelElementRelative(em_value, element.parentElement);
}

function percentToPixelElementRelative(percent, element=false, width_based=true) {
  if (element) {
    if (width_based) {
        var dimension = element.style.width || element.offsetWidth;
    } else {
        var dimension = element.style.height || element.offsetHeight;
    }
  } else {
    if (width_based) {
        var dimension = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    } else {
        var dimension = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    }
  }

  var pixels_in_percent = dimension / 100;

  return pixels_in_percent * percent;
}

function emToPixelElementRelative(em_value, element=false) {
  var font_size = getFontSize(element);
  var ppi = getPPI();
  var px_in_pt = 72 / ppi; /* 1pt is 1/72 of an inch */
  var value_in_pt = em_value * font_size;

  return value_in_pt * px_in_pt;
}

function getFontSize(element=false) {

    if (element) {
    return parseFloat(getComputedStyle(element).fontSize);
  } else {
    /* getting font size from body */
    return parseFloat(getComputedStyle(document.body).fontSize);
  }
}

function getPPI() {
  var inch_div_html = "<div id='inch-div' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>";
  document.body.insertAdjacentHTML( 'afterbegin', inch_div_html);

  var device_pixel_ratio = window.devicePixelRatio || 1;
  var ppi_test_div = document.getElementById('inch-div');
  var ppi = ppi_test_div.offsetWidth * devicePixelRatio;

  document.body.removeChild(ppi_test_div);

  return ppi;
}
</code>```

To poke it a bit, there is demo on JSFiddle.

Now, a bit of explanation/remarks: emToPixelElementRelative and percentToPixelElementRelative each converts value passed to it as a first argument em=>px and %=>px respectively. Second argument to both functions (element) is an element, based on which dimensions, values in px will be calculated (NB: keep in mind that you pass radius, not diameter to the arc(), which for percents means that if you'll pass a 50(%) and will base calculations on canvas element — diameter of the circle will be 100% and will fill the whole canvas (in case of square canvas)), if the argument is not passed — values are calculated, based on a viewport's dimensions. Third argument (width_based) reflects if values calculated should be relative to width (if set to true, which is default) or height (if set to false).

percentToPixelParentBased and emToPixelParentBased are just wrappers for percentToPixelElementRelative and emToPixelElementRelative, which base conversion on the parent of the passed element.

getFontSize returns font size for the element passed, or for  element, if called without arguments.

getPPI is getting current PPI via, sort of, hack mentioned in this answer, it accepts a single argument (width_based) indicating whether to base it's calculations on width (if true - default) or height (if false).

Also note, that I have based em=>px calculations on the following assumptions:

font size is measured in pt (based on this article)

1em is equal to the size of current font in pt (based on pxtoem.com and this answer)

formula for converting pt=>px is 1pt = 72 / ppi (based on this answer)

Questions (and answers to them, of course)/resources, which helped me to put this solution together:

Getting current PPI:

how to remove HTML element by id

how to insert element into HTML

general recipe of how to get current PPI

Getting current font size:

how to get current font size

getting  HTML element (MDN wed docs)

Percent to pixel conversion:

of course, based on an answer above by Magix

Em to pixel conversion:

what is em (PXtoEM.com)

how em is calculated

how to convert pt to px

Misc:

answer with link to PXtoEM.com

difference between offsetWidth, clientWidth, scrollWidth and -Height

how to make nested lists in stackoverflow markup =)

ContentLicense: CC BY-SA 4.0

Body:
I'm working on something right now, where I had to solve the exact same problem (i.e. setting radius values for CanvasRenderingContext2D.arc() in percents or ems).

Here is JavaScript code of my solution:

function percentToPixelParentBased(percent, element, width_based=true) {
  return percentToPixelElementRelative(percent, element.parentElement, width_based);
}

function emToPixelParentBased(em_value, element) {
  return emToPixelElementRelative(em_value, element.parentElement);
}

function percentToPixelElementRelative(percent, element=false, width_based=true) {
  if (element) {
    if (width_based) {
        var dimension = element.style.width || element.offsetWidth;
    } else {
        var dimension = element.style.height || element.offsetHeight;
    }
  } else {
    if (width_based) {
        var dimension = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    } else {
        var dimension = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    }
  }

  var pixels_in_percent = dimension / 100;

  return pixels_in_percent * percent;
}

function emToPixelElementRelative(em_value, element=false) {
  var font_size = getFontSize(element);
  var ppi = getPPI();
  var px_in_pt = 72 / ppi; /* 1pt is 1/72 of an inch */
  var value_in_pt = em_value * font_size;

  return value_in_pt * px_in_pt;
}

function getFontSize(element=false) {

    if (element) {
    return parseFloat(getComputedStyle(element).fontSize);
  } else {
    /* getting font size from body */
    return parseFloat(getComputedStyle(document.body).fontSize);
  }
}

function getPPI() {
  var inch_div_html = "<div id='inch-div' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>";
  document.body.insertAdjacentHTML( 'afterbegin', inch_div_html);

  var device_pixel_ratio = window.devicePixelRatio || 1;
  var ppi_test_div = document.getElementById('inch-div');
  var ppi = ppi_test_div.offsetWidth * devicePixelRatio;

  document.body.removeChild(ppi_test_div);

  return ppi;
}

To poke it a bit, there is demo on JSFiddle.

Now, a bit of explanation/remarks: emToPixelElementRelative and percentToPixelElementRelative each converts value passed to it as a first argument em=>px and %=>px respectively. Second argument to both functions (element) is an element, based on which dimensions, values in px will be calculated (NB: keep in mind that you pass radius, not diameter to the arc(), which for percents means that if you'll pass a 50(%) and will base calculations on canvas element — diameter of the circle will be 100% and will fill the whole canvas (in case of square canvas)), if the argument is not passed — values are calculated, based on a viewport's dimensions. Third argument (width_based) reflects if values calculated should be relative to width (if set to true, which is default) or height (if set to false).

percentToPixelParentBased and emToPixelParentBased are just wrappers for percentToPixelElementRelative and emToPixelElementRelative, which base conversion on the parent of the passed element.

getFontSize returns font size for the element passed, or for <body> element, if called without arguments.

getPPI is getting current PPI via, sort of, hack mentioned in this answer, it accepts a single argument (width_based) indicating whether to base it's calculations on width (if true - default) or height (if false).

Also note, that I have based em=>px calculations on the following assumptions:

font size is measured in pt (based on this article)

1em is equal to the size of current font in pt (based on pxtoem.com and this answer)

formula for converting pt=>px is 1pt = 72 / ppi (based on this answer)

Questions (and answers to them, of course)/resources, which helped me to put this solution together:

Getting current PPI:

how to remove HTML element by id

how to insert element into HTML

general recipe of how to get current PPI

Getting current font size:

how to get current font size

getting  HTML element (MDN wed docs)

Percent to pixel conversion:

of course, based on an answer above by Magix

Em to pixel conversion:

what is em (PXtoEM.com)

how em is calculated

how to convert pt to px

Misc:

answer with link to PXtoEM.com

difference between offsetWidth, clientWidth, scrollWidth and -Height

how to make nested lists in stackoverflow markup =)


问:
How do i post text from textarea to mysql database
I have tried the code below but it just wrote '1' in the database instead of the text i wrote. i tried the same with input type="text" and it worked. Why does it not work with textarea?
Ofc i have the if(isset) function too..
PHP:

```<code>$connectionText = mysql_connect("localhost", "root");
if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$t = isset($_POST['tekst']);

$sqlScript = "INSERT INTO forms (tekst) VALUES ('$t')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);

?>
</code>```

HTML:

```<code><form action="post.php" method="POST">
<textarea name="tekst" autocapitalize="on" autocomplete="off"
autocorrect="off"
class="textBox" maxlength="140"></textarea>
<input type="submit" value="Offentligør" name="submit">
</form>
</code>```

答:
You only need to add an id value to the <form> and then add the form
attribute to the textarea with the form id value

```<code><form id="sample".....>
  <textarea name="aba" form="sample".....></textarea>
</form>
</code>```

Body:
I have tried the code below but it just wrote '1' in the database instead of the text i wrote. i tried the same with input type="text" and it worked. Why does it not work with textarea?
Ofc i have the if(isset) function too..
PHP:

$connectionText = mysql_connect("localhost", "root");
if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$t = isset($_POST['tekst']);

$sqlScript = "INSERT INTO forms (tekst) VALUES ('$t')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);

?>

HTML:

<form action="post.php" method="POST">
<textarea name="tekst" autocapitalize="on" autocomplete="off"
autocorrect="off"
class="textBox" maxlength="140"></textarea>
<input type="submit" value="Offentligør" name="submit">
</form>

Body:
You only need to add an id value to the <form> and then add the form
attribute to the textarea with the form id value

<form id="sample".....>
  <textarea name="aba" form="sample".....></textarea>
</form>


答:
What is the reason that it's not made to work?

A range based loop like

```<code> for(auto a : y) {
     // ...
 }
</code>```

is just syntactic sugar for the following expression

```<code> auto endit = std::end(y);
 for(auto it = std::begin(y); it != endit; ++it) {
     auto a = *it;
     // ...
 }
</code>```

Since std::begin() and std::end() cannot be used with a plain pointer, this can't be applied with a pointer allocated with new[].

As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work)

How delete[] keeps track of the memory block that was allocated with new[] (which isn't necessarily the same size as was specified by the user), is a completely different thing and the compiler most probably doesn't even know how exactly this is implemented.

Title: Why doesn't C++ support range based for loop for dynamic arrays?

Body:
Why doesn't C++ support range based for loop over dynamic arrays?  That is, something like this:

int* array = new int[len];
for[] (int i : array) {};

I just invented the for[] statement to rhyme with new[] and delete[].  As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work) so in theory, range based for loop could also be made to work.  What is the reason that it's not made to work?

Body:
What is the reason that it's not made to work?

A range based loop like

 for(auto a : y) {
     // ...
 }

is just syntactic sugar for the following expression

 auto endit = std::end(y);
 for(auto it = std::begin(y); it != endit; ++it) {
     auto a = *it;
     // ...
 }

Since std::begin() and std::end() cannot be used with a plain pointer, this can't be applied with a pointer allocated with new[].

As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work)

How delete[] keeps track of the memory block that was allocated with new[] (which isn't necessarily the same size as was specified by the user), is a completely different thing and the compiler most probably doesn't even know how exactly this is implemented.


问:
What is a SQL "pseudocolumn"?
I accidentally coded SELECT $FOO.. and got the error "Invalid pseudocolumn "$FOO".

I can't find any documentation for them.   Is it something I should know?

Edit: this is a MS SQL Server specific question.

答: Pseudocolumns are symbolic aliases for actual columns, that have special properties, for example, $IDENTITY is an alias for the column that has the IDENTITY assigned, $ROWGUID for the column with ROWGUIDCOL assigned. It's used for the internal plumbing scripts.</p>

OwnerDisplayName: Corey Trager

Title: What is a SQL "pseudocolumn"?

LastEditorDisplayName: Corey Trager


问:
Installing nodejs through Ansible playbook
I have created a Vagrant vm (Ubuntu) and installed Ansible. I can ping my localhost, that means to my vm. I wrote a playbook to install nodejs.

```<code>---
- hosts: node #it contains localhost
  gather_facts: no
  tasks:
  - name: install node.js
    shell: apt-get install nodejs
    sudo: yes
</code>```

When I run the playbook the status show success. To my understanding, it should install nodejs and also npm in my vm. However, if I type node -v, it shows it is not installed yet.

```<code>vagrant@vagrant-ubuntu-trusty-64:/vagrant_data$ ansible-playbook ping.yml

PLAY [node] *******************************************************************

TASK: [install node.js] *******************************************************
changed: [localhost]

PLAY RECAP ********************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0

vagrant@vagrant-ubuntu-trusty-64:/vagrant_data$ node -v
The program 'node' can be found in the following packages:
 * node
 * nodejs-legacy
Ask your administrator to install one of them
</code>```

What am I doing wrong here?

答:
What am I doing wrong here?

you are executing a command through shell module instead of using a native, idempotent Ansible module;

you are executing apt-get without arguments to prevent interactive prompts (-y);

you are using a long-outdated sudo parameter (which in current Ansible version is ignored) instead of become;

finally, you seem to have problems with reading on-screen messages and distinguishing package names: expecting node.js to install the node executable, while your system clearly states it can be found in node or nodejs-legacy packages.

Bonus: you are installing - through a separate process - a set of programs which set and utilise user environment variables, but continue to use the shell session without the environment set (this has no direct influence on node executable availability, but is a mistake anyway).

Body:
I have created a Vagrant vm (Ubuntu) and installed Ansible. I can ping my localhost, that means to my vm. I wrote a playbook to install nodejs.

---
- hosts: node #it contains localhost
  gather_facts: no
  tasks:
  - name: install node.js
    shell: apt-get install nodejs
    sudo: yes

When I run the playbook the status show success. To my understanding, it should install nodejs and also npm in my vm. However, if I type node -v, it shows it is not installed yet.

vagrant@vagrant-ubuntu-trusty-64:/vagrant_data$ ansible-playbook ping.yml

PLAY [node] *******************************************************************

TASK: [install node.js] *******************************************************
changed: [localhost]

PLAY RECAP ********************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0

vagrant@vagrant-ubuntu-trusty-64:/vagrant_data$ node -v
The program 'node' can be found in the following packages:
 * node
 * nodejs-legacy
Ask your administrator to install one of them

What am I doing wrong here?


问:
javascript set timeout is not working
I expected the below code snippet to print out the console log after pausing for every 1 sec.

But the code snippet executes instantaneously (prints out 100 times though) with the following output.

Can someone tell me what I am doing wrong ?

let i = 0;
for (; i < 100; i++) {
  setTimeout(console.log("test"), 1000);
}
console.log('Loop Done');
console.log('Value of i ==>' + i);```

答:
As I mentioned in my comment, you are calling console.log right away, and also setTimeout is asynchronous and thus it is nonblocking.

One of the correct ways to do it would be

```<code>for (let i = 0; i < 100; i++) {
    setTimeout(() => console.log("test"), 1000 * i);
}
</code>```

Title: javascript set timeout is not working

Body:
As I mentioned in my comment, you are calling console.log right away, and also setTimeout is asynchronous and thus it is nonblocking.

One of the correct ways to do it would be

for (let i = 0; i < 100; i++) {
    setTimeout(() => console.log("test"), 1000 * i);
}


问:
Media Foundation Capture - how do you detect the true native input format
I've got a few video converter boxes (Marshall VAC-11SU3, Marshall VAC-11HU3, Magewell USB Capture SDI, Blackmagic UltraStudio Express) and no cameras.
They all have an incoming video signal plugged into their respective SDI or HDMI ports.

The issue is that GetNativeMediaType always returns the same format as GetMediaTypeByIndex does for index 0 regardless of the actual video format that is coming into the SDI/HDMI port.

Every Media Foundation example I've seen so far has a UI to pick the "correct" native format. This menu is populated from GetMediaTypeCount and GetMediaTypeByIndex for the device.

My users will not know what to pick!

We've been using Blackmagic's DeckLink APIs and our users see the incoming video signal format in the UI.
We'd like to expand support for multiple device manufacturers but this one has me stumped.

答:
Media Foundation does not employ a concept of signal format detection you have with recent Blackmagic hardware (earlier Blackmagic products, by the way, did not offer detection).

A video source driver could indeed enumerate the media type it sees on the wire as first GetNativeMediaType output and/or offer dynamic format change during streaming session to such format. Media Foundation video sources are mostly assuming however webcamera-like devices and have a fixed type enumeration order.

I would not assume Blackmagic driver to be different because it mostly mimics a webcamera, so that with a WDM driver Blackmagic device inputs could be consumed using standard APIs. If one needs extended functionality, such as signal detection, Blackmagic suggests using their DeckLink SDK (which is good by the way).


问:
How to create a hidden navbar with bootstrap that shows after you scroll?
Can you tell me how I can create with bootstrap a navbar which is hidden and only shows after you start scrolling the page ?</p>

答:
This answer will work
Because of the scrollbar way to go down it will hide and if the scrollbar up it will show
not in one point

//The variable takes the value of the new position each time
var scrollp=0;
    (function ($) {
        $(document).ready(function(){
            $(function () {
                $(window).scroll(function () {
                // ask about the position of scroll

                    if ($(this).scrollTop() < scrollp) {
                        $('.navbar').fadeIn();
                        scrollp= $(this).scrollTop();
                    } else {
                        $('.navbar').fadeOut();
                        scrollp= $(this).scrollTop();
                    }
                });
            });

        });
    }(jQuery));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
This answer will work
Because of the scrollbar way to go down it will hide and if the scrollbar up it will show
not in one point

//The variable takes the value of the new position each time
var scrollp=0;
    (function ($) {
        $(document).ready(function(){
            $(function () {
                $(window).scroll(function () {
                // ask about the position of scroll

                    if ($(this).scrollTop() < scrollp) {
                        $('.navbar').fadeIn();
                        scrollp= $(this).scrollTop();
                    } else {
                        $('.navbar').fadeOut();
                        scrollp= $(this).scrollTop();
                    }
                });
            });

        });
    }(jQuery));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Zappa/AWS - Emails won't send and just timeout
Currently, I have tried both plain-old Django SMTP and a few different api-based Django libraries for my transactional email provider (Postmark).

When I run my development server, everything works perfectly. Emails send via the Postmark API with no problem.

When I deploy to AWS with Zappa, visit my website, and do a task that is supposed to send an email (Ex. Resetting a user's password) the page continually loads until it says Endpoint request timed out.

I have tried setting the timeout of my AWS Lambda function to a longer duration in case Django decides to throw an error.

Here is the error that was thrown. Just keep in mind this error only happens in production. I created a custom management command in able to retrieve this error.

```<code>HTTPSConnectionPool(host='api.postmarkapp.com', port=443): Max retries exceeded with url: /email/batch (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f6cfbd5dd30>: Failed to establish a new connection: [Errno 110] Connection timed out',)): ConnectionError
Traceback (most recent call last):
  File "/var/task/handler.py", line 509, in lambda_handler
    return LambdaHandler.lambda_handler(event, context)
  File "/var/task/handler.py", line 240, in lambda_handler
    return handler.handler(event, context)
  File "/var/task/handler.py", line 376, in handler
    management.call_command(*event['manage'].split(' '))
  File "/var/task/django/core/management/__init__.py", line 131, in call_command
    return command.execute(*args, **defaults)
  File "/var/task/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/var/task/users/management/commands/sendemail.py", line 13, in handle
    fail_silently=False,
  File "/var/task/django/core/mail/__init__.py", line 62, in send_mail
    return mail.send()
  File "/var/task/django/core/mail/message.py", line 348, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/var/task/postmarker/django/backend.py", line 66, in send_messages
    responses = self.client.emails.send_batch(*prepared_messages, TrackOpens=self.get_option('TRACK_OPENS'))
  File "/var/task/postmarker/models/emails.py", line 332, in send_batch
    return self.EmailBatch(*emails).send(**extra)
  File "/var/task/postmarker/models/emails.py", line 247, in send
    responses = [self._manager._send_batch(*batch) for batch in chunks(emails, self.MAX_SIZE)]
  File "/var/task/postmarker/models/emails.py", line 247, in <listcomp>
    responses = [self._manager._send_batch(*batch) for batch in chunks(emails, self.MAX_SIZE)]
  File "/var/task/postmarker/models/emails.py", line 276, in _send_batch
    return self.call('POST', '/email/batch', data=emails)
  File "/var/task/postmarker/models/base.py", line 72, in call
    return self.client.call(*args, **kwargs)
  File "/var/task/postmarker/core.py", line 106, in call
    **kwargs
  File "/var/task/postmarker/core.py", line 129, in _call
    method, url, json=data, params=kwargs, headers=default_headers, timeout=self.timeout
  File "/var/task/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/var/task/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/var/task/requests/adapters.py", line 508, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.postmarkapp.com', port=443): Max retries exceeded with url: /email/batch (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f6cfbd5dd30>: Failed to establish a new connection: [Errno 110] Connection timed out',))
</code>```

I have allowed all incoming and outgoing traffic to my AWS security group in an attempt to fix this. Still to no avail.

Any help would be greatly, greatly appreciated. Cheers.

答:
The explanation is simple: A Lambda instance running in a VPC cannot access the internet:

When you add VPC configuration to a Lambda function, it can only access resources in that VPC. If a Lambda function needs to access both VPC resources and the public Internet, the VPC needs to have a Network Address Translation (NAT) instance inside the VPC.

The solution is also simple, if annoying: run a NAT Instance or NAT Gateway in the VPC. (An alternate solution is to take your Lambda out of the VPC, but that is a much bigger change.)

I am running Django / Zappa in Lambda with a NAT instance for connecting to Amazon Simple Email Service and it works fine.

Body:
Currently, I have tried both plain-old Django SMTP and a few different api-based Django libraries for my transactional email provider (Postmark).

When I run my development server, everything works perfectly. Emails send via the Postmark API with no problem.

When I deploy to AWS with Zappa, visit my website, and do a task that is supposed to send an email (Ex. Resetting a user's password) the page continually loads until it says Endpoint request timed out.

I have tried setting the timeout of my AWS Lambda function to a longer duration in case Django decides to throw an error.

Here is the error that was thrown. Just keep in mind this error only happens in production. I created a custom management command in able to retrieve this error.

HTTPSConnectionPool(host='api.postmarkapp.com', port=443): Max retries exceeded with url: /email/batch (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f6cfbd5dd30>: Failed to establish a new connection: [Errno 110] Connection timed out',)): ConnectionError
Traceback (most recent call last):
  File "/var/task/handler.py", line 509, in lambda_handler
    return LambdaHandler.lambda_handler(event, context)
  File "/var/task/handler.py", line 240, in lambda_handler
    return handler.handler(event, context)
  File "/var/task/handler.py", line 376, in handler
    management.call_command(*event['manage'].split(' '))
  File "/var/task/django/core/management/__init__.py", line 131, in call_command
    return command.execute(*args, **defaults)
  File "/var/task/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/var/task/users/management/commands/sendemail.py", line 13, in handle
    fail_silently=False,
  File "/var/task/django/core/mail/__init__.py", line 62, in send_mail
    return mail.send()
  File "/var/task/django/core/mail/message.py", line 348, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/var/task/postmarker/django/backend.py", line 66, in send_messages
    responses = self.client.emails.send_batch(*prepared_messages, TrackOpens=self.get_option('TRACK_OPENS'))
  File "/var/task/postmarker/models/emails.py", line 332, in send_batch
    return self.EmailBatch(*emails).send(**extra)
  File "/var/task/postmarker/models/emails.py", line 247, in send
    responses = [self._manager._send_batch(*batch) for batch in chunks(emails, self.MAX_SIZE)]
  File "/var/task/postmarker/models/emails.py", line 247, in <listcomp>
    responses = [self._manager._send_batch(*batch) for batch in chunks(emails, self.MAX_SIZE)]
  File "/var/task/postmarker/models/emails.py", line 276, in _send_batch
    return self.call('POST', '/email/batch', data=emails)
  File "/var/task/postmarker/models/base.py", line 72, in call
    return self.client.call(*args, **kwargs)
  File "/var/task/postmarker/core.py", line 106, in call
    **kwargs
  File "/var/task/postmarker/core.py", line 129, in _call
    method, url, json=data, params=kwargs, headers=default_headers, timeout=self.timeout
  File "/var/task/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/var/task/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/var/task/requests/adapters.py", line 508, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.postmarkapp.com', port=443): Max retries exceeded with url: /email/batch (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f6cfbd5dd30>: Failed to establish a new connection: [Errno 110] Connection timed out',))

I have allowed all incoming and outgoing traffic to my AWS security group in an attempt to fix this. Still to no avail.

Any help would be greatly, greatly appreciated. Cheers.


问:
How to share a photo correctly on php and URL solution - Webproject
I have a question about a web project I'm on it.

The situation:
There is a log-in system -> after log-in there is a lot of photos.

1) I enter with my credentials -> login.php to index.php

2) I see my profile and then I want to share it with twitter(for example..).

3) The thing I share it is the URL which is "page.com/index.php#&album=1&id=1"

The problem is the URL, if I share will be useless because if the other user have an account, will show his photo and not mine.

I try to find a solution, I do not know how the other sites do to share photos without this problem.

Hope u can help me and sorry if my english not the best.

答:
You need make one more route for sharing pictures.

```<code>/share.php?user=1&album=1&id=1
</code>```

In this file you get all parameters (user, album, id) to show correct photo.

And you need to add this route to share in index.php.

Facebook example: https://www.facebook.com/sharer/sharer.php?u=http%3A//site.com/share.php?user=1%26album=1%26id=1

Body:
You need make one more route for sharing pictures.

/share.php?user=1&album=1&id=1

In this file you get all parameters (user, album, id) to show correct photo.

And you need to add this route to share in index.php.

Facebook example: https://www.facebook.com/sharer/sharer.php?u=http%3A//site.com/share.php?user=1%26album=1%26id=1


答:
You are actually setting a timeout for the return value of console.log, i.e., undefined, instead of an actual function.

setTimeout requires a function as the first argument in order for it to work. You have passed undefined. To fix this, there are 2 ways.

Pass a function that calls console.log

```<code>setTimeout(function () {
  console.log("test");
}, 100);
</code>```

In ES6, that would be much shorter:

```<code>setTimeout(() => console.log("test"), 100);
</code>```

Bind arguments to console.log

```<code>setTimeout(console.log.bind(undefined, "test"), 100);
</code>```

bind()-ing arguments to a function is like telling the function to to execute with the arguments we are giving it. The function is not executed immediately when you call bind, but the arguments are stored.

Also, as a side-note, the first argument we passed for bind, i.e., undefined, is the this value for the function. We do not care about the this value of console.log, and we want to pass only "test", we write undefined as the this value.

Title: javascript set timeout is not working

Body:
I expected the below code snippet to print out the console log after pausing for every 1 sec.

But the code snippet executes instantaneously (prints out 100 times though) with the following output.

Can someone tell me what I am doing wrong ?

let i = 0;
for (; i < 100; i++) {
  setTimeout(console.log("test"), 1000);
}
console.log('Loop Done');
console.log('Value of i ==>' + i);

Body:
You are actually setting a timeout for the return value of console.log, i.e., undefined, instead of an actual function.

setTimeout requires a function as the first argument in order for it to work. You have passed undefined. To fix this, there are 2 ways.

Pass a function that calls console.log

setTimeout(function () {
  console.log("test");
}, 100);

In ES6, that would be much shorter:

setTimeout(() => console.log("test"), 100);

Bind arguments to console.log

setTimeout(console.log.bind(undefined, "test"), 100);

bind()-ing arguments to a function is like telling the function to to execute with the arguments we are giving it. The function is not executed immediately when you call bind, but the arguments are stored.

Also, as a side-note, the first argument we passed for bind, i.e., undefined, is the this value for the function. We do not care about the this value of console.log, and we want to pass only "test", we write undefined as the this value.


问:
Device/Memory Specific issue in reading a file Android
I have a very weird issue with my application.
  I have a file in my Assets folder of size around 2MB. On some of the devices it reads the file and parses it and creates the DB and everything works fine.
  If i run the same app on the emulator then the file doesn't get read and nothing comes on my UI.
  So i thought the issue could be with some space allocation on emulator.
But the same issue comes up even with some Android devices and on some devices it works fine.
  i got to make it work for all the devices. So how can i solve this issue?? Is there any solution for this issue? people say they have around 1.5GB free space in their mobiles....still they are not able to read the file. Is available space only the problem or is there any other issue??
   Any help is greatly appreciated.

Thanks in advance

答:
You cannot have files larger than 1 MB in the assets. Period.

See this related question


问:
Lazy vs init for singleton design in swift
I'm using Socket.io library to add the real-time feature to my app, and I'm using Singleton design

```<code>import SocketIO

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    var socket: SocketIOClient!

    func establishConnection() {
       socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
       socket.connect()

    }

    func closeConnection() {
        socket.disconnect()
    }

}
</code>```

So technically whenever my app loads up socket cannot be nil or else it will crash. I found two solutions that could solve this problem

Lazy

```<code>lazy var socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
</code>```

By using this method socket will never be nil, because it will always be initialized. But the problem with this method is that if creating SocketIOClient is not cheap then it would be a great method to use.

Init()

```<code>class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    let socket: SocketIOClient!

init() {
        super.init()
        socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
  }
}
</code>```

By using this method, I'm a little bit confused because I don't initially create the SocketIOManager object like

```<code>let socket = SocketIOManager()
</code>```

because if I'm not mistaken the socket will get initialized if only object is created, and I'm not sure about using init() in the Singleton design

Which method is suitable for my use case?

答:
In Swift globals, including static members of classes are lazy by default so this is correct:

```<code>class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    let socket: SocketIOClient!

    private override init() {
        super.init()
        socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
  }
}
</code>```

Note the private on the init to prevent anyone else from trying to instantiate this class, since its a singleton.

Body:
I'm using Socket.io library to add the real-time feature to my app, and I'm using Singleton design

import SocketIO

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    var socket: SocketIOClient!

    func establishConnection() {
       socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
       socket.connect()

    }

    func closeConnection() {
        socket.disconnect()
    }

}

So technically whenever my app loads up socket cannot be nil or else it will crash. I found two solutions that could solve this problem

Lazy

lazy var socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])

By using this method socket will never be nil, because it will always be initialized. But the problem with this method is that if creating SocketIOClient is not cheap then it would be a great method to use.

Init()

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    let socket: SocketIOClient!

init() {
        super.init()
        socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
  }
}

By using this method, I'm a little bit confused because I don't initially create the SocketIOManager object like

let socket = SocketIOManager()

because if I'm not mistaken the socket will get initialized if only object is created, and I'm not sure about using init() in the Singleton design

Which method is suitable for my use case?

Body:
In Swift globals, including static members of classes are lazy by default so this is correct:

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    let socket: SocketIOClient!

    private override init() {
        super.init()
        socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
  }
}

Note the private on the init to prevent anyone else from trying to instantiate this class, since its a singleton.


问:
script src not loading javascript for angular
HTML

```<code>    <!DOCTYPE html>
<html ng-app="dropApp">
<head>
    <meta charset="utf-8" />
    <title>DropBox</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
</head>
<body ng-controller="mainctrl">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>

    <div class="jumbotron">
        <div class="container">
            <div class="col-sm-8 col-sm-offset-2">
                <a id="btn-login" ng-click="login()" ng-model="logbut" ng-show="logbut" class="btn btn-success">Login  </a>
                <div ng-include="template"></div>
            </div>
        </div>
    </div>
    <div class="credits text-center">
        <p>
            Amey Totawar
        </p>
    </div>
    <script src="angularsrc.js"></script>

</body>
</html>
</code>```

Javascript File

```<code>var dropApp = angular.module("dropApp",[]);
var path = require('path');

dropApp.controller("mainctrl", function($scope) {
    $scope.logbut = true;
    $scope.login = function() {
        $scope.logbut = false;
        $scope.template = {
            name: 'login.html',
            url: path.join(__dirname,'views','login.html')
        };
    }
});
</code>```

Getting Error:
GET http://localhost:8600/angularsrc.js net::ERR_ABORTED and hence angular module not found.
I tried including min.jquery earlier.
I also tried changing angularsrc.js location, but nothing is working.
Please help!!

答:
Your references should be inside head like</p>

```<code><html ng-app="dropApp">
<head>
    <meta charset="utf-8" />
    <title>DropBox</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
    <script src="angularsrc.js"></script>
</head>
<body ng-controller="mainctrl">
    {{your code or logic goes here}}
</body>
</html>
</code>```

Body:
HTML

    <!DOCTYPE html>

    <meta charset="utf-8" />
    <title>DropBox</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />

                Login

            Amey Totawar

Javascript File

var dropApp = angular.module("dropApp",[]);
var path = require('path');

dropApp.controller("mainctrl", function($scope) {
    $scope.logbut = true;
    $scope.login = function() {
        $scope.logbut = false;
        $scope.template = {
            name: 'login.html',
            url: path.join(__dirname,'views','login.html')
        };
    }
});

Getting Error:
GET http://localhost:8600/angularsrc.js net::ERR_ABORTED and hence angular module not found.
I tried including min.jquery earlier.
I also tried changing angularsrc.js location, but nothing is working.
Please help!!

Body:
Your references should be inside head like

<html ng-app="dropApp">
<head>
    <meta charset="utf-8" />
    <title>DropBox</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
    <script src="angularsrc.js"></script>
</head>
<body ng-controller="mainctrl">
    {{your code or logic goes here}}
</body>
</html>


问:
Faster calculation of squared norm in Cython
I would like to calculate squared norms, which can be written as

W is a matrix and has V rows. u is a vector. I have two numpy objects W and u.

```<code>import numpy as np
import numpy.random as npr
V = 10
W = npr.normal(size=(V, 3))
u = npr.normal(size=(1,3))
</code>```

If I calculate row by row, I can do like this:

```<code>res = np.zeros(V)
for v in range(V):
    res[v] = (W[v] - u).dot((W[v] - u).transpose())
</code>```

But it could be slow once V gets large (say 5000) and  I need to recalculate it again and again.
So I tried matrix multiplication, but it did not work out because it is not a row by row multiplication.

```<code>((W - u).transpose()).dot(W - u)
</code>```

How can I calculate the squared norm fast in Numpy?

I am planning to use Cython, so could row by row multiplication in loop be faster than Numpy? I learned that Cython has parallelization, but it seems Cython can not parallelize for loop if I use Numpy object inside (Added on 20/Nov: probably I can not use Python object inside the prange but I can use Numpy object).

答:
Approach #1

You can leverage the fast BLAS based np.dot right with NumPy without any looping, like so -

```<code>res = (W**2).sum(1) + (u**2).sum(1) -2*W.dot(u.ravel())
</code>```

Bringing in np.einsum to get the row-wise summations of W and np.inner for those of u -

```<code>res = np.einsum('ij,ij->i',W,W) + np.inner(u,u).ravel() -2*W.dot(u.ravel())
</code>```

Explanation on the method

With (W[v] - u).dot((W[v] - u) at each iteration, we are doing inner dot product. Since, we are doing this for all rows of W, that translates to ((W - u)**2).sum(1) upon leveraging broadcasting.

Now,

```<code>(Xik-Yjk)**2 = Xik**2 + Yjk**2 - 2*Xik*Yjk
</code>```

Hence,

```<code>sum_k((Xik-Yjk)**2) = sum_k(Xik**2) + sum_k(Yjk**2) - 2*sum_k(Xik*Yjk)
</code>```

The last term on RHS is basically matrix-multiplication, which we are leveraging with np.dot.

Approach #2

Alternatively, using more of np.einsum, it would be like so -

```<code>d = W -u
res = np.einsum('ij,ij->i',d,d)
</code>```

Body:
I would like to calculate squared norms, which can be written as

W is a matrix and has V rows. u is a vector. I have two numpy objects W and u.

import numpy as np
import numpy.random as npr
V = 10
W = npr.normal(size=(V, 3))
u = npr.normal(size=(1,3))

If I calculate row by row, I can do like this:

res = np.zeros(V)
for v in range(V):
    res[v] = (W[v] - u).dot((W[v] - u).transpose())

But it could be slow once V gets large (say 5000) and  I need to recalculate it again and again.
So I tried matrix multiplication, but it did not work out because it is not a row by row multiplication.

((W - u).transpose()).dot(W - u)

How can I calculate the squared norm fast in Numpy?

I am planning to use Cython, so could row by row multiplication in loop be faster than Numpy? I learned that Cython has parallelization, but it seems Cython can not parallelize for loop if I use Numpy object inside (Added on 20/Nov: probably I can not use Python object inside the prange but I can use Numpy object).

Body:
Approach #1

You can leverage the fast BLAS based np.dot right with NumPy without any looping, like so -

res = (W**2).sum(1) + (u**2).sum(1) -2*W.dot(u.ravel())

Bringing in np.einsum to get the row-wise summations of W and np.inner for those of u -

res = np.einsum('ij,ij->i',W,W) + np.inner(u,u).ravel() -2*W.dot(u.ravel())

Explanation on the method

With (W[v] - u).dot((W[v] - u) at each iteration, we are doing inner dot product. Since, we are doing this for all rows of W, that translates to ((W - u)**2).sum(1) upon leveraging broadcasting.

Now,

(Xik-Yjk)**2 = Xik**2 + Yjk**2 - 2*Xik*Yjk

Hence,

sum_k((Xik-Yjk)**2) = sum_k(Xik**2) + sum_k(Yjk**2) - 2*sum_k(Xik*Yjk)

The last term on RHS is basically matrix-multiplication, which we are leveraging with np.dot.

Approach #2

Alternatively, using more of np.einsum, it would be like so -

d = W -u
res = np.einsum('ij,ij->i',d,d)