问:
PHP OOP need advice
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

```<code><?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>
</code>```

would this lines:

```<code>$found = $this->find_member($id);
$status_check = $this->status_check($id);
</code>```

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

```<code><?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>
</code>```

答:
Well, I think OOP is mostly about creating meaningful actions that are easy to reuse and, especially, make it easy to find out what's going on when you revisit your code some months later (or when someone else reads your code, which is more or less the same). Also, when you found your member, you can then perform logic on that, instead of on the id. So, in this case it might be better to create your methods like this, for example:

```<code>protected $max_sms_messages = 10;

protected function can_still_send_sms($member){
    return !empty($member) && $member->counter < $this->max_sms_messages;
}

public function send_sms($id, $message){
    $found = $this->find_member($id);
    if ($this->can_still_send_sms($found)) { // or even if($found->can_still_send_sms()), if you want to implement it that way

        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}
</code>```

Also, for the record, you can't call non-static methods from static methods.

Title: PHP OOP need advice

Body:
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

<?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>

would this lines:

$found = $this->find_member($id);
$status_check = $this->status_check($id);

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

<?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>

Body:
Well, I think OOP is mostly about creating meaningful actions that are easy to reuse and, especially, make it easy to find out what's going on when you revisit your code some months later (or when someone else reads your code, which is more or less the same). Also, when you found your member, you can then perform logic on that, instead of on the id. So, in this case it might be better to create your methods like this, for example:

protected $max_sms_messages = 10;

protected function can_still_send_sms($member){
    return !empty($member) && $member->counter < $this->max_sms_messages;
}

public function send_sms($id, $message){
    $found = $this->find_member($id);
    if ($this->can_still_send_sms($found)) { // or even if($found->can_still_send_sms()), if you want to implement it that way

        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

Also, for the record, you can't call non-static methods from static methods.


来源: stackexchange

问:
Firebase. how to save data as transactions without overwriting the existing data, but updating it? Swift3
Is it possible to save data as transactions as per firebase docs, but without overwriting the whole node? I would like to know if there is any equivalent for updateChildValues when calling runTransactionBlock. The only option I see in the docs with runTransactionBlock is to overwrite the existing data at /path/somepath.

Please provide alternative or I'd appreciate your advice if I am on a wrong path here and I should not key:value to existing data.

答:
When you run a transaction, your callback/handler is invoked with the existing data in the location. So all you do is update the properties that you want modified and return that combination from your callback/handler.

There is no way to just tell the client what properties to update. But since your handler is invoked with the existing value from the location it's updating, that should not lead to inefficiencies in the code.

If you're having trouble making this work, please post a single, minimal-but-complete code snippet that reproduces the problem.

ContentLicense: CC BY-SA 3.0


问:
When should I use git pull --rebase?
I know of some people who use git pull --rebase by default and others who insist never to use it.  I believe I understand the difference between merging and rebasing, but I'm trying to put this in the context of git pull.  Is it just about not wanting to see lots of merge commit messages, or are there other issues?

答:
Just remember:

pull = fetch + merge

pull --rebase = fetch + rebase

So, choose the way what you want to handle your branch.

You'd better know the difference between merge and rebase :)

Title: When should I use git pull --rebase?


问:
preventing hardcoded url to delete in django
I have a link and button inside it that deletes a record associated with the button

```<code><a href="{% url 'parts:stock_delete' stock.id  %}">
  <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button>
</a>
</code>```

but I want the record to be deleted only when the button is pressed but not when URL is typed in the address bar like:

http://127.0.0.1:8000/parts/stock_delete/16/

what can be done for this?

答:
You can use post method. And when the button is pressed, you can pass some flag, say flag1.

```<code><form action="{% url 'parts:stock_delete' stock.id  %}" method="post" >
    <input type="hidden" name="flag1" value="True" >{% csrf_token %}
    <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button></a>
</form>
</code>```

and in the backend you can write like this in your function in views.py.

```<code># delete view
....
if request.method == 'POST':
    if 'flag1' in request.POST:
        ... # deleted your object here
</code>```

Body:
I have a link and button inside it that deletes a record associated with the button

  <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button>

but I want the record to be deleted only when the button is pressed but not when URL is typed in the address bar like:

http://127.0.0.1:8000/parts/stock_delete/16/

what can be done for this?

Body:
You can use post method. And when the button is pressed, you can pass some flag, say flag1.

<form action="{% url 'parts:stock_delete' stock.id  %}" method="post" >
    <input type="hidden" name="flag1" value="True" >{% csrf_token %}
    <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button></a>
</form>

and in the backend you can write like this in your function in views.py.

# delete view
....
if request.method == 'POST':
    if 'flag1' in request.POST:
        ... # deleted your object here


问:
how to print proper error message
I have following small shell script.

```<code>value='testdir/imp'
`mkdir -m 755 $value`
echo $
</code>```

the out put is

```<code>$ ./dir.sh
mkdir: Failed to make directory "testdir/imp"; Permission denied
2
</code>```

Here i want to print this error message to a text file
How i can do this

答:
mkdir prints error messages to stderr. You can also redirect the output from stderr to a file. Knowing these 2 things you can do this:

```<code>mkdir /etc/test 2>somefile
</code>```

And then the output from mkdir will be in a somefile.

The syntax 2>somefile redirects stderr to a file called somefile.

ContentLicense: CC BY-SA 2.5

Title: how to print proper error message

Body:
I have following small shell script.

value='testdir/imp'
`mkdir -m 755 $value`
echo $

the out put is

$ ./dir.sh
mkdir: Failed to make directory "testdir/imp"; Permission denied
2

Here i want to print this error message to a text file
How i can do this

Body:
mkdir prints error messages to stderr. You can also redirect the output from stderr to a file. Knowing these 2 things you can do this:

mkdir /etc/test 2>somefile

And then the output from mkdir will be in a somefile.

The syntax 2>somefile redirects stderr to a file called somefile.


问:
How does this C++ unordered_map have four values? I thought it was a key value pair
I came across the following code: unordered_map<id, id, hashid, eqid> map

All the unordered maps I've seen only have two "params", the key and value types, what do the other two do?

答:
The STL container classes are parameterized by more than just the types they store. The first two types in the template instantiation are the key & value types. The second two are 'functor' types that control first, how the hash of the key is generated, and second how to compare two keys for equality. The latter is necessary because hash functions can and will have collisions that map several keys to the same hash value. The last parameter is the allocator to use for obtaining storage for the nodes in the hash as well as the underlying lookup table.

99% of the time, you'll only need to concern yourself with the (key,value) pair of template parameters - the other parameters are very useful for tweaking performance characteristics after the fact, but use the defaults for them unless you have compelling reasons to change them.

Lastly, consider using std::set/std::map instead of the unordered variety. Those containers are based on red-black trees and offer extremely good amortized performance, with several additional benefits that you do not get with a hash table (sorted keys and operations like lower_bound()), all without having to worry about mananging the hash table load factor, iterator stability, and a few other nasties.


问:
Which Version of Xcode is suitable for mac os yosemite
I am using mac os yosemite [hackentos] 10.10. I want to install Xcode on my Mac, but the current version of Xcode 8.3.3 needs macOS Sierra, and I am not able to upgrade to Sierra.

Which version of Xcode is suitable for Mac OS X Yosemite?

答:
Which version of Xcode is suitable for MacOS Yosemite ...

Use Xcode 6 for MacOS Yosemite (10.10).

Xcode 6 is kind of disjoint. Its pretty typical considering Xcode supports OS X and iOS across OS releases. Xcode 6.0 - 6.2 was released for MacOS Mavericks (10.9). Xcode 6.3 - 6.4 was released for MacOS Yosemite (10.10).

It looks like Xcode 7.0 - 7.2.1 is applicable as well. Also see the Xcode 5.0 - 6.x and Xcode 7.0 - 8.x support on Wikipedia.

If you need to use the command line to determine versions of what you have, then see Determine xcode command line tools version on Apple Stack Exchange.


问:
How do I set up Rails for French language?
I have to develop a Ruby on Rails app for my company and don't know how to configure it for a French site.

I don't need multiple language support, I just want to have error messages, pluralization and date format for French.

I tried to set:

```<code>config.i18n.default_locale = :fr
</code>```

in my application.rb file but it doesn't seem to have any effect.

Are these features already implemented in RoR 3? Or I will have to translate these things myself?

答:
Add to rails-i18n your Gemfile:

```<code>gem 'rails-i18n'
</code>```

Body:
I have to develop a Ruby on Rails app for my company and don't know how to configure it for a French site.

I don't need multiple language support, I just want to have error messages, pluralization and date format for French.

I tried to set:

config.i18n.default_locale = :fr

in my application.rb file but it doesn't seem to have any effect.

Are these features already implemented in RoR 3? Or I will have to translate these things myself?

Body:
Add to rails-i18n your Gemfile:

gem 'rails-i18n'


问:
Amend script to select active document rather than running for all open docs as it does currently
```<code>Sub Macro1()
'
' Macro1 Macro
'
'Sub InsertImagesAllDocuments()

    Dim n, c As Integer
    n = Application.Documents.Count
    c = 1

    Dim r As Range

    Windows(c).Activate

    Do
        Dim imageFullPath As String
        Dim FindText As String
        imageFullPath = "C:\Logo.png"
        FindText = "?????"
        With Selection
            .HomeKey Unit:=wdStory

            With .Find
                .ClearFormatting
                .Text = FindText
                ' Loop until Word can no longer
                ' find the search string, inserting the specified image at each location
                Do While .Execute
                    Selection.MoveRight
                    Selection.InlineShapes.AddPicture FileName:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True
                Loop

            End With
        End With

        c = c + 1

        On Error Resume Next
        Windows(c).Activate

    Loop Until c > n

    With Selection.Find
        .ClearFormatting
        .Text = "?????"
        .Replacement.ClearFormatting
        .Replacement.Text = ""
        .Execute Replace:=wdReplaceAll, Forward:=True, _
        Wrap:=wdFindContinue
    End With

End Sub
</code>```

答:
use with ActiveDocument</p>

```<code>With ActiveDocument
    ' do stuff
End With
</code>```

Body:
use with ActiveDocument

With ActiveDocument
    ' do stuff
End With


问:
Best WPF open source projects
I have programmed with WPF for more than a year. When I started there weren't so many examples and guidelines to follow, now the situation is much more better.

I would like to ask you some help in listing the best WPF (open) source code examples or projects that you suggest to study in order to learn more about project structure, best practices, etc.

Thank you,
Marco

答: Crack.NET and Prism come to mind.</p>

Title: Best WPF open source projects

Body: Crack.NET and Prism come to mind.

OwnerDisplayName: Kent Boogaart


问:
Task scheduling for multiple tasks in java?
i have build a java clock with using timer,which works fine for a single task to alarm on next given/setted time, but i am having problem in scheduling multiple tasks(alarms for diff. times) with this timer, as two times can clash each other(same times for two different works) how to synchronize between such conditions, please help....

Thanks and Regards

Alok Sharma

答:
I'm not sure what you're trying to do, but if you use quartz scheduler, you can resolve just about any scheduling/synchronisation task:

http://www.quartz-scheduler.org/


问:
Add a record to a text box using the same button that deletes a record from a different text box
I have a button in an access Form that does this command in VBA

```<code>Private Sub Command12_Click()
On Error GoTo Command12_Click_Err

If Not IsNull (txtSearchbar) Then
  DoCmd.ApplyFilter "", "[Progress] Like "*" & [Forms]![APIReleasing]![txtSearchbar] & ""*""",""
  DoCmd.RunCommand acCmdDeleteRecord
End Sub
</code>```

The thing is that I also want to add the same info entered in txtSearchbar to be added to another textbox.  So how do I do it?

答:
I would use this filter criteria:

```<code>"[Progress] Like '*" & Me.txtSearchbar & "*'"
</code>```

Add text to another textbox:

```<code>Me.txtAnotherTextBox.Value = Me.txtSearchbar.Value
</code>```

.Value can be omitted, but in some cases it may lead to incorrect results.

Body:
I have a button in an access Form that does this command in VBA

Private Sub Command12_Click()
On Error GoTo Command12_Click_Err

If Not IsNull (txtSearchbar) Then
  DoCmd.ApplyFilter "", "[Progress] Like "*" & [Forms]![APIReleasing]![txtSearchbar] & ""*""",""
  DoCmd.RunCommand acCmdDeleteRecord
End Sub

The thing is that I also want to add the same info entered in txtSearchbar to be added to another textbox.  So how do I do it?

Body:
I would use this filter criteria:

"[Progress] Like '*" & Me.txtSearchbar & "*'"

Add text to another textbox:

Me.txtAnotherTextBox.Value = Me.txtSearchbar.Value

.Value can be omitted, but in some cases it may lead to incorrect results.


问:
Bash script with wildcards
here's an example of my script:

```<code>#!/bin/bash
cd /upper/folder.test*/subfolder
ls
</code>```

The folder.test folder s actually named something like "folder.test13kwekrjk1234jk3", and it's completely random, so I want to use a wild card. The "Upper" folder is in root, where I want it and the CD command works outside the script (and I'm executing it in the root directory, just like the script)

However, when I execute (using ./) it gives me:

"- No such file or directory] cd:/upper/folder.test*/subfolder"

What gives? It works outside of the script but it won't work inside the script? Should I be doing this a different way inside the script?

答:
I once had a related problem when I tried to cd to my home directory using "~" in a bash script.

This code worked in the terminal, but not in my script:

```<code>cd ~/Documents/important_folder*
</code>```

However, the below code worked fine in the script:

```<code>cd /home/my_username/Documents/important_folder*
</code>```

Title: Bash script with wildcards

Body:
here's an example of my script:

#!/bin/bash
cd /upper/folder.test*/subfolder
ls

The folder.test folder s actually named something like "folder.test13kwekrjk1234jk3", and it's completely random, so I want to use a wild card. The "Upper" folder is in root, where I want it and the CD command works outside the script (and I'm executing it in the root directory, just like the script)

