问:
Pretty printing XML with javascript
I have a string that represents a non indented XML that I would like to pretty-print. For example:

```<code><root><node/></root>
</code>```

should become:

```<code><root>
  <node/>
</root>
</code>```

Syntax highlighting is not a requirement. To tackle the problem I first transform the XML to add carriage returns and white spaces and then use a pre tag to output the XML. To add new lines and white spaces I wrote the following function:

```<code>function formatXml(xml) {
    var formatted = '';
    var reg = /(>)(<)(\/*)/g;
    xml = xml.replace(reg, '$1\r\n$2$3');
    var pad = 0;
    jQuery.each(xml.split('\r\n'), function(index, node) {
        var indent = 0;
        if (node.match( /.+<\/\w[^>]*>$/ )) {
            indent = 0;
        } else if (node.match( /^<\/\w/ )) {
            if (pad != 0) {
                pad -= 1;
            }
        } else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) {
            indent = 1;
        } else {
            indent = 0;
        }

        var padding = '';
        for (var i = 0; i < pad; i++) {
            padding += '  ';
        }

        formatted += padding + node + '\r\n';
        pad += indent;
    });

    return formatted;
}
</code>```

I then call the function like this:

```<code>jQuery('pre.formatted-xml').text(formatXml('<root><node1/></root>'));
</code>```

This works perfectly fine for me but while I was writing the previous function I thought that there must be a better way. So my question is do you know of any better way given an XML string to pretty-print it in an html page? Any javascript frameworks and/or plugins that could do the job are welcome. My only requirement is this to be done on the client side.

答:
This can be done using native javascript tools, without 3rd party libs, extending the @Dimitre Novatchev's answer:

var prettifyXml = function(sourceXml)
{
    var xmlDoc = new DOMParser().parseFromString(sourceXml, 'application/xml');
    var xsltDoc = new DOMParser().parseFromString([
        // describes how we want to modify the XML - indent everything
        '<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">',
        '  <xsl:strip-space elements="*"/>',
        '  <xsl:template match="para[content-style][not(text())]">', // change to just text() to strip space in text nodes
        '    <xsl:value-of select="normalize-space(.)"/>',
        '  </xsl:template>',
        '  <xsl:template match="node()|@*">',
        '    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>',
        '  </xsl:template>',
        '  <xsl:output indent="yes"/>',
        '</xsl:stylesheet>',
    ].join('\n'), 'application/xml');

    var xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xsltDoc);
    var resultDoc = xsltProcessor.transformToDocument(xmlDoc);
    var resultXml = new XMLSerializer().serializeToString(resultDoc);
    return resultXml;
};

console.log(prettifyXml('<root><node/></root>'));
```

<p>Outputs:</p>

```<root>
  <node/>
</root>
```

JSFiddle

Note, as pointed out by @jat255, pretty printing with <xsl:output indent="yes"/> is not supported by firefox. It only seems to work in chrome, opera and probably the rest webkit-based browsers.

OwnerDisplayName: darin

Title: Pretty printing XML with javascript

Body:
I have a string that represents a non indented XML that I would like to pretty-print. For example:

<root><node/></root>

should become:

<root>
  <node/>
</root>

Syntax highlighting is not a requirement. To tackle the problem I first transform the XML to add carriage returns and white spaces and then use a pre tag to output the XML. To add new lines and white spaces I wrote the following function:

function formatXml(xml) {
    var formatted = '';
    var reg = /(>)(<)(\/*)/g;
    xml = xml.replace(reg, '$1\r\n$2$3');
    var pad = 0;
    jQuery.each(xml.split('\r\n'), function(index, node) {
        var indent = 0;
        if (node.match( /.+<\/\w[^>]*>$/ )) {
            indent = 0;
        } else if (node.match( /^<\/\w/ )) {
            if (pad != 0) {
                pad -= 1;
            }
        } else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) {
            indent = 1;
        } else {
            indent = 0;
        }

        var padding = '';
        for (var i = 0; i < pad; i++) {
            padding += '  ';
        }

        formatted += padding + node + '\r\n';
        pad += indent;
    });

    return formatted;
}

I then call the function like this:

jQuery('pre.formatted-xml').text(formatXml('<root><node1/></root>'));

This works perfectly fine for me but while I was writing the previous function I thought that there must be a better way. So my question is do you know of any better way given an XML string to pretty-print it in an html page? Any javascript frameworks and/or plugins that could do the job are welcome. My only requirement is this to be done on the client side.

Body:
This can be done using native javascript tools, without 3rd party libs, extending the @Dimitre Novatchev's answer:

var prettifyXml = function(sourceXml)
{
    var xmlDoc = new DOMParser().parseFromString(sourceXml, 'application/xml');
    var xsltDoc = new DOMParser().parseFromString([
        // describes how we want to modify the XML - indent everything
        '<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">',
        '  <xsl:strip-space elements="*"/>',
        '  <xsl:template match="para[content-style][not(text())]">', // change to just text() to strip space in text nodes
        '    <xsl:value-of select="normalize-space(.)"/>',
        '  </xsl:template>',
        '  <xsl:template match="node()|@*">',
        '    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>',
        '  </xsl:template>',
        '  <xsl:output indent="yes"/>',
        '</xsl:stylesheet>',
    ].join('\n'), 'application/xml');

    var xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xsltDoc);
    var resultDoc = xsltProcessor.transformToDocument(xmlDoc);
    var resultXml = new XMLSerializer().serializeToString(resultDoc);
    return resultXml;
};

console.log(prettifyXml('<root><node/></root>'));

Outputs:

<root>
  <node/>
</root>

JSFiddle

Note, as pointed out by @jat255, pretty printing with <xsl:output indent="yes"/> is not supported by firefox. It only seems to work in chrome, opera and probably the rest webkit-based browsers.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
TSQL ROW_NUMBER() OVER (PARTITION BY... ORDER BY....)
Can I do row_number without partition? (see data at end of post) I can use this statement to get an ORDER#.

```<code>     ROW_NUMBER() OVER (PARTITION BY LOG_ID ORDER BY ORDER_ID)
</code>```

Any suggestions to get the LOG# ?

```<code>-LOG#   ORDER#  LOG_ID  ORDER_ID
-1      1       340580  387373215
-1      2       340580  387373225
-2      1       340925  387812330
-3      1       340935  388093450
-4      1       340945  387615845
-5      1       340990  386433405
-6      1       341675  376247120
-6      2       341675  376247130
-6      3       341675  388352445
</code>```

答:
```<code>SELECT
    - DENSE_RANK() OVER (ORDER BY LOG_ID) AS "#LOG",
    ROW_NUMBER() OVER (PARTITION BY LOG_ID ORDER BY ORDER_ID) AS "#ORDER",
    LOG_ID,
    ORDER_ID
FROM UnnamedTable
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can I do row_number without partition? (see data at end of post) I can use this statement to get an ORDER#.

     ROW_NUMBER() OVER (PARTITION BY LOG_ID ORDER BY ORDER_ID)

Any suggestions to get the LOG# ?

-LOG#   ORDER#  LOG_ID  ORDER_ID
-1      1       340580  387373215
-1      2       340580  387373225
-2      1       340925  387812330
-3      1       340935  388093450
-4      1       340945  387615845
-5      1       340990  386433405
-6      1       341675  376247120
-6      2       341675  376247130
-6      3       341675  388352445


问:
woocommerce order list action button on click
I am trying to add a custom button in woocommerce order list that will send an email to the customer (the button will only show next to orders that have status 'processing' and a custom field 'deltime' is not empty). So I got the button to show but the email is send every time that I am in woocommerce/orders or during refresh instead sending only when the button is clicked. I must have understood something wrong about action hooks...any ideas?

here is the code used in functions.php :

```<code>// Add your custom order status action button (for orders with "processing" status)
add_filter( 'woocommerce_admin_order_actions', 'add_custom_email_button', 100, 2 );
function add_custom_email_button( $actions, $order ) {
// Display the button for all orders that have a 'processing' status

    // Get Order ID (compatibility all WC versions)
    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    global $wpdb;
    $deltime = $wpdb->get_var( "SELECT meta_value FROM wp_postmeta WHERE post_id = $order_id AND meta_key = 'is_gift' " );

    if ( $order->has_status( array( 'processing' ) ) && (!empty($deltime)) ) {

    $mailer = WC()->mailer();
$mails = $mailer->get_emails();
if ( ! empty( $mails ) ) {
foreach ( $mails as $mail ) {
    if ( $mail->id == 'customer_processing_order' ) {
       $mail->trigger( $order_id );
    }
 }
}

    // Set the action button
    $actions['partial'] = array(
        'url'       => wp_nonce_url( admin_url( 'admin-ajax.php?action=add_custom_email_button&order_id=' . $order_id )),
        'name'      => __( 'Αποστολή Email', 'woocommerce' ),
        'action'    => "view partial", // keep "view" class for a clean button CSS
    );
}
return $actions;
}

// Set Here the WooCommerce icon for your action button
add_action( 'admin_head', 'add_custom_email_button_css' );
function add_custom_email_button_css() {
echo '<style>.view.partial::after { font-family: woocommerce; content: "\1F4E7" !important; }</style>';
}
</code>```

button image

答:
The way you have it defined now, the button definition and action are in the same function, so when the button is created, its action is also performed.
You have to split the button definition and the action in two different functions:</p>

```<code>add_filter( 'woocommerce_admin_order_actions', 'add_custom_email_button', 100, 2 );
function add_custom_email_button( $actions, $order ) {
  if ( $order->status == "processing" ) {
    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    global $wpdb;
    $deltime = $wpdb->get_var( "SELECT meta_value FROM wp_postmeta WHERE post_id = $order_id AND meta_key = 'is_gift' " );

    if ( !empty( $deltime ) ) {
      // Set the action button
      $actions['partial'] = array(
        'url'       => wp_nonce_url( admin_url( 'admin-ajax.php?action=click_custom_email_button&order_id=' . $order_id )),
        'name'      => __( 'Αποστολή Email', 'woocommerce' ),
        'action'    => "view partial", // keep "view" class for a clean button CSS
      );
    }
  }
  return $actions;
}

add_action( 'wp_ajax_click_custom_email_button', 'click_custom_email_button' );
function click_custom_email_button( $order_id ) {
  $mailer = WC()->mailer();
  $mails = $mailer->get_emails();
  if ( ! empty( $mails ) ) {
    foreach ( $mails as $mail ) {
      if ( $mail->id == 'customer_processing_order' ) {
        $mail->trigger( $order_id );
      }
    }
  }
}
</code>```

