问:
How to add custom file field to user profile in wordpress?
I've found endless examples online on how to add extra custom fields to user profiles in wordpress. But non of them have shown how to add fields to upload files.

Heres what I got for my extra field:

```<code>add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) {
?>
    <h3><?php _e("Extra Information", "blank"); ?></h3>
    <table class="form-table">

        <tr>
            <th><label for="my_document"><?php _e("My Document"); ?></label></th>
            <td>
                <input type="file" name="my_document" id="my_document" value="<?php echo esc_attr( get_the_author_meta( 'my_document', $user->ID ) ); ?>" />
            </td>
        </tr>

    </table>

<?php
}
</code>```

Then for the form submit:

```<code>add_action( 'personal_options_update', 'yoursite_save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'yoursite_save_extra_user_profile_fields' );

function yoursite_save_extra_user_profile_fields( $user_id ) {
    $saved = false;

    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;

    if(!empty($_FILES['my_document']['name'])) {

        // Use the WordPress API to upload the file
        $upload = wp_upload_bits($_FILES['my_document']['name'], null, file_get_contents($_FILES['my_document']['tmp_name']));

        if(isset($upload['error']) && $upload['error'] != 0) {
            wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
        } else {
            add_post_meta($user_id, 'my_document', $upload);
            update_post_meta($user_id, 'my_document', $upload);
        } // end if/else

    } // end if

}
</code>```

The document isn't saving, I suspect the form in the edit profile hasn't the tags to upload files. I also don't know how to retrieve the document in the front end once its saved, as to show the user he has the file uploaded.

答:
What do you see in your console when you dump the output?

```<code>var_dump($upload);
</code>```

It could be related to the /tmp directory permissions (or existence).

I apologize if this isn't what you're asking, but have you tried ACF?

Here is how to get fields from a User field group.

Body:
I've found endless examples online on how to add extra custom fields to user profiles in wordpress. But non of them have shown how to add fields to upload files.

Heres what I got for my extra field:

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) {
?>

<?php _e("Extra Information", "blank"); ?>

            <?php _e("My Document"); ?>

                <input type="file" name="my_document" id="my_document" value="<?php echo esc_attr( get_the_author_meta( 'my_document', $user->ID ) ); ?>" />

<?php
}

Then for the form submit:

add_action( 'personal_options_update', 'yoursite_save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'yoursite_save_extra_user_profile_fields' );

function yoursite_save_extra_user_profile_fields( $user_id ) {
    $saved = false;

    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;

    if(!empty($_FILES['my_document']['name'])) {

        // Use the WordPress API to upload the file
        $upload = wp_upload_bits($_FILES['my_document']['name'], null, file_get_contents($_FILES['my_document']['tmp_name']));

        if(isset($upload['error']) && $upload['error'] != 0) {
            wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
        } else {
            add_post_meta($user_id, 'my_document', $upload);
            update_post_meta($user_id, 'my_document', $upload);
        } // end if/else

    } // end if

}

The document isn't saving, I suspect the form in the edit profile hasn't the tags to upload files. I also don't know how to retrieve the document in the front end once its saved, as to show the user he has the file uploaded.

Body:
What do you see in your console when you dump the output?

var_dump($upload);

It could be related to the /tmp directory permissions (or existence).

I apologize if this isn't what you're asking, but have you tried ACF?

Here is how to get fields from a User field group.


来源: stackexchange

问:
NAudio: Convert IEEE Float input stream to MP3 output stream in WCF
I have WAV data in IEEE float at 16000Hz, 32-bit, 1-channel format in a byte array (from database). I would like to convert that to mp3 on the fly and stream it out via the response object from a WCF service.

Working with NAudio package, so far what I have working is using MediaFoundationEncoder.EncodetoMp3() to write to a file.  But once that file is written out to the response, though, it's useless.  I would like to just skip the file writing step and output to a stream or byte array and write that to the response object.

Is there a way to get MediaFoundationEncoder to output an mp3 in some kind of memory object (without a file)?

Alternatively, trying to use the LameMP3FileWriter, which does write to streams,
I can send the IEEE float wav input directly to LameMP3FileWriter but the resulting mp3 stream sounds like a loud hiss seemingly regardless of the output format I use (44100,16,1), (22050,16,1), (11025,16,1),...

When I try to convert the IEEE float source to a PCM or upsample it using WaveFormatConversion, it errors out with

AcmNotPossible calling acmStreamOpen

if I use Wave32to16Stream on the IEEE float source, it does not error but there is no audio.  This chain is not working for me:

```<code>    byte[] bytes = (Byte[])dt.Rows[0]["AudioContent"];//this is the dataTable from the database query containing the WAV audio

    var ms = new MemoryStream(bytes);
    var OLDfmt = WaveFormat.CreateIeeeFloatWaveFormat(16000,1);
    var NEWfmt = new WaveFormat(16000, 16, 1);//tried many
    var readr = new RawSourceWaveStream(ms,OLDfmt);

    //the following line errors on 'AcmNotPossible calling acmStreamOpen'
    //var wav16 = new WaveFormatConversionStream(NEWfmt, readr);

    //the following does not error but no mp3 streams out at the end
    var wav16 = new Wave32To16Stream(readr);

    var outptMP3 = new MemoryStream();
    var writr = new LameMP3FileWriter(outptMP3, NEWfmt, LAMEPreset.STANDARD);
    wav16.CopyTo(writr);
    HttpContext.Current.Response.BufferOutput = true;
    HttpContext.Current.Response.AddHeader("Content-Type", "audio/mpeg");
    HttpContext.Current.Response.BinaryWrite(outptMP3.ToArray());
</code>```

The raw audio plays fine in Chrome (as a WAV stream) if I just do a BinaryWrite of the ms MemoryStream, so I think the IEEE float source data is valid.

Correct me if wrong, but that error (AcmNotPossible) appears to mean there is no ACM codec on my machine for the IEEE float format?  I query my machine and there appear to be no 32-bit ACM codecs, which is why I'm trying the Wave32To16Stream conversion.

Is there an interim step of the Lame MP3 pipeline to go from IEEE float 32-bit to mp3?

答:
Sorry there were so many sub-questions to my main question about transcoding a IEEE float 32-bit wave to an mp3 stream, but I can at least tell you how I got it to work using ACM codecs (I think) on my simple WCF service:

change the return type on the service to a Stream

set the MemoryStream position to 0 before returning

Otherwise the chain above actually does work for me.  I will give the complete code, with all the extraneous SQL stuff, for the sake of completeness and because I found the answer in an unrelated SO issue:

```<code>public Stream playWAVEFileFromDB() {
        //if using the file output method, I change the return type to string and return text instead of streams
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "SELECT theWAVEColumn FROM myTable WHERE allThoseAudiosAreStored";
            SqlDataAdapter sda = new SqlDataAdapter();
            DataTable dt = new DataTable();

            conn.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);

            //read the raw audio from database into a byte array
            byte[] bytes = (Byte[])dt.Rows[0]["colName"];
            var ms = new MemoryStream(bytes);
            var NEWfmt = new WaveFormat(16000, 16, 1);
            var OLDfmt = WaveFormat.CreateIeeeFloatWaveFormat(16000,1);//how its stored
            var readr = new RawSourceWaveStream(ms,OLDfmt);
            var wav16 = new Wave32To16Stream(readr);
            var outptMP3 = new MemoryStream();
            var writr = new LameMP3FileWriter(outptMP3, NEWfmt, LAMEPreset.STANDARD);
            wav16.CopyTo(writr);
            outptMP3.Position = 0;

            HttpContext.Current.Response.BufferOutput = true;
            HttpContext.Current.Response.AddHeader("Content-Type", "audio/mpeg");

            conn.Close();
            conn.Dispose();
            sda.Dispose();

            return outptMP3;
        }
            catch (Exception e)
        {
            //do the error logging stuff
            return Stream.Null;
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have WAV data in IEEE float at 16000Hz, 32-bit, 1-channel format in a byte array (from database). I would like to convert that to mp3 on the fly and stream it out via the response object from a WCF service.

Working with NAudio package, so far what I have working is using MediaFoundationEncoder.EncodetoMp3() to write to a file.  But once that file is written out to the response, though, it's useless.  I would like to just skip the file writing step and output to a stream or byte array and write that to the response object.

Is there a way to get MediaFoundationEncoder to output an mp3 in some kind of memory object (without a file)?

Alternatively, trying to use the LameMP3FileWriter, which does write to streams,
I can send the IEEE float wav input directly to LameMP3FileWriter but the resulting mp3 stream sounds like a loud hiss seemingly regardless of the output format I use (44100,16,1), (22050,16,1), (11025,16,1),...

When I try to convert the IEEE float source to a PCM or upsample it using WaveFormatConversion, it errors out with

AcmNotPossible calling acmStreamOpen

if I use Wave32to16Stream on the IEEE float source, it does not error but there is no audio.  This chain is not working for me:

    byte[] bytes = (Byte[])dt.Rows[0]["AudioContent"];//this is the dataTable from the database query containing the WAV audio

    var ms = new MemoryStream(bytes);
    var OLDfmt = WaveFormat.CreateIeeeFloatWaveFormat(16000,1);
    var NEWfmt = new WaveFormat(16000, 16, 1);//tried many
    var readr = new RawSourceWaveStream(ms,OLDfmt);

    //the following line errors on 'AcmNotPossible calling acmStreamOpen'
    //var wav16 = new WaveFormatConversionStream(NEWfmt, readr);

    //the following does not error but no mp3 streams out at the end
    var wav16 = new Wave32To16Stream(readr);

    var outptMP3 = new MemoryStream();
    var writr = new LameMP3FileWriter(outptMP3, NEWfmt, LAMEPreset.STANDARD);
    wav16.CopyTo(writr);
    HttpContext.Current.Response.BufferOutput = true;
    HttpContext.Current.Response.AddHeader("Content-Type", "audio/mpeg");
    HttpContext.Current.Response.BinaryWrite(outptMP3.ToArray());

The raw audio plays fine in Chrome (as a WAV stream) if I just do a BinaryWrite of the ms MemoryStream, so I think the IEEE float source data is valid.

Correct me if wrong, but that error (AcmNotPossible) appears to mean there is no ACM codec on my machine for the IEEE float format?  I query my machine and there appear to be no 32-bit ACM codecs, which is why I'm trying the Wave32To16Stream conversion.

Is there an interim step of the Lame MP3 pipeline to go from IEEE float 32-bit to mp3?

Body:
Sorry there were so many sub-questions to my main question about transcoding a IEEE float 32-bit wave to an mp3 stream, but I can at least tell you how I got it to work using ACM codecs (I think) on my simple WCF service:

change the return type on the service to a Stream

set the MemoryStream position to 0 before returning

Otherwise the chain above actually does work for me.  I will give the complete code, with all the extraneous SQL stuff, for the sake of completeness and because I found the answer in an unrelated SO issue:

public Stream playWAVEFileFromDB() {
        //if using the file output method, I change the return type to string and return text instead of streams
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "SELECT theWAVEColumn FROM myTable WHERE allThoseAudiosAreStored";
            SqlDataAdapter sda = new SqlDataAdapter();
            DataTable dt = new DataTable();

            conn.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);

            //read the raw audio from database into a byte array
            byte[] bytes = (Byte[])dt.Rows[0]["colName"];
            var ms = new MemoryStream(bytes);
            var NEWfmt = new WaveFormat(16000, 16, 1);
            var OLDfmt = WaveFormat.CreateIeeeFloatWaveFormat(16000,1);//how its stored
            var readr = new RawSourceWaveStream(ms,OLDfmt);
            var wav16 = new Wave32To16Stream(readr);
            var outptMP3 = new MemoryStream();
            var writr = new LameMP3FileWriter(outptMP3, NEWfmt, LAMEPreset.STANDARD);
            wav16.CopyTo(writr);
            outptMP3.Position = 0;

            HttpContext.Current.Response.BufferOutput = true;
            HttpContext.Current.Response.AddHeader("Content-Type", "audio/mpeg");

            conn.Close();
            conn.Dispose();
            sda.Dispose();

            return outptMP3;
        }
            catch (Exception e)
        {
            //do the error logging stuff
            return Stream.Null;
        }
    }


问:
Index was outside the bounds of the array
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

```<code> Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub
</code>```

答: try If aryTemp(aryTemp.Length - 1) < aryTemp2(aryTemp2.Length - 1) Then but it does follow the assumption that last names can't have spaces.  If this is not the case then the code could be built out more to handle that situation.

ContentLicense: CC BY-SA 2.5

Body:
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

 Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub


问:
deepstream list subscribing to data
is it possible in deepstream to subscribe to data using a list?  it appears that changes to the data does not trip the subscribe() function, only something like an addEntry() appears to affect the list subscription.

```<code>const   deepstream      = require('deepstream.io-client-js')            ;
const   util            = require('util')                               ;

const   client  = deepstream('localhost:6020').login();

var obj_1       =       { 'sequelizeName':'Mark', 'sequelizeAddr':'123 Elm Lane'    , 'sequelizeId':'1111'};
var obj_2       =       { 'sequelizeName':'Lori', 'sequelizeAddr':'948 Maple Street'    , 'sequelizeId':'2222'};

const rec_1     = client.record.getRecord('obj_one');
const rec_2     = client.record.getRecord('obj_two');

rec_1.set(obj_1);
rec_2.set(obj_2);

var listTest    =       client.record.getList('listTest');

listTest.setEntries(    ['obj_one' ,'obj_two' ] );

listTest.subscribe( (result) => {
        console.log('LIST SUBSCRIBE: ' + util.inspect(result));
})

setTimeout( () =>       {
        obj_1.sequelizeAddr = '321 New Address';
        rec_1.set(obj_1); // how can this change show up in the list subscribe?
}, 2000 );
</code>```

I have been encouraged to try a new approach using lists, but I am unclear how to subscribe to changes in the data itself using a list, except to somehow have some sort of "generic" or "global" subscribe, which i am not sure is even possible.

Or is there some way I can subscribe using an anonymous record?

答:
this suggestion was made by both wolfram and phillipp:

```<code>class User{
    constructor( recordName ) {
        this.record = ds.record.getRecord( recordName );
        this.record.subscribe( this._processUpdate.bind( this ) );
    }

    _processUpdate( data ) {
        if( this.record.name === '...') {
            // do stuff
        }
    }
}
</code>```

this works great.  thank you both.

Title: deepstream list subscribing to data

Body:
is it possible in deepstream to subscribe to data using a list?  it appears that changes to the data does not trip the subscribe() function, only something like an addEntry() appears to affect the list subscription.

const   deepstream      = require('deepstream.io-client-js')            ;
const   util            = require('util')                               ;

const   client  = deepstream('localhost:6020').login();

var obj_1       =       { 'sequelizeName':'Mark', 'sequelizeAddr':'123 Elm Lane'    , 'sequelizeId':'1111'};
var obj_2       =       { 'sequelizeName':'Lori', 'sequelizeAddr':'948 Maple Street'    , 'sequelizeId':'2222'};

const rec_1     = client.record.getRecord('obj_one');
const rec_2     = client.record.getRecord('obj_two');

rec_1.set(obj_1);
rec_2.set(obj_2);

var listTest    =       client.record.getList('listTest');

listTest.setEntries(    ['obj_one' ,'obj_two' ] );

listTest.subscribe( (result) => {
        console.log('LIST SUBSCRIBE: ' + util.inspect(result));
})

setTimeout( () =>       {
        obj_1.sequelizeAddr = '321 New Address';
        rec_1.set(obj_1); // how can this change show up in the list subscribe?
}, 2000 );

I have been encouraged to try a new approach using lists, but I am unclear how to subscribe to changes in the data itself using a list, except to somehow have some sort of "generic" or "global" subscribe, which i am not sure is even possible.

Or is there some way I can subscribe using an anonymous record?

Body:
this suggestion was made by both wolfram and phillipp:

class User{
    constructor( recordName ) {
        this.record = ds.record.getRecord( recordName );
        this.record.subscribe( this._processUpdate.bind( this ) );
    }

    _processUpdate( data ) {
        if( this.record.name === '...') {
            // do stuff
        }
    }
}

this works great.  thank you both.


问:
Android: how to determine new size of a view
I have a LinearLayout (vertical) with two child views in it. The 1st one is a ScrollView and the 2nd one is another layout with Visibility.GONE, its size is not fixed (determined by its children).

```<code><LinearLayout vertical>

    <ScrollView> ... </ScrollView>

    <AnotherLayout visibility=GONE height=wrap_content> ... </AnotherLayout>

</LinearLayout>
</code>```

At some point of time I want to show AnotherLayout. But, once it pops up, I also want to adjust the scrolling of my ScollView one. For this, I need to know the size of this AnotherLayout.

I'm doing something like that:

```<code>int oldHeight = scrollArea.getHeight();
linearLayout.setVisibility(VISIBLE);
int newHeight = scrollArea.getHeight();
</code>```

But oldHeight and newHeight are still the same.

How can I calculate the new height?

答:
The two dimensions are the same because visibility change took time and the line of code was run before that so it returns the same.
You can use a visibility listener to calculate the dimension after visibility change , You may use that </p>

```<code>    linearLayout.setTag(linearLayout.getVisibility());
    linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int newVis = linearLayout.getVisibility();
            if((int)linearLayout.getTag() != newVis)
            {
                linearLayout.setTag(linearLayout.getVisibility());
                //visibility has changed
                int newHeight = scrollArea.getHeight();
            }
        }
    });
</code>```

Body:
I have a LinearLayout (vertical) with two child views in it. The 1st one is a ScrollView and the 2nd one is another layout with Visibility.GONE, its size is not fixed (determined by its children).

<LinearLayout vertical>

    <ScrollView> ... </ScrollView>

    <AnotherLayout visibility=GONE height=wrap_content> ... </AnotherLayout>

</LinearLayout>

At some point of time I want to show AnotherLayout. But, once it pops up, I also want to adjust the scrolling of my ScollView one. For this, I need to know the size of this AnotherLayout.

I'm doing something like that:

int oldHeight = scrollArea.getHeight();
linearLayout.setVisibility(VISIBLE);
int newHeight = scrollArea.getHeight();

But oldHeight and newHeight are still the same.

How can I calculate the new height?

Body:
The two dimensions are the same because visibility change took time and the line of code was run before that so it returns the same.
You can use a visibility listener to calculate the dimension after visibility change , You may use that

    linearLayout.setTag(linearLayout.getVisibility());
    linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int newVis = linearLayout.getVisibility();
            if((int)linearLayout.getTag() != newVis)
            {
                linearLayout.setTag(linearLayout.getVisibility());
                //visibility has changed
                int newHeight = scrollArea.getHeight();
            }
        }
    });


问:
VBA type mismatch error when deleting pictures
Trying to delete all pictures in a range.
I found the below code online but its throwing a type mismatch error on row:

```<code>For Each pic In ws.Pictures
</code>```

Any input or alternative code is much appreciated.

```<code>Sub clearPics()
Dim s As String
Dim pic As Picture
Dim rng As Range

Set ws = Worksheets("sort")
Set rng = ws.Range("c:c")

For Each pic In ws.Pictures
    With pic
        s = .TopLeftCell.Address & ":" & .BottomRightCell.Address
    End With
    If Not Intersect(rng, ws.Range(s)) Is Nothing Then
        pic.Delete
    End If
Next

End Sub
</code>```

Thanks,
jj

答:
The below code deletes only pictures in the sheet.
By checking Shape.Type = 11 for pictures.</p>

```<code>Sub clearPics()
Dim shp As Shape

    For Each shp In Worksheets("sort").Shapes

        If shp.Type = 11 Then
                shp.Delete
        End If

    Next shp