However, when I execute (using ./) it gives me:

"- No such file or directory] cd:/upper/folder.test*/subfolder"

What gives? It works outside of the script but it won't work inside the script? Should I be doing this a different way inside the script?

Body:
I once had a related problem when I tried to cd to my home directory using "~" in a bash script.

This code worked in the terminal, but not in my script:

cd ~/Documents/important_folder*

However, the below code worked fine in the script:

cd /home/my_username/Documents/important_folder*


问:
How to get the uri of captured Bitmap correctly?
This code does not work correctly on all Android Versions

On Android 4.x works fine, but on 7.0 this code does not work. the code can capture and save the image but last step about Crop Image : I get balck Screen, means the uri is lost. check the screenshot after the code below pls.

Here is my Demo :

```<code>import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;

public class CameraCrop1 extends AppCompatActivity {
    Uri picUri;
    Bitmap bitmap, bitmap2;
    ImageView img, img_original;

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

        img=(ImageView)findViewById(R.id.imageView);
        img_original=(ImageView)findViewById(R.id.imageView_original);
    }

    public void Capture(View view) {
        Capture_Cam();
    }

    private void Capture_Cam() {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            picUri = data.getData();
            try {
                // bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri); // bitmap2 = original before cur
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse("file://"+picUri));
                img_original.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
            performCrop();

        } else if (requestCode == 2) {

            bitmap2=(Bitmap) data.getExtras().get("data");
            img.setImageBitmap(bitmap2);

        }else{
            super.onActivityResult(requestCode, resultCode, data);
        }

    }

    private void performCrop(){
        try {

            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            //indicate image type and Uri
            cropIntent.setDataAndType(picUri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("outputX", 100);
            cropIntent.putExtra("outputY", 100);
            cropIntent.putExtra("scale", true);
            cropIntent.putExtra("return-data", true);
            startActivityForResult(cropIntent, 2);
            Toast toast = Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
        }
        catch(ActivityNotFoundException anfe){
            //display an error message
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }

    }

}
</code>```

Here is xml :

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_camera_crop1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="Test.testing.CameraCrop1">

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/colorAccent"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:text="Capture Camera"
        android:onClick="Capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button4"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/wallet_highlighted_text_holo_dark"
        android:id="@+id/imageView_original"
        android:layout_below="@+id/imageView"
        android:layout_alignLeft="@+id/imageView"
        android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