Body:
I am trying to add a custom button in woocommerce order list that will send an email to the customer (the button will only show next to orders that have status 'processing' and a custom field 'deltime' is not empty). So I got the button to show but the email is send every time that I am in woocommerce/orders or during refresh instead sending only when the button is clicked. I must have understood something wrong about action hooks...any ideas?

here is the code used in functions.php :

// Add your custom order status action button (for orders with "processing" status)
add_filter( 'woocommerce_admin_order_actions', 'add_custom_email_button', 100, 2 );
function add_custom_email_button( $actions, $order ) {
// Display the button for all orders that have a 'processing' status

    // Get Order ID (compatibility all WC versions)
    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    global $wpdb;
    $deltime = $wpdb->get_var( "SELECT meta_value FROM wp_postmeta WHERE post_id = $order_id AND meta_key = 'is_gift' " );

    if ( $order->has_status( array( 'processing' ) ) && (!empty($deltime)) ) {

    $mailer = WC()->mailer();
$mails = $mailer->get_emails();
if ( ! empty( $mails ) ) {
foreach ( $mails as $mail ) {
    if ( $mail->id == 'customer_processing_order' ) {
       $mail->trigger( $order_id );
    }
 }
}

    // Set the action button
    $actions['partial'] = array(
        'url'       => wp_nonce_url( admin_url( 'admin-ajax.php?action=add_custom_email_button&order_id=' . $order_id )),
        'name'      => __( 'Αποστολή Email', 'woocommerce' ),
        'action'    => "view partial", // keep "view" class for a clean button CSS
    );
}
return $actions;
}

// Set Here the WooCommerce icon for your action button
add_action( 'admin_head', 'add_custom_email_button_css' );
function add_custom_email_button_css() {
echo '';
}

button image

Body:
The way you have it defined now, the button definition and action are in the same function, so when the button is created, its action is also performed.
You have to split the button definition and the action in two different functions:

add_filter( 'woocommerce_admin_order_actions', 'add_custom_email_button', 100, 2 );
function add_custom_email_button( $actions, $order ) {
  if ( $order->status == "processing" ) {
    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    global $wpdb;
    $deltime = $wpdb->get_var( "SELECT meta_value FROM wp_postmeta WHERE post_id = $order_id AND meta_key = 'is_gift' " );

    if ( !empty( $deltime ) ) {
      // Set the action button
      $actions['partial'] = array(
        'url'       => wp_nonce_url( admin_url( 'admin-ajax.php?action=click_custom_email_button&order_id=' . $order_id )),
        'name'      => __( 'Αποστολή Email', 'woocommerce' ),
        'action'    => "view partial", // keep "view" class for a clean button CSS
      );
    }
  }
  return $actions;
}

add_action( 'wp_ajax_click_custom_email_button', 'click_custom_email_button' );
function click_custom_email_button( $order_id ) {
  $mailer = WC()->mailer();
  $mails = $mailer->get_emails();
  if ( ! empty( $mails ) ) {
    foreach ( $mails as $mail ) {
      if ( $mail->id == 'customer_processing_order' ) {
        $mail->trigger( $order_id );
      }
    }
  }
}


问:
Linq expression with Join, and conditional OrderBy / OrderByDescending
I am building a Linq expression, I don't have the ability to use Dynamic Linq in this project.  Here is my initial statement.

```<code>                   var orderListQuery = context.Orders.Where(oExpr)
                        .Join(context.Members,
                            o => o.MemberId,
                            m => m.Id,
                            (o, m) => new {Order = o, Member = m})
                        .Where(oM => oM.Member.CustomerId == custId);
</code>```

The next part is where I would like to conditionally add a descending expression:

```<code>                orderListQuery = descending
                    ? orderListQuery.OrderByDescending(sortProperty)
                    : orderListQuery.OrderBy(sortProperty);
</code>```

the error which I already saw a post on is that I need to explicitly list the <TSource, TKey>, but due to the complexity of the syntax from the join, I have no idea how to explicitly list these. I tried <Order, string>, which does not work.

Anything helps, thanks.

答:
Thanks for that incredible detailed answer.  It has been a few months now, and more about MVC and the existing application code is becoming clear.  What had happened in my case was that we had an extension method defined that allowed OrderBy and OrderByDescending to accept strings passed in by our sorting module from the front end. e.g:

```<code>    public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
    {
        return GetExpression(source, propertyName);
    }
</code>```

This would then funnel it into a GetExpression function that returned an IOrderedQueryable<T>

I had not included the reference to this, and due to my inexperience with both the framework and the application I was cranking my head for essentially no reason.

Body:
I am building a Linq expression, I don't have the ability to use Dynamic Linq in this project.  Here is my initial statement.

                   var orderListQuery = context.Orders.Where(oExpr)
                        .Join(context.Members,
                            o => o.MemberId,
                            m => m.Id,
                            (o, m) => new {Order = o, Member = m})
                        .Where(oM => oM.Member.CustomerId == custId);

The next part is where I would like to conditionally add a descending expression:

                orderListQuery = descending
                    ? orderListQuery.OrderByDescending(sortProperty)
                    : orderListQuery.OrderBy(sortProperty);

the error which I already saw a post on is that I need to explicitly list the <TSource, TKey>, but due to the complexity of the syntax from the join, I have no idea how to explicitly list these. I tried <Order, string>, which does not work.

Anything helps, thanks.

Body:
Thanks for that incredible detailed answer.  It has been a few months now, and more about MVC and the existing application code is becoming clear.  What had happened in my case was that we had an extension method defined that allowed OrderBy and OrderByDescending to accept strings passed in by our sorting module from the front end. e.g:

    public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
    {
        return GetExpression(source, propertyName);
    }

This would then funnel it into a GetExpression function that returned an IOrderedQueryable<T>

I had not included the reference to this, and due to my inexperience with both the framework and the application I was cranking my head for essentially no reason.


问:
ImmutableJS - How to sort a date in descendent order
I have this function that sorts dates in ascendent order (from the first date to the last date), I'm using immutableJS https://facebook.github.io/immutable-js/docs/#/Map/sortBy:

```<code>export const OrderedMapSelector = (state) => {
  if ( state.allRetrospectivesMap ) {
    return state.allRetrospectivesMap.sortBy((retro) => retro.get('date'))
  } else {
    return Map({})
  }
}
</code>```

I want to sort it by descendent order, from the last date to the first date. How can I do this?

Thanks :)

答:
You can reverse() the results:

```<code>state.allRetrospectivesMap.sortBy((retro) => retro.get('date')).reverse()
</code>```

Or you can use sort() with a comparator:

```<code>state.allRetrospectivesMap.sort((a, b) => b.get('date') - a.get('data')) // or any other relevant comparison between the dates
</code>```

Body:
I have this function that sorts dates in ascendent order (from the first date to the last date), I'm using immutableJS https://facebook.github.io/immutable-js/docs/#/Map/sortBy:

export const OrderedMapSelector = (state) => {
  if ( state.allRetrospectivesMap ) {
    return state.allRetrospectivesMap.sortBy((retro) => retro.get('date'))
  } else {
    return Map({})
  }
}

I want to sort it by descendent order, from the last date to the first date. How can I do this?

Thanks :)

Body:
You can reverse() the results:

state.allRetrospectivesMap.sortBy((retro) => retro.get('date')).reverse()

Or you can use sort() with a comparator:

state.allRetrospectivesMap.sort((a, b) => b.get('date') - a.get('data')) // or any other relevant comparison between the dates


问:
enum as parameter in c function
I am writing a Library to load and save ascii and binary images. I defined an Enum containing 4 different flags for 4 different ways to save a bitmap:

```<code>enum jmpr_PNMMode
{
    BINARY_PPM,             /* Binary Portable Pixmap (P6)  */
    ASCII_PPM,          /* Portable pixmap ASCII (P3)   */
    BINARY_PGM,         /* Portable Graymap binary (P5) */
    ASCII_PGM            /* Portable Graymap ASCII (P2) */
};
</code>```

I pass those to my save-function as a parameter:

```<code>void jmpr_savePNM(char* filename, jmpr_Image* img, enum jmpr_PNMMode mode)
{

}
</code>```

Now how can I check which distinct instance of the enum I got? it doesn't work with:

```<code>if (strcmp(mode, "ASCII_PPM") != 0)
</code>```

since the second parameter is technically not a char*.

答:
this code:

```<code>enum jmpr_PNMMode
{
    BINARY_PPM,             /* Binary Portable Pixmap (P6)  */
    ASCII_PPM,          /* Portable pixmap ASCII (P3)   */
    BINARY_PGM,         /* Portable Graymap binary (P5) */
    ASCII_PGM            /* Portable Graymap ASCII (P2) */
};
</code>```

gives meaningful names to 4 integers, where BINARY_PPM is 0 and each following line increments that number by 1.

so the code in the called function could be using:

```<code>if ( BINARY_PPM == mode )
    ...
else if( ASCII_PPM == mode )
    ...
else if( BINARY_PGM == mode )
    ...
else if( ASCII_PGM == mode )
    ...
else
{
    perror( "invalid mode sent to jmpr_savePNM()" );
    exit( EXIT_FAILURE );
}
</code>```

or could be using:

```<code>switch( mode )
    case BINARY_PPM:
        ...
        break;

    case ASCII_PPM:
        ...
        break;

    case BINARY_PGM:
        ...
        break;

    case ASCII_PGM:
        ...
        break;

    default:
        perror( "invalid mode sent to jmpr_savePNM()" );
        exit( EXIT_FAILURE );
        break;
} // end switch()
</code>```

for clarity in the code and ease of readability and understanding, I would use the switch() statement.

Title: enum as parameter in c function

Body:
I am writing a Library to load and save ascii and binary images. I defined an Enum containing 4 different flags for 4 different ways to save a bitmap:

enum jmpr_PNMMode
{
    BINARY_PPM,             /* Binary Portable Pixmap (P6)  */
    ASCII_PPM,          /* Portable pixmap ASCII (P3)   */
    BINARY_PGM,         /* Portable Graymap binary (P5) */
    ASCII_PGM            /* Portable Graymap ASCII (P2) */
};