End Sub
</code>```

Body:
Trying to delete all pictures in a range.
I found the below code online but its throwing a type mismatch error on row:

For Each pic In ws.Pictures

Any input or alternative code is much appreciated.

Sub clearPics()
Dim s As String
Dim pic As Picture
Dim rng As Range

Set ws = Worksheets("sort")
Set rng = ws.Range("c:c")

For Each pic In ws.Pictures
    With pic
        s = .TopLeftCell.Address & ":" & .BottomRightCell.Address
    End With
    If Not Intersect(rng, ws.Range(s)) Is Nothing Then
        pic.Delete
    End If
Next

End Sub

Thanks,
jj

Body:
The below code deletes only pictures in the sheet.
By checking Shape.Type = 11 for pictures.

Sub clearPics()
Dim shp As Shape

    For Each shp In Worksheets("sort").Shapes

        If shp.Type = 11 Then
                shp.Delete
        End If

    Next shp
End Sub


问:
ghostscript or python : how to combine pdf of different page sizes into a pdf of same page sizes?
I searched the stackoverflow for the problem. The nearest link is:

How to set custom page size with Ghostscript

How to convert multiple, different-sized PostScript files to a single PDF?

But this could NOT solve my problem.

The question is plain simple.

How can we combine multiple pdf (with different page sizes) into a combined pdf which have all the pages of same size.

Example:

two input pdfs are:

hw1.pdf with single page of size 5.43x3.26 inch (found from adobe reader)

hw6.pdf with single page of size 5.43x6.51 inch

The pdfs can be found here:

https://github.com/bhishanpdl/Questions

The code is:

```<code>gs -sDEVICE=pdfwrite -r720 -g2347x3909 -dPDFFitPage -o homeworks.pdf hw1.pdf hw6.pdf
</code>```

PROBLEM: First pdf is portrait, and second page is landscape.

QUESTION: How can we make both pages portrait ?

NOTE:

-r720 is pixels/inch.

 The size -g2347x3909 is found using python script:

```<code>wd = int(np.floor(720 * 5.43))
ht = int(np.floor(720 * 3.26))

gsize = '-g' + str(ht) + 'x' + str(wd) + ' '
# this gives:  gsize = -g4308x6066
</code>```

Another Attempt

```<code>commands = 'gs -o homeworks.pdf -sDEVICE=pdfwrite -dDEVICEWIDTHPOINTS=674 ' +\
               ' -dDEVICEHEIGHTPOINTS=912 -dPDFFitPage ' +\
               'hw1.pdf hw6.pdf'
subprocess.call(commands, shell=1)
</code>```

This gives first both pages portrait, but they do not have the same size.

First page is smaller is size, and second is full when I open the output in adobe reader.

In general, how can we make size of all the pages same?

答:
You have tagged this question "ghostscript" but I assume by your use of subprocess.call() that you are not averse to using Python.

The pagemerge canvas of the pdfrw Python library can do this.  There are some examples of dealing with different sized pages in the examples directory and at the source of pagemerge.py.  The fancy_watermark.py shows an example of dealing with different page sizes, in the context of applying watermarks.

pdfrw can rotate, scale, or simply position source pages on the output.  If you want rotation or scaling, you can look in the examples directory.  (Since this is for homework, for extra credit you can control the scaling and rotation by looking at the various page sizes. :)  But if all you want is the second page to be extended to be as long as the first, you could do that with this bit of code:

```<code>from pdfrw import PdfReader, PdfWriter, PageMerge

pages = PdfReader('hw1.pdf').pages + PdfReader('hw6.pdf').pages
output = PdfWriter()

rects = [[float(num) for num in page.MediaBox] for page in pages]
height = max(x[3] - x[1] for x in rects)
width = max(x[2] - x[0] for x in rects)

mbox = [0, 0, width, height]

for page in pages:
    newpage = PageMerge()
    newpage.mbox = mbox              # Set boundaries of output page
    newpage.add(page)                # Add one old page to new page
    image = newpage[0]               # Get image of old page (first item)
    image.x = (width - image.w) / 2  # Center old page left/right
    image.y = (height - image.h)     # Move old page to top of output page
    output.addpage(newpage.render())

output.write('homeworks.pdf')
</code>```

(Disclaimer:  I am the primary pdfrw author.)

Body:
I searched the stackoverflow for the problem. The nearest link is:

How to set custom page size with Ghostscript

How to convert multiple, different-sized PostScript files to a single PDF?

But this could NOT solve my problem.

The question is plain simple.

How can we combine multiple pdf (with different page sizes) into a combined pdf which have all the pages of same size.

Example:

two input pdfs are:

hw1.pdf with single page of size 5.43x3.26 inch (found from adobe reader)

hw6.pdf with single page of size 5.43x6.51 inch

The pdfs can be found here:

https://github.com/bhishanpdl/Questions

The code is:

gs -sDEVICE=pdfwrite -r720 -g2347x3909 -dPDFFitPage -o homeworks.pdf hw1.pdf hw6.pdf

PROBLEM: First pdf is portrait, and second page is landscape.

QUESTION: How can we make both pages portrait ?

NOTE:

-r720 is pixels/inch.

 The size -g2347x3909 is found using python script:

wd = int(np.floor(720 * 5.43))
ht = int(np.floor(720 * 3.26))

gsize = '-g' + str(ht) + 'x' + str(wd) + ' '
# this gives:  gsize = -g4308x6066

Another Attempt

commands = 'gs -o homeworks.pdf -sDEVICE=pdfwrite -dDEVICEWIDTHPOINTS=674 ' +\
               ' -dDEVICEHEIGHTPOINTS=912 -dPDFFitPage ' +\
               'hw1.pdf hw6.pdf'
subprocess.call(commands, shell=1)

This gives first both pages portrait, but they do not have the same size.

First page is smaller is size, and second is full when I open the output in adobe reader.

In general, how can we make size of all the pages same?

Body:
You have tagged this question "ghostscript" but I assume by your use of subprocess.call() that you are not averse to using Python.

The pagemerge canvas of the pdfrw Python library can do this.  There are some examples of dealing with different sized pages in the examples directory and at the source of pagemerge.py.  The fancy_watermark.py shows an example of dealing with different page sizes, in the context of applying watermarks.

pdfrw can rotate, scale, or simply position source pages on the output.  If you want rotation or scaling, you can look in the examples directory.  (Since this is for homework, for extra credit you can control the scaling and rotation by looking at the various page sizes. :)  But if all you want is the second page to be extended to be as long as the first, you could do that with this bit of code:

from pdfrw import PdfReader, PdfWriter, PageMerge

pages = PdfReader('hw1.pdf').pages + PdfReader('hw6.pdf').pages
output = PdfWriter()

rects = [[float(num) for num in page.MediaBox] for page in pages]
height = max(x[3] - x[1] for x in rects)
width = max(x[2] - x[0] for x in rects)

mbox = [0, 0, width, height]

for page in pages:
    newpage = PageMerge()
    newpage.mbox = mbox              # Set boundaries of output page
    newpage.add(page)                # Add one old page to new page
    image = newpage[0]               # Get image of old page (first item)
    image.x = (width - image.w) / 2  # Center old page left/right
    image.y = (height - image.h)     # Move old page to top of output page
    output.addpage(newpage.render())

output.write('homeworks.pdf')

(Disclaimer:  I am the primary pdfrw author.)


问:
Why adding association mark my model as not valid?
I'm developing a simple weather API in Rails. This API will give the forecast for a given day. The forecast will have hourly data about the wind, temperature, relative humidity, etc.

I have implemented a model for the Forecast. The forecast have an association "has_many" with the other models, for example, the Wind. I have developed the following model for the Wind object:

```<code>class Wind < ApplicationRecord
  belongs_to :forecast, foreign_key: true
  validates_presence_of :period
  validates :velocity, numericality: true, allow_blank: true
  validates :direction, length: { maximum: 2 }, allow_blank: true
end
</code>```

As I am trying to use TDD, I have implemented the following tests (among others):

```<code>class WindTest < ActiveSupport::TestCase
  setup do
    @valid_wind = create_valid_wind
    @not_valid_wind = create_not_valid_wind
  end

  test 'valid_wind is valid' do
    assert @valid_wind.valid?
  end

  test 'valid_wind can be persisted' do
    assert @valid_wind.save
    assert @valid_wind.persisted?
  end

  test 'not_valid_wind is not valid' do
    assert_not @not_valid_wind.valid?
  end

  test 'not valid wind cannot be persisted' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.persisted?
  end

  test 'not_valid_wind has error messages for period' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:period].empty?
  end

  test 'not_valid_wind has error messages for velocity' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:velocity].empty?
  end

  test 'not_valid_wind has error messages for direction' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:direction].empty?
  end

  private

  def create_valid_wind
    valid_wind = Wind.new
    valid_wind.direction = 'NO'
    valid_wind.velocity = 2
    valid_wind.period = '00-06'
    valid_wind.forecast_id = forecasts(:one).id
    valid_wind
  end

  def create_not_valid_wind
    not_valid_wind = Wind.new
    not_valid_wind.velocity = 'testNumber'
    not_valid_wind.direction = '123'
    not_valid_wind
  end
end
</code>```

This bunch of tests was passing before I add the association with forecast:

```<code>belongs_to :forecast, foreign_key: true
</code>```

Indeed, if I remove that line, any test fails. But with that line in the model, the following tests are failing (they are false and the test expects true):

```<code>  test 'valid_wind is valid' do
    assert @valid_wind.valid?
  end

  test 'valid_wind can be persisted' do
    assert @valid_wind.save
    assert @valid_wind.persisted?
  end
</code>```

I am trying to understand why this is happening. Anyone knows why those tests are failing? Also, is there any proper way to test associations?

Thank you in advance.

答:
```<code>test 'valid_wind can be persisted' do
  assert @valid_wind.save
  assert @valid_wind.persisted?