</code>```

Screenshot

答:
You have to get the URI of the picture with FileProvider.getUriForFile(Context, String, File) to get a URI like content://

For more recent apps targeting Android 7.0 (API level 24) and higher,
  passing a file:// URI across a package boundary causes a
  FileUriExposedException.

Take a look here that describes how to achieve that.

Body:
This code does not work correctly on all Android Versions

On Android 4.x works fine, but on 7.0 this code does not work. the code can capture and save the image but last step about Crop Image : I get balck Screen, means the uri is lost. check the screenshot after the code below pls.

Here is my Demo :

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;

public class CameraCrop1 extends AppCompatActivity {
    Uri picUri;
    Bitmap bitmap, bitmap2;
    ImageView img, img_original;

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

        img=(ImageView)findViewById(R.id.imageView);
        img_original=(ImageView)findViewById(R.id.imageView_original);
    }

    public void Capture(View view) {
        Capture_Cam();
    }

    private void Capture_Cam() {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            picUri = data.getData();
            try {
                // bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri); // bitmap2 = original before cur
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse("file://"+picUri));
                img_original.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
            performCrop();

        } else if (requestCode == 2) {

            bitmap2=(Bitmap) data.getExtras().get("data");
            img.setImageBitmap(bitmap2);

        }else{
            super.onActivityResult(requestCode, resultCode, data);
        }

    }

    private void performCrop(){
        try {

            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            //indicate image type and Uri
            cropIntent.setDataAndType(picUri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("outputX", 100);
            cropIntent.putExtra("outputY", 100);
            cropIntent.putExtra("scale", true);
            cropIntent.putExtra("return-data", true);
            startActivityForResult(cropIntent, 2);
            Toast toast = Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
        }
        catch(ActivityNotFoundException anfe){
            //display an error message
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }

    }

}

Here is xml :

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_camera_crop1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="Test.testing.CameraCrop1">

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/colorAccent"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:text="Capture Camera"
        android:onClick="Capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button4"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/wallet_highlighted_text_holo_dark"
        android:id="@+id/imageView_original"
        android:layout_below="@+id/imageView"
        android:layout_alignLeft="@+id/imageView"
        android:layout_alignStart="@+id/imageView" />
</RelativeLayout>

Screenshot


问:
Error in render function: “TypeError: Cannot read property of undefined”, using Vuex and Vue Router
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

```<code>export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}
</code>```

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

```<code>getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}
</code>```

Here is Card.vue:

```<code><template>
  <div>
    <br>
    <div v-if="flipped" class="container">
      <div class="box">
        <pre v-if="card.code"><code class="preserve-ws">{{card.back}}</code>```

{{card.back}}

{{card.front}}

</template>

```

<p>I am getting the TypeError referenced in the title. My understanding is that the <code>created()</code> hook happens after <code>data()</code> has been set up, so then I can assign <code>{card}</code> using the getter. Unfortunately this displays nothing...</p>

<p>If I assign <code>card()</code> as a computed property:</p>

```computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}
```

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.

答:
I think it was throw error in this step

```<code>getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}
</code>```

in this step, it can not find _id of cars, because allcards was null;

and then you use computed instead, when allcards has been change, it will get again;
you can change code like this

```<code>getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card && card._id === id);
  }
}
</code>```

Body:
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}

Here is Card.vue:

<template>

{{card.back}}

{{card.back}}

{{card.front}}

</template>

I am getting the TypeError referenced in the title. My understanding is that the created() hook happens after data() has been set up, so then I can assign {card} using the getter. Unfortunately this displays nothing...

If I assign card() as a computed property:

computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.

Body:
I think it was throw error in this step

getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}

in this step, it can not find _id of cars, because allcards was null;

and then you use computed instead, when allcards has been change, it will get again;
you can change code like this

getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card && card._id === id);
  }
}


问:
How to get Time to interact to a webpage via App Insights
I am using App Insights from Azure to get the analytic data for a website.
From the browserTimings and Pageviews settings I am able to get the Load time and receiveDuration.

My website has certain ajax requests loading in (async=true) manner. Due to which in chrome network capture, I am able to see Finish:2.15 Sec , DOMContentLoaded :1.05 s, Load: 1.57 s.

Problem statement is How to get the actual time (which attribute) by which the html (DOM) is ready for a user for interaction in App Insights analytics report.

答:
Answer is Client Processing Time. You can understand better from this pic.

MS disclaimer:

The time is measured from when the browser sends the initial HTTP request until all synchronous load events have been processed, including layout and running scripts. It doesn't include asynchronous tasks such as loading web parts from AJAX calls.

For more details: MS documentation

ContentLicense: CC BY-SA 4.0


问:
multiple form actions in html page?
i currently worked with is code...i must insert data into a table in oracle databse 10g and the table name is REGISTER ..so i made register.html page like this and put the jsp file according to it and created validation page too ...wer do i add validation page in????

<marquee>
WELCOME FOR REGISTRATION
</marquee>

<form action="./register.jsp">

First Name:
<input type="text" name="fname" placeholder="Enter first Name" value="">

Last Name:
<input type="text" name="lname" placeholder="Enter Last Name" value="">

Contact:
<input type="text" name="contact" placeholder="Enter contact" value="">

Address:
<input type="text" name="address" placeholder="Enter address" value="">

Gender:
<input type="radio" name="gender" value="Male" checked="checked">Male
<input type="radio" name="gender" value="female">Female

Type Of User	<select name="user" >
<option value="technician">TECHNICIAN</option>
<option value="supervisor">SUPERVISOR</option>
<option value="client">CLIENT</option>
</select>

State:	 <select name="state">
<option value="Default">Select a State</option>
<optgroup label="INDIA">
<option value="karnataka">karnataka</option>
<option value="Telangana">Telangana</option>
<option value="Uttar Pradesh">Uttar Pradesh</option>
</optgroup>
</select>

City:	 <select name="city">
<option value="Default">Select a City</option>
<optgroup label="Andhra Pradesh">
<option value="Kakinada">Kakinada</option>
<option value="Vishakhapatnam">Vizag</option>
<option value="Vijaywada">Vijaywada</option>
</optgroup>
<optgroup label="Uttar Pradesh">
<option value="Mathura">Mathura</option>
<option value="Varanasi">Varanasi</option>
<option value="Lucknow">Lucknow</option>
</optgroup>
</select>

EmailID:
<input type="text" name="emailid" placeholder="Enter Email Here">

Password:
<input type="password" name="password" placeholder="Enter Password Here">

Confirm Password:
<input type="password" name="password1" placeholder="Enter password here">

Date Of Birth
<input type="date" name="dob" placeholder="Enter date" value="">

captcha

Enter captcha 	<input type="text" name="code">

<input type="submit" value="Register">
<input type="reset" value="Refresh">

</form>

```
</div>
</div>
</p>

<p>and the jsp file goes like</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><%@ page import="java.sql.*" session="true"%>
<%!
Connection con;
PreparedStatement ps;
String a,b,c,d,e,f,g,h,i,j,k;
int l,m;
%>

<%
a=request.getParameter("fname");
b=request.getParameter("lname");
c=request.getParameter("address");
d=request.getParameter("gender");
e=request.getParameter("user");
f=request.getParameter("state");
g=request.getParameter("city");
h=request.getParameter("emailid");
i=request.getParameter("password");
j=request.getParameter("password1");
k=request.getParameter("code");
l=Integer.parseInt(request.getParameter("contact"));
m=Integer.parseInt(request.getParameter("dob"));
session.setAttribute("aa",a);
session.setAttribute("bb",b);
session.setAttribute("cc",c);
session.setAttribute("dd",d);
session.setAttribute("ee",e);
session.setAttribute("ff",f);
session.setAttribute("gg",g);
session.setAttribute("hh",h);
session.setAttribute("ii",i);
session.setAttribute("jj",k);
session.setAttribute("ll",l);
session.setAttribute("mm",m);

try
{
 Class.forName("oracle.jdbc.driver.OracleDriver");
 con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","root");

    ps=con.prepareStatement("insert into register values(?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,h);
ps.setString(2,a);
ps.setString(3,b);
ps.setString(4,l);
ps.setString(5,c);
ps.setString(6,d);
ps.setString(7,f);
ps.setString(8,g);
ps.setString(9,i);
ps.setString(10,m);
ps.setString(11,e);
ps.execute();
}
catch(Exception e)
{
}
%></code>```

答:
For both validation and registration functions, I suggest you to use PHP. You can do it all in one or at the same page of register.html to make your work easy with $_SERVER['PHP_SELF']!

I can code php for you :-)

Title: multiple form actions in html page?

Body:
i currently worked with is code...i must insert data into a table in oracle databse 10g and the table name is REGISTER ..so i made register.html page like this and put the jsp file according to it and created validation page too ...wer do i add validation page in????

<marquee>
WELCOME FOR REGISTRATION
</marquee>

<form action="./register.jsp">

First Name:
<input type="text" name="fname" placeholder="Enter first Name" value="">

Last Name:
<input type="text" name="lname" placeholder="Enter Last Name" value="">

Contact:
<input type="text" name="contact" placeholder="Enter contact" value="">

Address:
<input type="text" name="address" placeholder="Enter address" value="">

Gender:
<input type="radio" name="gender" value="Male" checked="checked">Male
<input type="radio" name="gender" value="female">Female

Type Of User	<select name="user" >
<option value="technician">TECHNICIAN</option>
<option value="supervisor">SUPERVISOR</option>
<option value="client">CLIENT</option>
</select>

State:	 <select name="state">
<option value="Default">Select a State</option>
<optgroup label="INDIA">
<option value="karnataka">karnataka</option>
<option value="Telangana">Telangana</option>
<option value="Uttar Pradesh">Uttar Pradesh</option>
</optgroup>
</select>