I pass those to my save-function as a parameter:

void jmpr_savePNM(char* filename, jmpr_Image* img, enum jmpr_PNMMode mode)
{

}

Now how can I check which distinct instance of the enum I got? it doesn't work with:

if (strcmp(mode, "ASCII_PPM") != 0)

since the second parameter is technically not a char*.

Body:
this code:

enum jmpr_PNMMode
{
    BINARY_PPM,             /* Binary Portable Pixmap (P6)  */
    ASCII_PPM,          /* Portable pixmap ASCII (P3)   */
    BINARY_PGM,         /* Portable Graymap binary (P5) */
    ASCII_PGM            /* Portable Graymap ASCII (P2) */
};

gives meaningful names to 4 integers, where BINARY_PPM is 0 and each following line increments that number by 1.

so the code in the called function could be using:

if ( BINARY_PPM == mode )
    ...
else if( ASCII_PPM == mode )
    ...
else if( BINARY_PGM == mode )
    ...
else if( ASCII_PGM == mode )
    ...
else
{
    perror( "invalid mode sent to jmpr_savePNM()" );
    exit( EXIT_FAILURE );
}

or could be using:

switch( mode )
    case BINARY_PPM:
        ...
        break;

    case ASCII_PPM:
        ...
        break;

    case BINARY_PGM:
        ...
        break;

    case ASCII_PGM:
        ...
        break;

    default:
        perror( "invalid mode sent to jmpr_savePNM()" );
        exit( EXIT_FAILURE );
        break;
} // end switch()

for clarity in the code and ease of readability and understanding, I would use the switch() statement.


问:
Performance penalty of long list in python logging.debug()
How lazy is evaluation in Python? If I have code that looks like

logging.debug('My very long list: %s' % list(x for x in long_generator))

and the logging effective level is such that debug messages are ignored, do I incur a performance penalty for having this line?

答:
You will have a performance penalty because list(x for x in long_generator) will be created before calling logging.debug() even if debug messages are ignored.

There is no lazy evaluation in Python. Every line is evaluated/executed before the next line. It means that expressions are evaluated when they are bound to variables.


问:
How to transpose data in R without losing information?
I am looking to transpose my data set.

Pretext: As QIIME2 outputs so that 'Feature.ID' (essentially bacterial species) are rows and Sites are columns, with abundance in the cell values. As many R packages such as Biodiversity require the sites are rows and species as columns, I am looking to transpose my data.

```<code>library(tidyverse)

Ftable <- read_tsv('table.feature-table_biom.txt', col_names = TRUE, skip = 1) #opens my QIIME2 file, removing the top line

names(Ftable)[names(Ftable)=="#OTU ID"] <- "Feature.ID" #Renames the species column

Ftable <- cbind(Ftable, "observation"=1:nrow(Ftable)) #adds an indexing column 'observation' so that I can later remove the column containing the species names as they are complex and I do not wish to type them out

Ftable <- Ftable %>% select(observation, everything()) #Moves observation to the front

OtuOb <- Ftable

OtuOb <- as.tibble(OtuOb)

write_tsv(OtuOb, "OtuToObservationReference.tsv") #These 3 lines save a reference so I can look to see which observations align to which species

Ftable <- Ftable[,-2] #removes 'Feature.ID' column so that the observation column shows the species

Ftable <- t(Ftable) #I have been trying to get this to work but it doesnt

Ftable <- as.tibble(Ftable)

write_tsv(Ftable, "Ftable.tsv")
</code>```

When transposing it removes the sample references (along the top in the original) which means I have no way of seeing how they match up to the abundancies of that species.

Small sample of my data

答:
Before transposing, assign your row names to an object, do the transpose, then assign the stored row names to the new column names:</p>

```<code>Ftable_rownames <- rownames(Ftable)

# transpose
Ftable <- t(Ftable)

# assign names from the stored object
colnames(Ftable) <- Ftable_rownames
</code>```

Body:
I am looking to transpose my data set.

Pretext: As QIIME2 outputs so that 'Feature.ID' (essentially bacterial species) are rows and Sites are columns, with abundance in the cell values. As many R packages such as Biodiversity require the sites are rows and species as columns, I am looking to transpose my data.

library(tidyverse)

Ftable <- read_tsv('table.feature-table_biom.txt', col_names = TRUE, skip = 1) #opens my QIIME2 file, removing the top line

names(Ftable)[names(Ftable)=="#OTU ID"] <- "Feature.ID" #Renames the species column

Ftable <- cbind(Ftable, "observation"=1:nrow(Ftable)) #adds an indexing column 'observation' so that I can later remove the column containing the species names as they are complex and I do not wish to type them out

Ftable <- Ftable %>% select(observation, everything()) #Moves observation to the front

OtuOb <- Ftable

OtuOb <- as.tibble(OtuOb)

write_tsv(OtuOb, "OtuToObservationReference.tsv") #These 3 lines save a reference so I can look to see which observations align to which species

Ftable <- Ftable[,-2] #removes 'Feature.ID' column so that the observation column shows the species

Ftable <- t(Ftable) #I have been trying to get this to work but it doesnt

Ftable <- as.tibble(Ftable)

write_tsv(Ftable, "Ftable.tsv")

When transposing it removes the sample references (along the top in the original) which means I have no way of seeing how they match up to the abundancies of that species.

Small sample of my data

Body:
Before transposing, assign your row names to an object, do the transpose, then assign the stored row names to the new column names:

Ftable_rownames <- rownames(Ftable)

# transpose
Ftable <- t(Ftable)

# assign names from the stored object
colnames(Ftable) <- Ftable_rownames


问:
CakePHP conditional query with controller that 'hasAndBelongsToMany'
I apologize for the horrible title, I couldn't think of how to explain my problem.

In my database I have the following tables, articles, tags, and articles_tags. An article can have many tags.

Currently I am able to grab all the articles, with all the tags, but I want to be able to find articles based upon it's tags.

My select is simple:

```<code>$articles = $this->Article->find('all', array(
    // extra condition to check for tag, maybe?
    'conditions'    => array('Article.status' => 'active'),
    'limit'         => $this->articles_per_page,
    'offset'        => ($page_num-1)*$this->articles_per_page
));
</code>```

My return from the database is as follows:

```<code>Array
(
[0] => Array
    (
        [Article] => Array
            (
                [id] => 1
            )

        [Tag] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [name] => Ruby
                        [slug] => ruby
                        [uses] => 1
                        [ArticlesTag] => Array
                            (
                                [id] => 1
                                [article_id] => 1
                                [tag_id] => 1
                            )

                    )

            )

    )
</code>```

What do I do if I only want to return the articles with a Ruby tag?

答:
I'm updating this question with an answer for CakePHP 3.x.

You can find all articles for a given tag using an INNER JOIN. The benefit of this join is that it keeps articles as the primary table in the query. Making this an easy solution when you're paginating results by a HABTM join.

```<code>$tag_id = 3; // the ID of the tag

$query = $this->Articles->find('all')
                 ->innerJoin('articles_tags', [
                      'Articles.id = articles_tags.article_id',
                      'articles_tags.tag_id' => $tag_id
                 ]);
</code>```

The first join condition has to be the array key. If you use a => array assignment then CakePHP will pass the articles_tags.article_id as a string argument to the join condition. Which won't work.

You can also stack innerJoin for multiple HABTM conditions. For example; find all articles for a tag and also for a category. You can also use the in query expression to match multiple tags.

You can also use the above in pagination like this $articles = $this->paginate($query);

I'm sure this information is out on the web, but this question was the top of google's results. So maybe this will help others.

Body:
I apologize for the horrible title, I couldn't think of how to explain my problem.

In my database I have the following tables, articles, tags, and articles_tags. An article can have many tags.

Currently I am able to grab all the articles, with all the tags, but I want to be able to find articles based upon it's tags.

My select is simple:

$articles = $this->Article->find('all', array(
    // extra condition to check for tag, maybe?
    'conditions'    => array('Article.status' => 'active'),
    'limit'         => $this->articles_per_page,
    'offset'        => ($page_num-1)*$this->articles_per_page
));

My return from the database is as follows:

Array
(
[0] => Array
    (
        [Article] => Array
            (
                [id] => 1
            )

        [Tag] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [name] => Ruby
                        [slug] => ruby
                        [uses] => 1
                        [ArticlesTag] => Array
                            (
                                [id] => 1
                                [article_id] => 1
                                [tag_id] => 1
                            )

                    )

            )

    )

What do I do if I only want to return the articles with a Ruby tag?

Body:
I'm updating this question with an answer for CakePHP 3.x.

You can find all articles for a given tag using an INNER JOIN. The benefit of this join is that it keeps articles as the primary table in the query. Making this an easy solution when you're paginating results by a HABTM join.

$tag_id = 3; // the ID of the tag

$query = $this->Articles->find('all')
                 ->innerJoin('articles_tags', [
                      'Articles.id = articles_tags.article_id',
                      'articles_tags.tag_id' => $tag_id
                 ]);

The first join condition has to be the array key. If you use a => array assignment then CakePHP will pass the articles_tags.article_id as a string argument to the join condition. Which won't work.

You can also stack innerJoin for multiple HABTM conditions. For example; find all articles for a tag and also for a category. You can also use the in query expression to match multiple tags.

You can also use the above in pagination like this $articles = $this->paginate($query);

I'm sure this information is out on the web, but this question was the top of google's results. So maybe this will help others.


问:
ui-router does not transition to child state from abstract parent
After a successful login the my is supposed to transition from the login state to the home state. Prior to the home, or any other state in the app accessible AFTER logging in, I want a few resolve methods to fire, making sure privilege/access data is loaded before the controllers. To do this I've created an abstract parent state with the resolves, and made all states other than login child states.

When the login controller fires $state.go('home'), the $stateChangeStart event is triggered, however the app seems to dissapear in to the ether after that. The $stateChangeSuccess never fires and if I step through the code I simply exit the debugger after $stateChangeStart. The state hasn't changed (I'm still on the login page) and better yet no error messages. Thinking/hoping I have some simple configuration set up improperly.

config.js