end
</code>```

This test is close to worthless since you are only testing that the test setup is correct, it tells you nothing about the application under test.

Instead in your model tests you should test on a per validation basis:

```<code>test 'does not allow non numerical values for velocity' do
  wind = Wind.new(velocity: 'foo')
  wind.valid?
  assert_match "is not a number", wind.errors.full_messages_for(:velocity)
end

test 'allows numerical values for velocity' do
  wind = Wind.new(velocity: 3)
  wind.valid?
  refute(wind.errors.include?(:velocity))
end
</code>```

Testing passing values is usually just marginally useful but can be valuable if bugs occur.

In your models you don't really need to worry about setting up completely valid records - your functional and integration tests will cover that anyways.

Body:
I'm developing a simple weather API in Rails. This API will give the forecast for a given day. The forecast will have hourly data about the wind, temperature, relative humidity, etc.

I have implemented a model for the Forecast. The forecast have an association "has_many" with the other models, for example, the Wind. I have developed the following model for the Wind object:

class Wind < ApplicationRecord
  belongs_to :forecast, foreign_key: true
  validates_presence_of :period
  validates :velocity, numericality: true, allow_blank: true
  validates :direction, length: { maximum: 2 }, allow_blank: true
end

As I am trying to use TDD, I have implemented the following tests (among others):

class WindTest < ActiveSupport::TestCase
  setup do
    @valid_wind = create_valid_wind
    @not_valid_wind = create_not_valid_wind
  end

  test 'valid_wind is valid' do
    assert @valid_wind.valid?
  end

  test 'valid_wind can be persisted' do
    assert @valid_wind.save
    assert @valid_wind.persisted?
  end

  test 'not_valid_wind is not valid' do
    assert_not @not_valid_wind.valid?
  end

  test 'not valid wind cannot be persisted' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.persisted?
  end

  test 'not_valid_wind has error messages for period' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:period].empty?
  end

  test 'not_valid_wind has error messages for velocity' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:velocity].empty?
  end

  test 'not_valid_wind has error messages for direction' do
    assert_not @not_valid_wind.save
    assert_not @not_valid_wind.errors.messages[:direction].empty?
  end

  private

  def create_valid_wind
    valid_wind = Wind.new
    valid_wind.direction = 'NO'
    valid_wind.velocity = 2
    valid_wind.period = '00-06'
    valid_wind.forecast_id = forecasts(:one).id
    valid_wind
  end

  def create_not_valid_wind
    not_valid_wind = Wind.new
    not_valid_wind.velocity = 'testNumber'
    not_valid_wind.direction = '123'
    not_valid_wind
  end
end

This bunch of tests was passing before I add the association with forecast:

belongs_to :forecast, foreign_key: true

Indeed, if I remove that line, any test fails. But with that line in the model, the following tests are failing (they are false and the test expects true):

  test 'valid_wind is valid' do
    assert @valid_wind.valid?
  end

  test 'valid_wind can be persisted' do
    assert @valid_wind.save
    assert @valid_wind.persisted?
  end

I am trying to understand why this is happening. Anyone knows why those tests are failing? Also, is there any proper way to test associations?

Thank you in advance.

Body:
test 'valid_wind can be persisted' do
  assert @valid_wind.save
  assert @valid_wind.persisted?
end

This test is close to worthless since you are only testing that the test setup is correct, it tells you nothing about the application under test.

Instead in your model tests you should test on a per validation basis:

test 'does not allow non numerical values for velocity' do
  wind = Wind.new(velocity: 'foo')
  wind.valid?
  assert_match "is not a number", wind.errors.full_messages_for(:velocity)
end

test 'allows numerical values for velocity' do
  wind = Wind.new(velocity: 3)
  wind.valid?
  refute(wind.errors.include?(:velocity))
end

Testing passing values is usually just marginally useful but can be valuable if bugs occur.

In your models you don't really need to worry about setting up completely valid records - your functional and integration tests will cover that anyways.


问:
How to override php cli configuration with custom php.ini
I'm struggling to override the php cli configuration with my custom php.ini

My custom php.ini

```<code>max_execution_time = 90
memory_limit = 256M
safe_mode = Off
</code>```

Running php cli

```<code>php -c /home/env/php.ini -r 'phpinfo();' | grep 'memory_limit'
</code>```

outputs

```<code>memory_limit => 256M => 256M
</code>```

However the custom php.ini doesn't seem to override max_execution_time nor safe_mode as it outputs 0 and On rather than 90 and Off.

Running this simple script

```<code>#!/usr/bin/php -c /home/env/php.ini
<?php echo 'memory_limit: ' . ini_get('memory_limit');
</code>```

outputs the default cli configuration (128M) rather than 256M as expected.

Running this simple script

```<code>#!/usr/bin/php -d max_execution_time=90
<?php echo 'max_execution_time: ' . ini_get('max_execution_time');
</code>```

outputs 90 as expected.

So far I've managed to override only one single configuration directive at runtime, so any help much appreciated how to override multiple configuration directives.

Edit:

```<code>php -a
php > parse_ini_file('/home/env/php.ini');
</code>```

outputs no errors, so I guess my custom php.ini is ok. I'd though just discover that executing

```<code>#!/usr/bin/php -c /home/env/php.ini
<?php echo 'memory_limit: ' . ini_get('memory_limit'); phpinfo();
</code>```

says Loaded Configuration File => (none). That seems to be the issue. PHP CLI doesn't seem to load my custom php.ini file even though the path is correct and syntax seems fine too.

Solution:

It doesn't seem possible to override multiple configuration directive at runtime with shebang, at least for me. But removing shebang and executing the following command solved the issue for me.

```<code>php -d max_execution_time=90 -d memory_limit=256M -d safe_mode=Off -f test.php
</code>```

答:
I was trying to set max_execution_time by CLI too and I was unable to do it.

From documentation I understand it is hard-coded and cannot be changed in CLI enviroment.

Anyway, I found the timeout command useful :

```<code>timeout 60 php -d memory_limit=1024M script.php
</code>```

(run script for 60 seconds max).

Body:
I'm struggling to override the php cli configuration with my custom php.ini

My custom php.ini

max_execution_time = 90
memory_limit = 256M
safe_mode = Off

Running php cli

php -c /home/env/php.ini -r 'phpinfo();' | grep 'memory_limit'

outputs

memory_limit => 256M => 256M

However the custom php.ini doesn't seem to override max_execution_time nor safe_mode as it outputs 0 and On rather than 90 and Off.

Running this simple script

#!/usr/bin/php -c /home/env/php.ini
<?php echo 'memory_limit: ' . ini_get('memory_limit');

outputs the default cli configuration (128M) rather than 256M as expected.

Running this simple script

#!/usr/bin/php -d max_execution_time=90
<?php echo 'max_execution_time: ' . ini_get('max_execution_time');

outputs 90 as expected.

So far I've managed to override only one single configuration directive at runtime, so any help much appreciated how to override multiple configuration directives.

Edit:

php -a
php > parse_ini_file('/home/env/php.ini');

outputs no errors, so I guess my custom php.ini is ok. I'd though just discover that executing

#!/usr/bin/php -c /home/env/php.ini
<?php echo 'memory_limit: ' . ini_get('memory_limit'); phpinfo();

says Loaded Configuration File => (none). That seems to be the issue. PHP CLI doesn't seem to load my custom php.ini file even though the path is correct and syntax seems fine too.

Solution:

It doesn't seem possible to override multiple configuration directive at runtime with shebang, at least for me. But removing shebang and executing the following command solved the issue for me.

php -d max_execution_time=90 -d memory_limit=256M -d safe_mode=Off -f test.php

Body:
I was trying to set max_execution_time by CLI too and I was unable to do it.

From documentation I understand it is hard-coded and cannot be changed in CLI enviroment.

Anyway, I found the timeout command useful :

timeout 60 php -d memory_limit=1024M script.php

(run script for 60 seconds max).


问:
Xamarin.Android 7.0 Build Errors
I am trying to update an older Xamarin.Android codebase. I was using a pre-API 21 target and now trying to update to API 24 (Android Nuget). I think I have resolved the majority of the compatibility issues, but one is troubling me. When I do a build I get the following error.

```<code>/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets: Error: Tool exited with code: 10. Output: Error: Can't read [/Library/Frameworks/Xamarin.Android.framework/Versions/7.0.2-37/lib/xbuild-frameworks/MonoAndroid/v7.0/mono.android.jar] (Can't process class [android/app/ActivityTracker.class] (Unsupported class version number [52.0] (maximum 51.0, Java 1.7)))
</code>```

After doing some Google searching I found that the majority of people who are having this issue are using Java 1.8, as am I. Apparently, the bundled version of ProGuard does not support Java 1.8 byte code. I have manually installed the latest version of ProGuard (5.3.1) over the packaged version in the folder below.

```<code>~/Library/Android/sdk/tools/proguard
</code>```

Unfortunately I am still having the same error. I am also using the latest version of the following packages (see screenshot).

Does anyone have any idea how to resolve this build issue?

答:
Just download the latest version of proguard from the this link;

Unzip the content to a folder called proguard;

Replace the folder ~/Library/Developer/Xamarin/android-sdk-macosx/tools/proguard with the folder from the previous step.

Title: Xamarin.Android 7.0 Build Errors

Body:
I am trying to update an older Xamarin.Android codebase. I was using a pre-API 21 target and now trying to update to API 24 (Android Nuget). I think I have resolved the majority of the compatibility issues, but one is troubling me. When I do a build I get the following error.

/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets: Error: Tool exited with code: 10. Output: Error: Can't read [/Library/Frameworks/Xamarin.Android.framework/Versions/7.0.2-37/lib/xbuild-frameworks/MonoAndroid/v7.0/mono.android.jar] (Can't process class [android/app/ActivityTracker.class] (Unsupported class version number [52.0] (maximum 51.0, Java 1.7)))

After doing some Google searching I found that the majority of people who are having this issue are using Java 1.8, as am I. Apparently, the bundled version of ProGuard does not support Java 1.8 byte code. I have manually installed the latest version of ProGuard (5.3.1) over the packaged version in the folder below.

~/Library/Android/sdk/tools/proguard

Unfortunately I am still having the same error. I am also using the latest version of the following packages (see screenshot).

Does anyone have any idea how to resolve this build issue?


问:
Cloud Function for Firebase Type Error - Cannot Read Property
I'm trying to write a Cloud Function that creates a record whenever someone uses our legacy app to create a record (we have changed the Firebase backend architecture and want to slowly migrate users). However, I'm getting the following error in my logs:

```<code>TypeError: Cannot read property 'update' of undefined
    at exports.makeNewComment.functions.database.ref.onWrite.event (/user_code/index.js:14:92)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)