City:	 <select name="city">
<option value="Default">Select a City</option>
<optgroup label="Andhra Pradesh">
<option value="Kakinada">Kakinada</option>
<option value="Vishakhapatnam">Vizag</option>
<option value="Vijaywada">Vijaywada</option>
</optgroup>
<optgroup label="Uttar Pradesh">
<option value="Mathura">Mathura</option>
<option value="Varanasi">Varanasi</option>
<option value="Lucknow">Lucknow</option>
</optgroup>
</select>

EmailID:
<input type="text" name="emailid" placeholder="Enter Email Here">

Password:
<input type="password" name="password" placeholder="Enter Password Here">

Confirm Password:
<input type="password" name="password1" placeholder="Enter password here">

Date Of Birth
<input type="date" name="dob" placeholder="Enter date" value="">

captcha

Enter captcha 	<input type="text" name="code">

<input type="submit" value="Register">
<input type="reset" value="Refresh">

</form>

and the jsp file goes like

<%@ page import="java.sql.*" session="true"%>
<%!
Connection con;
PreparedStatement ps;
String a,b,c,d,e,f,g,h,i,j,k;
int l,m;
%>

<%
a=request.getParameter("fname");
b=request.getParameter("lname");
c=request.getParameter("address");
d=request.getParameter("gender");
e=request.getParameter("user");
f=request.getParameter("state");
g=request.getParameter("city");
h=request.getParameter("emailid");
i=request.getParameter("password");
j=request.getParameter("password1");
k=request.getParameter("code");
l=Integer.parseInt(request.getParameter("contact"));
m=Integer.parseInt(request.getParameter("dob"));
session.setAttribute("aa",a);
session.setAttribute("bb",b);
session.setAttribute("cc",c);
session.setAttribute("dd",d);
session.setAttribute("ee",e);
session.setAttribute("ff",f);
session.setAttribute("gg",g);
session.setAttribute("hh",h);
session.setAttribute("ii",i);
session.setAttribute("jj",k);
session.setAttribute("ll",l);
session.setAttribute("mm",m);