```<code>    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('/', {
            templateUrl: 'app/components/home/home.html',
            controller: 'HomeController',
            controllerAs: 'vm',
            parent: 'app',
            authenticate: true,
            data:{
                rule: function($rootScope){
                    return true;
                }
            }
        })
        .state('login', {
            url: '/login',
            templateUrl: 'app/components/login/login.html',
            controller: 'LoginController',
            controllerAs: 'vm',
            reloadOnSearch: false,
            authenticate: false,
            params: {
                'passwordResetSuccess': ''
            }
        })
        .state('forgotPassword', {
            url: '/forgotPassword',
            templateUrl: 'app/components/login/forgotPassword.html',
            controller: 'ForgotPasswordController',
            controllerAs: 'vm',
            authenticate: false,
            params: {
                'username':''
            }
        })
        .state('app', {
            url:'',
            abstract: true,
            template: '<div ui-view class="slide-animation"></div>',
            resolve:{
                privilege: ['privilegesService', function(privilegesService){
                    return privilegesService.getPrivileges().then(privilegesService.privilegesData)
                                                            .catch(privilegesService.getPrivilegesError);
                }],
                alarms: ['alarmsService', function(alarmsService){
                    return alarmsService.setAlarms();
                }],
                firmsData: ['chosenFirmService', function(chosenFirmService){
                    return chosenFirmService.getFirmsData();
                }],
                notifications: ['notificationsService', function(notificationsService){
                    return notificationsService.setupGlobalAccess();
                }],
                releaseNotes: ['releaseNotesService, $rootScope', function(releaseNotesService, $rootScope){
                    $rootScope.loadNotificationData();
                    releaseNotesService.setupGlobalAccess();
                    return;
                }],
                setIdle: ['Idle', function(Idle){
                    Idle.watch();
                    Idle.setIdle(15*60);
                    return;
                }]
            }
        })
        .state('home', {
            url: '/home',
            templateUrl: 'app/components/home/home.html',
            controller: 'HomeController',
            controllerAs: 'vm',
            parent: 'app',
            authenticate: true,
            data:{
                rule: function($rootScope){
                    return true;
                }
            }
        })
</code>```

app.route.js

```<code>    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        $('[data-toggle="popover"]').popover('hide');

        //////////////////
        //Check for auth key if missing redirect to login
        /////////////////
        if(toState.authenticate){
            if(authService.authKeyExists()){
                var authorized = toState.data ? toState.data.rule ? toState.data.rule($rootScope) : true : true;
                if(authorized){
                    if(toState.url.indexOf("/add") > -1){
                        $rootScope.selectedFirmId = null;
                    } else {
                        $rootScope.selectedFirmId = $rootScope.cachedFirmId;
                    }
                    var navigateFromString = fromState && fromState.name ? "Navigated from " + fromState.name + " to " : "Started from ";
                    navigationService.addNavObject("activity", {
                        summary : "Page navigation",
                        activity : navigateFromString + toState.name,
                        page : $location.absUrl().replace("#/", ""),
                        level : "debug"
                    });
                } else {
                    $state.go('home');
                }
            } else {
                event.preventDefault();
                $state.go('login');
            }
        }
    });

    // Hack because ui-router doesn't save previous $state
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
        if(fromState.name){
            $state.lastKnownState = {};
            $state.lastKnownState.name = toState.name;
            $state.lastKnownState.params = toParams;
            $state.previousState = {};
            $state.previousState.name = fromState.name;
            $state.previousState.params = fromParams;
        }
    });
</code>```

index.html

```<code><div class="slide-animation-container">
    <div ui-view id="ng-view" class="slide-animation"></div>
    {{scrollTo}}
</div>
</code>```

答: This is apparently due to the inclusion of $rootScope in the releaseNotes resolve. Removing this dependency allows the app to load.

Body:
After a successful login the my is supposed to transition from the login state to the home state. Prior to the home, or any other state in the app accessible AFTER logging in, I want a few resolve methods to fire, making sure privilege/access data is loaded before the controllers. To do this I've created an abstract parent state with the resolves, and made all states other than login child states.

When the login controller fires $state.go('home'), the $stateChangeStart event is triggered, however the app seems to dissapear in to the ether after that. The $stateChangeSuccess never fires and if I step through the code I simply exit the debugger after $stateChangeStart. The state hasn't changed (I'm still on the login page) and better yet no error messages. Thinking/hoping I have some simple configuration set up improperly.

config.js

    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('/', {
            templateUrl: 'app/components/home/home.html',
            controller: 'HomeController',
            controllerAs: 'vm',
            parent: 'app',
            authenticate: true,
            data:{
                rule: function($rootScope){
                    return true;
                }
            }
        })
        .state('login', {
            url: '/login',
            templateUrl: 'app/components/login/login.html',
            controller: 'LoginController',
            controllerAs: 'vm',
            reloadOnSearch: false,
            authenticate: false,
            params: {
                'passwordResetSuccess': ''
            }
        })
        .state('forgotPassword', {
            url: '/forgotPassword',
            templateUrl: 'app/components/login/forgotPassword.html',
            controller: 'ForgotPasswordController',
            controllerAs: 'vm',
            authenticate: false,
            params: {
                'username':''
            }
        })
        .state('app', {
            url:'',
            abstract: true,
            template: '

',
            resolve:{
                privilege: ['privilegesService', function(privilegesService){
                    return privilegesService.getPrivileges().then(privilegesService.privilegesData)
                                                            .catch(privilegesService.getPrivilegesError);
                }],
                alarms: ['alarmsService', function(alarmsService){
                    return alarmsService.setAlarms();
                }],
                firmsData: ['chosenFirmService', function(chosenFirmService){
                    return chosenFirmService.getFirmsData();
                }],
                notifications: ['notificationsService', function(notificationsService){
                    return notificationsService.setupGlobalAccess();
                }],
                releaseNotes: ['releaseNotesService, $rootScope', function(releaseNotesService, $rootScope){
                    $rootScope.loadNotificationData();
                    releaseNotesService.setupGlobalAccess();
                    return;
                }],
                setIdle: ['Idle', function(Idle){
                    Idle.watch();
                    Idle.setIdle(15*60);
                    return;
                }]
            }
        })
        .state('home', {
            url: '/home',
            templateUrl: 'app/components/home/home.html',
            controller: 'HomeController',
            controllerAs: 'vm',
            parent: 'app',
            authenticate: true,
            data:{
                rule: function($rootScope){
                    return true;
                }
            }
        })

app.route.js

    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        $('[data-toggle="popover"]').popover('hide');

        //////////////////
        //Check for auth key if missing redirect to login
        /////////////////
        if(toState.authenticate){
            if(authService.authKeyExists()){
                var authorized = toState.data ? toState.data.rule ? toState.data.rule($rootScope) : true : true;
                if(authorized){
                    if(toState.url.indexOf("/add") > -1){
                        $rootScope.selectedFirmId = null;
                    } else {
                        $rootScope.selectedFirmId = $rootScope.cachedFirmId;
                    }
                    var navigateFromString = fromState && fromState.name ? "Navigated from " + fromState.name + " to " : "Started from ";
                    navigationService.addNavObject("activity", {
                        summary : "Page navigation",
                        activity : navigateFromString + toState.name,
                        page : $location.absUrl().replace("#/", ""),
                        level : "debug"
                    });
                } else {
                    $state.go('home');
                }
            } else {
                event.preventDefault();
                $state.go('login');
            }
        }
    });

    // Hack because ui-router doesn't save previous $state
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
        if(fromState.name){
            $state.lastKnownState = {};
            $state.lastKnownState.name = toState.name;
            $state.lastKnownState.params = toParams;
            $state.previousState = {};
            $state.previousState.name = fromState.name;
            $state.previousState.params = fromParams;
        }
    });

index.html

    {{scrollTo}}


问:
MYSQL Sort by non alphanumeric
I have a site that stores cooking tutorials. one of the columns in the mysql database holds either Novice, Intermediate, Advanced, Expert. I'd like to know if there was a way to write the MySQL query to order the results in the above fashion? Is this even possible?

答:
You can sort by INSTR if its a small table:

```<code>ORDER BY INSTR('Novice, Intermediate, Advanced, Expert', `colname`)
</code>```

But this will be slow on a large table. Better to just store a numeric value from 1 to 4 and add an index on it. Then translate the number to Novice, Intermediate, Advanced, or Expert when needed. Or perhaps two columns but that could lead to differences between the numeric and textual value.

Title: MYSQL Sort by non alphanumeric

Body:
You can sort by INSTR if its a small table:

ORDER BY INSTR('Novice, Intermediate, Advanced, Expert', `colname`)

But this will be slow on a large table. Better to just store a numeric value from 1 to 4 and add an index on it. Then translate the number to Novice, Intermediate, Advanced, or Expert when needed. Or perhaps two columns but that could lead to differences between the numeric and textual value.


问:
Default keyboard is not coming when Barcode Scanner Device is Connected by Bluetooth in IOS
I am facing issue with keyboard when barcode scanner device is connected using bluetooth.

Flow:

1) I have turned on Bluetooth, and connected barcode scanner device using bluetooth by entering displayed code in it to connect.

2) I am able to use scanner, but the default keyboard is not displaying even we call becomeFirstResponder.

3) When I disconnect the scanner device or turn off bluetooth connectivity then the keyboard is coming.

Note: Below is the link for the Barcode Scanner device i am using

Barcode Scanner Device Information

Anyone faced this kind of issue?
Please suggest how to fix this issue.

Thanks in Advance..!

答: This solution only works on Ipad. when the soft keyboard disappears just press and hold the down arrow on the bottom right of the screen and the soft keyboard will be back.</p>


问:
What is the difference between the `ttest` and `ttest2` function in Matlab
I have two samples X and Y, both are N*1 vectors, I found that in Matlab(R2015), both ttest and ttest2 can accept two samples and give the P value, but their results are somewhat different.

For ttest, ttest(X,Y) gives P = 1.8e-7, for ttest2, ttest2(X,Y) gives P = 8.0e-11. It seems that both functions give relatively low P values. However, I am not familiar with the differences between these two functions, also, if I am going to report the P-value, which value should I choose?

答:
This question is more about statistics than programming.

With two samples, ttest performs a paired t-test while ttest2 does a
genuine two-sample test. The paired test is equivalent to a one-sample t-test
on the difference of the paired values.