</code>```

Here is the script in question:

```<code>//required modules
var functions = require('firebase-functions');
const admin = require('firebase-admin');

// Listens for new comments added to /comments/ and adds it to /post-comments/

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const commentId = event.params.commentId;
  const comment = event.data.val();
  // You must return a Promise when performing asynchronous tasks inside a Functions such as
  // writing to the Firebase Realtime Database.
  //return event.data.ref.parent.child('post-comments').set(comment);
  return functions.database.ref('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return functions.database.ref('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

//initialize
admin.initializeApp(functions.config().firebase);
</code>```

Thanks!

答:
You can't use functions.database.ref() in the middle of a function to get a ref to somewhere in your database.  That's only for defining a new Cloud Function.

If you want a ref to somewhere in your database, you can use event.data.ref or event.data.adminRef to get a ref to the location where the event triggered.  You could then use the root property of that to rebuild a new ref to somewhere else in the database.  Or you can use your admin object to build a new ref.

It might be helpful to look at some sample code to get a sense of how things work.

Body:
I'm trying to write a Cloud Function that creates a record whenever someone uses our legacy app to create a record (we have changed the Firebase backend architecture and want to slowly migrate users). However, I'm getting the following error in my logs:

TypeError: Cannot read property 'update' of undefined
    at exports.makeNewComment.functions.database.ref.onWrite.event (/user_code/index.js:14:92)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Here is the script in question:

//required modules
var functions = require('firebase-functions');
const admin = require('firebase-admin');

// Listens for new comments added to /comments/ and adds it to /post-comments/

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const commentId = event.params.commentId;
  const comment = event.data.val();
  // You must return a Promise when performing asynchronous tasks inside a Functions such as
  // writing to the Firebase Realtime Database.
  //return event.data.ref.parent.child('post-comments').set(comment);
  return functions.database.ref('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return functions.database.ref('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

//initialize
admin.initializeApp(functions.config().firebase);

Thanks!


问:
JQuery .center is not a function
I am working on JQuery. I am getting this error. I ma trying to find out the root cause but i am not able to find it. If any one can help me out that would be really great.

JS ERROR:

```<code>Uncaught TypeError: $(...).center is not a function
at HTMLDivElement.<anonymous> (myjs:879)
at HTMLDivElement.opt.complete (jquery-1.8.3.js:9154)
at fire (jquery-1.8.3.js:974)
at Object.add [as done] (jquery-1.8.3.js:1020)
at Animation (jquery-1.8.3.js:8719)
at HTMLDivElement.doAnimation (jquery-1.8.3.js:9034)
at Function.dequeue (jquery-1.8.3.js:1895)
at HTMLDivElement.<anonymous> (jquery-1.8.3.js:1938)
at Function.each (jquery-1.8.3.js:611)
at init.each (jquery-1.8.3.js:241)
</code>```

My Script:

```<code>function centerdiv() {
    $('#id').show(0, function () {
         $('#id1').css('z-index','5');
        $('body').css('overflow', 'hidden');
        $('.class').center();
    });
}
</code>```

All JQuery functions are working and i am not sure why it is stating .center as not a function.

答:
The error means $.center() is not a jQuery method you can use. Instead of trying to call a method that doesn't exist, you have to change the CSS to center something. For example:

Centering a div vertically & horizontally using jQuery

You can create your own center method, but you cannot just call $.center() because it doesn't exist.

Title: JQuery .center is not a function

Body:
I am working on JQuery. I am getting this error. I ma trying to find out the root cause but i am not able to find it. If any one can help me out that would be really great.

JS ERROR:

Uncaught TypeError: $(...).center is not a function
at HTMLDivElement.<anonymous> (myjs:879)
at HTMLDivElement.opt.complete (jquery-1.8.3.js:9154)
at fire (jquery-1.8.3.js:974)
at Object.add [as done] (jquery-1.8.3.js:1020)
at Animation (jquery-1.8.3.js:8719)
at HTMLDivElement.doAnimation (jquery-1.8.3.js:9034)
at Function.dequeue (jquery-1.8.3.js:1895)
at HTMLDivElement.<anonymous> (jquery-1.8.3.js:1938)
at Function.each (jquery-1.8.3.js:611)
at init.each (jquery-1.8.3.js:241)

My Script:

function centerdiv() {
    $('#id').show(0, function () {
         $('#id1').css('z-index','5');
        $('body').css('overflow', 'hidden');
        $('.class').center();
    });
}

All JQuery functions are working and i am not sure why it is stating .center as not a function.


问:
How to add circle on click event in JavaScript?
Could you tell me how to add circle on click event in JavaScript? Actually, I want to achieve that if user click anywhere in div element, it add circle at that position. Currently, it added anywhere not added in correct position. It should be added where user clicks.

This is my code.

```<code>$(function(){
  $('#fx').click(function(e){
    var circle=$('<div class="circle"></div>');
    circle.css('top',e.pageX);
    circle.css('left',e.pageX);
    $('#fx').append(circle);
  });
});
</code>```

答:
If you want the circle to start exactly at the point where you clicked, the top is supposed to be e.pageY.

Then you will have to negate (r) to point it to the origin. As the radius for the circle is 15px, it translates to

```<code>circle.css('top',e.pageY - 15);
circle.css('left',e.pageX - 15)
</code>```

plunker

Body:
Could you tell me how to add circle on click event in JavaScript? Actually, I want to achieve that if user click anywhere in div element, it add circle at that position. Currently, it added anywhere not added in correct position. It should be added where user clicks.

This is my code.

$(function(){
  $('#fx').click(function(e){
    var circle=$('

');
    circle.css('top',e.pageX);
    circle.css('left',e.pageX);
    $('#fx').append(circle);
  });
});

Body:
If you want the circle to start exactly at the point where you clicked, the top is supposed to be e.pageY.

Then you will have to negate (r) to point it to the origin. As the radius for the circle is 15px, it translates to

circle.css('top',e.pageY - 15);
circle.css('left',e.pageX - 15)

plunker


问:
How do I make a true default route for a MVC CORE project?
I have the following setup for my HomeController. I want all my MVC controllers to respond from /mvc/[controler]/[action] and the WebApi ones on /api/

But when someone goes to the no-path version of the host, I want it to go to /mvc/home/index, my setup doesn't seem to do that!

I want http://hostname/ to got to http:/hostname/Home/Index

```<code>    [Route("mvc/[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class HomeController : Controller
{
    [Route("Index")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("Error")]
    public IActionResult Error()
    {
        return View();
    }
}
</code>```

my startup.cs:

```<code>      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseMiddleware(typeof(ErrorHandlingMiddleware));
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                "default",
                "mvc/{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            var swaggerendpoint = Configuration["SwaggerEndpoint"];
            c.SwaggerEndpoint(swaggerendpoint, "Public Cloud Interface");
        });
    }
}
</code>```

答:
Add a route specifically for the / case:

```<code>app.UseMvc(routes =>
    {
        routes.MapRoute(
            "home",
            "/",
            new{controller="Home", Action="Index"});

        routes.MapRoute(
            "default",
            "mvc/{controller=Home}/{action=Index}/{id?}");
    });
</code>```

Body:
I have the following setup for my HomeController. I want all my MVC controllers to respond from /mvc/[controler]/[action] and the WebApi ones on /api/

But when someone goes to the no-path version of the host, I want it to go to /mvc/home/index, my setup doesn't seem to do that!

I want http://hostname/ to got to http:/hostname/Home/Index

    [Route("mvc/[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class HomeController : Controller
{
    [Route("Index")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("Error")]
    public IActionResult Error()
    {
        return View();
    }
}

my startup.cs:

      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseMiddleware(typeof(ErrorHandlingMiddleware));
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                "default",
                "mvc/{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            var swaggerendpoint = Configuration["SwaggerEndpoint"];
            c.SwaggerEndpoint(swaggerendpoint, "Public Cloud Interface");
        });
    }
}

Body:
Add a route specifically for the / case:

app.UseMvc(routes =>
    {
        routes.MapRoute(
            "home",
            "/",
            new{controller="Home", Action="Index"});

        routes.MapRoute(
            "default",
            "mvc/{controller=Home}/{action=Index}/{id?}");
    });


问:
AngularJS: SELECT Option not selected when ng-model is an array
How can I get the Broken example (below) to work without changing it from an array (as I have a lot of code that depends on it being an array in other parts of the application)?

I'd like to continue using an array but I'd like the correct select option to show when the model changes.  The model changes correctly when the button is clicked but the option isn't being found in the select (ng-model and ng-options just aren't matching up when it's an array).

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.valueBroken = ['value1'];
    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2', 'value3']}];

  }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">

  <strong>Working</strong> (SELECT <i>is</i> updated when ng-model is a string):<br>
  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}<br><br>

  <strong>Broken</strong> (SELECT <i>not</i> updated when ng-model is an array):<br>
  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueBroken=['value2','value3']">Assign to Array of ["value2","value3"]</button> {{valueBroken}}

</div></code>```