try
{
 Class.forName("oracle.jdbc.driver.OracleDriver");
 con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","root");

    ps=con.prepareStatement("insert into register values(?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,h);
ps.setString(2,a);
ps.setString(3,b);
ps.setString(4,l);
ps.setString(5,c);
ps.setString(6,d);
ps.setString(7,f);
ps.setString(8,g);
ps.setString(9,i);
ps.setString(10,m);
ps.setString(11,e);
ps.execute();
}
catch(Exception e)
{
}
%>


问:
Checking if a variable is defined?
How can I check whether a variable is defined in Ruby?  Is there an isset-type method available?

答:
WARNING Re: A Common Ruby Pattern

the defined? method is the answer. See the accepted answer above.

But watch out... consider this common ruby pattern:

```<code> def method1
    @x ||= method2
 end

 def method2
    nil
 end
</code>```

method2 always returns nil.

The first time you call method1, the @x variable is not set - therefore method2 will be run. and

method2 will set @x to nil.

But what happens the second time you call method1?

Remember @x has already been set to nil. But method2 will still be run again!! If method2 is a costly undertaking this might not be something that you want.

Let the defined? method come to the rescue:

```<code>  def method1
    return @x if defined? @x
    @x = method2
  end
</code>```

As with most things, the devil is in the implementation details.

OwnerDisplayName: Readonly

Title: Checking if a variable is defined?

Body:
WARNING Re: A Common Ruby Pattern

the defined? method is the answer. See the accepted answer above.

But watch out... consider this common ruby pattern:

 def method1
    @x ||= method2
 end

 def method2
    nil
 end

method2 always returns nil.

The first time you call method1, the @x variable is not set - therefore method2 will be run. and

method2 will set @x to nil.

But what happens the second time you call method1?

Remember @x has already been set to nil. But method2 will still be run again!! If method2 is a costly undertaking this might not be something that you want.

Let the defined? method come to the rescue:

  def method1
    return @x if defined? @x
    @x = method2
  end

As with most things, the devil is in the implementation details.


问:
Getting Error "ExecJS::ProgramError in Subjects#index" in Lynda.com Rails Tutorial
Let me start off by saying I'm sorry if I don't explain my issue as clearly as I could, I'm extremely new to Ruby on Rails and this is the first time I'm actually asking a question here rather than instantly finding the answer here.

I'm going through the Ruby on Rails 4 Essential Training tutorial and was working on the section covering assets where I imported two stylesheets ("admin.css" and "public.css") and then altered the code in the application.css stylesheet to include these two files.

I then created a new layout called admin.html.erb and inserted the following line to reference the new stylesheets:

```<code><%= stylesheet_link_tag('application', :media => 'all') %>
</code>```

But now I get the following error any time I load any page in my app:

I've seen several similar questions asked here but all of their code has another line below mine referencing JavaScript that needs to be fixed.  Often the second line is altered to:

```<code><%= stylesheet_link_tag('default', :media => 'all') %>
</code>```

But that just makes it so that no stylesheet loads.

Here are my files:
admin.html.erb layout

```<code><!DOCTYPE html>
<html>
<head>
    <title>Simple CMS | <%= @page_title || "Admin" %></title>
    <%= stylesheet_link_tag('application', :media => 'all') %>
</head>
<body>
    <div id="header">
        <h1>Simple CMS Admin</h1>
    </div>
    <div id="main">
        <% if !flash[:notice].blank? %>
            <div class="notice">
                <%= flash[:notice] %>
            </div>
        <% end %>
        <div id="content">
            <%= yield %>
        </div>
    </div>
    <div id="footer">
        <p id="copywright">© lynda.com / Brian Arpaio</p>
    </div>
</body>
</html>
</code>```

application.css stylesheet:

```<code>/*
* This is a manifest file that'll be compiled into application.css, which      will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets,  vendor/assets/stylesheets,
* or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
* defined in the other CSS/SCSS files in this directory. It is generally better to create a new
* file per style scope.
*
*= require_tree .
*= require public
*= require admin
*= require_self
*/
</code>```

My subjects index.html.erb view:

```<code><% @page_title = "Subjects" %>
<div class="subjects index">
  <h2>Subjects</h2>

<%= link_to("Add new subject", {:action => 'new'}, :class => 'action new') %>

<table class="listing" summary="Subject list">
    <tr class="header">
        <th> </th>
        <th>Subject</th>
        <th>Visible</th>
        <th>Pages</th>
        <th>Actions</th>
    </tr>
    <% @subjects.each do |subject| %>
    <tr>
        <td><%= subject.position %></td>
        <td><%= subject.name %></td>
        <td class="center"><%= status_tag(subject.visible) %></td>
        <td class="center"><%= subject.pages.size %></td>
        <td class="actions">
            <%= link_to("Show", {:action => 'show', :id => subject.id}, :class => 'action show') %>
            <%= link_to("Edit", {:action => 'edit', :id => subject.id}, :class => 'action edit') %>
            <%= link_to("Delete", {:action => 'delete', :id => subject.id}, :class => 'action delete') %>
        </td>
    </tr>
    <% end %>
</table>
</code>```

My gem file:

```<code>source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5.1'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.3.13', '< 0.5'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read    more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end

group :development do
 # Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

Sorry if this is too much / too little information.  Any help would be greatly appreciated, thanks!

答:
Okay! This fixed it for me. This problem occurs mainly in Windows OS. Force your Coffee Script Source version to 1.8.0. Higher versions are not supported properly.

Change or add this to your gem file:

```<code>gem 'coffee-script-source', '1.8.0'
</code>```

then update the coffee-script-source bundle

```<code>bundle update coffee-script-source
</code>```

This should fix the issue.

Body:
Let me start off by saying I'm sorry if I don't explain my issue as clearly as I could, I'm extremely new to Ruby on Rails and this is the first time I'm actually asking a question here rather than instantly finding the answer here.

I'm going through the Ruby on Rails 4 Essential Training tutorial and was working on the section covering assets where I imported two stylesheets ("admin.css" and "public.css") and then altered the code in the application.css stylesheet to include these two files.

I then created a new layout called admin.html.erb and inserted the following line to reference the new stylesheets:

<%= stylesheet_link_tag('application', :media => 'all') %>

But now I get the following error any time I load any page in my app:

I've seen several similar questions asked here but all of their code has another line below mine referencing JavaScript that needs to be fixed.  Often the second line is altered to:

<%= stylesheet_link_tag('default', :media => 'all') %>

But that just makes it so that no stylesheet loads.

Here are my files:
admin.html.erb layout

<!DOCTYPE html>

    <title>Simple CMS | <%= @page_title || "Admin" %></title>
    <%= stylesheet_link_tag('application', :media => 'all') %>

Simple CMS Admin

        <% if !flash[:notice].blank? %>

                <%= flash[:notice] %>

        <% end %>

            <%= yield %>

© lynda.com / Brian Arpaio

application.css stylesheet:

/*
* This is a manifest file that'll be compiled into application.css, which      will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets,  vendor/assets/stylesheets,
* or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
* defined in the other CSS/SCSS files in this directory. It is generally better to create a new
* file per style scope.
*
*= require_tree .
*= require public
*= require admin
*= require_self
*/

My subjects index.html.erb view:

<% @page_title = "Subjects" %>

Subjects

<%= link_to("Add new subject", {:action => 'new'}, :class => 'action new') %>

        Subject
        Visible
        Pages
        Actions

    <% @subjects.each do |subject| %>

        <%= subject.position %>
        <%= subject.name %>
        <%= status_tag(subject.visible) %>
        <%= subject.pages.size %>

            <%= link_to("Show", {:action => 'show', :id => subject.id}, :class => 'action show') %>
            <%= link_to("Edit", {:action => 'edit', :id => subject.id}, :class => 'action edit') %>
            <%= link_to("Delete", {:action => 'delete', :id => subject.id}, :class => 'action delete') %>

    <% end %>

My gem file:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5.1'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.3.13', '< 0.5'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read    more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end

group :development do
 # Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Sorry if this is too much / too little information.  Any help would be greatly appreciated, thanks!

Body:
Okay! This fixed it for me. This problem occurs mainly in Windows OS. Force your Coffee Script Source version to 1.8.0. Higher versions are not supported properly.

Change or add this to your gem file:

gem 'coffee-script-source', '1.8.0'

then update the coffee-script-source bundle

bundle update coffee-script-source

This should fix the issue.


问:
node.js express, a very strange behaviour
I have an Express server running.

What i do is upload an Excel File from HTML and then Express parse that file and do some calculating.

In the Excel file, each row has information about address of a User.

For each Address, our Express server will use google map geocoding API to calculate the latitude & longitude.

But, because Google doesn't accept more than 50 request per second to their geocoding API, so i have to use settimeout to delay the calculating.

For example if the Excel file has 50 addresses, so i have to use settimeout on each address to avoid that rate limit.

Here is my code to use settimeout and calculate latitude, longitude

createFromFile(req, res) {
    var form = new formidable.IncomingForm();
    return form.parse(req, function (err, fields, files) {
      if (err)
        return res.status(500).json({error: err.message})

      var workbook = new exceljs.Workbook();
      return workbook.xlsx.readFile(files.excelfile.path).then(function() {
        // use workbook
        var worksheet = workbook.getWorksheet(1)
        var data = []
        for (var i=2; i<=worksheet.rowCount; i++) {
          data.push({
            from_name: worksheet.getCell('A'+i).value + '',
            from_address: worksheet.getCell('B'+i).value + '',
            from_phone: worksheet.getCell('C'+i).value + '',
            receiver_name: worksheet.getCell('D'+i).value + '',
            receiver_address: worksheet.getCell('E'+i).value + '',
            receiver_phone: worksheet.getCell('F'+i).value + '',
            note: worksheet.getCell('H'+i).value + ''
          })
        }

        var delay = function(t) {
          return new Promise(function(resolve)           {
            setTimeout(resolve, t)
          })
        }

        return Promise.all(data.map(function(item, i) {
          return function() {
            return delay(750*i).then(function() {
              winston.log('debug', 'process for item '+i)
              return geocoder.geocode(item.from_address).then(function(geo_data) {
                data[i].from_coord = {
                  lat: geo_data[0].latitude,
                  lng: geo_data[0].longitude
                }
                return geocoder.geocode(item.receiver_address).then(function(geo_data) {
                  data[i].receiver_coord = {
                    lat: geo_data[0].latitude,
                    lng: geo_data[0].longitude
                  }
                })
              })
              .catch(function(geo_error) {
                winston.log('error', 'geo_error', {error: geo_error})
                throw new Error('Address in line ' + i + ' is not valid')
              })
            })
          }()
        }))
        .then(function() {
          winston.log('debug', 'we are done calculating location')
          return res.status(201).json(data)
        })
      })
      .catch(function(e) {
        winston.log('error', 'an error occurred')
        return res.status(500).json({error: e.message})
      })
    })
  }```
</div>
</div>
</p>

<p>And below is my codes to call that Express API, i used React to do frontend job & used javascript fetch api to request to server.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>startUploadFile() {
  this.props.showLoader()
  let data = new FormData()
  data.append('excelfile', this.state.selectedFile)
  data.append('name', 'excelfile')
  var me = this
  fetch(Const.restServer + '/create-from-file', {
    headers: {
      'Access-Token': this.props.access_token,
    },
    method: 'POST',
    body: data
  })
  .then(function(r) {
    return r.json()
  })
  .then(function(r) {
    if (r.hasOwnProperty('error'))
      throw new Error(r.error)

    me.props.hideLoader()
    me.props.showDialog('success', 'Process Complete')
  })
  .catch(function(e) {
    console.log(e)
    me.props.hideLoader()
    me.props.showDialog('error', e.message)
  })
}</code>```

My problem is when i used above codes to uploading a file on browser, i see two request in express log file. Something like this:

I will provide my codes to log info of every request here too

app.use(function(req, res, next) {
  winston.log('debug', 'call api:', {
    api: req.url, requestMethod: req.method
  })
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Access-Token, Web-Admin-Request"
  );
  next()
});

function isAuthenticated(req, res, next) {
  /**
  ** Rest API Middleware check if access_token is valid
  */
  let accessToken = req.body.accessToken || req.get('Access-Token')

  // bunch of codes to check accessToken
  next()
}

app.post('/order/create-from-file', isAuthenticated, orderController.createFromFile);```

I don't understand why this happen. If I use Postman & select a File & upload, it works fine - just only One Request in logs.

Can anyone tell me what is the reason. I feel like this is a Bug of Express. My Express version is 4.15.2

答:
The Access-Token request header your code adds to the request triggers browsers to send a CORS preflight OPTIONS request before trying the POST request.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests gives more detail but the gist of it is, as long as your code’s adding that Access-Token header to the request, there’s no way you can prevent browsers from making the extra preflight OPTIONS request—because it’s something browsers do automatically as part of the CORS protocol.

The reason you don’t see the extra request when you use Postman is that it doesn’t do the CORS preflight OPTIONS request—only browsers send it, and only for requests made by XHR/Fetch from frontend JavaScript code running in a browser at a specific origin (which Postman isn’t).

Body:
I have an Express server running.

What i do is upload an Excel File from HTML and then Express parse that file and do some calculating.

In the Excel file, each row has information about address of a User.

For each Address, our Express server will use google map geocoding API to calculate the latitude & longitude.

But, because Google doesn't accept more than 50 request per second to their geocoding API, so i have to use settimeout to delay the calculating.

For example if the Excel file has 50 addresses, so i have to use settimeout on each address to avoid that rate limit.

Here is my code to use settimeout and calculate latitude, longitude

createFromFile(req, res) {
    var form = new formidable.IncomingForm();
    return form.parse(req, function (err, fields, files) {
      if (err)
        return res.status(500).json({error: err.message})

      var workbook = new exceljs.Workbook();
      return workbook.xlsx.readFile(files.excelfile.path).then(function() {
        // use workbook
        var worksheet = workbook.getWorksheet(1)
        var data = []
        for (var i=2; i<=worksheet.rowCount; i++) {
          data.push({
            from_name: worksheet.getCell('A'+i).value + '',
            from_address: worksheet.getCell('B'+i).value + '',
            from_phone: worksheet.getCell('C'+i).value + '',
            receiver_name: worksheet.getCell('D'+i).value + '',
            receiver_address: worksheet.getCell('E'+i).value + '',
            receiver_phone: worksheet.getCell('F'+i).value + '',
            note: worksheet.getCell('H'+i).value + ''
          })
        }

        var delay = function(t) {
          return new Promise(function(resolve)           {
            setTimeout(resolve, t)
          })
        }

        return Promise.all(data.map(function(item, i) {
          return function() {
            return delay(750*i).then(function() {
              winston.log('debug', 'process for item '+i)
              return geocoder.geocode(item.from_address).then(function(geo_data) {
                data[i].from_coord = {
                  lat: geo_data[0].latitude,
                  lng: geo_data[0].longitude
                }
                return geocoder.geocode(item.receiver_address).then(function(geo_data) {
                  data[i].receiver_coord = {
                    lat: geo_data[0].latitude,
                    lng: geo_data[0].longitude
                  }
                })
              })
              .catch(function(geo_error) {
                winston.log('error', 'geo_error', {error: geo_error})
                throw new Error('Address in line ' + i + ' is not valid')
              })
            })
          }()
        }))
        .then(function() {
          winston.log('debug', 'we are done calculating location')
          return res.status(201).json(data)
        })
      })
      .catch(function(e) {
        winston.log('error', 'an error occurred')
        return res.status(500).json({error: e.message})
      })
    })
  }

And below is my codes to call that Express API, i used React to do frontend job & used javascript fetch api to request to server.

startUploadFile() {
  this.props.showLoader()
  let data = new FormData()
  data.append('excelfile', this.state.selectedFile)
  data.append('name', 'excelfile')
  var me = this
  fetch(Const.restServer + '/create-from-file', {
    headers: {
      'Access-Token': this.props.access_token,
    },
    method: 'POST',
    body: data
  })
  .then(function(r) {
    return r.json()
  })
  .then(function(r) {
    if (r.hasOwnProperty('error'))
      throw new Error(r.error)

    me.props.hideLoader()
    me.props.showDialog('success', 'Process Complete')
  })
  .catch(function(e) {
    console.log(e)
    me.props.hideLoader()
    me.props.showDialog('error', e.message)
  })
}

My problem is when i used above codes to uploading a file on browser, i see two request in express log file. Something like this:

I will provide my codes to log info of every request here too

app.use(function(req, res, next) {
  winston.log('debug', 'call api:', {
    api: req.url, requestMethod: req.method
  })
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Access-Token, Web-Admin-Request"
  );
  next()
});