问:
Extract data from yahoo finance using Excel VBA
Hi I need help with this code I'm trying to extract data from this page https://finance.yahoo.com/quote/ADM.L/balance-sheet?p=ADM.L ,
but the problem is page is by default set to annual but I need quarterly values of total assets and total liabilities.

This code runs but most of the time it is picking annual values. Please suggest something what can I do.

```<code>Private Sub CommandButton3_Click()
'
Dim ie As Object
Set Rng = Range("A2:A50")
Set Row = Range(Rng.Offset(1, 0), Rng.Offset(1, 0).End(xlDown))
Set ie = CreateObject("InternetExplorer.Application")
With ie
'.Visible = False
For Each Row In Rng
.navigate "https://finance.yahoo.com/quote/" & Range("A" & Row.Row).Value & "/balance-sheet?p=" & Range("A" & Row.Row).Value
'Application.Wait (Now + TimeValue("0:00:02"))
While ie.readyState <> 4
Wend

Do While ie.Busy: DoEvents: Loop

Dim doc As HTMLDocument
Set doc = ie.document

doc.getElementsByClassName("P(0px) M(0px) C($actionBlue) Bd(0px) O(n)")(2).Click

Do While ie.Busy: DoEvents: Loop
Application.Wait (Now + TimeValue("0:00:05"))
Range("D" & Row.Row).Value = doc.getElementsByClassName("Fw(b) Fz(s) Ta(end)")(4).innerText
Range("E" & Row.Row).Value = doc.getElementsByClassName("Fw(b) Fz(s) Ta(end)")(12).innerText
Range("F" & Row.Row).Value = doc.getElementsByClassName("C($gray) Ta(end)")(0).innerText

Next Row
End With
ie.Quit
'
End Sub
</code>```

答:
It is not possible to extract Quarterly data from Yahoo using VBA.
Annual data can be extracted, but not quarterly.</p>

Body:
Hi I need help with this code I'm trying to extract data from this page https://finance.yahoo.com/quote/ADM.L/balance-sheet?p=ADM.L ,
but the problem is page is by default set to annual but I need quarterly values of total assets and total liabilities.

This code runs but most of the time it is picking annual values. Please suggest something what can I do.

Private Sub CommandButton3_Click()
'
Dim ie As Object
Set Rng = Range("A2:A50")
Set Row = Range(Rng.Offset(1, 0), Rng.Offset(1, 0).End(xlDown))
Set ie = CreateObject("InternetExplorer.Application")
With ie
'.Visible = False
For Each Row In Rng
.navigate "https://finance.yahoo.com/quote/" & Range("A" & Row.Row).Value & "/balance-sheet?p=" & Range("A" & Row.Row).Value
'Application.Wait (Now + TimeValue("0:00:02"))
While ie.readyState <> 4
Wend

Do While ie.Busy: DoEvents: Loop

Dim doc As HTMLDocument
Set doc = ie.document

doc.getElementsByClassName("P(0px) M(0px) C($actionBlue) Bd(0px) O(n)")(2).Click

Do While ie.Busy: DoEvents: Loop
Application.Wait (Now + TimeValue("0:00:05"))
Range("D" & Row.Row).Value = doc.getElementsByClassName("Fw(b) Fz(s) Ta(end)")(4).innerText
Range("E" & Row.Row).Value = doc.getElementsByClassName("Fw(b) Fz(s) Ta(end)")(12).innerText
Range("F" & Row.Row).Value = doc.getElementsByClassName("C($gray) Ta(end)")(0).innerText

Next Row
End With
ie.Quit
'
End Sub


问:
Flex-lex: Match r if there is something in front of it
Using flex,

how do you match something when there is something in front of it.

for example: If there is R before D print something

I tried

{something}/D          {printf("V");}

but it doesn't work.

答:
That's not how (f)lex works. (F)lex is a tokeniser; it splits the input into consecutive tokens. At each point in the input, it selects the appropriate token starting at precisely that point; the next token will start at the end of the previous token.

If you want to recognize certain tokens only in some particular context, you can use start conditions, but it is your responsibility to notice context changes. So you could, for example, change to a different start condition in the action associated with any token which ends with an R:

```<code>%x AFTER_R
%%
[[:alpha:]]+   { if (yytext[yyleng-1] == 'R') BEGIN(AFTER_R);
                 /* handle this token */
               }
  /* Etc. for other patterns which might end with an R */
<AFTER_R>"D"   { puts("Found a D after an R"); }
</code>```

Excessive use of start conditions can make lexical description files hard to read and debug; it may indicate that your problem is not well-suited to the (f)lex tokenizing model.

Body:
That's not how (f)lex works. (F)lex is a tokeniser; it splits the input into consecutive tokens. At each point in the input, it selects the appropriate token starting at precisely that point; the next token will start at the end of the previous token.

If you want to recognize certain tokens only in some particular context, you can use start conditions, but it is your responsibility to notice context changes. So you could, for example, change to a different start condition in the action associated with any token which ends with an R:

%x AFTER_R
%%
[[:alpha:]]+   { if (yytext[yyleng-1] == 'R') BEGIN(AFTER_R);
                 /* handle this token */
               }
  /* Etc. for other patterns which might end with an R */
<AFTER_R>"D"   { puts("Found a D after an R"); }

Excessive use of start conditions can make lexical description files hard to read and debug; it may indicate that your problem is not well-suited to the (f)lex tokenizing model.


问:
Validate username and password without postback in login form ASP.NET MVC
I want to validate the entered username and password entered in the textboxes present in a form without Postback/Refresh. I know I am gonna need Javascript or AJAX for this purpose, but somebody please guide me through this like refer me to any tutorial or please explain me the code here.
My present code without this feature looks like this:</p>

```<code>@using(Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(u => u.PPNumber, new { @class = "form-control", type = "number", placeholder = "Enter Number",@min="1" })
    @Html.ValidationMessageFor(u => u.PPNumber)
    @Html.TextBoxFor(u => u.Password, new { @class = "form-control", type = "Password", placeholder = "Password" })
    @Html.ValidationMessageFor(u => u.Password)
    <input type="submit" value="Login" class="btn btn-primary btn-block" />
}
</code>```

答:
You can use ajax.

When user submits the form, you need to hijack that event in javascript and stop that(prevent the normal full page form submit) and instead make an ajax call to the action method with the form data. This action method should have code to verify the user credentials and can return a JSON data structure which has a status property which says whether the credential validation is successful or not. You can inspect this response in your ajax call's success/done callback and act accordingly.

Here is a quick sample using jQuery $.post method.

Give an Id to your form so that we can use that to wire up the submit event.

```<code>@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id="loginForm"))
{
    @Html.TextBoxFor(u => u.PPNumber)
    @Html.TextBoxFor(u => u.Password, new { @class = "form-control", type = "Password"})
    <input type="submit" value="Login" class="btn btn-primary btn-block" />
}
</code>```

and the javascript code to hijack the submit event and do an ajax post instead.

```<code>$(function () {

    $("#loginForm").submit(function(e) {
        e.preventDefault();
        $.post($(this).attr("action"), $(this).serialize())
            .done(function(response) {
                if (response.status === 'success') {
                    alert("Login successful.Do something else now");
                } else {
                    alert("Login failed");
                }
            });
    });
});
</code>```

Assuming your Login action method in AccountController will return a Json response with a status property.

```<code>public ActionResult Login(string PPNumber,string password)
{
    if(PPNumber=="thisIsDemo" && password=="ButDoTheActualCheck")
    {
        return Json(new { status = "success" });
    }
    return Json(new { status = "failed" });
}
</code>```

Here i just hard coded the usrename /password check to 2 static values. You can change that to check it against your db table/whatever your credentials checking mechanism is.

Body:
I want to validate the entered username and password entered in the textboxes present in a form without Postback/Refresh. I know I am gonna need Javascript or AJAX for this purpose, but somebody please guide me through this like refer me to any tutorial or please explain me the code here.
My present code without this feature looks like this:

@using(Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(u => u.PPNumber, new { @class = "form-control", type = "number", placeholder = "Enter Number",@min="1" })
    @Html.ValidationMessageFor(u => u.PPNumber)
    @Html.TextBoxFor(u => u.Password, new { @class = "form-control", type = "Password", placeholder = "Password" })
    @Html.ValidationMessageFor(u => u.Password)
    <input type="submit" value="Login" class="btn btn-primary btn-block" />
}

Body:
You can use ajax.

When user submits the form, you need to hijack that event in javascript and stop that(prevent the normal full page form submit) and instead make an ajax call to the action method with the form data. This action method should have code to verify the user credentials and can return a JSON data structure which has a status property which says whether the credential validation is successful or not. You can inspect this response in your ajax call's success/done callback and act accordingly.

Here is a quick sample using jQuery $.post method.

Give an Id to your form so that we can use that to wire up the submit event.

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id="loginForm"))
{
    @Html.TextBoxFor(u => u.PPNumber)
    @Html.TextBoxFor(u => u.Password, new { @class = "form-control", type = "Password"})
    <input type="submit" value="Login" class="btn btn-primary btn-block" />
}

and the javascript code to hijack the submit event and do an ajax post instead.

$(function () {

    $("#loginForm").submit(function(e) {
        e.preventDefault();
        $.post($(this).attr("action"), $(this).serialize())
            .done(function(response) {
                if (response.status === 'success') {
                    alert("Login successful.Do something else now");
                } else {
                    alert("Login failed");
                }
            });
    });
});

Assuming your Login action method in AccountController will return a Json response with a status property.

public ActionResult Login(string PPNumber,string password)
{
    if(PPNumber=="thisIsDemo" && password=="ButDoTheActualCheck")
    {
        return Json(new { status = "success" });
    }
    return Json(new { status = "failed" });
}

Here i just hard coded the usrename /password check to 2 static values. You can change that to check it against your db table/whatever your credentials checking mechanism is.


问:
Parsing Human Names and matching them in Ruby
I'm looking for a gem or project that would let me identify that two names are the same person.  For example

J.R. Smith == John R. Smith == John Smith == John Roy Smith == Johnny Smith

I think you get the idea.  I know nothing is going to be 100% accurate but I'd like to get something that at least handles the majority of cases.  I know that last one is probably going to need a database of nicknames.

答:
I don't think such a library exists.