Upon clicking 'Run code snippet' above, notice that the initial option is not selected (on the Broken select, when it's an array), but is initially selected on the Working select when it's a string. The correct option is also not shown when 'Assign to Array of ["value2"]' is clicked.

UPDATE:  I'm trying to get the OPTIONS ($scope.selectFilterBroken) to match the MODEL, rather than the other way around - hence my need to keep the model as an array.  The button click is merely to simulate the other parts of the application that manipulate the array.

Any help would be great.  Thanks and please.

答:
Objects in Javascript are not equal even though they look identical but strings or other primitive types are. For example, var a = [1]; var b = [1]; a === b returns false. However, if you do JSON.stringify(a) === JSON.stringify(b), it will return true.

When you assign ['value2'] to valueBroken, valueBroken is redeclared as a new array so it doesn't match with the one in the selectFilterBroken.

To fix this, we wanna find a way to assign the reference of ['value2'] to valueBroken. I wrote a function to find which array in selectFilterBroken matches the one we want by comparing their stringified versions. Once found, assign the reference of the one in the selectFilterBroken to valueBroken.

Without knowing what exactly is going on in your app, it is hard to guess if the solution fits you, but you can go from there.

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.valueBroken = ['value1'];
    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2']}];

    $scope.selectBroken = function(valueAry){
    for(var i = 0, m = $scope.selectFilterBroken.length; i < m; i++){
       if(JSON.stringify($scope.selectFilterBroken[i].value) === JSON.stringify(valueAry)){

       $scope.valueBroken = $scope.selectFilterBroken[i].value;
       break;
    }
    }

    }
  }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">

  <strong>Working</strong> (SELECT <i>is</i> updated when ng-model is a string):<br>
  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}<br><br>

  <strong>Broken</strong> (SELECT <i>not</i> updated when ng-model is an array):<br>
  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="selectBroken(['value2'])">Assign to Array of ["value2"]</button> {{valueBroken}}

</div></code>```

Body:
How can I get the Broken example (below) to work without changing it from an array (as I have a lot of code that depends on it being an array in other parts of the application)?

I'd like to continue using an array but I'd like the correct select option to show when the model changes.  The model changes correctly when the button is clicked but the option isn't being found in the select (ng-model and ng-options just aren't matching up when it's an array).

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.valueBroken = ['value1'];
    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2', 'value3']}];

  }]);

  Working (SELECT is updated when ng-model is a string):

  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}

  Broken (SELECT not updated when ng-model is an array):

  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueBroken=['value2','value3']">Assign to Array of ["value2","value3"]</button> {{valueBroken}}

Upon clicking 'Run code snippet' above, notice that the initial option is not selected (on the Broken select, when it's an array), but is initially selected on the Working select when it's a string. The correct option is also not shown when 'Assign to Array of ["value2"]' is clicked.

UPDATE:  I'm trying to get the OPTIONS ($scope.selectFilterBroken) to match the MODEL, rather than the other way around - hence my need to keep the model as an array.  The button click is merely to simulate the other parts of the application that manipulate the array.

Any help would be great.  Thanks and please.

Body:
Objects in Javascript are not equal even though they look identical but strings or other primitive types are. For example, var a = [1]; var b = [1]; a === b returns false. However, if you do JSON.stringify(a) === JSON.stringify(b), it will return true.

When you assign ['value2'] to valueBroken, valueBroken is redeclared as a new array so it doesn't match with the one in the selectFilterBroken.

To fix this, we wanna find a way to assign the reference of ['value2'] to valueBroken. I wrote a function to find which array in selectFilterBroken matches the one we want by comparing their stringified versions. Once found, assign the reference of the one in the selectFilterBroken to valueBroken.

Without knowing what exactly is going on in your app, it is hard to guess if the solution fits you, but you can go from there.

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function($scope) {

    $scope.valueWorking = 'value1';
    $scope.selectFilterWorking = [{name: 'name1', value: 'value1'},{name: 'name2', value: 'value2'}];

    $scope.valueBroken = ['value1'];
    $scope.selectFilterBroken = [{name: 'name1', value: ['value1']},{name: 'name2', value: ['value2']}];

    $scope.selectBroken = function(valueAry){
    for(var i = 0, m = $scope.selectFilterBroken.length; i < m; i++){
       if(JSON.stringify($scope.selectFilterBroken[i].value) === JSON.stringify(valueAry)){

       $scope.valueBroken = $scope.selectFilterBroken[i].value;
       break;
    }
    }

    }
  }]);

<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">

  <strong>Working</strong> (SELECT <i>is</i> updated when ng-model is a string):<br>
  <select ng-model="valueWorking"
          ng-options="select.value as select.name for select in selectFilterWorking">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="valueWorking='value2'">Assign to String of 'value2'</button> {{valueWorking}}<br><br>

  <strong>Broken</strong> (SELECT <i>not</i> updated when ng-model is an array):<br>
  <select ng-model="valueBroken"
          ng-options="select.value as select.name for select in selectFilterBroken">
    <option value="">Select an Option</option>
  </select>
  <button ng-click="selectBroken(['value2'])">Assign to Array of ["value2"]</button> {{valueBroken}}

</div>


问:
keep leading spaces when reading strings into pandas data frame?
I have a csv that I am trying to load into pandas. There are three columns in the csv, separated by a pipe. The first 2 columns are integers and the third column is a string. There are irregularities in the data such that some strings start with a space and some do not. I am in the situation where I must preserve those leading white spaces for a later processing step, however, it appears that pandas strips it. any help would be much appreciated!

example data:

```<code>1|2|Dogs are better than cats!
1|4| Cats are superior to dogs.
2|3|Birds Rule. More than you think! #birdsrule
2|10|Birds birds birds
</code>```

I have tried both the read_csv function and building my own parser, both to no avail. Here are my attempts:

read_csv:

```<code>my_df=pd.read_csv("foo.txt", sep="|", dtype=str, names=['num1','num2','some_Text'], encoding = 'utf8', skipinitialspace=False)
</code>```

my own parser:

```<code>my_df = []

with open("foo.txt", "r") as data:
    for row in data:
        num1, num2, some_text = row.split("|")
        some_text = some_text.strip("\n")
        my_df.append(
            pd.DataFrame({
                "num1": [num1],
                "num2": [num2],
                "some_text": [some_text]
            })
        )
my_df = pd.concat(my_df)
</code>```

答:
Your code should work just fine.

```<code>In [17]: df = pd.read_csv("foo.txt", sep="|", dtype=str, names=['num1','num2','some_Text'], encoding = 'utf8', skipinitialspace=False)

In [18]: df
Out[18]:
  num1 num2                                    some_Text
0    1    2                   Dogs are better than cats!
1    1    4                   Cats are superior to dogs.
2    2    3  Birds Rule. More than you think! #birdsrule
3    2   10                            Birds birds birds

In [19]: df.values
Out[19]:
array([['1', '2', 'Dogs are better than cats!'],
       ['1', '4', ' Cats are superior to dogs.'],
       ['2', '3', 'Birds Rule. More than you think! #birdsrule'],
       ['2', '10', 'Birds birds birds']], dtype=object)