function isAuthenticated(req, res, next) {
  /**
  ** Rest API Middleware check if access_token is valid
  */
  let accessToken = req.body.accessToken || req.get('Access-Token')

  // bunch of codes to check accessToken
  next()
}

app.post('/order/create-from-file', isAuthenticated, orderController.createFromFile);

I don't understand why this happen. If I use Postman & select a File & upload, it works fine - just only One Request in logs.

Can anyone tell me what is the reason. I feel like this is a Bug of Express. My Express version is 4.15.2


问:
Calling a formula within a custom function using quosures
I am trying to run a t-test within a custom function, and am running into a quosure misapplication (I believe). Any help would be greatly appreciated.

```<code>library(tidyverse)

tp_pull <- function(mydata, dv, iv){
  dv <- enquo(dv)
  iv <- enquo(iv)
  t.test(!!dv ~ !!iv, mydata)
}

tp_pull(mydata = mtcars, dv = mpg, iv = vs)
</code>```

My error message reads:

```<code>numerical expression has 2 elements: only the first usedNAs introduced by
coercion
Show Traceback
Error in quo_name(dv):~!(!iv) : NA/NaN argument
</code>```

For context this t-test will be part of a larger custom function.

答:
Quosures are unique to tidyeval and are not supposed by the base R language. Right now they only work with dplyr. It is very unlikely these will ever work with base functions such as t.test.

If you want to do this with base R, you can use G. Grothendieck's suggestion of

```<code>tp_pull <- function(mydata, dv, iv){
  t.test(formula(substitute(dv ~ iv)), mydata)
}

tp_pull(mydata = mtcars, dv = mpg, iv = vs)
</code>```

The substitute captures the un-evaulated symbol names from the promise passed to the call and allows you to re-assemble them into a new expression. The formula() call helps coerce the un-evaulated expression returned by substitute() into a proper R formula object.

Body:
I am trying to run a t-test within a custom function, and am running into a quosure misapplication (I believe). Any help would be greatly appreciated.

library(tidyverse)

tp_pull <- function(mydata, dv, iv){
  dv <- enquo(dv)
  iv <- enquo(iv)
  t.test(!!dv ~ !!iv, mydata)
}

tp_pull(mydata = mtcars, dv = mpg, iv = vs)

My error message reads:

numerical expression has 2 elements: only the first usedNAs introduced by
coercion
Show Traceback
Error in quo_name(dv):~!(!iv) : NA/NaN argument

For context this t-test will be part of a larger custom function.

Body:
Quosures are unique to tidyeval and are not supposed by the base R language. Right now they only work with dplyr. It is very unlikely these will ever work with base functions such as t.test.

If you want to do this with base R, you can use G. Grothendieck's suggestion of

tp_pull <- function(mydata, dv, iv){
  t.test(formula(substitute(dv ~ iv)), mydata)
}

tp_pull(mydata = mtcars, dv = mpg, iv = vs)

The substitute captures the un-evaulated symbol names from the promise passed to the call and allows you to re-assemble them into a new expression. The formula() call helps coerce the un-evaulated expression returned by substitute() into a proper R formula object.


问:
How to process standart html tags in xml file using xslt
I have not practiced XML in over a year.
My question is, using the samples below, why my for-each statement is only printing the first paragraph.

If you are wanting to know why my XML is using standard HTML "p" tags that I am trying to put back into "p" tags in my XSL file: the reason is I am batch processing several long writer documents from a word processor into HTML files. There are thousands (maybe tens of thousands) of paragraph tags. I cannot output XML files in any format I can use or manipulate the way I want.

I can however save the HTML file with an XML extension and work with that. I have already converted a few other files, but not tried to for-each the
 tags yet.

My XML file

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>

<Library>
    <Books>
        <MyBooks>

            <my_favorite_book>
                <title>the title of my favorite book</title>
                <p>paragraph 1</p>
                <p>paragraph 2</p>
                <p>paragraph 3</p>
                <p>paragraph 4</p>
                <p>paragraph 5</p>
                <p>paragraph 6</p>
                <p>paragraph 7</p>
                <p>paragraph 8</p>
                <p>paragraph 9</p>
           </my_favorite_book>

        </MyBooks>
    </Books>
</Library>
</code>```

My XSL file

```<code>    <?xml version="1.0"?>
    <xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

            <xsl:template match="/">

                <html>
                   <body>

                    <p align="center">
                        <span style="font-size: 5em;">
                            <b>
                                <xsl:value-of select="Library/Books/MyBooks/my_favorite_book/title" />
                            </b>
                        </span>
                        <br/>
                     </p>

                    <xsl:for-each select="Library/Books/MyBooks/my_favorite_book">
                        <p>
                            <xsl:value-of select="p" />
                        </p>
                    </xsl:for-each>

            </body>
        </html>

        </xsl:template>
    </xsl:stylesheet>
</code>```

The Web browser output (FireFox 54.0.1 (32-bit))

答:
My question is, using the samples below, why my for-each statement is
  only printing the first paragraph.

Because your for-each,

```<code><xsl:for-each select="Library/Books/MyBooks/my_favorite_book">
</code>```

is selecting the only my_favorite_book, and your xsl:value-of,

```<code>   <xsl:value-of select="p" />
</code>```

is selecting all of my_favority_book's children only to take the string value of the first such p,

```<code>   paragraph 1
</code>```

The shortest fix to your program would be to loop over the paragraphs,

```<code><xsl:for-each select="Library/Books/MyBooks/my_favorite_book/p">
</code>```

and take the value-of each,

```<code>   <xsl:value-of select="." />
</code>```

or, instead of looping with xsl:for-each, you might use apply-templates instead:

```<code><xsl:apply-templates select="Library/Books/MyBooks/my_favorite_book/p">
</code>```

if you come to have further pattern matching to do, or copy-of if you don't:

```<code><xsl:copy-of select="Library/Books/MyBooks/my_favorite_book/p">
</code>```

Body:
I have not practiced XML in over a year.
My question is, using the samples below, why my for-each statement is only printing the first paragraph.

If you are wanting to know why my XML is using standard HTML "p" tags that I am trying to put back into "p" tags in my XSL file: the reason is I am batch processing several long writer documents from a word processor into HTML files. There are thousands (maybe tens of thousands) of paragraph tags. I cannot output XML files in any format I can use or manipulate the way I want.

I can however save the HTML file with an XML extension and work with that. I have already converted a few other files, but not tried to for-each the
 tags yet.

My XML file

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>

<Library>
    <Books>
        <MyBooks>

            <my_favorite_book>
                <title>the title of my favorite book</title>

paragraph 1

paragraph 2

paragraph 3

paragraph 4

paragraph 5

paragraph 6

paragraph 7

paragraph 8

paragraph 9

           </my_favorite_book>

        </MyBooks>
    </Books>
</Library>

My XSL file

    <?xml version="1.0"?>
    <xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

            <xsl:template match="/">

                                <xsl:value-of select="Library/Books/MyBooks/my_favorite_book/title" />

                    <xsl:for-each select="Library/Books/MyBooks/my_favorite_book">

                            <xsl:value-of select="p" />

                    </xsl:for-each>

        </xsl:template>
    </xsl:stylesheet>

The Web browser output (FireFox 54.0.1 (32-bit))

Body:
My question is, using the samples below, why my for-each statement is
  only printing the first paragraph.

Because your for-each,

<xsl:for-each select="Library/Books/MyBooks/my_favorite_book">

is selecting the only my_favorite_book, and your xsl:value-of,

   <xsl:value-of select="p" />

is selecting all of my_favority_book's children only to take the string value of the first such p,

   paragraph 1

The shortest fix to your program would be to loop over the paragraphs,

<xsl:for-each select="Library/Books/MyBooks/my_favorite_book/p">

and take the value-of each,

   <xsl:value-of select="." />

or, instead of looping with xsl:for-each, you might use apply-templates instead:

<xsl:apply-templates select="Library/Books/MyBooks/my_favorite_book/p">

if you come to have further pattern matching to do, or copy-of if you don't:

<xsl:copy-of select="Library/Books/MyBooks/my_favorite_book/p">


问:
Cannot implicitly convert type 'string' to 'System.DateTime'
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

```<code>DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);
</code>```

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.

答: I guess that you have made a typo - change Convert.ToString(s2) to Convert.ToDateTime(s2).

Body:
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.


问:
How to make an HTML element readonly based on PHP value
I have this code:

```<code><input type = "text" value = "$va" name = "n"/>
</code>```

and I want it to be readonly if va is not whitespace. How can I accomplish this?

答:
This should make it so that if $va contains whitespace the field will be readonly.

```<code><?php