I don't mean to offend, but this problem seems like it arises from poor design. Maybe if you post more details about the general problem you are trying to solve, people can suggest a better way.

ContentLicense: CC BY-SA 2.5


问:
Convert Slim code to ERB
I have this slim code:

```<code>.search-wrapper
  - if content_for?(:fulltext_search)
    = yield(:fulltext_search)
  - else
    - placeholder = nil unless defined? placeholder
    = form_tag collection_path, method: :get
      .input-group style='margin-bottom: 0;'
        = text_field_tag :term, params[:term], placeholder: placeholder || t(:search, default: 'search'), class: 'form-control'
        .btn-group
          button.btn.btn-search tabindex="-1" type='submit' title=t(:search, default: 'search')
            i.fa.fa-search
</code>```

I want to convert to erb code. I have tried for some first lines:

```<code><div class="search-wrapper">
  <% if content_for(:fulltext_search) %>
      <%= yield(:fulltext_search) %>
  <% else %>
  <% placeholder = nil unless defined? placeholder %>
      <%= form_tag collection_path, method: :get %>
  <% end %>
</div>
</code>```

The think I am struggling is. I don't know how to convert this code to erb:

```<code>= form_tag collection_path, method: :get
  .input-group style='margin-bottom: 0;'
</code>```

Please tell me how to converting above code.

thanks

答:
The easiest way is to use the built-in erb converter. Why not use that?

Just run:

```<code>slimrb -e your_file.slim
</code>```

You get everything converted to erb.

Title: Convert Slim code to ERB

Body:
I have this slim code:

.search-wrapper
  - if content_for?(:fulltext_search)
    = yield(:fulltext_search)
  - else
    - placeholder = nil unless defined? placeholder
    = form_tag collection_path, method: :get
      .input-group style='margin-bottom: 0;'
        = text_field_tag :term, params[:term], placeholder: placeholder || t(:search, default: 'search'), class: 'form-control'
        .btn-group
          button.btn.btn-search tabindex="-1" type='submit' title=t(:search, default: 'search')
            i.fa.fa-search

I want to convert to erb code. I have tried for some first lines:

  <% if content_for(:fulltext_search) %>
      <%= yield(:fulltext_search) %>
  <% else %>
  <% placeholder = nil unless defined? placeholder %>
      <%= form_tag collection_path, method: :get %>
  <% end %>

The think I am struggling is. I don't know how to convert this code to erb:

= form_tag collection_path, method: :get
  .input-group style='margin-bottom: 0;'

Please tell me how to converting above code.

thanks

Body:
The easiest way is to use the built-in erb converter. Why not use that?

Just run:

slimrb -e your_file.slim

You get everything converted to erb.


问:
Replace two buttons with a toggle switch
I have the following code:

```<code><img id="v1" src="pic1.jpg"><br>
<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>
<br>
<img id="v2" src="pic3.jpg"><br>
<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>
<br>
</code>```

However, I would like to replace these 'Before' and 'After' buttons with a toggle switch (already made) in the form of a checkbox:

```<code><label class="switchBA">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</code>```

In a way that each time it's clicked it switches between the two functions. I guess this needs to be done inline since these are just two of many comparisons.

Thanks in advance.

P.S: I would like to do with only with JS. No need for jQuery or other frameworks.

答:
Here's a nice way to achieve this by listening for the toggle in javascript and setting the image to that of the custom data attribute set under the image tag.

var toggleClass = document.getElementsByClassName("toggle");

var toggleFunction = function() {
  var imageElement = this.parentElement.parentElement.getElementsByClassName("imageItem")[0];
  if(this.checked){
    imageElement.src = imageElement.getAttribute("data-image-2");
  }else{
    imageElement.src = imageElement.getAttribute("data-image-1");
  }
};

for (var i = 0; i < toggleClass.length; i++) {
    toggleClass[i].addEventListener('click', toggleFunction, false);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}</code>```

Toggle Image Demo

    <input class="toggle" type="checkbox">

    <input class="toggle" type="checkbox">

```

Taking this approach over CSS and Backgrounds or setting the second image URL in the javascript should help keep the code cleaner. Also by doing this, the code will be easier to scale to accommodate multiple images toggles on one page without changing the Javascript.

Body:
I have the following code:

<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>

<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>

However, I would like to replace these 'Before' and 'After' buttons with a toggle switch (already made) in the form of a checkbox:

<input type="checkbox" checked>

In a way that each time it's clicked it switches between the two functions. I guess this needs to be done inline since these are just two of many comparisons.

Thanks in advance.

P.S: I would like to do with only with JS. No need for jQuery or other frameworks.

Body:
Here's a nice way to achieve this by listening for the toggle in javascript and setting the image to that of the custom data attribute set under the image tag.

var toggleClass = document.getElementsByClassName("toggle");

var toggleFunction = function() {
  var imageElement = this.parentElement.parentElement.getElementsByClassName("imageItem")[0];
  if(this.checked){
    imageElement.src = imageElement.getAttribute("data-image-2");
  }else{
    imageElement.src = imageElement.getAttribute("data-image-1");
  }
};