</code>```

Note that the space before Cats is preserved, although since the string columns are right-justified, you might be fooled into thinking otherwise.

```<code>In [24]: df["some_Text"][1]
Out[24]: ' Cats are superior to dogs.'
</code>```

It should also work, and treat the types appropriately (having num1 and num2 become ints, I mean) with a simpler call, namely pd.read_csv("foo.txt", sep="|", names=['num1','num2','some_Text']).

Body:
I have a csv that I am trying to load into pandas. There are three columns in the csv, separated by a pipe. The first 2 columns are integers and the third column is a string. There are irregularities in the data such that some strings start with a space and some do not. I am in the situation where I must preserve those leading white spaces for a later processing step, however, it appears that pandas strips it. any help would be much appreciated!

example data:

1|2|Dogs are better than cats!
1|4| Cats are superior to dogs.
2|3|Birds Rule. More than you think! #birdsrule
2|10|Birds birds birds

I have tried both the read_csv function and building my own parser, both to no avail. Here are my attempts:

read_csv:

my_df=pd.read_csv("foo.txt", sep="|", dtype=str, names=['num1','num2','some_Text'], encoding = 'utf8', skipinitialspace=False)

my own parser:

my_df = []

with open("foo.txt", "r") as data:
    for row in data:
        num1, num2, some_text = row.split("|")
        some_text = some_text.strip("\n")
        my_df.append(
            pd.DataFrame({
                "num1": [num1],
                "num2": [num2],
                "some_text": [some_text]
            })
        )
my_df = pd.concat(my_df)

Body:
Your code should work just fine.

In [17]: df = pd.read_csv("foo.txt", sep="|", dtype=str, names=['num1','num2','some_Text'], encoding = 'utf8', skipinitialspace=False)

In [18]: df
Out[18]:
  num1 num2                                    some_Text
0    1    2                   Dogs are better than cats!
1    1    4                   Cats are superior to dogs.
2    2    3  Birds Rule. More than you think! #birdsrule
3    2   10                            Birds birds birds

In [19]: df.values
Out[19]:
array([['1', '2', 'Dogs are better than cats!'],
       ['1', '4', ' Cats are superior to dogs.'],
       ['2', '3', 'Birds Rule. More than you think! #birdsrule'],
       ['2', '10', 'Birds birds birds']], dtype=object)

Note that the space before Cats is preserved, although since the string columns are right-justified, you might be fooled into thinking otherwise.

In [24]: df["some_Text"][1]
Out[24]: ' Cats are superior to dogs.'

It should also work, and treat the types appropriately (having num1 and num2 become ints, I mean) with a simpler call, namely pd.read_csv("foo.txt", sep="|", names=['num1','num2','some_Text']).


问:
UPDATE with table a and table b
```<code>TABLEA ( id - gcoins )
TABLEB ( id - prezzo )
</code>```

Should I do a kind of subtraction: at number/value of 'gcoins' subtract number/value of 'prezzo'.

I tried:

```<code>UPDATE TABLEA SET TABLEA.gcoins = TABLEA.gcoins - TABLEB.prezzo FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id;
</code>```

I read this same code in this site at question in the 2010 but not work.

Error: You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id' at line 1

答:
You wrote "UPDATE TABLEA.gcoins", and you don't need wrote again "FROM TABLEA.gcoins". Join goes after the UPDATE value, see this example above:

Try write:
UPDATE (your table) JOIN (your join) ON (your join comparison) SET (your update) WHERE (your clausure if you want)

Title: UPDATE with table a and table b

Body:
TABLEA ( id - gcoins )
TABLEB ( id - prezzo )

Should I do a kind of subtraction: at number/value of 'gcoins' subtract number/value of 'prezzo'.

I tried:

UPDATE TABLEA SET TABLEA.gcoins = TABLEA.gcoins - TABLEB.prezzo FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id;

I read this same code in this site at question in the 2010 but not work.

Error: You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id' at line 1


问:
Why does ts-loader not compile my typescript?
I am trying to use Webpack to compile some typescript using ts-loader but it is not running tsc as I'm expecting. If I make changes to a ts file, webpack is not compiling it back to js, the same happens if I delete the generated js file altogether and re-run webpack.

Typescript is set up fine because I can run ./node_modules/typescript/bin/tsc and it generates the js files just fine. Am I right in thinking that ts-loader is just supposed to run tsc against my tsconfig.json? If so, why does it not pick up changes and generate my js as expected?

As you can see, my entry point is ./Client/boot-client.ts and not even this gets compiled when running through webpack.

The specific webpack command I'm running is:

./node_modules/webpack/bin/webpack.js --progress

Which gives the following output

```<code>[0] building modulests-loader: Using typescript@2.2.2 and C:\git\coliver\couchtrace\Couchtrace.Web\tsconfig.json
[1] building modulests-loader: Using typescript@2.2.2 and C:\git\coliver\couchtrace\Couchtrace.Web\tsconfig.json
[1] Hash: 568887199c9c2bcbe47ec00669704990969dbee5
Version: webpack 2.3.2
Child
    Hash: 568887199c9c2bcbe47e
    Time: 20096ms
                 Asset    Size  Chunks                    Chunk Names
        main-client.js  554 kB       0  [emitted]  [big]  main-client
    main-client.js.map  859 kB       0  [emitted]         main-client
       [0] delegated ./node_modules/rxjs/Observable.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
       [5] delegated ./node_modules/rxjs/Subject.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [14] delegated ./node_modules/@angular/core/index.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [19] ./~/rxjs/AsyncSubject.js 1.6 kB {0} [built]
      [20] ./~/rxjs/ReplaySubject.js 2.99 kB {0} [built]
      [33] delegated ./node_modules/angular2-universal/browser/index.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [34] ./~/rxjs/add/operator/map.js 156 bytes {0} [built]
      [60] ./Client/src/app.module.ts 1.86 kB {0} [built]
      [61] delegated ./node_modules/angular2-universal-polyfills/browser.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [68] ./~/rxjs/Rx.js 9.61 kB {0} [built]
     [180] ./~/rxjs/add/operator/takeUntil.js 186 bytes {0} [built]
     [335] ./Client/boot-client.ts 951 bytes {0} [built]
     [344] delegated ./node_modules/rxjs/symbol/rxSubscriber.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
     [351] delegated ./node_modules/rxjs/util/ObjectUnsubscribedError.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
     [353] delegated ./node_modules/@angular/router/index.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
        + 345 hidden modules
Child
    Hash: c00669704990969dbee5
    Time: 20085ms
             Asset    Size  Chunks                    Chunk Names
    main-server.js  552 kB       0  [emitted]  [big]  main-server
       [5] delegated ./node_modules/rxjs/Subject.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [14] delegated ./node_modules/@angular/core/bundles/core.umd.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [19] ./~/rxjs/AsyncSubject.js 1.6 kB {0} [built]
      [20] ./~/rxjs/ReplaySubject.js 2.99 kB {0} [built]
      [21] ./~/rxjs/util/ArgumentOutOfRangeError.js 974 bytes {0} [built]
      [32] delegated ./node_modules/angular2-universal/node/index.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [53] delegated ./node_modules/rxjs/add/operator/map.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [59] ./Client/src/app.module.ts 1.86 kB {0} [built]
      [60] delegated ./node_modules/zone.js/dist/zone-node.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [61] delegated ./node_modules/angular2-universal-polyfills/node.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [62] delegated ./node_modules/aspnet-prerendering/index.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [69] ./~/rxjs/Rx.js 9.61 kB {0} [built]
     [336] ./Client/boot-server.ts 1.37 kB {0} [built]
     [356] delegated ./node_modules/rxjs/symbol/rxSubscriber.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
     [360] delegated ./node_modules/@angular/router/bundles/router.umd.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
        + 346 hidden modules
</code>```

Versions

webpack: 2.3.2

ts-loader: 2.0.3

typescript: 2.2.2

webpack.config.js

```<code>var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');

// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
    context: __dirname,
    resolve: { extensions: [ '.ts', '.js' ]  },
    output: {
        filename: '[name].js',
       // publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
    },
    module: {
        rules: [
            { test: /\.js$/, enforce: 'pre', use: 'source-map-loader' },
            { test: /\.ts$/, enforce: 'pre', use: 'source-map-loader' },
            { test: /\.ts$/, use: ['ts-loader', 'angular2-template-loader'], exclude: /node_modules/ },
            { test: /\.html$/, use: 'html-loader?minimize=false' },
            { test: /\.css$/, use: ['to-string-loader','css-loader'] },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url-loader', query: { limit: 25000 } },
            { test: /\.json$/, use: 'json-loader' }
        ]
    }
};

// Configuration for client-side bundle suitable for running in browsers
var clientBundleOutputDir = './wwwroot/dist';
var clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './Client/boot-client.ts' },
    output: { path: path.join(__dirname, clientBundleOutputDir) },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [
        // Plugins that apply in development builds only
        new webpack.SourceMapDevToolPlugin({
            filename: '[file].map', // Remove this line if you prefer inline source maps
            moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
        })
    ] : [
        // Plugins that apply in production builds only
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin()
    ]),
    target: 'web',
    devtool: 'inline-source-map'
});

// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
    resolve: { mainFields: ['main'] },
    entry: { 'main-server': './Client/boot-server.ts' },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./Client/dist/vendor-manifest.json'),
            sourceType: 'commonjs2',
            name: './vendor'
        })
    ],
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './Client/dist')
    },
    target: 'node'
});