$readonly = (!empty($va) && strlen(trim($va)) == 0) ? null : 'readonly';
echo '<input type="text" value="'.$va.'" name = "n" '.$readonly.' />';
</code>```

However I'm not sure if you also want to include an empty string as "only including whitespace", in which case you could alter the first line to:

```<code>$readonly = (strlen(trim($va)) == 0) ? null : 'readonly';
</code>```

Body:
I have this code:

<input type = "text" value = "$va" name = "n"/>

and I want it to be readonly if va is not whitespace. How can I accomplish this?

Body:
This should make it so that if $va contains whitespace the field will be readonly.

<?php

$readonly = (!empty($va) && strlen(trim($va)) == 0) ? null : 'readonly';
echo '<input type="text" value="'.$va.'" name = "n" '.$readonly.' />';

However I'm not sure if you also want to include an empty string as "only including whitespace", in which case you could alter the first line to:

$readonly = (strlen(trim($va)) == 0) ? null : 'readonly';


问:
Pandas: How to check if a list-type column is in dataframe
How can I create a new list column from a list column

My dataframe:

```<code>id    x    list_id
1     20   [2, 4]
2     10   [1, 3]
3     10   [1]
4     30   [1, 2]
</code>```

What I want:

```<code>id    x    list_id    list_x
1     20   [2, 4]     [10, 30]
2     10   [1, 3]     [20, 10]
3     10   [1]        [20]
4     30   [1, 2]     [20, 10]
</code>```

My first idea is to iterate on each line then check if the id is in the list

```<code>for index, row in df.iterrows():
  if ( df['id'].isin(row['list_id']) ):
     do_somthing
</code>```

But its not working, any suggestion !!

答:
Use a list comprehension:

```<code>df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id]
</code>```

Full example with dummy data:

```<code>import pandas as pd

data= {
    'id': [1,2,3,4],
    'x': [20,10,10,30],
    'list_id': [[2,4],[1,3],[1],[1,2]],
}

df = pd.DataFrame(data)

df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id]
</code>```

Output

```<code>print df

  list_id   x    list_x
1  [2, 4]  20  [10, 30]
2  [1, 3]  10  [20, 10]
3     [1]  10      [20]
4  [1, 2]  30  [20, 10]
</code>```

Body:
How can I create a new list column from a list column

My dataframe:

id    x    list_id
1     20   [2, 4]
2     10   [1, 3]
3     10   [1]
4     30   [1, 2]

What I want:

id    x    list_id    list_x
1     20   [2, 4]     [10, 30]
2     10   [1, 3]     [20, 10]
3     10   [1]        [20]
4     30   [1, 2]     [20, 10]

My first idea is to iterate on each line then check if the id is in the list

for index, row in df.iterrows():
  if ( df['id'].isin(row['list_id']) ):
     do_somthing

But its not working, any suggestion !!

Body:
Use a list comprehension:

df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id]

Full example with dummy data:

import pandas as pd

data= {
    'id': [1,2,3,4],
    'x': [20,10,10,30],
    'list_id': [[2,4],[1,3],[1],[1,2]],
}

df = pd.DataFrame(data)

df.loc[:,'list_x'] = [df.x[df['id'].isin(l)].values for l in df.list_id]

Output

print df

  list_id   x    list_x
1  [2, 4]  20  [10, 30]
2  [1, 3]  10  [20, 10]
3     [1]  10      [20]
4  [1, 2]  30  [20, 10]


问:
Make Bootstrap columns to take 100% of the row width
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row" style="margin-top:40px;margin-bottom:40px;border-right: 1px solid red;border-left: 1px solid red;">
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
     </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
   </div>
  </div></code>```

答:
Change your class from container to container-fluid:

```<code><div class="container-fluid">
...
</div>
</code>```

More about it here

Body:
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

Body:
Change your class from container to container-fluid:

<div class="container-fluid">
...
</div>

More about it here


问:
Main view stacks on the same page after calling partial view
I have this action that returns different partial view based on the selected value from the drop down list.

Controller:

```<code>[HttpPost]
        public ActionResult Foo(SomeViewModel VM)
        {
            var model = VM
            if (Request.IsAjaxRequest())
            {
                if (model.SelectedValue == 1 || model.SelectedValue == 2 || model.SelectedValue == 3)
                {
                    // ...
                    return PartialView("PartialView1", model);
                }
                else if (model.SelectedValue == 4)
                {
                    // ...
                    return PartialView("PartialView2", model);
                }
                else (model.SelectedValue == 5)
                {
                    // ...
                    return PartialView("PartialView3", model);
                }
            }
            return View(model);
        }
</code>```

Main View:

```<code><script src="~/Scripts/jquery-3.2.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
    <h2>Paint Computation</h2>
    @using (Ajax.BeginForm("Foo", "Controller",
 new AjaxOptions
 {
     HttpMethod = "POST",
     UpdateTargetId = "Result"
 }))
    {
        <div class="col-md-10">
            <h5>Type of Paint</h5>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.PaintType, "Value", "Text"),
                "Please Select", htmlAttributes: new { @class = "form-control" })
            </div>
            <br />

        // Some HTML helpers
            <input type="submit" value="Compute" class="btn btn-default" id="Submit" />

        </div>
    }
</div>

//This is how I render my partial view using jQuery in my main View:

    <div id="Result">
        <hr />
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#Submit').click(function () {
                $('#Result').load('/Controller/Foo');
            });
        });
    </script>
</code>```

Whenever I clicked the button, the partial view appears, but when I clicked it again for the 3rd or 4th time, the main view content stacks on the same main view. I tried to use the inspect element and that's how I determined that it stacks the same main view elements.

Is my way of calling the partial view is right? As much as possible I want to use ajax for calling the partial view every time the button is clicked. Please guide me to correct it. Thanks.

Here's the  of the problem.

答:
```<code><script type="text/javascript">
    $(document).ready(function () {
        $('#Submit').click(function () {
            $.ajax({
                type: 'POST',
                url: '/Controller/Foo',
                cache: false,
                contentType: "application/html; charset=utf-8",
                dataType: 'html',
                success: function (result) {
                    $('#Result').html(result);
                }
            });
        });
    });
</script>
</code>```

Now it works. I changed my code and use the code above. I use .html() rather than .append() or .replaceWith(). Now every time i click the button, it changes the
 content.

Body:
I have this action that returns different partial view based on the selected value from the drop down list.

Controller:

[HttpPost]
        public ActionResult Foo(SomeViewModel VM)
        {
            var model = VM
            if (Request.IsAjaxRequest())
            {
                if (model.SelectedValue == 1 || model.SelectedValue == 2 || model.SelectedValue == 3)
                {
                    // ...
                    return PartialView("PartialView1", model);
                }
                else if (model.SelectedValue == 4)
                {
                    // ...
                    return PartialView("PartialView2", model);
                }
                else (model.SelectedValue == 5)
                {
                    // ...
                    return PartialView("PartialView3", model);
                }
            }
            return View(model);
        }

Main View:

Paint Computation

    @using (Ajax.BeginForm("Foo", "Controller",
 new AjaxOptions
 {
     HttpMethod = "POST",
     UpdateTargetId = "Result"
 }))
    {

Type of Paint

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.PaintType, "Value", "Text"),
                "Please Select", htmlAttributes: new { @class = "form-control" })

        // Some HTML helpers
            <input type="submit" value="Compute" class="btn btn-default" id="Submit" />

    }