for (var i = 0; i < toggleClass.length; i++) {
    toggleClass[i].addEventListener('click', toggleFunction, false);
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

<h2>Toggle Image Demo</h2>
<div class="imageContainer">
  <img class="imageItem" src="https://lorempixel.com/400/200/sports/5/Image1/" data-image-1="https://lorempixel.com/400/200/sports/5/Image1/" data-image-2="https://lorempixel.com/400/200/sports/6/Image2/">

  <label class="switch">
    <input class="toggle" type="checkbox">
    <span class="slider"></span>
  </label>
</div>
<div class="imageContainer">
  <img class="imageItem" src="https://lorempixel.com/400/200/sports/5/Image1/" data-image-1="https://lorempixel.com/400/200/sports/5/Image1/" data-image-2="https://lorempixel.com/400/200/sports/6/Image2/">

  <label class="switch">
    <input class="toggle" type="checkbox">
    <span class="slider"></span>
  </label>
</div>

Taking this approach over CSS and Backgrounds or setting the second image URL in the javascript should help keep the code cleaner. Also by doing this, the code will be easier to scale to accommodate multiple images toggles on one page without changing the Javascript.


问:
How do I store a custom user selected CSS template style (like wordpress visual editor)?
I am making a diary app. I want users to be able to customize/style the skin of their journal e.g. covers/backgrounds/fonts/colors etc.

I want to create something like the wordpress theme editor that allows users to update the background color in real time:

Here is how style editor would look.

For example if a user wants to set the writing area of the diary to a light yellow, how do I save that color into a custom CSS template and then render it again? Would I need to create a MySQL table just for style templates and have a row for color, background-color, etc... ?

答:
It is hard to explain how to deal with your issue without knowing your complete environment and complete use-case. I assume, by your tags, that you use PHP to fetch your pages using the Laravel framework.

Now, you have several ways of doing what you are asking. But all ways reduce to one thing : how are you willing to manage persistence ?

Basically, you want users being able to "save" variables (in your case a variable like say "background_cover" or something similar) so that they can get a better visual experience or for tuning colors etc...

There are a lot of ways to store a variable, here are some of the most commonly used as of 2017:

LocalStorage: you basically store a background_color = yellow into each user's browser. This is cool as it's easy to implement, but it is quite not the best way to persist data. If the user clear its cache: he's gonna lose the data... simple as that. I would suggest you go this route first, and evolves to other methods if you need more persistence. Also, don't forget the variable is stored in user's browser, this means it is not shareable to any other user later: it's private.

On-Demand storage: A pretty good solution nowadays, given the cloud being more reliable each day. I would first go to on-demand solutions like Firebase by Google. It just let you send REST commands to save or retrieve whatever... and even using real-time capabilities. It's reliable. It's scalable. It's used by big names. Hard to do better for this little investment in time and money. You can use it using any technology able to send a /POST or /GET request like PHP does. You just need a thin client to better manipulate these requests and make sure they are always handled (supported by old internet explorer or mobile browsers...). One of those thin clients I'd recommend is axios and from what I know it is supported by Laravel. This is clearly the path I would suggest you if LocalStorage is not a good fit for your use-case.

NoSQL databases: MongoDB and the likes are databases that are not really databases in the pure sense of it. Rather you could CONCEPTUALLY think them as an infinite notepad where you would write and read from as needed. Obviously it's not that simple but you get the point. They are quite fast and reliable for production persistence. There may be connectors for you to plug them somewhat easily into Laravel so that you could run some commands against it in a few hours of learning curve. Be carefull, most of NoSQL solution are more "Javascript-oriented" so you can get lost in your way. Nevertheless, it's a rather good approach to build a big app though it is not designed just to store 1 or 2 things, rather it is better at modeling relationships between data. But well, due to its popularity I'd say developers overused it for other purposes.

Relational Database: Mysql, PostGreSql etc... are databases that uses SQL to store and retrieve entries. Clearly, it has a lot of performance behind the scenes but you should be warned that it also envolves A LOT of resources before you can just say "store this please". Most of the time it implies you installing the database on a server (which you should maintain as well...), learn SQL (quite easy but it's still something), and figure out how to model your data (primary keys, indexes etc...) then gather a solution able to connect the database to your PHP application so that you can run some SQL commands against it.
Clearly, this is not a "plug-n-play" solution: if you don't know it yet, clear yourself 50 hours of time just to be able to run a working SQL command from your app, or hire someone.
This would be the LAST thing i'd recommend in quite any case. SQL Databases or RDBMS are better at retrieving huge data, I think it's a non-sense to go this route just for two variables.

Let me know if this answer is ok for you.

EDIT

After seeing some other replies, I am wondering what level of depth is asked. I originally thought the question "How do I store..." like a broader workflow explanation. If really the need is to have real code to persist data, I would say this is a duplicate of this question.

Now the whole procedure depends on the architecture already available but to stick with my proposition using firebase and axios it all boils down to :

register to firebase

generate a private API key in Firebase

create an API endpoint named say /POST/user/preferences in Firebase that will store "selected_color" (and other variables if needed)

create an HTML page to authenticate a user using Firebase (by email, facebook or whatever)

create an HTML page with a form that matches the options to give to the user (here a color switch for example)

Create a workflow to serve login-page first, then authorize the user to go to the "color selection" form if the login/password is ok.

Let the user pick his favorite color

Make the user submit the form (click on SAVE)

/POST the form data (including the API_KEY + USER_ID + SELECTED_COLOR) using axios to the firebase endpoint API

Done.

Now, whenever the user returns back to the page, you want to display the selected color back to its interface. For this, the procedure would look like:

Make the user login using Firebase

before fetching the relevant page, you want to retrieve back the variables you previously stored in Firebase using axios by requesting the endpoint with a /GET method.

Once you have the data loaded in a PHP variable, you can update your CSS accordingly by generating a new CSS file based on the variables from your PHP server

Then you can send the page to the user with relevant variables already plugged-in

Once again, we don't have enough input to gather the conditions into giving a specific answer to the problem.

Now I don't think StackOverflow is a good fit to make a whole tutorial on how to implement those steps one by one. Either the question is too broad and please fill in another more specific question about the exact part that is blocking/buggy/not understood... or you may look for some more detailed tutorials on Laravel/PHP. I can suggest this video series (I have no links with this site whatsoever) on the matter: they are of very good quality (I used them to learn Vue.js which could also serve as a front-end framework for PHP) and will surely lead you to your desired use-case.
If not, please edit the question to the exact step you need.
:)


问:
Display result of Pdo
Hi i have an slight problem i'm trying top geht tow Results of My pdo query and Print Them but No such luck i've probably just Made a Stupid mistake i'm Not seeing The query seems to be finde so it does make a difference if the name is in the database (and it makes a difference if you put it in quotes) probably the variables are getting a null value or something...</p>

```<code>$username="xxx";
$firstname="xxx";
$check=0;
    if (isset($_GET['u'])){
        $username=strip_tags(@$_GET['u']);
        if (ctype_alnum($username)){
            $check=$stmt=$link->prepare("SELECT * FROM
users WHERE username = ?");
            $stmt->execute(array($username));
            $check=$stmt->fetchAll();
            if(count($check)==1){
                $get=$stmt->fetch(PDO::FETCH_BOTH);
                echo "$get";
                $username =$get["username"];
                $firstname = $get["first_name"];
            }else{
                echo "<h2> User does not exist!</h2>";
                exit();
            }
        }
    }
?>
<h2>Profilepage for: <?php echo "$username"; ?></h2>
<h2>First name: <?php echo "$firstname"; ?></h2
</code>```

答:
$stmt->fetchAll() is fetching all the results of the query. Once this is done, there are no more results available for $stmt->fetch() to fetch. You should get the data from the $check array.

```<code>if (count($check) == 1) {
    $get = $check[0];
    $username = $get["username"];
    $firstname = $get["first_name"];
} else {
    echo "<h2> Username does not exist </h2>";
    exit();
}
</code>```

Or you could just replace the fetchAll with fetch.

```<code>$stmt->execute(array($username));
$get = $stmt->fetch(PDO::FETCH_ASSOC);
if ($get) {
    $username = $get["username"];
    $firstname = $get["first_name"];
} else {
    echo "<h2> Username does not exist </h2>";
    exit();
}
</code>```

Also, echo "$get" makes no sense. $get is an array, you can't echo it, you need to use print_r($get) or var_dump($get).

Title: Display result of Pdo

Body:
Hi i have an slight problem i'm trying top geht tow Results of My pdo query and Print Them but No such luck i've probably just Made a Stupid mistake i'm Not seeing The query seems to be finde so it does make a difference if the name is in the database (and it makes a difference if you put it in quotes) probably the variables are getting a null value or something...

$username="xxx";
$firstname="xxx";
$check=0;
    if (isset($_GET['u'])){
        $username=strip_tags(@$_GET['u']);
        if (ctype_alnum($username)){
            $check=$stmt=$link->prepare("SELECT * FROM
users WHERE username = ?");
            $stmt->execute(array($username));
            $check=$stmt->fetchAll();
            if(count($check)==1){
                $get=$stmt->fetch(PDO::FETCH_BOTH);
                echo "$get";
                $username =$get["username"];
                $firstname = $get["first_name"];
            }else{
                echo "
 User does not exist!
";
                exit();
            }
        }
    }
?>

Profilepage for: <?php echo "$username"; ?>

First name: <?php echo "$firstname"; ?></h2

Body:
$stmt->fetchAll() is fetching all the results of the query. Once this is done, there are no more results available for $stmt->fetch() to fetch. You should get the data from the $check array.

if (count($check) == 1) {
    $get = $check[0];
    $username = $get["username"];
    $firstname = $get["first_name"];
} else {
    echo "<h2> Username does not exist </h2>";
    exit();
}

Or you could just replace the fetchAll with fetch.

$stmt->execute(array($username));
$get = $stmt->fetch(PDO::FETCH_ASSOC);
if ($get) {
    $username = $get["username"];
    $firstname = $get["first_name"];
} else {
    echo "<h2> Username does not exist </h2>";
    exit();
}

Also, echo "$get" makes no sense. $get is an array, you can't echo it, you need to use print_r($get) or var_dump($get).


问:
Active admin dashboard redirect
When an admin logs in, it automatically redirects to the main home page (i.e. not the admin dashboard). It is happening because i have already specified a dashboard_path in my application controller therefore it always redirects to that path. can anyone tell me how can i chnage path for active_admin.

Application_controller.rb

```<code>def after_sign_in_path_for(resource)
  admin_dasboard_path || session[:application_url] || dashboard_path
end
</code>```

It is not working for admin.

答: Load an Active Admin initializer file and define config.load_paths to set the new url / endpoint of active admin. More details here

Title: Active admin dashboard redirect

Body:
When an admin logs in, it automatically redirects to the main home page (i.e. not the admin dashboard). It is happening because i have already specified a dashboard_path in my application controller therefore it always redirects to that path. can anyone tell me how can i chnage path for active_admin.

Application_controller.rb

def after_sign_in_path_for(resource)
  admin_dasboard_path || session[:application_url] || dashboard_path
end

It is not working for admin.


问:
VueJS 1.0 : how to use a method of a component itself in an attribute?
I have defined a VueJS component my_button, with a property 'caption' and a method 'click_button'.

I use this component in another VueJS component

```<code><template ....
    <my_button
      caption="test"
      v-on:click="click_button"
    >
    </my_button>
</template>
</code>```

The problem is that when I click the button it complains about the click_button function being in the wrong scope (apparently of the parent component instead of my_button).

How can I make it refer to the click_button of my_button ? I tried this.click_button and $this.click_button, but of course that didnt work.

答:
I imagine that in your my_button component, you have a button. There, do something like:

```<code><button onClick="click_button">{{caption}}</button>
</code>```

Body:
I have defined a VueJS component my_button, with a property 'caption' and a method 'click_button'.

I use this component in another VueJS component

<template ....
    <my_button
      caption="test"
      v-on:click="click_button"
    >
    </my_button>
</template>

The problem is that when I click the button it complains about the click_button function being in the wrong scope (apparently of the parent component instead of my_button).

How can I make it refer to the click_button of my_button ? I tried this.click_button and $this.click_button, but of course that didnt work.

Body:
I imagine that in your my_button component, you have a button. There, do something like:

<button onClick="click_button">{{caption}}</button>


问:
How To Disable Uploading Within a Time Limit
How can I keep a client from uploading more after having uploaded something within a time limit?  Based on IP address.</p>

答:
You can retrieve IP address using $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_X_FORWARDED_FOR'] variables, and store it somewhere together with request date (for example, in database). On each upload request you can check, whether (last upload time from this IP) - (current time) > period.

BTW, user is not always bound to single IP, and single IP can be used by many users. So, for example, this will restrict uploading from users, who are hidden behind the same NAT.


问:
appium how to type into textField automatically
hello i'm working on ui-test  nativescript, with the appium plugin, I would like to know how to insert text in a field, I notify that I have already tried

type("hello");
sendKeys("Text");
setValue("text");
getKeyboard().sendKeys("Text");
setText("text");

they return to me all, example for type("hello");

type is not a function

i added a screenshot for more details !

what is the good function to use ?

答:
My guess is that you are using nativescript-
dev-appium, that is a wrapper over wd (node.js client for webdriver/appium)

This should work:

```<code>const element = await mascotteValue.element()
await element.sendKeys("text")
</code>```

The error you face basically means there is not such function for ui-element object and you can see all the available ones here.

Body:
My guess is that you are using nativescript-
dev-appium, that is a wrapper over wd (node.js client for webdriver/appium)

This should work:

const element = await mascotteValue.element()
await element.sendKeys("text")

The error you face basically means there is not such function for ui-element object and you can see all the available ones here.


问:
AngularJS Provider doesn't accept ES6 function declaration
I've been trying to rewrite some code of ours to comply with ES6 and have encountered the following issue.

angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
  Error: [$injector:pget] Provider 'books' must define $get factory method.

This is when I write the provider object in this code.

```<code>(() => {
    const app = angular.module('app', []);

    const books = () => { // Error is here
        let includeVersionInTitle = false;

        this.$get = () => {
            const appName = "Book Logger";
            const appDesc = "Track which books you read.";
            let version = "1.0";

            appName = (includeVersionInTitle) ? (appName += " " + version) : appName;

            return {
                appName: appName,
                appDesc: appDesc
            }
        };

        this.setIncludeVersionInTitle = (value) => {
            includeVersionInTitle = value;
        };
    };

    app.provider("books", [books]);
})();
</code>```

When I change const books = () => { ... } to this, const books = function() { ... }. It'll work and not throw that error.

I thought that const a = function() { ... } and const a = () => { ... } where the same thing? Why does it throw this error out?

答:
Arrow functions do not have their own "this", but use that of the surrounding code.  You must use a traditional function.

```<code>this.$get = function() {
</code>```

You can check out a deeper explanation here:

https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/

Body:
I've been trying to rewrite some code of ours to comply with ES6 and have encountered the following issue.

angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
  Error: [$injector:pget] Provider 'books' must define $get factory method.

This is when I write the provider object in this code.

(() => {
    const app = angular.module('app', []);

    const books = () => { // Error is here
        let includeVersionInTitle = false;

        this.$get = () => {
            const appName = "Book Logger";
            const appDesc = "Track which books you read.";
            let version = "1.0";

            appName = (includeVersionInTitle) ? (appName += " " + version) : appName;

            return {
                appName: appName,
                appDesc: appDesc
            }
        };

        this.setIncludeVersionInTitle = (value) => {
            includeVersionInTitle = value;
        };
    };

    app.provider("books", [books]);
})();

When I change const books = () => { ... } to this, const books = function() { ... }. It'll work and not throw that error.

I thought that const a = function() { ... } and const a = () => { ... } where the same thing? Why does it throw this error out?

Body:
Arrow functions do not have their own "this", but use that of the surrounding code.  You must use a traditional function.

this.$get = function() {

You can check out a deeper explanation here:

https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/


问:
TSQL ROW_NUMBER() OVER (PARTITION BY... ORDER BY....)
Can I do row_number without partition? (see data at end of post) I can use this statement to get an ORDER#.

```<code>     ROW_NUMBER() OVER (PARTITION BY LOG_ID ORDER BY ORDER_ID)
</code>```

Any suggestions to get the LOG# ?

```<code>-LOG#   ORDER#  LOG_ID  ORDER_ID
-1      1       340580  387373215
-1      2       340580  387373225
-2      1       340925  387812330
-3      1       340935  388093450
-4      1       340945  387615845
-5      1       340990  386433405
-6      1       341675  376247120
-6      2       341675  376247130
-6      3       341675  388352445
</code>```

Body:
Can I do row_number without partition? (see data at end of post) I can use this statement to get an ORDER#.

     ROW_NUMBER() OVER (PARTITION BY LOG_ID ORDER BY ORDER_ID)

Any suggestions to get the LOG# ?

-LOG#   ORDER#  LOG_ID  ORDER_ID
-1      1       340580  387373215
-1      2       340580  387373225
-2      1       340925  387812330
-3      1       340935  388093450
-4      1       340945  387615845
-5      1       340990  386433405
-6      1       341675  376247120
-6      2       341675  376247130
-6      3       341675  388352445

Body:
declare @yourtable table ([ORDER#] int, LOG_ID int, ORDER_ID bigint);
insert @yourtable values
(1,340580,387373215),
(2,340580,387373225),
(1,340925,387812330),
(1,340935,388093450),
(1,340945,387615845),
(1,340990,386433405),
(1,341675,376247120),
(2,341675,376247130),
(3,341675,388352445);

select [-LOG#] = -dense_rank() over (order by LOG_ID), *
from @yourtable;

Returns

-LOG#                ORDER#      LOG_ID      ORDER_ID
-------------------- ----------- ----------- --------------------
-1                   1           340580      387373215
-1                   2           340580      387373225
-2                   1           340925      387812330
-3                   1           340935      388093450
-4                   1           340945      387615845
-5                   1           340990      386433405
-6                   1           341675      376247120
-6                   2           341675      376247130
-6                   3           341675      388352445

Edit: @bacon bits beat me to it. :(


问:
HTML & CSS for printed posters

Introduction

HTML5 tools such as deck.js or reveal.js seem great for presentations, including scientific presentations where good-looking mathematics can easily be added with MathJax.

Closely related to scientific presentations are printed posters (examples), and I am wondering if it would be possible to use HTML & CSS to produce them. This seems to me to be a good idea because:

Images, tables, mathematics etc can all be easily included

Typical grid-based layouts are commonly in both posters and HTML/CSS

The content would be well-separated from the presentation, making re-use easier (e.g. between presentations and posters)

A copy of the poster could be shared on the web with little modification

The problem is that most CSS frameworks (e.g. Bootstrap) allow for fixed-width layouts but assume that the page will scroll down as far as necessary to fit all the content. On the other hand, for a poster the layout needs to behave similarly in the horizontal and vertical directions, with a grid which fills the exact dimensions of the paper.

Questions

Are there any CSS frameworks that allow easy layout of content on a fixed-width & fixed-height 2D grid?

Are any special techniques needed to get from the HTML page to, say, an A1 size PDF?

Edit:

I know about LaTeX and have used it to make presentations and reports. It's possible to use it for posters too, but my experience has been that it very quickly requires a lot more tweaking and knowledge if you need to alter the most basic poster layouts.

答:
It is surprisingly straightforward to roll out your own CSS/HTML template for a printer poster. It is much easier than LaTeX with its weird defaults and obtuse treatment of graphics, layout, and color. And it is much neater than PowerPoint as it provides a lot more consistency and "reuse/programmability" in the creation of the layout.

First of all, you need to set the size of your paper:

```<code>body {
width: 48in;
height: 36in;
}
</code>```

Then you need some generic layout:

```<code><body>
<div class="poster">
  <h1 class="poster-title">...</h1>
  <h2 class="poster-authors">...</h2>
  <h3 class="poster-affiliations">...</h3>
  <hr class="fancy-line">
  <div class="container">
    <div class="row">
      <!-- A bunch of Bootstrap columns (but here it would be a good place to
      use CCS Grids too) -->
    </div>
  </div>
</div>
</body>
</code>```

And if you like the defaults of a CSS library like Bootstrap, you can use it for most of the components (I particularly like the panels).

You can also use some newer flexbox styling for a neater layout

I have template based on those ideas that I would be happy to share (and a somewhat longer description of the tools I used)

And here is an example of a poster built with it

It is not a ready to use CSS framework, but importantly, it is just 20ish lines of custom CSS you can put on top of any CSS framework.

Title: HTML & CSS for printed posters

Body:
It is surprisingly straightforward to roll out your own CSS/HTML template for a printer poster. It is much easier than LaTeX with its weird defaults and obtuse treatment of graphics, layout, and color. And it is much neater than PowerPoint as it provides a lot more consistency and "reuse/programmability" in the creation of the layout.

First of all, you need to set the size of your paper:

body {
width: 48in;
height: 36in;
}

Then you need some generic layout:

<body>
<div class="poster">
  <h1 class="poster-title">...</h1>
  <h2 class="poster-authors">...</h2>
  <h3 class="poster-affiliations">...</h3>
  <hr class="fancy-line">
  <div class="container">
    <div class="row">
      <!-- A bunch of Bootstrap columns (but here it would be a good place to
      use CCS Grids too) -->
    </div>
  </div>
</div>
</body>

And if you like the defaults of a CSS library like Bootstrap, you can use it for most of the components (I particularly like the panels).

You can also use some newer flexbox styling for a neater layout

I have template based on those ideas that I would be happy to share (and a somewhat longer description of the tools I used)

And here is an example of a poster built with it

It is not a ready to use CSS framework, but importantly, it is just 20ish lines of custom CSS you can put on top of any CSS framework.


问:
Using "Microsoft Save as PDF" add-in programmatically without installing Word
The sample code in this article for creating a PDF from a Word doc works great if you have word installed on the machine.

http://msdn.microsoft.com/en-us/library/bb412305.aspx

I'm curious if it is possible to do this without having to install Word.

答:
I ended up using OpenOffice Portable...

http://portableapps.com/apps/office/openoffice_portable


问:
react-router-dom: getting props.location from within <BrowserRouter> component
I have a simple App that uses BrowserRouter from 'react-router-dom' v4. I'm trying to access the location.pathname property from within the <BrowserRouter/> component, without avail:

```<code>class App extends Component{
  render(){
    return (
      <BrowserRouter>
        // How do I access this.props.location?
        <div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
          <Switch>
            <Route path="/login" component={LoginPage}/>
            <Route path="/success" component={LoginSuccess}/>
            <Route path="/account" component={MyAccount}/>
            ...
            <Route component={Error404}/>
          </Switch>
        </div>
      </BrowserRouter>
    );
  }
}
</code>```

I know that I can access the app's current path location through the child components with this.props.location.pathname, but I need to access it from the parent component, just below <BrowserRouter/> to run additional logic that doesn't pertain to child components. How can I get this location?

答:
After digging through their GitHub issues, I found the solution. I must render a <Route /> within <BrowserRouter /> and pass the rest of my app into its render() function with history as a parameter. Within the render function, I can find the app's location in history.location.pathname.

```<code>class App extends Component{
  render(){
    return (
      <BrowserRouter>

        // We must add a parent <Route> and render its children while passing 'history' as parameter
        <Route path={Paths.reserve} render={(history) =>

          // Within render(), we can find it in history.location.pathname
          <div className={(history.location.pathname === "/account") ? "background-black" : "background-white"} >
            <Switch>
              <Route path="/login" component={LoginPage}/>
              <Route path="/success" component={LoginSuccess}/>
              <Route path="/account" component={MyAccount}/>
              ...
              <Route component={Error404}/>
            </Switch>
          </div>
          }/>
        }} />
      </BrowserRouter>
    );
  }
}
</code>```

This will update the history parameter automatically, without having to re-render on componentDidMount() or componentDidUpdate()

Body:
I have a simple App that uses BrowserRouter from 'react-router-dom' v4. I'm trying to access the location.pathname property from within the <BrowserRouter/> component, without avail:

class App extends Component{
  render(){
    return (
      <BrowserRouter>
        // How do I access this.props.location?

          <Switch>
            <Route path="/login" component={LoginPage}/>
            <Route path="/success" component={LoginSuccess}/>
            <Route path="/account" component={MyAccount}/>
            ...
            <Route component={Error404}/>
          </Switch>

      </BrowserRouter>
    );
  }
}

I know that I can access the app's current path location through the child components with this.props.location.pathname, but I need to access it from the parent component, just below <BrowserRouter/> to run additional logic that doesn't pertain to child components. How can I get this location?

Body:
After digging through their GitHub issues, I found the solution. I must render a <Route /> within <BrowserRouter /> and pass the rest of my app into its render() function with history as a parameter. Within the render function, I can find the app's location in history.location.pathname.

class App extends Component{
  render(){
    return (
      <BrowserRouter>

        // We must add a parent <Route> and render its children while passing 'history' as parameter
        <Route path={Paths.reserve} render={(history) =>

          // Within render(), we can find it in history.location.pathname
          <div className={(history.location.pathname === "/account") ? "background-black" : "background-white"} >
            <Switch>
              <Route path="/login" component={LoginPage}/>
              <Route path="/success" component={LoginSuccess}/>
              <Route path="/account" component={MyAccount}/>
              ...
              <Route component={Error404}/>
            </Switch>
          </div>
          }/>
        }} />
      </BrowserRouter>
    );
  }
}

This will update the history parameter automatically, without having to re-render on componentDidMount() or componentDidUpdate()