module.exports = [clientBundleConfig, serverBundleConfig];
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "noImplicitAny": false,
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "lib": [ "es6", "dom" ],
    "types": [ "node" ]
  },
  "exclude": [ "bin", "node_modules" ]
}
</code>```

答:
ts-loader does not write any file to disk. It compiles your TypeScript files and passes the resulting JavaScript to webpack, this happens in memory. There is no reason to output the compiled JavaScript as it's included in the bundle. The bundle contains everything you need.

You can see that the ./Client/boot-client.ts is compiled (it does not mean written to disk) by the following line:

```<code>[335] ./Client/boot-client.ts 951 bytes {0} [built]
</code>```

Body:
I am trying to use Webpack to compile some typescript using ts-loader but it is not running tsc as I'm expecting. If I make changes to a ts file, webpack is not compiling it back to js, the same happens if I delete the generated js file altogether and re-run webpack.

Typescript is set up fine because I can run ./node_modules/typescript/bin/tsc and it generates the js files just fine. Am I right in thinking that ts-loader is just supposed to run tsc against my tsconfig.json? If so, why does it not pick up changes and generate my js as expected?

As you can see, my entry point is ./Client/boot-client.ts and not even this gets compiled when running through webpack.

The specific webpack command I'm running is:

./node_modules/webpack/bin/webpack.js --progress

Which gives the following output

[0] building modulests-loader: Using typescript@2.2.2 and C:\git\coliver\couchtrace\Couchtrace.Web\tsconfig.json
[1] building modulests-loader: Using typescript@2.2.2 and C:\git\coliver\couchtrace\Couchtrace.Web\tsconfig.json
[1] Hash: 568887199c9c2bcbe47ec00669704990969dbee5
Version: webpack 2.3.2
Child
    Hash: 568887199c9c2bcbe47e
    Time: 20096ms
                 Asset    Size  Chunks                    Chunk Names
        main-client.js  554 kB       0  [emitted]  [big]  main-client
    main-client.js.map  859 kB       0  [emitted]         main-client
       [0] delegated ./node_modules/rxjs/Observable.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
       [5] delegated ./node_modules/rxjs/Subject.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [14] delegated ./node_modules/@angular/core/index.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [19] ./~/rxjs/AsyncSubject.js 1.6 kB {0} [built]
      [20] ./~/rxjs/ReplaySubject.js 2.99 kB {0} [built]
      [33] delegated ./node_modules/angular2-universal/browser/index.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [34] ./~/rxjs/add/operator/map.js 156 bytes {0} [built]
      [60] ./Client/src/app.module.ts 1.86 kB {0} [built]
      [61] delegated ./node_modules/angular2-universal-polyfills/browser.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
      [68] ./~/rxjs/Rx.js 9.61 kB {0} [built]
     [180] ./~/rxjs/add/operator/takeUntil.js 186 bytes {0} [built]
     [335] ./Client/boot-client.ts 951 bytes {0} [built]
     [344] delegated ./node_modules/rxjs/symbol/rxSubscriber.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
     [351] delegated ./node_modules/rxjs/util/ObjectUnsubscribedError.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
     [353] delegated ./node_modules/@angular/router/index.js from dll-reference vendor_c9f874e7c2f104739cd8 42 bytes {0} [not cacheable] [built]
        + 345 hidden modules
Child
    Hash: c00669704990969dbee5
    Time: 20085ms
             Asset    Size  Chunks                    Chunk Names
    main-server.js  552 kB       0  [emitted]  [big]  main-server
       [5] delegated ./node_modules/rxjs/Subject.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [14] delegated ./node_modules/@angular/core/bundles/core.umd.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [19] ./~/rxjs/AsyncSubject.js 1.6 kB {0} [built]
      [20] ./~/rxjs/ReplaySubject.js 2.99 kB {0} [built]
      [21] ./~/rxjs/util/ArgumentOutOfRangeError.js 974 bytes {0} [built]
      [32] delegated ./node_modules/angular2-universal/node/index.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [53] delegated ./node_modules/rxjs/add/operator/map.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [59] ./Client/src/app.module.ts 1.86 kB {0} [built]
      [60] delegated ./node_modules/zone.js/dist/zone-node.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [61] delegated ./node_modules/angular2-universal-polyfills/node.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [62] delegated ./node_modules/aspnet-prerendering/index.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
      [69] ./~/rxjs/Rx.js 9.61 kB {0} [built]
     [336] ./Client/boot-server.ts 1.37 kB {0} [built]
     [356] delegated ./node_modules/rxjs/symbol/rxSubscriber.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
     [360] delegated ./node_modules/@angular/router/bundles/router.umd.js from dll-reference ./vendor 42 bytes {0} [not cacheable] [built]
        + 346 hidden modules

Versions

webpack: 2.3.2

ts-loader: 2.0.3

typescript: 2.2.2

webpack.config.js

var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');

// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
    context: __dirname,
    resolve: { extensions: [ '.ts', '.js' ]  },
    output: {
        filename: '[name].js',
       // publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
    },
    module: {
        rules: [
            { test: /\.js$/, enforce: 'pre', use: 'source-map-loader' },
            { test: /\.ts$/, enforce: 'pre', use: 'source-map-loader' },
            { test: /\.ts$/, use: ['ts-loader', 'angular2-template-loader'], exclude: /node_modules/ },
            { test: /\.html$/, use: 'html-loader?minimize=false' },
            { test: /\.css$/, use: ['to-string-loader','css-loader'] },
            { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url-loader', query: { limit: 25000 } },
            { test: /\.json$/, use: 'json-loader' }
        ]
    }
};

// Configuration for client-side bundle suitable for running in browsers
var clientBundleOutputDir = './wwwroot/dist';
var clientBundleConfig = merge(sharedConfig, {
    entry: { 'main-client': './Client/boot-client.ts' },
    output: { path: path.join(__dirname, clientBundleOutputDir) },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./wwwroot/dist/vendor-manifest.json')
        })
    ].concat(isDevBuild ? [
        // Plugins that apply in development builds only
        new webpack.SourceMapDevToolPlugin({
            filename: '[file].map', // Remove this line if you prefer inline source maps
            moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
        })
    ] : [
        // Plugins that apply in production builds only
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin()
    ]),
    target: 'web',
    devtool: 'inline-source-map'
});

// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
    resolve: { mainFields: ['main'] },
    entry: { 'main-server': './Client/boot-server.ts' },
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./Client/dist/vendor-manifest.json'),
            sourceType: 'commonjs2',
            name: './vendor'
        })
    ],
    output: {
        libraryTarget: 'commonjs',
        path: path.join(__dirname, './Client/dist')
    },
    target: 'node'
});

module.exports = [clientBundleConfig, serverBundleConfig];

tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": false,
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "lib": [ "es6", "dom" ],
    "types": [ "node" ]
  },
  "exclude": [ "bin", "node_modules" ]
}

Body:
ts-loader does not write any file to disk. It compiles your TypeScript files and passes the resulting JavaScript to webpack, this happens in memory. There is no reason to output the compiled JavaScript as it's included in the bundle. The bundle contains everything you need.

You can see that the ./Client/boot-client.ts is compiled (it does not mean written to disk) by the following line:

[335] ./Client/boot-client.ts 951 bytes {0} [built]


问:
How to map a domain to another domain's subfolder?
I have a very fast web server (IIS6, ASP.NET) that I want to use for several sites. Now, I already have a domain that maps directly to the IP address of the server, but how can I get another domain to map to a subfolder (i.e., a separate ASP.NET application) on that same computer? Is it theoretically possible? (note: only port 80 is open, I cannot open other ones.)

Accepted answer: shown below. I actually followed the tutorial and got it working. Hooray! Thanks, everyone! :)

答:
Just create a new site in your "IIS Manager" application - the wizard will ask for the DNS hostname of the new site.

To see (or change) that value later, on the "Web Site" tab of the properties pages for that site, use the "Advanced..." options to chose which values for the HTTP/1.1 "Host:" header are used to get to that particular site.

OwnerDisplayName: Dmitri Nesteruk

LastEditorDisplayName: Dmitri Nesteruk

OwnerDisplayName: Alnitak


问:
best way to stop ondraw() opengl for a time
I use opengl to draw values from an array. The values are from the 3 Android sensors. I want to turn of the renderer during I collect the values. It seems that drawing and gathering at the same time have differenet results, so I want to turn off rendering while I gathering sensorvalues. At the moment I use a boolean in the ondraw() to stop drawing. But is there a better way to do this? There happen freaky things when I stop drawing , like the stuff I draw jittering a little bit some times, but it can't be because there are no drawing( ondraw(){ if(boolean){.........}}

Thank you so much for your help :-)

答:
I have a suggestion:  Create a thread to collect the sensor data, and make it available as an object.  This thread would gather all the data, and synchronize on the public value object.  Blocking time would be minimized.

```<code>collectLocalData = getData();
synchronized(pubData) {
  pubData.set(collectLocalData);
}
</code>```

Your render thread can then Do the same when copying the public values for local consumption.

```<code>synchronized(pubData) {
  renderLocalData.set( pubData );
}

renderData( renderLocalData );
</code>```

If polling the sensors takes longer than rendering time, the same data will be rendered more than once.  The animation might get a little twitchy, but no more so than what the data represents.

PS: your jitters may be a result of the data itself rather than your code.

Body:
I have a suggestion:  Create a thread to collect the sensor data, and make it available as an object.  This thread would gather all the data, and synchronize on the public value object.  Blocking time would be minimized.

collectLocalData = getData();
synchronized(pubData) {
  pubData.set(collectLocalData);
}

Your render thread can then Do the same when copying the public values for local consumption.

synchronized(pubData) {
  renderLocalData.set( pubData );
}

renderData( renderLocalData );

If polling the sensors takes longer than rendering time, the same data will be rendered more than once.  The animation might get a little twitchy, but no more so than what the data represents.

PS: your jitters may be a result of the data itself rather than your code.


问:
Checking 'checked' property selects radio button
I have two radio buttons, neither of them is checked by default, and depending on which one is clicked/checked i should collect text from two different textboxes.

```<code>if ($("#70").prop("checked", true)) {
    var s=$('input[name="a"]').val();
}
else {
    var s=$('input[name="b"]').val();
}
</code>```

The problem is that if I check the second one, with id '60', the first one gets the checked property, If I set the if statement to check the second one, id='60', then the same thing happens but this time the second one gets checked.

This is the code for the radio buttons

```<code><label id="a" for="70" style="width:50px">
          <input type="radio" name="brojBodova" value="70" id="70">70
    </label>
    <label id="b" for="60" style="width:50px;">
          <input type="radio" name="brojBodova" value="60" id="60">60
    </label>
</code>```

答:
If the buttons are in the same group they need to share the same name= attribute

Fiddle Below

$("input[type='radio']").click(function(ele){
var s = $(this).attr('value');
$("#result").html(s);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="a" for="70" style="width:50px">
  <input type="radio" name="a" value="70" id="70">70
</label>
<label id="b" for="60" style="width:50px;">
  <input type="radio" name="a" value="60" id="60">60
</label>

<div id="result">
Click a button
</div></code>```

Body:
I have two radio buttons, neither of them is checked by default, and depending on which one is clicked/checked i should collect text from two different textboxes.

if ($("#70").prop("checked", true)) {
    var s=$('input[name="a"]').val();
}
else {
    var s=$('input[name="b"]').val();
}

The problem is that if I check the second one, with id '60', the first one gets the checked property, If I set the if statement to check the second one, id='60', then the same thing happens but this time the second one gets checked.

This is the code for the radio buttons

          <input type="radio" name="brojBodova" value="70" id="70">70

          <input type="radio" name="brojBodova" value="60" id="60">60

Body:
If the buttons are in the same group they need to share the same name= attribute

Fiddle Below

$("input[type='radio']").click(function(ele){
var s = $(this).attr('value');
$("#result").html(s);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="a" for="70" style="width:50px">
  <input type="radio" name="a" value="70" id="70">70
</label>
<label id="b" for="60" style="width:50px;">
  <input type="radio" name="a" value="60" id="60">60
</label>

<div id="result">
Click a button
</div>


答:
I show that it works... whats more is that skipinitialspace=False is the default.

```<code>import pandas as pd
from io import StringIO

txt = """1|2|Dogs are better than cats!
1|4| Cats are superior to dogs.
2|3|Birds Rule. More than you think! #birdsrule
2|10|Birds birds birds
"""

df = pd.read_csv(StringIO(txt), sep='|', header=None)

# get first character of third column
df.iloc[:, 2].str[0]

0    D
1
2    B
3    B
Name: 2, dtype: object
</code>```

Title: keep leading spaces when reading strings into pandas data frame?

Body:
I show that it works... whats more is that skipinitialspace=False is the default.

import pandas as pd
from io import StringIO

txt = """1|2|Dogs are better than cats!
1|4| Cats are superior to dogs.
2|3|Birds Rule. More than you think! #birdsrule
2|10|Birds birds birds
"""

df = pd.read_csv(StringIO(txt), sep='|', header=None)

# get first character of third column
df.iloc[:, 2].str[0]

0    D
1
2    B
3    B
Name: 2, dtype: object