//This is how I render my partial view using jQuery in my main View:

Whenever I clicked the button, the partial view appears, but when I clicked it again for the 3rd or 4th time, the main view content stacks on the same main view. I tried to use the inspect element and that's how I determined that it stacks the same main view elements.

Is my way of calling the partial view is right? As much as possible I want to use ajax for calling the partial view every time the button is clicked. Please guide me to correct it. Thanks.

Here's the  of the problem.

Body:
<script type="text/javascript">
    $(document).ready(function () {
        $('#Submit').click(function () {
            $.ajax({
                type: 'POST',
                url: '/Controller/Foo',
                cache: false,
                contentType: "application/html; charset=utf-8",
                dataType: 'html',
                success: function (result) {
                    $('#Result').html(result);
                }
            });
        });
    });
</script>

Now it works. I changed my code and use the code above. I use .html() rather than .append() or .replaceWith(). Now every time i click the button, it changes the <div id = "Result> content.


答:
1st Option With Java Script

in javascript you can do it like this:

1st: put an id to your element

```<code><input type = "text" value = "$va" name = "n" id='n'/> //i just made it the same as the name
</code>```

2nd: get the element with the id of 'n'

```<code><script>
$(document).ready(function(){
    var nValue = $("#n").val();
    if( nValue != " " ) {
        $("#n").prop("readonly",true);
    }
});
</script>
</code>```

2nd Option With PHP

in php, assuming that you are printing your element via php:

```<code>//other codes here
<?php $va = "noAWhiteSpace";
$readOnly = "";
if($va != ""){
    $readOnly = "readonly";
}
?>
<input type = "text" value = "<?php echo $va; ?>" name = "n" <?php echo $readOnly;  ?> />;
</code>```

Title: How to make an HTML element readonly based on PHP value

Body:
1st Option With Java Script

in javascript you can do it like this:

1st: put an id to your element

<input type = "text" value = "$va" name = "n" id='n'/> //i just made it the same as the name

2nd: get the element with the id of 'n'

<script>
$(document).ready(function(){
    var nValue = $("#n").val();
    if( nValue != " " ) {
        $("#n").prop("readonly",true);
    }
});
</script>

2nd Option With PHP

in php, assuming that you are printing your element via php:

//other codes here
<?php $va = "noAWhiteSpace";
$readOnly = "";
if($va != ""){
    $readOnly = "readonly";
}
?>
<input type = "text" value = "<?php echo $va; ?>" name = "n" <?php echo $readOnly;  ?> />;


问:
CADisplayLink frame rate on 10.5" iPad Pro
We have an OpenGL-based iOS app.  We use a CADisplayLink to control our drawing updates.

I just got the new 10.5" iPad Pro and we are getting a maximum frame rate of 60 rather than the 120 we can theoretically get on the new hardware.

We set up the display link like this:

```<code>    self.caDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkCalled:)];
    caDisplayLink.preferredFramesPerSecond = 120;
    NSLog(@"Maximum FPS = %ld", [UIScreen mainScreen].maximumFramesPerSecond);
    [caDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
</code>```

The displayLinkCalled: method is called 60 times per second.  The log statement does indicate the UIScreen's maximum frame rate is 120 FPS.

Is there anything else I need to do to update at higher than 60 FPS?

答:
Did you opt-in? You need to add a key to your plist</p>

```<code><key>CADisableMinimumFrameDuration</key>
 <true/>
</code>```

Body:
We have an OpenGL-based iOS app.  We use a CADisplayLink to control our drawing updates.

I just got the new 10.5" iPad Pro and we are getting a maximum frame rate of 60 rather than the 120 we can theoretically get on the new hardware.

We set up the display link like this:

    self.caDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkCalled:)];
    caDisplayLink.preferredFramesPerSecond = 120;
    NSLog(@"Maximum FPS = %ld", [UIScreen mainScreen].maximumFramesPerSecond);
    [caDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

The displayLinkCalled: method is called 60 times per second.  The log statement does indicate the UIScreen's maximum frame rate is 120 FPS.

Is there anything else I need to do to update at higher than 60 FPS?

Body:
Did you opt-in? You need to add a key to your plist

<key>CADisableMinimumFrameDuration</key>
 <true/>


问:
Turn html text into markdown manually (javascript / nodejs)
I'm a bit stuck. I have scraped a website and would now like to convert it into markdown. My html looks like this:

```<code>Some text more text, and more text. Some text more text, and more text.
Once in a while  <span class="bold">something is bold</span>.
Then some more text. And <span class="bold">more bold stuff</span>.
</code>```

There are html to markdown modules available, however, they would only work if the text  looked like this .

How could I go through the html, and everytime I find a span which is supposed to bold something, turn this piece of the html into bold markdown, that is, make it **look like this**

答:
Try this one https://github.com/domchristie/to-markdown, an HTML to Markdown converter written in JavaScript.

It can be extended by passing in an array of converters to the options object:

```<code>toMarkdown(stringOfHTML, { converters: [converter1, converter2, …] });
</code>```

In your case, the converter can be

```<code>{
    filter: 'span',
    replacement: function(content) {
       return '**' + content + '**';
   }
}
</code>```

Refer to its readme for more details.

Body:
I'm a bit stuck. I have scraped a website and would now like to convert it into markdown. My html looks like this:

Some text more text, and more text. Some text more text, and more text.
Once in a while  something is bold.
Then some more text. And more bold stuff.

There are html to markdown modules available, however, they would only work if the text  looked like this .

How could I go through the html, and everytime I find a span which is supposed to bold something, turn this piece of the html into bold markdown, that is, make it **look like this**

Body:
Try this one https://github.com/domchristie/to-markdown, an HTML to Markdown converter written in JavaScript.

It can be extended by passing in an array of converters to the options object:

toMarkdown(stringOfHTML, { converters: [converter1, converter2, …] });

In your case, the converter can be

{
    filter: 'span',
    replacement: function(content) {
       return '**' + content + '**';
   }
}

Refer to its readme for more details.


问:
XML Elements Move Inside New Descendant with Linq to XML C#?
I have this XML document:

```<code><aaa>
    <x1></x1>
    <x2></x2>
    <x3></x3>
</aaa>
</code>```

And need to convert it to this document:

```<code><aaa>
    <bbb note="moved to new">
        <x1></x1>
        <x2></x2>
        <x3></x3>
    </bbb>
</aaa>
</code>```

Using Linq-to-XML, what would be the right code to add all child nodes of  to a new descendant , but only if  descendant does not exist? I started with this

```<code>var docRaw = XElement.Parse( documentString );
var bbbElem = docRaw.Elements( "aaa" ).Where( docRaw => !docRaw.Elements( "bbb" ).Any() );
</code>```

But I think that takes me down the wrong strategy-path.

All ideas appreciated, thanks.

答:
You can use ReplaceNodes() to replace the content of the root element. You can replace them with a new node named <bbb> that contains the root's former child elements.

```<code>doc.Root.ReplaceNodes(
    new XElement("bbb",
        new XAttribute("note", "moved to new"),
        doc.Root.Elements()
    )
);
</code>```

Body:
I have this XML document:

<aaa>
    <x1></x1>
    <x2></x2>
    <x3></x3>
</aaa>

And need to convert it to this document:

<aaa>
    <bbb note="moved to new">
        <x1></x1>
        <x2></x2>
        <x3></x3>
    </bbb>
</aaa>

Using Linq-to-XML, what would be the right code to add all child nodes of  to a new descendant , but only if  descendant does not exist? I started with this

var docRaw = XElement.Parse( documentString );
var bbbElem = docRaw.Elements( "aaa" ).Where( docRaw => !docRaw.Elements( "bbb" ).Any() );

But I think that takes me down the wrong strategy-path.

All ideas appreciated, thanks.

Body:
You can use ReplaceNodes() to replace the content of the root element. You can replace them with a new node named <bbb> that contains the root's former child elements.

doc.Root.ReplaceNodes(
    new XElement("bbb",
        new XAttribute("note", "moved to new"),
        doc.Root.Elements()
    )
);


问:
JavaFX 8 How to set program icon to alert?
How can I set program icon to alert without using alert.initOwner()?
Why without initOwner? It's because some alert must be shown before whole window is initialized, so there's no scene that I can put to initOwner function.

答:
```<code>public class AlertWithIcon
extends Application {
    @Override
    public void start(Stage stage) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
            "Are you sure you want to delete this item?",
        ButtonType.YES, ButtonType.NO);
       alert.setHeaderText("Delete Item");
   ((Stage)alert.getDialogPane().getScene().getWindow()).getIcons().add(new image("GenericApp.png"));
    alert.showAndWait();
}
}
</code>```