text:
Q: Change Woocommerce email subject if order have this specific category I just want to know if possible to change the email subject if the order have the specific category like (Preorder). I want to put PO at beginning (PO New customer order #0000) then all other order the customer receive the default email subject (New Customer Order #0000).
add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 1, 2);
function change_admin_email_subject( $subject, $order ) {

    global $woocommerce;
    global $product;
    if ( has_term( 'preorder', $product->ID ) ) {
        $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
        $subject = sprintf( '[%s]New customer order (# %s) from %s %s', $blogname, $order->id, $order->billing_first_name, $order->billing_last_name );
    }
    return $subject;
}

Note: I just copy this code somewhere.

A: This can be done this way, making some small changes:
add_filter('woocommerce_email_subject_new_order', 'custom_admin_email_subject', 1, 2);
function custom_admin_email_subject( $subject, $order ) {
    $backordered = false;

    foreach($order->get_items() as $item_id => $item ){
        if ( has_term( 'preorder', 'product_cat' , $item->get_product_id() ) ) {
            $backordered = true;
            break;
        }
    }
    if ( $backordered ) {
        $subject = sprintf( '[PO]New customer order (# %s) from %s %s', $order->get_id(), $order->get_billing_first_name(), $order->get_billing_last_name() );
    }
    return $subject;
}

Code goes in function.php file of the active child theme (or active theme). Tested and works.

Or it can be done this way without a product category, checking that product is backordered:
add_filter('woocommerce_email_subject_new_order', 'custom_admin_email_subject', 1, 2);
function custom_admin_email_subject( $subject, $order ) {
    $backordered = false;

    foreach($order->get_items() as $item_id => $item ){
        $product = $item->get_product();
        if( $product->get_backorders() == 'yes' && $product->get_stock_quantity() < 0 ){
            $backordered = true;
            break;
        }
    }
    if ( $backordered ) {
        $subject = sprintf( '[PO]New customer order (# %s) from %s %s', $order->get_id(), $order->get_billing_first_name(), $order->get_billing_last_name() );
    }
    return $subject;
}

Code goes in function.php file of the active child theme (or active theme). Tested and works.

A: Use this:
function change_admin_email_subject( $subject, $order ) {
    // Get all order items
    $items = $order->get_items();
    $found = false;
    // Loop through the items
    foreach ( $items as $item ) {
        $product_id = $item['product_id'];
        // get the categories for current item
        $terms = get_the_terms( $product_id, 'product_cat' );
        // Loop through the categories to find if 'preorder' exist.
        foreach ($terms as $term) {
            if($term->slug == 'preorder'){
                $subject = 'PO '. $subject;
                $found = true;
                break;
            }
        }
        if($found == true){
            break;
        }
    }
    return $subject;
}


text:
Q: Unknown receiver 'jsonParser' error in iOS project I'm getting a couple of errors with the code below. The errors are 'use of undeclared identifier 'SBJSON' and 'unknown receiver 'jsonParser', did you mean SBJsonParser'?
I have the JSON library in my project. It's working with Facebook Graph API and Google Places. For some reason though the code below (also for the Facebook API) isn't finding the JSON files. Any idea why? I'm wondering if I drag/dropped them into the project incorrectly or something.
thanks for any help.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        [self hideActivityIndicator];

        NSString* responseString = [[[NSString alloc] initWithData:receivedData
                                                          encoding:NSUTF8StringEncoding]
                                    autorelease];
        NSLog(@"Response from photo upload: %@",responseString);
        [self clearConnection];
        // Check the photo upload server completes successfully
        if ([responseString rangeOfString:@"ERROR:"].location == NSNotFound) {
            SBJSON *jsonParser = [[SBJSON new] autorelease];
            id result = [jsonParser objectWithString:responseString];
            // Look for expected parameter back
            if ([result objectForKey:@"image_name"]) {
                productImageData = [result copy];
                // Now that we have successfully uploaded the photo
                // we will make the Graph API call to send our Wishlist
                // information.
                [self apiGraphAddToWishlist];
            } else {
                [self showAlertErrorMessage:@"Could not upload the photo." ];
            }
        } else {
            [self showAlertErrorMessage:@"Could not upload the photo." ];
        }
    }

A: Instead of using
SBJSON *jsonParser

use:
SBJsonParser *jsonParser;

A:
Please make sure you have this files included in your project and all the .m files are in the "Compile Sources" list on your target.
Also make sure the file you're referring to is importing SBJSON.h:
#import "SBJSON.h"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple PHP for changing page? On my website I have a gallery page. On it I would like a file to be included, and then on a click of a button, I want the next story to load. I know how to use php to include a file with a certain filename by using variables. But how do I integrate a button? Thanks in advance

A: You can create  and style it to be like a button..but for grabbing more content from files it would be better to use ajax.
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/


text:
Q: TypeScript: How to create a type-safe mapObject function? I created a util function, mapObject, which is Array.map but for objects.
It's used like so...
mapObject(
  (value) => value * 100,
  {a: 1, b: 2, c: 3}
)
// {a: 100, b: 200, c: 300}

Here's the implementation. I got a pretty type-safe version working, but had to silence 2 errors about using obj[key] without an index signature.
type ValueOf<T> = T[keyof T];

export const mapObject = <OldObject, NewValue>(
  mappingFn: (value: ValueOf<OldObject>) => NewValue,
  obj: OldObject
): Record<keyof OldObject, NewValue> =>
  Object.keys(obj).reduce((newObj, key) => {
    // @ts-ignore (Not sure how to work around this)
    const oldValue = obj[key];

    // @ts-ignore (Not sure how to work around this)
    newObj[key] = mappingFn(oldValue);

    return newObj;
  }, {} as Record<keyof OldObject, NewValue>);

What's a better way to code this? The function correctly infers what's being passed in, and the return value has great type-safety. I'd love to remove the @ts-ignores, but without using index signatures as they hurt type-safety.

A: If you use a for loop instead of reduce then TypeScript is able to correctly track the type of the i iterator variable.
Otherwise, as Psidom pointed out, Object.keys() returns string[] which loses the property:value mapping.
Here's the minimally changed version of your code:
    type ValueOf<T> = T[keyof T];

    export const mapObject = <OldObject extends object, NewValue>(
        mappingFn: (value: ValueOf<OldObject>) => NewValue,
        obj: OldObject
    ): Record<keyof OldObject, NewValue> => {
        let newObj = {} as Record<keyof OldObject, NewValue>;
        for (let i in obj) {
            if (obj.hasOwnProperty(i)) {
                const oldValue = obj[i];
                newObj[i] = mappingFn(oldValue);
            }
        }
        return newObj;
    }

But there are a few different ways of annotating it to achieve the same result, the semantics vary slightly.
Here's an alternative version using mapped types (it looks similar but it's not an index signature).
This might be slightly more flexible because the input object doesn't need to be a Record type with values of the same type.
The implementation is the same, it's just the type annotations which are different:
    type ValueOf<T> = T[keyof T];

    type MapTo<T, U> = {
        [P in keyof T]: U
    }

    function mapObject<T extends object, U>(mappingFn: (v: ValueOf<T>) => U, obj: T): MapTo<T, U> {
        let newObj = {} as MapTo<T, U>;
        for (let i in obj) {
            if (obj.hasOwnProperty(i)) {
                const oldValue = obj[i];
                newObj[i] = mappingFn(oldValue);
            }
        }
        return newObj;
    }

A: Object.keys return string[]. One possible solution is to use type assertion on Object.keys as suggested in this stack overflow answer:
(Object.keys(obj) as Array<keyof typeof obj>).reduce((newObj, key) => {
...
})

Typescript playground.

A: Try ramda's mapObjIndexed.
export function mapObjIndexed<T, TResult, TKey extends string>(
    fn: (value: T, key: TKey, obj?: Record<TKey, T>) => TResult,
    obj: Record<TKey, T>
): Record<TKey, TResult>;


text:
Q: Matrix rows and columns notation confusion There is this example in my text:
#include <iostream>
#include <iomanip>
using namespace std ;

int main()
{
    double mat[3][3] ;

    for(int i=0; i<3; ++i) // column index.
    for(int j=0; j<3; ++j) // row index.
        mat[i][j] = 10*(i+1) + (j+1) ;

    cout << "The matrix: " << endl ;
    for(int i=0; i<3; ++i) // column index.
    {
    cout << "[ " ;
    for(int j=0; j<3; ++j) // row index.
        cout << setw(4) << mat[i][j] ;
    cout << " ]" << endl ;
    }

    return 0 ;
}

Now what I found odd here is that the initial loop represents the column index while the 2nd one is the row index, which to me, is a bit unconventional. Usually we in mathematics use the first index for the row and the 2nd for the column.
My first question was, why does the compiler consider the first loop as the one moving along the columns while the 2nd moving in a row. It feels very arbitrary, no reason why this happens. Hence I did a test. I wrote the following simple code:
#include <iostream>
#include <iomanip>
using namespace std ;
int main()
{
    double mat[3][3];
    int k=0;

    for(int i=1;i<=3;i++)
    {
         for(int j=1;j<=3;j++)
         {
            k++;
            mat[i][j]=k;

         }
    }

    for(int i=1;i<=3;i++)
    {

        for(int j=1;j<=3;j++)
        {
           cout <<" " << mat[i][j];
        }
        cout <<endl;
    }

    return 0;
}

The result here gives what I wanted and expected to give. The first loop represents the row index while the 2nd loop the column.
Now I am confused, why does the compiler now takes the reverse ? In the lecture example : first loop->column index, second loop -> row index. While in my example is the reverse. And in both cases the index of the first loop is in the first bracket, while the index of the 2nd loop in the 2nd bracket. Anyone can help me?


text:
Q: php filter content to find span with specific id i have content. there is too many spans.
i want to get content of span which has id='credit-id'.
for example:  535
i want to get the content of the span which has id credit-id.
how to do that?
i tried preg_match method but not getting  out put. getting blank array.
 preg_match_all('/(.*?)<\/span>/s',$file_contents,$estimates);

getting blank array;
  ARRAY()

A: See this fiddle.
Important to note is the regex in combination with the '-enclosure of the spans id attribute:
/(.*?)<\/span>/

If your spans id attribute is enclosed with " instead of ', then you have to edit the regular expression. And if you do, don't forget to escape the double quotation marks.


text:
Q: load images in ascending order by id I am reading Images by json . i have total 16 images .. i want to read images by Ascending order like . id1,id2,id3 and so on .
Currently they are loading in descending order
$(document).ready(function() {
    var globe;
    /*   Reading the data from XML file*/

    $.ajax({
        type: "GET",
        url: "photos.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('item').each(function() {
                var path = $(this).attr('path');
                var width = $(this).attr('width');
                var height = $(this).attr('height');
                var id = $(this).attr('id');
                var alt = $(this).attr('alt');
                var longdesc = $(this).find('longdesc').text();
                var description = $(this).find('desc').text();
                $('#myImageFlow').prepend('');
                imgArr[i] = description;
            });
        }
    });
});

A: use .append() instead of .prepend()
try this
$('#myImageFlow').append('');
                    imgArr[i] = description;


text:
Q: while loop within foreach I've got a form with questions which gets answered.  Then on the following page I'm trying to validate the questions to see if the answer is correct or not because eventually I must work out a percentage for the test.
$tid1 = $_SESSION['tid'];
$departmentid = $_SESSION['deptid'];
$userid = $_SESSION['userid'];

foreach($_POST['question'] as $key => $answer) {
    include 'datalogin.php';
    mysql_query("INSERT INTO ex_answer (id,class_name,testname,name,percentage,qnr,answer_chosen,points_scored,result)
VALUES ('0','$departmentid','$tid1','$userid','0','$key','$answer[0] $answer[1] $answer[2] $answer[3] $answer[4] $answer[5] $answer[6] $answer[7] $answer[8]','0','0')");

    $sql1="SELECT * FROM ex_question WHERE test_name = '$tid1' AND q_nr = '$key'";
    $result1=mysql_query($sql1);
    while($row1 = mysql_fetch_array($result1)) {
        $q_nr=$row1['q_nr'];
        echo $q_nr;
    }
}

The problem is (I think) that it is not selecting the question number q_nr = '$key' correctly from the table because echo $q_nr gives no output

A: Use mysql_fetch_assoc to be able to use column name indexes on returned array.

A: If you are getting a valid result (Test the sql in your Database client ) then you should just use the following to access it as an associative array:
mysql_fetch_assoc($result1);

instead of the mysql_fetch_array() or use
    mysql_fetch_array($result1, MYSQL_ASSOC)
Test what is being returned to you, comment out your while loop and then do:
$row1 = mysql_fetch_array($result1);
print_r($row1);

before you while loop add the following for validation:
if (!$result1) {
    die('Could not query:' . mysql_error());
}

A: You can also output the SQL and test it on the DB, that will show that you are getting the expected results


text:
Q: Can a command be defined to have key=value in it? I am learning about making LaTeX commands. I thought that they were just macro, and the command is replaced literally by its definition. But the following example does not work and I wanted to ask if it could be made to work and, more important, why it does not work.
Given this
\documentclass[]{article}%
\usepackage[demo]{graphicx}
\begin{document}
  \includegraphics[width=0.8\textwidth]{whatever}  %standard
\end{document}

I wanted to build the width=0.8\textwidth using my own command. This works:
\documentclass[]{article}%
\usepackage[demo]{graphicx}
  \newcommand{\X}[1]{#1\textwidth}  %works
\begin{document}
  \includegraphics[width=\X{0.8}]{whatever} %newcommand
\end{document}

But when changing the whole thing to be command, like this:
\documentclass[]{article}%
\usepackage[demo]{graphicx}
  \newcommand{\Y}[1]{width=#1\textwidth} %does not work
\begin{document}
  \includegraphics[\Y{0.8}]{whatever}
\end{document}

Latex gave the following error:
 Missing \endcsname inserted. \includegraphics[\Y{0.8}]{whatever}

So my whole thinking that commands are just blind macro replacements (like #define in C) was wrong, or maybe Latex is trying to evaluate things inside the \newcommand and that is why it complained?
Is there a way to make the last example above work as shown?
TL 2015

A: You will have to expand the optional argument in order for \Y{<x>} to appropriately be seen as width=<x>\textwidth. Here are a number of ways to achieve this:
First approach:
An indirect way of expanding the optional argument (and possibly the mandatory one, depending on the usage).
\documentclass{article}
\usepackage{graphicx}
\newcommand{\Y}[1]{width=#1\textwidth}
\let\oldincludegraphics\includegraphics
\renewcommand{\includegraphics}{\expandafter\oldincludegraphics\expandafter}
\begin{document}
\includegraphics[\Y{0.1},height=50pt]{example-image}
\end{document}

Second approach
A more direct approach by expanding only the optional argument.
\documentclass{article}
\usepackage{graphicx,letltxmacro}
\newcommand{\Y}[1]{width=#1\textwidth}
\LetLtxMacro\oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[2][]{%
  \expandafter\oldincludegraphics\expandafter[#1]{#2}}
\begin{document}
\includegraphics[\Y{0.1},height=50pt]{example-image}
\end{document}

Third approach
A complete expansion of the macros argument(s).
\documentclass{article}
\usepackage{graphicx,letltxmacro}
\newcommand{\Y}[1]{width=#1\textwidth}
\LetLtxMacro\oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[2][]{%
  \begingroup\edef\x{\endgroup%
    \noexpand\oldincludegraphics[#1]{#2}}\x}
\begin{document}
\includegraphics[\Y{0.1},height=50pt]{example-image}
\end{document}


text:
Q: In my AWS, codebuild build, I get an error 'No artifact files specified' when I try to specify my endpoint in my yml file. I have googled and searched within stackoverflow and found some suggestions but still no succedd. My build process in AWS Codebuild runs and gives me a success output but in the log shows -> 'No artifact files specified', and as the result no files are being copied in my S3. Could anybody help me figure this out. Here I share my yml setting:
version: 0.1
phases:
  build:
    commands:
      - echo Nothing to do yet
addons:
  artifacts:
    s3_region: "eu-central-1"
    files:
      - '**/*'

A: I suggest you refer to the Build Specification Reference.
Specifically, you should remove addons: as well as s3_region: as neither of these are valid CodeBuild flags. You should also be using version: 0.2, as version: 0.1 has been deprecated.
Here is what your buildspec.yml should look like:
version: 0.2
phases:
  build:
    commands:
      - echo Nothing to do yet

artifacts:
  files:
    - '**/*'


text:
Q: How to delete all but most recent X children in a Firebase node? Given a Firebase node lines filled with unique-ID children (from push() operations), such as this:
Firebase--
  --lines
    --K3qx02jslkdjNskjwLDK
    --K3qx23jakjdz9Nlskjja
    --K3qxRdXhUFmEJdifOdaj
    --etc...

I want to be able to delete all children of lines except the most recently added 200 (or 100, or whatever). Basically this is a cleanup operation. Now I know I could do this by grabbing a snapshot of all children of lines on the client side, counting the entries, then using an endsAt(totalChildren-numToKeep) to grab the relevant data and run remove(). But I want to avoid grabbing all that data to the client.
Is there an alternative to my idea above?

A: Keep the most recent N items, is one of the trickier use-cases to implement. If you have any option to change it into "keep items from the past N hours", I recommend going that route.
The reason the use-case is tricky, is that you're counting items and Firebase does (intentionally) not have any count-based operations. Because of this, you will need to retrieve the first N items to know which item is N+1.
ref.child('lines').once('value', function(snapshot) {
  if (snapshot.numChildren() > MAX_COUNT) {
    var childCount = 0;
    var updates = {};
    snapshot.forEach(function (child) {
      if (++childCount < snapshot.numChildren() - MAX_COUNT) {
        updates[child.key()] = null;
      }
    });
    ref.child('lines').update(updates);
  }
});

A few things to note here:

*

*this will download all lines

*it performs a single update() call to remove the extraneous lines

One way to optimize this (aside from picking a different/time-based truncating strategy) is to keep a separate list of the "line ids".
lineids
  --K3qx02jslkdjNskjwLDK
  --K3qx23jakjdz9Nlskjja
  --K3qxRdXhUFmEJdifOdaj

So you'll still keep the data for each line in lines, but also keep a list of just the ids. The code to then delete the extra ones then becomes:
ref.child('lineids').once('value', function(snapshot) {
  if (snapshot.numChildren() > MAX_COUNT) {
    var childCount = 0;
    var updates = {};
    snapshot.forEach(function (child) {
      if (++childCount < snapshot.numChildren() - MAX_COUNT) {
        updates['lineids/'+child.key()] = null;
        updates['lines/'+child.key()] = null;
      }
    });
    ref.update(updates);
  }
});

This last snippet is slightly more involved, but prevents from having to download all lines data by just downloading the line ids.
There are many variations you can choose, but I hope this serves as enough inspiration to get started.


text:
Q: Is there a find command that shows the files from the current directory for which a certain user has read premissions? I am trying to learn find and got stuck when tried to find files (if there are any) from current directory that a user can print (so to which user has read permissions). Pretty much what this command does:
find / -type f -user whateverUser

A: To do this using grep:
ls -o to list the current folder
ls -o . */** to list sub folder as well, but for each file show the full sub path
ls -o */** | grep -v '^d' to exclude directories in the list
To see which files 'you' can read, you can grep for the owner :
ls -o . */** | grep -v '^d' | grep " $LOGNAME "
A subtlety is that you can all read files that have group group level r permission, or all user level r permission.
To include the latter is easy:
ls -o . */** | grep -v '^d' | egrep "( $LOGNAME |^.......r..)"
To include files you can access via group permissions is a little more complex. Not tested so here goes:
GROUP_GREP=$( groups | sed 's/ /|/g' )

ls -l */** | grep -v '^d' | egrep "( $LOGNAME |^.......r..|$GROUP_GREP)"

Now, you might need to make refinements in the cases where the filename contains any grep search terms (e.g. the user name, or group names).


text:
Q: Method to safely get a string in C I'm very new to C and want to write a function that safely prompts the user for a string and returns it. While I think I have the safety part handled, I can't return the string to the main method and print it out. Here is my code
//Method to safely read user input
char * getFileName(char* fileName) {
    char* str[50];
    int isValid = 0;
    while (isValid == 0) {
        isValid = 1;
        printf("Enter file name: ");
        fgets(str, 50, stdin);
        if (strlen(str) == 49 && str[48] != '\n') { //http://stackoverflow.com/questions/21691843/how-to-correctly-input-a-string-in-c
            isValid = 0;
            if (strlen(str) > 0 && str[strlen(str) - 1] != '\n') {//http://stackoverflow.com/questions/35136026/simple-loops-and-string-length-in-c?noredirect=1#comment58000759_35136026
                printf("Error! String is too long\n\n");
                do {
                    fgets(str, 50, stdin);
                } while (strlen(str) > 0 && str[strlen(str) - 1] != '\n');
            }
        }
        for (int i = 0; i < strlen(str); i++) {
            if (str[i] == '%') {
                printf("Error: Attempted string format attack\n\n");
                isValid = 0;
            }
        }
    }
    for (int i = 0; i < strlen(str); i++) {
        fileName[i] = str[i];
    }
    return fileName;
}

int main()
{
    //Opening text file
    char fileName[50];
    getFileName(fileName);
    printf(fileName);

    printf("Press Enter to continue...");
    getchar();
    //
    return 0;
}

Running this code prints this result

and I have no idea why. Any help would be greatly appreciated!

A: Because you never copy the null terminator. This
for (int i = 0; i < strlen(str); i++)
    fileName[i] = str[i];

only copies all the characters, but not the null terminator. You could use strcpy() since you included string.h as you overuse strlen().
Try like this
int i;
for (i = 0; str[i] != '\0' ; ++i)
    fileName[i] = str[i];
fileName[i] = str[i];

and it should work as you expect it, and really avoid using strlen() like that.
You also have another major problem,
char *str[50];

is an array of 50 char pointers, and that doesn't seem to be what you want but instead
char str[50];

Your code is too complicated and very hard to understand, I think this is what you want
#include <stdio.h>
#include <string.h>

char *
getFileName(char *str, size_t size)
{
    int isValid = 0;
    while (isValid == 0)
    {
        size_t length;
        isValid = 1;

        printf("Enter file name: ");
        if (fgets(str, size, stdin) == NULL)
            return NULL;
        length = strlen(str);
        if ((length == size - 1) && (str[size - 2] != '\n'))
        {
            isValid = 0;
            if ((length > 0) && (str[length - 1] != '\n'))
            {
                printf("Error! String is too long\n\n");
                continue;
            }
        }

        if (strchr(str, '%') != NULL)
        {
            printf("Error: Attempted string format attack\n\n");
            isValid = 0;
        }
    }
    return str;
}

int main()
{
    char array[100];
    if (getFileName(array, sizeof(array)) == NULL)
        fprintf(stderr, "error: input problem?\n");
    else
        printf(array);
    return 0;
}

A: While you have found the nul-terminator issue that was causing initial problems, there are a couple of other issues you will want to address when taking input. Your choice of fgets is a good one. However, like all line-oriented input functions, it will read up to and including the newline ('\n') into your buffer. This leaves your buffer with an embedded '\n' at the end. You will want to remove or trim the trailing newline as part of your input routine. Otherwise, this will cause problems later on (imagine calling strcat to add to the buffer later).
Handling removal is straight forward. To help yourself in this task, when you call strlen in your function, save the results. This will prevent having to make repeated calls to strlen in your function. With the length known, you can perform your test to check if additional characters remain unread, and following that test, you know whether there is a '\n' located at buffer[len-1] or not. If one is present, just overwrite the '\n' with the nul-terminating character to remove the trailing newline. e.g.
buf[--length] = 0;  /* remove newline, decrement length */

Decrementing the length at the same time, updates the length to the current length reflecting the removal of the newline. Since you have gone to the trouble to compute the length of the string taken as input, it would be nice to make the length available to the calling function without having to repeat the strlen call.
Since you are returning a pointer to the buffer holding the input, one way to do this is to simply pass a pointer for the length as a parameter to your input function, and update the pointer value with the length of the string. That way the length is computed only once and it is available to the calling function immediately upon the function return.
In addition, you can make use to the strchr function to check for your choice of invalid characters in the input. If there are multiple values you would like to consider invalid, or if they change depending on the input your are taking, you can pass a string containing each of the characters as a parameter to your function. Another consideration is presented if an invalid character is found. While your error checking is fine, if you do find an invalid character, you can set your buffer to empty-string by setting the first character in the string to the nul-terminating character.
You can add flexibility to your input function by passing the prompt as a parameter to the function as well. That way, instead of having a function that prompts for and returns a filename, you have a function that can prompt for any input. The general idea is to get away from hard-coding values in your function and, instead, pass values that change as parameters to your function. You can do the same with your character limit as well. So instead of having a function limited to prompting for/reading a filename of 49-chars, you have a general input function that can read any length string into an adequately size character array.
Putting those pieces together, you could greatly increase the flexibility of your input function. The following is a short example function that passes changing information as parameter. Look it over and let me know if you have any questions. Hopefully the example will provide you with a few of the general considerations to consider when writing any function in C. Good luck with your coding:
char *getstr_input (char *buf, size_t max, size_t *n, const char *prompt)
{
    if (!buf) return NULL;
    if (*prompt) printf ("%s : ", prompt);      /* prompt      */
    if (!fgets (buf, max, stdin)) return NULL;  /* read input  */

    if (!(*n = strlen (buf))) return NULL;      /* test strlen */
    if (*n + 1 == max && buf[*n-1] != '\n') {   /* test short-read */
        fprintf (stderr, "warning: short-read, characters remain unread.\n");
    }
    else  /* remove trailing '\n' */
        buf[--*n] = 0;

    if (strchr (buf, '%')) { /* validate unwanted characters  */
        fprintf (stderr, "error: invalid character in string.\n");
        *buf = *n = 0;       /* set to empty-string, 0 length */
        return NULL;
    }
    return buf;
}

Where 'buf' is adequately sized to hold 'max' characters, that on return contains 'n' characters (not including the nul-terminating character) and for which the user is prompted with 'prompt' to input. A short test program could be:
#include <stdio.h>
#include <string.h>

enum { MAX = 50 };  /* create a constant 50, adjust as desired */

int main (void) {

    char fname[MAX] = {0};
    size_t len = 0;

    getstr_input (fname, MAX, &len, "enter a filename");

    printf ("\n filename : %s\n length   : %zu\n\n", fname, len);

    return 0;
}

Example Use/Output
$ ./bin/fgets_prompt
enter a filename : 12345678

 filename : 12345678
 length   : 8

$ ./bin/fgets_prompt
enter a filename : 12345%6
error: invalid character in string.

 filename :
 length   : 0


text:
Q: Template Metaprogramming: Problems with Partial Specialization I am Trying to explore partial specialization of templates in order to build a traits system. Unfortunately I cannot get the full thing working. I created the simplest model to show what does not work. It is not even clear to me whether I am trying something that is not supported (actually I see around examples of the same nature but the devil is in the details).
I am just creating a small example in which I have two enums and would like to create a string differently depending on the combination of the two. Of course this is just a dummy example to show the problem, the same thing in this case can be done in many other ways.
#ifndef TESTTRAITS_H_
#define TESTTRAITS_H_

#include <string>

using namespace std;

enum MovementType {
    WALKS = 0, SWIMS = 1
};

enum AnimalType {
    DOG = 0, CAT = 1, DOLPHIN = 2
};

template<AnimalType A, MovementType B>
struct movementAnimal {
    static const string quality;
};

template<AnimalType A>
struct movementAnimal<A,WALKS> {
    static const string quality;
};

template<AnimalType A>
struct movementAnimal<A,SWIMS> {
    static const string quality;
};

#endif /* TESTTRAITS_H_ */

Now I write the assignment of the static variable
#include "TestTraits.h"

template<>
const string movementAnimal<DOLPHIN, WALKS>::quality = "Not capable";

template<>
const string movementAnimal<DOLPHIN, SWIMS>::quality = "Excellent";

template<AnimalType A>
const string movementAnimal<A, SWIMS>::quality = "Decent";

template<AnimalType A>
const string movementAnimal<A, WALKS>::quality = "Very Well";

And a small main function
#include <iostream>
using namespace std;
#include "TestTraits.h"

int main() {
    cout << movementAnimal<DOLPHIN,WALKS>::quality  << endl;
    cout << movementAnimal<DOG,WALKS>::quality  << endl;
    return 0;
}

If I compile I get the error:

/src/TestProject.cpp:15: undefined reference to `movementAnimal<(AnimalType)0, (MovementType)0>::quality[abi:cxx11]'
collect2: error: ld returned 1 exit status>

If I remove the reference to movementAnimal<DOG,WALKS>::quality then it compiles perfectly.
I get that it is not digesting the partial template specification
template<AnimalType A>
const string movementAnimal<A, WALKS>::quality = "Very Well";

I do not know why and whether it is possible to have the pattern working.

A: As I can see, you put these definitions into separate files. The definition of the template classes is in TestTraits.h, but the definition of the static consts is somewhere else. The main CPP file includes just the TestTraits.h. That should sound like a good decision, but that doesn't work in the world of templates.
So, you have defined the enums and templates/partial specializations. Your main cpp module sees these definitions. Good. The compiler knows the template classes when it instantiates the walking dog here:
cout << movementAnimal<DOG,WALKS>::quality  << endl;

Does the compiler see the definition of the static const? If it doesn't, the code like that is useless:
template<AnimalType A>
const string movementAnimal<A, WALKS>::quality = "Very Well";

When the compiler sees the code above it cannot know all the values of A that you would use. So whenever you decide that the DOG WALKS, this instantiation point shall see the definition of const string movementAnimal<A, WALKS>::quality;
The solution is to ensure that the code from main function knows both definitions of template classes and the definitions of static consts.
There are two solutions. First is to put everything into one header file or to include both files from cpp file. Don't forget to include both.
The second solution is to have an explicit instantiation of some classes somewhere in your code:
template class movementAnimal<DOG, WALKS>;


text:
Q: Duplicated values using INNER JOIN in mysql i have 3 tables, i want to get the total sum, but im not getting the right results.
First table(investors)
id investor_id

1     27
2     27
3     29
4     30
5     31

Second table(payments)
id investor_id

1   27
2   27
3   28
4   29
5   30
6   31
7   27

Third table(billed)
id payments_id billed

1      1        189
2      2        300
3      3        500
4      4        700
5      5        200
6      6        300

HERE is my query
SELECT SUM(billed.billed)
FROM billed AS billed
INNER JOIN payments AS payments ON billed.payments_id = payments.id
INNER JOIN investors AS investors ON payments.investor_id = investors.investor_id

instead of getting 1689 only, im getting a results of 2178
i am really stuck with my answer is there really a way to do this just by using query only?

A: If you just want the total sum for bills, just query that table directly, no need to join:
SELECT SUM(billed) FROM billed

If for some reason you need to JOIN, the I select the distinct investors in a subquery, then join it:
SELECT SUM(billed.billed)
FROM billed AS billed
INNER JOIN payments AS payments ON billed.payments_id = payments.id
INNER JOIN (SELECT DISCTINCT investors FROM investors) AS investors ON payments.investor_id = investors.investor_id


text:
Q: Alternative for OR condition after where clause in select statement Cassandra Is it possible in Cassandra to use multiple conditions union ed together after the where clause in a select statement like in any of the RDBMS. Here is my code :
SELECT * from TABLE_NAME WHERE COND1= 'something' OR COND2 = 'something';

A: Assuming COND is the name of your table's primary key, you can do:
SELECT * from TABLE_NAME WHERE COND1 in ('something', 'something');

So, there is no fully general OR operation, but it looks like this may be equivalent to what you were trying to do.
Remember, as you use CQL, that query planning is not meant to be one of its strengths. Cassandra code typically makes the assumption that you have huge amounts of data, so it will try to avoid doing any queries that might end up being expensive. In the RMDBS world, you structure your data according to intrinsic relationships (3rd normal form, etc), whereas in Cassandra, you structure your data according to the queries you expect to need. Denormalization is (forgive the pun) the norm.
Point is, CQL is intended to be a more familiar, friendly syntax for making Cassandra queries than the older Thrift RPC interface. It's not intended to be completely expressive and flexible the way that SQL is.

A: Simple answer: there is no equivalent of OR
http://www.datastax.com/docs/0.8/dml/using_cql
Here is the command reference for v0.8:
http://www.datastax.com/docs/0.8/references/cql#cql-reference

SELECT [FIRST N] [REVERSED]  FROM   [USING ]
  [WHERE ] [LIMIT N];

..

The WHERE clause provides for filtering the rows that appear in results. The clause can filter on a key name, or range of keys, and in the case of indexed columns, on column values. Key filters are specified using the KEY keyword, a relational operator, (one of =, >, >=, <, and <=), and a term value. When terms appear on both sides of a relational operator it is assumed the filter applies to an indexed column. With column index filters, the term on the left of the operator is the name, the term on the right is the value to filter on.

A: Here is the syntax of CQL v3:
SELECT * | select_expression | DISTINCT partition
FROM [keyspace_name.] table_name
[WHERE partition_value
   [AND clustering_filters
   [AND static_filters]]]
[ORDER BY PK_column_name ASC|DESC]
[LIMIT N]
[ALLOW FILTERING]

then you can not use OR operation like SQL.


text:
Q: How do external java libraries(jars) actually work? A lot of times in Java we want to use some functionality that is given to us in the form of JARs(ex. some external library). Most often than not I've noticed that JARs contain .class files.
Since .class files represent compiled bytecode ready for use by the JVM, my question is the following:
How is it that .class files are all that's needed for us to make use of an external library? Maybe a certain JAR contains the class file called: Person.class. How am I able to reference this class in my code when all that the JAR file exposes is a .class file. Isn't the source code(.java file) what's important and what's needed? In the same way that I can have two classes in the same package, I'm able to reference one from the other, because the two .java files(not .class files) are in the same scope(just to give an example).
Excuse me if it's a dumb question, but I really want to understand this.

A: Even if you write your source code in .java files, they are eventually compiled to form .class files which store bytecode that can be interpreted easily. When you use the jar files in your project, all the class files inside those jar files are included in your classpath, hence enabling you to use them.
So in a JAR package, .class files are sufficient to be used as a dependency.

A: The Java compiler takes your Java code, which is something that humans can understand, into .class files, which is something that the Java Virtual Machine (JVM) can understand.  The JVM then takes the .class files and runs them on your machine.
A .jar file is effectively a collection of .class files packaged up (under the hood, it's really little more than a .zip in disguise).  When you add a .jar onto your classpath, you are telling the JVM that it is one more place it should look when it needs a particular class.

A: I am not sure if I totally got your question, but the JARs are simply compiled javacode, which means, that the semantic/logic etc of the code has not been changed. You need to be able to access the functions/classes etc of the java code you want to use, because otherwise you would not gain any advantage of using a JAR.
One advantage of the JARs is, that the source code of these libraries is already compiled. Since these .class files are compiled .java files, they are all you need to access the functions that were written in the .java file.


text:
Q: merging two datasets with corresponding columns Edited*
I need to make a loop or a function that can make this code much more faster and easier without dobbelt working.
d1<-cbind(c("Age","Height","Weight"), c("Age","Weight","Score"),
  c("Height","Score","Income"))

d2<-cbind(c(24,187,75), c(46,172,10),c(177,7,50000))

c1d1<-t(d1[,1])
c1d2<-t(d2[,1])
colnames(c1d2)<-c1d1

c2d1<-t(d1[,2])
c2d2<-t(d2[,2])
colnames(c2d2)<-c2d1

c3d1<-t(d1[,3])
c3d2<-t(d2[,3])
colnames(c3d2)<-c3d1

dataset<-smartbind(data.frame(c1d2),data.frame(c2d2),data.frame(c3d2))

A: it's hard for me to understand exactly what you're seeking to accomplish; some examples with code would help greatly, as @MrFlick suggested. I think, though, that you may benefit from investigating the map_df function from the purrr library.


text:
Q: Show that the function $f(z)=\frac{1-\cos z}{z^n}$ has no anti-derivative on $\mathbb C\setminus\{0\}$ if $n$ is an odd integer. Show that the function $f(z)=\frac{1-\cos z}{z^n}$ has no anti-derivative on $\mathbb C\setminus\{0\}$ if $n$ is a positive odd integer.
I think, If we can able to prove $\int_S f(z) dz \neq 0$, on the unit circle $S$, then by fundamental theorem of algebra gives the desired one. But, how can I use the definition $\int_\gamma f(z)dz=\int_a^b f(\gamma(t))\gamma'(t)dt$ for a continuous function $f(z)$ on a piecewise smooth contour $\gamma:=\gamma(t),~a \leq \gamma \leq b$ ?

A: Let $g(z)=1-\cos z$. Then\begin{align}\int_Sf(z)\,\mathrm dz&=\int_S\frac{g(z)}{z^n}\,\mathrm dz\\&=2\pi i\frac{g^{(n-1)}(0)}{(n-1)!}\end{align}which is $0$ if and only if $n$ is even.


text:
Q: how to correlate data strings from file in apache spark I'm new on Spark and I'm trying to understand if it can fit my use case.
I have the following scenario.
I have a file (it can be a log file, .txt, .csv, .xml or .json, I can
produce the data in whatever format I prefer) with some data, e.g.:
Event "X", City "Y", Zone "Z"
with different events, cities and zones. This data can be represented by
string (like the one I wrote) in a .txt, or by XML , CSV, or JSON, as I
wish. I can also send this data through TCP Socket, if I need it.
What I really want to do is to correlate each single entry with other
similar entries by declaring rules.
For example, I want to declare some rules on the data flow: if I received
event X1 and event X2 in same city and same zone, I'll want to do something
(execute a .bat script, write a log file, etc). Same thing if I received the
same string multiple times, or whatever rule I want to produce with these
data strings.
I'm trying to understand if Apache Spark can fit my use case. The only input
data will be these strings from this file.
Can I correlate these events and how? Is there a GUI to do it?
Any hints and advices will be appreciated.

A: Yes, it can:
spark.read.csv("your_file")
  .groupBy($"Y", $"Z")
  .agg(collect_list($"X").as("events"))
  .as[(String, String, Seq[String])]
  .filter(r => r._3.contains("X1") && r._3.contains("X2"))
  .foreach(r => {
    //do something with the relevant records
  })

There isn't really a GUI to speak of, unless you consider notebook type software a GUI, you'd be writing code either way.
Apache Spark is very powerful but has a bit of a learning curve. It's easy to start running in local mode for learning, but you won't have a performance benefit unless your data size requires you to scale to multiple nodes, and that comes with lots of admin overhead.


text:
Q: Why can't I install libusb? I'm running Ubuntu 16.04 and need to install libusb as part of a larger project. Here's the code I'm running:
sudo apt-get install libusb

and I get the error message
E: Unable to locate package libusb

I've checked other questions and tried their solutions. I tried updating my repositories to include the universe, but that didn't change anything. Am I missing something? Is there a new name for the package? Or how can I get it to install?

A: I guess you want either:
sudo apt-get install libusb-0.1-4

or
sudo apt-get install libusb-1.0-0

depending on which version you prefer.


text:
Q: Combine matching lines using sed or awk? I have a file like the following:
1,
cake:01351
12,
bun:1063
scone:13581
biscuit:1931
14,
jelly:1385

I need to convert it so that when a number is read at the start of a line it is combined with the line beneath it, but if there is no number at the start the line is left as is. This would be the output that I need:
1,cake:01351
12,bun:1063
scone:13581
biscuit:1931
14,jelly:1385

Having a lot of trouble achieving this with sed, it seems it may not be the best way for what I think should be quite simple.
Any suggestions greatly appreciated.

A: A very basic sed implementation:
sed -e '/^[0-9]/{N;s/\n//;}'

This relies on the first character on only the 'number' lines being a number (as you specified).
It

*

*matches lines starting with a number, ^[0-9]

*brings in the next line, N

*deletes the embedded newline, s/\n//

A: This is a file on my intranet. I can't recall where I found the handy sed one-liner. You might find something if you search for 'sed one-liner'

Have you ever needed to combine lines of text, but it's too tedious to do it by hand.
For example, imagine that we have a text file with hundreds of lines which look like this:
14/04/2003,10:27:47,0
IdVg,3.000,-1.000,0.050,0.006
GmMax,0.011,0.975,0.005
IdVg,3.000,-1.000,0.050,0.006
GmMax,0.011,0.975,0.005
14/04/2003,10:30:51,600
IdVg,3.000,-1.000,0.050,0.006
GmMax,0.011,0.975,0.005
IdVg,3.000,-1.000,0.050,0.006
GmMax,0.010,0.975,0.005
14/04/2003,10:34:02,600
IdVg,3.000,-1.000,0.050,0.006
GmMax,0.011,0.975,0.005
IdVg,3.000,-1.000,0.050,0.006
GmMax,0.010,0.975,0.005

Each date (14/04/2003) is the start of a data record, and it continues on the next four lines.
We would like to input this to Excel as a 'comma separated value' file, and see each record in its own row.
In our example, we need to append any line starting with a G or I to the preceding line, and insert a comma, so as to produce the following:
14/04/2003,10:27:47,0,IdVg,3.000,-1.000,0.050,0.006,GmMax,0.011,0.975,0.005,IdVg,3.000,...
14/04/2003,10:30:51,600,IdVg,3.000,-1.000,0.050,0.006,GmMax,0.011,0.975,0.0005,IdVg,3.000,...
14/04/2003,10:34:02,600,IdVg,3.000,-1.000,0.050,0.006,GmMax,0.011,0.975,0.0005,IdVg,3.000,...

This is a classic application of a 'regular expression' and, once again, sed comes to the rescue.
The editing can be done with a single sed command:
sed -e :a -e '$!N;s/\n\([GI]\)/,\1/;ta' -e 'P;D' filename >newfilename

I didn't say it would be obvious, or easy, did I?
This is the kind of command you write down somewhere for the rare occasions when you need it.

A: Try a regular expression, such as:
sed '/[0-9]\+,/{N}s/\n//)'

That checks the first line for a number (0-9) and a comma, then replaces the new line with nothing, removing it.

A: Another awk solution, less cryptic than some other answers:
awk '/^[0-9]/ {n = $0; getline; print n $0; next} 1'

A: $ awk 'ORS= /^[0-9]+,$/?" ":"\n"' file
1, cake:01351
12, bun:1063
scone:13581
biscuit:1931
14, jelly:1385


text:
Q: outMail[["From"]] In R I have a shared email account for my group at work. I've used StackOverflow to very helpfully automate the process of sending an email with multiple attachments from my personal email but I'd like to change the address to be from the shared email address. I notice that in outMail we have "To" "subject" "cc" body" etc. but there is no way to change "FROM." i.e. outMail[["From"]] Does anyone have any ideas?

A: Here is an approach that can be considered :
library(RDCOMClient)
vec_to <- c("email1@hotmail.com", "email2@hotmail.com")
vec_cc <- ""
vec_bcc <- ""
char_subject <- "Hi"
char_body <- "Hi"
char_htmlbody <- ""
vec_attachments <- ""

Outlook <- RDCOMClient::COMCreate("Outlook.Application")

Email <- Outlook$CreateItem(0)
Email[["to"]] <- vec_to
Email[["cc"]] <- vec_cc
Email[["bcc"]] <- vec_bcc
Email[["subject"]] <- char_subject
Email[["SentOnBehalfOfName"]] <- "sharedEmail@hotmail.com"

if(char_body != "" && char_htmlbody != "")
{
  stop("Error")
}

if(char_htmlbody == "")
{
  Email[["body"]] <- char_body

}else
{
  Email[["htmlbody"]] <- char_htmlbody
}

if(vec_attachments[1] != "")
{
  for(i in seq_along(vec_attachments))
  {
    Email[["attachments"]]$Add(vec_attachments[i])
  }
}

Email$Send()


text:
Q: UI not updating after updating the state I am Passing a function from Parent component to child component and then calling that function in child component to update the state of parent component.
In Parent component:
const [todos, setTodos] = useState([]);
const updateTodoInUiAfterEdit = (updatedTodo, todoIdOfEdited)=>{
        var temp = todos;
        for(var i = 0; i < temp.length; i++){
            if(temp[i].todo_id === todoIdOfEdited){
                temp[i].description = updatedTodo;
                break;
            }
        }
        setTodos(temp);
        console.log(todos);
}

It is logging the updated state here correctly, but UI is not updating as per latest state

A: The following code works:
const [todos, setTodos] = useState([]);
const updateTodoInUiAfterEdit = (updatedTodo, todoIdOfEdited)=>{
        let temp = todos;
        let newTodo = []
        for(var i = 0; i < temp.length; i++){
            if(temp[i].todo_id === todoIdOfEdited){
                temp[i].description = updatedTodo;
            }
            newTodo.push(temp[i]);
        }
        setTodos(newTodo);
        console.log(todos);
}

A: setTodos is an asynchronous function, which means that the state updates will not take effect immediately.
for tackling it you have to update the seTodo by using its previous state as an arguement.Here's helping code:
const updateTodoInUiAfterEdit = (updatedTodo, todoIdOfEdited) => {
  setTodos(prevTodos => {
    const temp = [...prevTodos];
    for (var i = 0; i < temp.length; i++) {
      if (temp[i].todo_id === todoIdOfEdited) {
        temp[i].description = updatedTodo;
        break;
      }
    }
    return temp;
  });
};

Upvote if it helps..  :)

A: The problem is, you are directly changing the state, which is wrong.
Do not mutate the state directly
See the updated code:
const [todos, setTodos] = useState([]);
const updateTodoInUiAfterEdit = (updatedTodo, todoIdOfEdited)=>{
        //making a copy of todos up to one depth, if you have more than
        //one depth, then you have to deep clone it
        const temp = [...todos];
        for(let i = 0; i < temp.length; i++){
            if(temp[i].todo_id === todoIdOfEdited){
                temp[i].description = updatedTodo;
                break;
            }
        }
        setTodos(temp);
        console.log(todos);
}

PS: Use let/const instead of var.


text:
Q: Dynamic dropping of handlers in restify Context
I am trying to build a dynamic server with restify (2.6.2) where services are to be installed and uninstalled once the server is started. I realized this can be seen as something odd but it has sense in the context of a DSL oriented project. To achieve this goal I have implemented the following functions:
var install = function (path, method, handler) {
    var id = server[method](path, function (request, response) { // [1]
        handler (request, response);
    });
    return id;
}
var uninstall = function (id) {
    delete server.routes[id]; // [2]
}

The install function, installs a handler in the route specified by a path and a method name [1]. The uninstall function, uninstall the handler by dropping it from routes [2]. This capabilities are exposed as services by the following code:
var db = ...
var server = restify.createServer ()
    .use (restify.bodyParser ({ mapParams: false }))
    .use (restify.queryParser ())
    .use (restify.fullResponse ());
service.post ('/services', function (request, response) {
   var path    = request.body.path;
   var method  = request.body.method;
   var handler = createHandler (request.body.dsl) // off-topic
   var id = install (path, method, handler)
   db.save (path, method, id); // [3]
});
service.del ('/services', function (request, response) {
   var path   = request.body.path;
   var method = request.body.method;
   var id     = db.load (path, method); // [4]
   uninstall (id);
});

In post method [3], a handler is obtained from body (it is off-topic how this is undertaken) and a service is installed storing the returned id in a database. The del method [4], retrieves the id from the database and invokes the uninstall function.
Problem
This code has been unit-tested and it works properly but a malfunction is reached when I try to execute an install/uninstall sequence like the following one. In this example, please suppose that the body of all requests contains the same path, http verb and proper content to build a correct handler:
/*
post: /services : Installed          -> ok
del:  /services : Resource not found -> ok
post: /services : Resource not found -> Error :(
*/

In the first install, handler is executed when resource is acceded via path and verb. The uninstall request is correctly fulfilled because a Resource not found message is obtained when path is visited on verb. Nevertheless, when the same body is installed secondly in the server, a Resource not found is returned when path is acceded on verb.
I suppose that the error is in [2] because, may be, I am not using the correct unregister strategy for restify.
Question
How can be effectively dropped handlers from restify once the server is started?

A: After looking at the restify source I found the following, which you may want to try instead of simply 'delete' (https://github.com/restify/node-restify/blob/master/lib/server.js).
/*
* Removes a route from the server.
* You pass in the route 'blob' you got from a mount call.
* @public
* @function rm
* @throws   {TypeError} on bad input.
* @param    {String}    route the route name.
* @returns  {Boolean}         true if route was removed, false if not.
*/
Server.prototype.rm = function rm(route) {
    var r = this.router.unmount(route);

    if (r && this.routes[r]) {
        delete this.routes[r];
    }

    return (r);
};


text:
Q: Install a beta package from TLContrib on MacTeX 2011 TeX Live I know this has been a question many times asked/answered.
But I have still difficulty to understand because TeX Live has different tree on Mac and is available also on Linux.

The question is simple:
I want to install, on MacTeX 2011, the beta version of Microtype package (for use with pdfTeX):
microtype package (beta) on TLContrib
On the page there is 3 zip to download:

*

*microtype.tar.xz

*microtype.doc.tar.xz

*microtype.source.tar.xz

Which one should I pick? And where should I place it? (here: /Users/myname/Library/texlive/2011/texmf-var ?)
Should I issue some commands on the Terminal like those proposed on this post.
I also want to be able to (easily) revert to the stable package in case I got some issues with the beta package.

A: As Joseph said, the preferred method for installing packages in TLContrib is through a package manager.
On Mac, you can use nice Tex Live Utility, which is installed with MacTeX by default.
Paste http://tlcontrib.metatex.org/2011 into address field (or into the Server URL field in Preferences in the old version of TLU) and refresh.

A: As Mike stated you'll need an aditional app to unpack the files. You may install these XZ Utils (which is part of TeX Live and therefore MacTeX too) and then you can type in your termial
xz -d /Path/to/File/microtype.tar.xz

to get the .tar which you can unpack by double clicking it in the Finder.

For own packages there is the user texmf folder (usually <Your User>/library/texmf/) an in there tex/latex/ where you can put the files. These files are preferred by (La)TeX to the files in the distribution folders. If you want to switch back just delete the files in user-texmf.
To find out the right path you cant type
kpsewhich -var-value=TEXMFHOME

to the terminal.
Note that kpsewhich gives the path but you maybe have to create this folder manually.

If you have only a .ins and .dtx file run latex <filename>.ins to get the .sty oder .cls and pdflatex <filename>.dtx to get the manual.


text:
Q: Display Label and Progressbar into combo box I have this code which is used to display text into combo box.
ProgressBar pb1 = new ProgressBar(0.6);
        ProgressIndicator pi1 = new ProgressIndicator(0.6);
        VBox vb1 = new VBox();
        vb1.getChildren().addAll(new Label("Progressbar 1"), pi1);

        ProgressBar pb2 = new ProgressBar(0.6);
        ProgressIndicator pi2 = new ProgressIndicator(0.6);
        VBox vb2 = new VBox();
        vb2.getChildren().addAll(new Label("Progressbar 2"), pi2);

        ProgressBar pb3 = new ProgressBar(0.6);
        ProgressIndicator pi3 = new ProgressIndicator(0.6);
        VBox vb3 = new VBox();
        vb3.getChildren().addAll(new Label("Progressbar 3"), pi3);

        TextChooser textChooser = new TextChooser(
            vb1, vb2, vb3
        );

        textChooser.setStyle("-fx-font: 10px \"Verdana\";");

        VBox layout = new VBox(textChooser);
        layout.setPadding(new Insets(22, 22, 22, 22));

public static class TextChooser extends StackPane {
        private Label label = new Label();
        private ComboBox<String> combo = new ComboBox<>();

        public TextChooser(String... options) {
            StackPane.setAlignment(label, Pos.CENTER_LEFT);
            StackPane.setAlignment(combo, Pos.CENTER_LEFT);

            label.textProperty().bind(
                combo.getSelectionModel().selectedItemProperty()
            );
            label.visibleProperty().bind(
                combo.visibleProperty().not()
            );
            label.setPadding(new Insets(0, 0, 0, 10));

            combo.getItems().setAll(options);
            combo.getSelectionModel().select(0);
            combo.setVisible(false);

            label.setOnMouseEntered(event -> combo.setVisible(true));
            combo.showingProperty().addListener(observable -> {
                if (!combo.isShowing()) {
                    combo.setVisible(false);
                }
            });
            combo.setOnMouseExited(event -> {
                if (!combo.isShowing()) {
                    combo.setVisible(false);
                }
            });

            getChildren().setAll(label, combo);
        }
    }

In my case I cannot insert VBox into the combo box. Any idea how I can fix this?

A: The biggest problem with your code is trying to construct a TextChooser using VBoxes when the formal parameters are Strings. Change your constructor to public TextChooser(VBox... options) and the ComboBox declaration to private ComboBox<VBox> combo = new ComboBox<>();.
Now you will be able to add the items to the combo box, and if it works, you are done. If you experience the issue with adding Nodes to a ComboBox, you may want to add more code. The problem and solution are described in the Javadoc for ComboBox: http://docs.oracle.com/javafx/2/api/javafx/scene/control/ComboBox.html. To get around the fact that the item you select will be removed from the combo box, you need to change this code (taken from the javadoc):
combo.setCellFactory(new Callback<ListView<VBox>, ListCell<VBox>>() {
    @Override public ListCell<VBox> call(ListView<VBox> p) {
        return new ListCell<VBox>() {
            @Override protected void updateItem(VBox item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setGraphic(null);
                } else {
                    setGraphic(item);
                }
            }
        };
    }
});

after the line getItems().setAll(options);.
This is what your full example code would turn into:
    ProgressBar pb1 = new ProgressBar(0.6);
    ProgressIndicator pi1 = new ProgressIndicator(0.6);
    VBox vb1 = new VBox();
    vb1.getChildren().addAll(new Label("Progressbar 1"), pi1);

    ProgressBar pb2 = new ProgressBar(0.6);
    ProgressIndicator pi2 = new ProgressIndicator(0.6);
    VBox vb2 = new VBox();
    vb2.getChildren().addAll(new Label("Progressbar 2"), pi2);

    ProgressBar pb3 = new ProgressBar(0.6);
    ProgressIndicator pi3 = new ProgressIndicator(0.6);
    VBox vb3 = new VBox();
    vb3.getChildren().addAll(new Label("Progressbar 3"), pi3);

    TextChooser textChooser = new TextChooser(
        vb1, vb2, vb3
    );

    textChooser.setStyle("-fx-font: 10px \"Verdana\";");

    VBox layout = new VBox(textChooser);
    layout.setPadding(new Insets(22, 22, 22, 22));

public static class TextChooser extends StackPane {
    private Label label = new Label();
    private ComboBox<VBox> combo = new ComboBox<>();

    public TextChooser(VBox... options) {
        StackPane.setAlignment(label, Pos.CENTER_LEFT);
        StackPane.setAlignment(combo, Pos.CENTER_LEFT);

        label.textProperty().bind(
            combo.getSelectionModel().selectedItemProperty()
        );
        label.visibleProperty().bind(
            combo.visibleProperty().not()
        );
        label.setPadding(new Insets(0, 0, 0, 10));

        combo.getItems().setAll(options);

        // vvvv Begin Optional Part vvvv
        combo.setCellFactory(new Callback<ListView<VBox>, ListCell<VBox>>() {
            @Override public ListCell<VBox> call(ListView<VBox> p) {
                return new ListCell<VBox>() {
                    @Override protected void updateItem(VBox item, boolean empty) {
                        super.updateItem(item, empty);

                        if (item == null || empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(item);
                        }
                    }
                };
            }
        });
        // ^^^^ End Optional Part ^^^^

        combo.getSelectionModel().select(0);
        combo.setVisible(false);

        label.setOnMouseEntered(event -> combo.setVisible(true));
        combo.showingProperty().addListener(observable -> {
            if (!combo.isShowing()) {
                combo.setVisible(false);
            }
        });
        combo.setOnMouseExited(event -> {
            if (!combo.isShowing()) {
                combo.setVisible(false);
            }
        });

        getChildren().setAll(label, combo);
    }
}


text:
Q: we're sorry, but something went wrong on heroku when a user tries signing up I can't correctly pinpoint what exactly is causing the issue
This is a new website I just pushed to heroku, ran heroku rake db:migrate, and heroku restart
It works just fine locally but this happens in production
Here's the relevant portion of heroku logs
2013-05-03T23:16:27.189569+00:00 app[web.1]:
2013-05-03T23:16:27.189569+00:00 app[web.1]: Started GET "/signup" for xx.xx.xx.
xxx at 2013-05-03 23:16:27 +0000
2013-05-03T23:16:27.253381+00:00 app[web.1]:   Rendered shared/_error_messages.h
tml.erb (0.4ms)
2013-05-03T23:16:27.253381+00:00 app[web.1]:   Rendered layouts/_shim.html.erb (
0.0ms)
2013-05-03T23:16:27.253381+00:00 app[web.1]:   Rendered layouts/_header.html.erb
 (2.9ms)
2013-05-03T23:16:27.253381+00:00 app[web.1]: Processing by UsersController#new a
s HTML
2013-05-03T23:16:27.253381+00:00 app[web.1]:   Rendered users/new.html.erb withi
n layouts/application (43.8ms)
2013-05-03T23:16:27.253381+00:00 app[web.1]: Completed 200 OK in 60ms (Views: 48
.4ms | ActiveRecord: 1.6ms | Solr: 0.0ms)
2013-05-03T23:16:27.922135+00:00 heroku[router]: at=info method=GET path=/favico
n.ico host= sleepy-river-xxxx.herokuapp.com fwd="xx.xx.xx.xxx" dyno=web.1 connect
=1ms service=4ms status=304 bytes=0
2013-05-03T23:16:27.268937+00:00 heroku[router]: at=info method=GET path=/signup
 host= sleepy-river-xxxx.herokuapp.com fwd="xx.xx.xx.xxx" dyno=web.1 connect=6ms
service=81ms status=304 bytes=0
2013-05-03T23:16:47.934099+00:00 app[web.1]:
2013-05-03T23:16:47.934099+00:00 app[web.1]:
2013-05-03T23:16:47.934099+00:00 app[web.1]: Started POST "/users" for xx.xx.xx.
xxx at 2013-05-03 23:16:47 +0000
2013-05-03T23:16:48.248989+00:00 app[web.1]: Redirected to http://sleepy-river-xxxx.herokuapp.com/home
2013-05-03T23:16:48.248989+00:00 app[web.1]:   Parameters: {"utf8"=>"???", "auth
enticity_token"=>"m+NCbnqHJk81yWgyY+Y709mQZ0N04MpW8MLGLXjbleA=", "user"=>{"name"
=>"testuser", "email"=>"testuser@email.com", "password"=>"[FILTERED]", "passwo
rd_confirmation"=>"[FILTERED]"}, "commit"=>"Create my account"}
2013-05-03T23:16:48.248989+00:00 app[web.1]: Completed 302 Found in 311ms (Activ
eRecord: 70.6ms)
2013-05-03T23:16:48.248989+00:00 app[web.1]: Processing by UsersController#creat
e as HTML
2013-05-03T23:16:48.435265+00:00 app[web.1]:
2013-05-03T23:16:48.435265+00:00 app[web.1]:
2013-05-03T23:16:48.435265+00:00 app[web.1]: Started GET "/home" for 75.82.32.16
4 at 2013-05-03 23:16:48 +0000
2013-05-03T23:16:48.649331+00:00 app[web.1]:               FROM pg_attribute a L
EFT JOIN pg_attrdef d
2013-05-03T23:16:48.649331+00:00 app[web.1]:              WHERE a.attrelid = '"h
ashtags"'::regclass
2013-05-03T23:16:48.649331+00:00 app[web.1]: LINE 4:              WHERE a.attrel
id = '"hashtags"'::regclass
2013-05-03T23:16:48.649331+00:00 app[web.1]:                 ON a.attrelid = d.a
drelid AND a.attnum = d.adnum
2013-05-03T23:16:48.649617+00:00 app[web.1]:     23:   <%= link_to "#"+h.hashtag
s, "#" %>

2013-05-03T23:16:48.649617+00:00 app[web.1]:     25:
2013-05-03T23:16:48.649845+00:00 app[web.1]:   Rendered shared/_user_info.html.e
rb (4.4ms)
2013-05-03T23:16:48.649331+00:00 app[web.1]: ActionView::Template::Error (PGErro
r: ERROR:  relation "hashtags" does not exist
2013-05-03T23:16:48.649617+00:00 app[web.1]:     22:   <% @htags.each do |h| %>
2013-05-03T23:16:48.649617+00:00 app[web.1]:
2013-05-03T23:16:48.649845+00:00 app[web.1]: Processing by StaticPagesController
#home as HTML
2013-05-03T23:16:48.649331+00:00 app[web.1]:
2013-05-03T23:16:48.649331+00:00 app[web.1]:
     ^
2013-05-03T23:16:48.649331+00:00 app[web.1]: :             SELECT a.attname, for
mat_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
2013-05-03T23:16:48.649617+00:00 app[web.1]:   app/views/static_pages/home.html.
erb:22:in `_app_views_static_pages_home_html_erb___3097102804728997358_70437520'

2013-05-03T23:16:48.649845+00:00 app[web.1]:
2013-05-03T23:16:48.649331+00:00 app[web.1]:                AND a.attnum > 0 AND
 NOT a.attisdropped
2013-05-03T23:16:48.649331+00:00 app[web.1]:              ORDER BY a.attnum
2013-05-03T23:16:48.649617+00:00 app[web.1]:     19:

2013-05-03T23:16:48.649617+00:00 app[web.1]:     24:   <% end %>
2013-05-03T23:16:48.649617+00:00 app[web.1]: ):
2013-05-03T23:16:48.649617+00:00 app[web.1]:     20:   Tagged Posts
2013-05-03T23:16:48.649617+00:00 app[web.1]:     21:

2013-05-03T23:16:48.649845+00:00 app[web.1]:   Rendered shared/_stats.html.erb (
38.9ms)
2013-05-03T23:16:48.649845+00:00 app[web.1]: Completed 500 Internal Server Error
 in 209ms
2013-05-03T23:16:48.649845+00:00 app[web.1]:   Rendered static_pages/home.html.e
rb within layouts/application (156.1ms)
2013-05-03T23:16:48.654562+00:00 heroku[router]: at=info method=GET path=/home h
ost=sleepy-river-xxxx.herokuapp.com fwd="xx.xx.xx.xxx" dyno=web.1 connect=1ms se
rvice=219ms status=500 bytes=643
2013-05-03T23:16:48.253053+00:00 heroku[router]: at=info method=POST path=/users
 host= sleepy-river-xxxx.herokuapp.com fwd="xx.xx.xx.xxx" dyno=web.1 connect=3ms
service=395ms status=302 bytes=109

A: Something is wrong with the template that is loaded after a user signs up. Try it locally, I bet you'll find the answer you need.
Added hint:
Look at the line Relation HashTags does not exist. That holds the key to your problem.
I bet if you run
heroku run rake db:setup

and
heroku run rake db:migrate

Your problem will be solved


text:
Q: How can I set and preserve an environment variable? I want a variable that every process on the system can read. I don't know whether an environment variable is the right thing for this in Android, but
in Linux, I can set an environment variable with
VARIABLE=value
export VARIABLE

I can make it persistent by appending these two lines to the file .bashrc (or whatever the file is called, depending on the shell). Then after a restart, every process can read the variable.
How can I do the same thing on the Android system?

A: You cannot set environment variables in android what you can do is use shared preference which can be accessed through out your app later


text:
Q: Maven WildFly Plugin: Could not execute goal deploy I want to deploy my war-files with the maven wildfly-plugin.
I use the wildfly-8.2.0.Final-version and I was to force to change the port of the management-console to http://127.0.0.1:9990.
This is my maven configuration:
             <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>1.0.2.Final</version>
                <configuration>
                    <jbossHome>C:\wildfly-8.2.0.Final</jbossHome>
                    <hostname>127.0.0.1</hostname>
                    <port>8080</port>
                    <serverConfig>standalone-full.xml</serverConfig>
                </configuration>
            </plugin>

I get following error:
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.705 s
[INFO] Finished at: 2016-02-01T22:46:43+01:00
[INFO] Final Memory: 21M/171M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.wildfly.plugins:wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) on project wildfly: Could not execute goal deploy on C:\Users\laudatio\Documents\Java\wildfly\target\wildfly.war. Reason: I/O Error could not execute operation '{
[ERROR] "operation" => "read-attribute",
[ERROR] "address" => [],
[ERROR] "name" => "launch-type"
[ERROR] }': java.io.IOException: Unknown service name
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Any suggestions?

A: The error message isn't great, it's been fixed upstream, but the issue is you've got the wrong port defined. The plugin uses the management port which by default is 9990. If you change the configuration to <port>9990</port> or leave it off it should work.
A side note most of the configuration you have is not needed. The jbossHome and serverConfig are only needed for the run and start goals. If you're just deploying you don't need any of that configuration defined. The defaults should be correct.

A: The reason of the problem could be one of the following:

*

*The deployment of any archive (jar, war, ear) through wildfly-maven-plugin plugin will happen only if the WildFly is listening at its management port which is 9990 by default. So make sure that WildFly is listening at its management port.

*If WildFly is listening at its management port then check if your host file located at %SYSTEM_ROOT%\System32\drivers\etc for windows machine is configured correctly. i.e. your local host is mapped correctly for both IPv4 and IPv6.
127.0.0.1 localhost
::1    localhost


text:
Q: How to identify the system time is set to 12hrs or 24hrs in javascript When I do "new date()" in javascript it gives the time in 24hrs.
I want to know whether the user has set the system time to 12hrs or 24hours in javascript.
Is there any way to detect this in javascript?


text:
Q: tooltip does not show date in the correct format The tool tip does not show the date in the correct format in the line chart.( the image below). However the data was displayed in the correct format in the table below.
My code is listed here. Could anyone share some useful information to convert the integer to the year/month/day in the tooltip. Thanks,
Hank
def makeplotTDS(samplesTDS):
years=[ri["CollectionDate"] for ri in samplesTDS]
values=[ri["TdsValue"] for ri in samplesTDS]

sourcetds = ColumnDataSource(
    data=dict(
        year=years,
        value=values,

    )
)

hover = HoverTool(
    tooltips="""

            Year, TDS Value

            (@year, @value)

    """

)

A: You can create another variable in the data source that contains the date in string format.
from bokeh.plotting import figure,show
from bokeh.models import ColumnDataSource,HoverTool
from time import gmtime,strftime
from calendar import timegm

dates = [(2011,3,15),(2011,8,22),(2012, 7,17),(2012,11,13),(2013, 7,16),
        (2013,11,18),(2014,12, 1),(2015, 6, 8),(2015,12, 7)]
values = [1050,1250,1100,1700,1200,2650,1400,1050,1100]
years = [timegm(x+(0,0,0))*1000 for x in dates]

p = figure(plot_width = 600, plot_height=300, x_axis_type="datetime")
sourcetds = ColumnDataSource(
    data=dict(
        year  = years,
        value = values,
        syear = [strftime("%Y-%m-%d",gmtime(x/1000)) for x in years]
        # syear is the date in string format
    )
)

p.line(x='year', y='value', source = sourcetds)
p.circle(x='year', y='value', source = sourcetds)

hover = HoverTool(
    tooltips="""

            Year, TDS Value

            (@syear, @value)

    """)
p.add_tools(hover)
show(p)

The result is:


text:
Q: node.js socket.io get cookie value i want to get cookie value in node server with socket.io
so every time socket send message to server i check the value of cookie
(i don't want session cookie) only in express i get the cookie by
 router.get('/', function(req, res, next) {

  var cookie_id = req.cookies.userIDf;
  console.log(cookie_id);
   res.render('index', { title: 'Express' });
});

its work here but with socket.io i cant get cookie any solution ?
io.sockets.on('connection', function (socket) {

var cookief =socket.handshake.headers['cookie'];
  console.log(cookief); // its give me session  id not the cookies
 });

A: You can use the cookie module to do this.

npm install --save cookie

var cookie = require("cookie") //installed from npm;

io.on('connection', function (socket) {

    var cookief = socket.handshake.headers.cookie;
    var cookies = cookie.parse(socket.handshake.headers.cookie);

});

cookief will return, but isn't accessible as a JSON object.
 io=5J1m_uXsDZvc61gTAAAA; userID=63kfh16tiu7md3ck7djv8856s0; userIDf=50

cookies, which parses cookief using cookie.parse(), will allow allow you to access each of the cookie values as a JSON object:
 cookies.io; //Returns 5J1m_uXsDZvc61gTAAAA
 cookies.userID; //Returns 63kfh16tiu7md3ck7djv8856s0
 cookies.userIDf; //Returns 50

or
 { io: 'RqIksBUQW4SM4zA4AAAA', userID: '63kfh16tiu7md3ck7djv8856s0', userIDf: '50' }


text:
Q: How to mail-merge multiple documents with the same mail-merge fields from Excel workbook into Word? On multiple documents I use to put create a PDF for, the same merge fields are seen on each document.
I have mail merge fields reading from an Excel workbook to the word documents with the following columns extracted in the Word docs.

*

*Name_of_account

*Account_number

*Effective_date_of_account_policy
These three same rows are seen in multiple documents, and I know how to merge these fields using "preview results" tab to view the merged data for each individual document.
How would I — for example — grab all these docs at once and have all three of these fields populate the merge fields from the excel workbook, without having to open up each document, replace it with merged data, saving, and repeating it for each document I open.
Or, is there a program where I can just shoot all these documents into something, and when I open each document, the merge fields are populated?

A: Here are two free utilities for batch processing if you want to do them all at once:

*

*Document Batch Processes

*Batch Folder Processes by Greg Maxey
I suspect, though, you want to use them one at a time.
I have done this for years and am happy to share my method.

*

*I do not use documents but Word templates. They create a new document, based on the template that has the merge fields. The templates are not merge documents but non-merge.

*The template has an AutoNew macro that runs when that new document is created. It changes the new document to a letter merge document and attaches the data source. It sets the view to preview the merge.

*Since this was set to work in any of the computers in my office, the macro identifies that data source relative to the location set for workgroup templates. That way it works for everyone in the office.

*There is a macro that can be used when you are done that changes it from a merge document to a regular document and locks the merge fields so they retain their content. This is attached to a button on the Mailings tab but could simply be a triggered by a keyboard shortcut or QAT button.

*There is another macro that can re-attach the data source and reactivate the merge fields. This one can be triggered using a QAT button.
The macro that sets the document as a merge document and attaches the data is in a Global Template. It is called from the AutoNew macro in the templates.
The other macros are in the global template. The QAT button and Ribbon button are also in the global template. That way any modifications can be made for all of the templates for the merges by changing the one in the global template.
Here are the macros in the Global Template.
Sub AttachData()
'   Written by Charles Kenyon
'   19 April 2005 revised 15 December 2006
'       revised 12 March 2014 to clean up attachment code
'
'   Requires WorkGroupPath function
'
'   Makes activedocument a mailmerge (letter) document and
'   attaches Clients_Merge.xls from Parts folder of Workgroup Templates folder.
'
'   Then displays search dialog and goes to client, makes sure merge info is
'   displayed instead of merge codes.
'
    On Error Resume Next
'
'   SET THE FOLLOWING CONSTANTS TO REFLECT THE LOCATION OF YOUR DATA IN RELATION TO THE WORKGROUP TEMPLATES FOLDER
    Const strDATAFILE As String = "Parts\Merge Data\Clients_Merge.xlsm"
    Const strSHEET_TABLE As String = "`Clients$`"
'   THE ABOVE LIKELY WILL REQUIRE CONSIDERABLE TWEAKING
'
    Call MergeFieldUnlockAllStory 'if merge fields locked, unlock
'
'   Name of file
    Dim strFileName As String

    Dim strProvider As String
    strFileName = WorkGroupPath & strDATAFILE
'
'   Attach Merge list
    With ActiveDocument.MailMerge
        .MainDocumentType = wdFormLetters
        .OpenDataSource Name:=strFileName, _
            SQLStatement:="SELECT * FROM " & strSHEET_TABLE ', _
'
'       Show merge data
        .ViewMailMergeFieldCodes = False
    End With
'
'   Find client
    Application.Dialogs(wdDialogMailMergeFindRecipient).Show
'
    On Error GoTo 0
'
'   Disconnect from Merge - OPTIONAL - use if you are not going to add merge fields in document after creation
    Call DisconnectMerge
End Sub

Sub DisconnectMerge()
' Charles Kenyon November 20, 2020
' DisconnectMerge Macro
'
'
    Call MergeFieldLockAllStory ' locks merge fields with current content
    '   MAKE CURRENT DOCUMENT NON-MERGE - ORDINARY DOCUMENT
    ActiveDocument.MailMerge.MainDocumentType = wdNotAMergeDocument
End Sub

Sub MergeFieldLockAllStory()
'   Written by Charles Kyle Kenyon 15 November 2020
'
'   All Story Field Locker - Merge fields
    Dim oField As Field
    Dim oStory As Range
'    On Error Resume Next
    For Each oStory In ActiveDocument.StoryRanges
    ' This goes into headers and footers as well as the regular document
        Do
            For Each oField In oStory.Fields
                If oField.Type = wdFieldMergeField Then
                    oField.Locked = True
                End If
            Next oField
            Set oStory = oStory.Next
        Loop Until oStory Is Nothing
    Next oStory
    Set oStory = Nothing
    Set oField = Nothing
End Sub

Sub MergeFieldUnlockAllStory()
'   Written by Charles Kyle Kenyon 15 November 2020
'
'   All Story Field Locker - Merge fields
    Dim oField As Field
    Dim oStory As Range
'    On Error Resume Next
    For Each oStory In ActiveDocument.StoryRanges
    ' This goes into headers and footers as well as the regular document
        Do
            For Each oField In oStory.Fields
                If oField.Type = wdFieldMergeField Then
                    oField.Locked = False
                End If
            Next oField
            Set oStory = oStory.Next
        Loop Until oStory Is Nothing
    Next oStory
    Set oStory = Nothing
    Set oField = Nothing
End Sub

Private Function WorkGroupPath() As String
'   Written by Charles Kenyon
'   February 28, 2003 Updated November 15, 2020
'
'   Used by templates menus to set location of templates.
'   Returns workgroup tempates path with "\" at the end.
'
'   This is needed because if the folder is a network drive rather
'   than a folder, it will have the "\" already. If it is a folder,
'   it will not have the backslash. This function gives a string
'   with the backslash in either case.
'
    Let WorkGroupPath = Application.Options.DefaultFilePath(wdWorkgroupTemplatesPath)
    If Right(WorkGroupPath, 1) <> "\" Then
        Let WorkGroupPath = WorkGroupPath & "\"
    End If
End Function

Here is the macro that goes into the document templates, which have the merge fields but are not, themselves, merge documents.
Sub AutoNew()
' Charles Kenyon November 20, 2020
     Application.Run AttachData
End Sub

Here is a link to a template with this code in it and more. I expect to tweak this later to add QAT buttons and Ribbon buttons for the macros.


text:
Q: CSS: Courier font not rendered consistently on Windows and iOS The typeface my client wants to use is "Courier". Courier is not installed on every computer or smartphone. When it's not there, it falls back to "Courier New". "Courier New" is a thinner typeface than "Courier" and I want the look of the page to be as consistent as possible across different OS and browsers. So I figured: if "Courier" is not installed, why not use "Courier New Bold"? See the image below:

After creating this image I got even more confused. I added some more font names to my font-family declaration in th css, to cover how the font ("Courier New Bold", that is) could be called on different OS. This is the new declaration:
font-family: Courier, CourierNewPS-BoldMT, 'Courier New Bold', 'Courier New Fett', monospace;

Now comes the weird part: on Chrome in Windows XP, the text is stoll rendered as thin as before. And it's the same with Mobile Safari.
What I suspect is this: both Chrome (WinXP) and Mobile Safari only check the first font I declared. They see it's "Courier". They do not have "Courier" installed so they serve "Courier New". They do not take into account the other fonts I declared in the CSS.
Sorry for this lengthy post. My problem boils down to this: How can I get the text to show up as either "Courier" or "Courier New Bold" consistently across all OS and browsers?
You can find the live example here.
Update: I've read about -webkit-font-smoothing: antialiased; and added it to the CSS but this does not solve the problem. The text still looks much thinner on Windows and iOS.
Update2: This post from 2007 explains how Courier is displayed as Courier New on iOS and why it sucks. I'm not sure if newer versions of iOS still behave the same, though.

A: CSS lacks programming features, so you cannot express things like "use font A in normal weight if available, otherwise font B in bold weight" in CSS. Font family and font size are independent of each other, in CSS terms.
If you have checked that embedding is not allowed for Courier, check out the available free fonts created to resemble Courier. For a starter, check out
http://en.wikipedia.org/wiki/Courier_%28typeface%29#Free_alternatives
If the client can accept some of them, you could use it with @font face. (I presume you have already explained to the client that Courier is about the worst choice, competing with Comic Sans, and that the visual boldness of Courier, on computers where it is still available, may be caused by its implementation as a bitmap font, which makes it look awful in large size or in high-resolution rendering. If the client still insists, a free Courier-like font is probably the simplest and technically most reliable approach.)

A: Get some free Courier-like font and embed it as webfont to have it displayed "consistently across all OS and browsers". This is the only way to ensrue the users sees the font you/your customer had in mind when designing the site first.


text:
Q: TYPO3: Render plugin to a mapped area (TemplaVoila) I would like to create a image slider plugin through KickStart Extension. I have already installed TemplaVoila and mapped the area for the slider.
So how to connect my plugin to that mapped  area.
I can insert static text in mapped area like this
lib.slidercontent = TEXT
lib.slidercontent.value = Slider Images!!!

then how do I render my slider plugin in to lib.slidercontent.
And what kind of plugin it should be? like Backend, Frontend, Frontend-plugin.. etc.
I want to show this slider in all pages

A: *

*Create an extension and add FE plugin in it

*in your TS template add:
lib.slidercontent < plugin.tx_myslider_pi1

*in TemplaVoila add new field in DataStructure

*

*name ie. : field_slider

*Element preset: TypoScript Object Path

*After adding it use Typoscript section and in  Object Path field add: lib.slidercontent

*Save it

*

*Save the field in DS,

*map the field to some templates' block,

*save the DS,

*clear the cache,check the FE


text:
Q: Vertical separator in between field and its value in Odoo Xml Views I have a view xml in Odoo V13. I had a code as below in div tags. I just want a vertical separated pipe or a line separating field name and its value.
View as Below:
<group>

       <field name="web_site" id="field_id" class="oe_inline"/>

       <field name="Apply_First" id="field_id" class="oe_inline"/>

       <field name="start_date" id="field_id" class="oe_inline"/>

       <field name="end_date" id="field_id" class="oe_inline"/>

</group>

My Expected O/p:

Currently I also see more space between Field Name and its value along with no vertical separator as shown in the image.  I want to reduce the space between field and its value.
I just want to understand if we have any css/bootstrap styling for that.

A: I'm guessing you could use css border to achieve something like that.
1 - First way to acheive this:
Put the border property on fields or labels:
HTML:

    Label 1
    <field class="field">Field 1</field>

    Label 2
    <field class="field">Field 2</field>

    Label 3
    <field class="field">Field 3</field>

CSS:
.label{
  padding-right: 8px;
  border-right: 1px solid grey;
}

.field{
  padding-left: 5px;
}

JSFiddle : https://jsfiddle.net/q6t1y3r7/4/

2 - Second way to acheive this:
Re-organise the divs to have a column display, and put the border property on one of them:
HTML:

    Label 1

    Label 2

    Label 3

   <field class="field">Field 1</field>

    <field class="field">Field 2</field>

    <field class="field">Field 3</field>

CSS:
.column{
  display:inline-block;
}
.column-with-border{
  border-right: 2px solid grey;
}
.label{
  padding-right: 8px;
}
.field{
  padding-left: 1px;
}

JSFiddle: https://jsfiddle.net/dmwc9sk2/5/


text:
Q: Formula or VBA for cell formatting using value based on a cell but formatting from an other cell I have a fixed set of values, (0%,20%,40%,60%,80% and 100%) in column E.
If I fill a cell in column E with any of the above values, the cell G should pick formatting from another cell.
For example,
if I fill 0 in E3, the cell G3 should pick formatting from H3
if I fill 20 in E3, the cell G3 should pick formatting from H3
if I fill 40 in E3, the cell G3 should pick formatting from I3
if I fill 60 in E3, the cell G3 should pick formatting from J3
if I fill 80 in E3, the cell G3 should pick formatting from K3
if I fill 100 in E3, the cell G3 should pick formatting from L3

I know it can be done in a series of conditional formatting but it is a bit difficult for to do it. Also, wanted to see if there is a simple answer?

A: Just as illustration, below is a simple VBA macro that does the formatting. It's up to you to decide if it's simple. Something similar could be put into the Worksheet_Change event sub.
This is a little more flexible than conditional formatting, because you can have different formats on each of row of the column your choosing the format from. (e.g. see column H in the screen cap's).
Here is a screen capture of the worksheet before running the macro ...

And here is a screen capture after running the macro ...

And here is the VBA code ...
Sub FormatTransfer()
Dim mySht As Worksheet
Dim myInRng As Range, myOutRng As Range, myFmtRng As Range
Dim myCell As Range

Set mySht = Worksheets("Sheet3")
Set myInRng = mySht.Range("E1", mySht.Range("E" & mySht.Rows.Count).End(xlUp))
Set myOutRng = myInRng.Offset(0, 2)
Set myFmtRng = mySht.Range(myInRng.Offset(0, 3), myInRng.Offset(0, 7))

For Each myCell In myInRng
    If myCell.Value < 20# Then
        myFmtRng(myCell.Row, 1).Copy
        myOutRng(myCell.Row, 1).PasteSpecial xlPasteFormats
    End If
    If myCell.Value >= 20# And myCell.Value < 40# Then
        myFmtRng(myCell.Row, 1).Copy
        myOutRng(myCell.Row, 1).PasteSpecial xlPasteFormats
    End If
    If myCell.Value >= 40# And myCell.Value < 60# Then
        myFmtRng(myCell.Row, 2).Copy
        myOutRng(myCell.Row, 1).PasteSpecial xlPasteFormats
    End If
    If myCell.Value >= 60# And myCell.Value < 80# Then
        myFmtRng(myCell.Row, 3).Copy
        myOutRng(myCell.Row, 1).PasteSpecial xlPasteFormats
    End If
    If myCell.Value >= 80# And myCell.Value <= 100# Then
         myFmtRng(myCell.Row, 4).Copy
         myOutRng(myCell.Row, 1).PasteSpecial xlPasteFormats
   End If
Next myCell

End Sub


text:
Q: How many fewer questions can I ask to guess a number? If I ask a person to select a number between 1 and 1200 in his mind. If I can only ask questions for which he will only reply with YES or NO, how many questions will I need to ask before I arrive at the answer for the number He had selected in my mind ?
I am looking for the less possible number of questions. Any proven solution would be appreciable.

A: To determine which of the numbers between 1 and n are chosen, you will need to ask at least log2 n questions.  There is no possible way to do better.
The intuition for this answer is as follows.  Suppose that you ask a total of k questions.  The maximum number of different possible answers you can receive to those questions, even if they're dependent on one another, is 2k.  Since there are n possible numbers that could be picked, you need to choose k such that

2k ≥ n

Which happens precisely when

k ≥ log2 n

In other words, you have to ask at least log2 n questions to be able to even have enough different possible outcomes to associate each possible number with some possible outcome.  Since the number of questions must always be a natural number, the minimum number of questions you can ask must be at least ⌈log2 n⌉
This is purely a lower bound on the answer.  At this point, we can't rule out the possibility that maybe you need far more questions than this to get the answer.  However, the fact that we know about the binary search algorithm means that we know that you never need more than ⌈log2 n⌉ questions to get the answer, since this is the number of questions you'd ask if you were doing a binary search.  This means that the binary search algorithm has to optimal, since there is no possible way of asking a smaller number of questions.
Hope this helps!

A: The log base 2 of 1200, rounded up to an integer: that's 11.  Basically, every question cuts the possible range in half, so you just continue with a binary search until the possible range has length 1.

A: Ask for all the bits in the number. 11 questions are enough for that.
Edit: I would argue, that it's impossible to do better, due to the bijectivity between the binary and decimal representation - at least for the worst case.

A: This also a classical example of adversary arguments method which is used to find lower bound complexity. In our case the person who knows the number is the adversary. So he will wisely change his real answer when you ask a new question. How does he determine in his answer in each step? Let, for example the number is between 1-100.
You ask: is n>=50?. He may say YES OR NO both will be equally well for him since intervals are equal. Let assume he says yes.
Then you say a number between 50<=N<=100, lets say you ask: is n>=80.Then he should say NO even if the number he picked is larger than 80 because that 50<=n<=80 is larger interval.Now the number may be between 50 and 80
Maintaining this way, he will guarentee the maximum number of questions, that is logn since the interval size is decreasing like in binary search


text:
Q: How can I reference the Windows 8 Runtime (specifically BLE API) in a console application? I am using C# in Visual Studio Professional 13 on Windows 8.1 with the WDK installed.
I need to write a desktop application that interacts with a BLE device using a custom Service UUID. Using the Bluetooth Generic Attribute Profile - Heart Rate Service sample project available from MSDN, I am able to edit the service UUID being searched for and find my specific device.
However, the sample project is a Windows Store (Metro) App, and I need a console app.
When I create a new project of type Visual C# > Store App > Windows App, the Windows 8 SDK is automatically included in the project.
BUT when creating a Visual C# > Windows Desktop > * project, I cannot find a way to include the Windows 8 Runtime AND the BLE API that I need to access.
Certainly Microsoft wasn't so short-sighted as to restrict the BLE API to Store Apps? How does one create/modify their project to develop desktop and console applications that utilize the BLE API?
The research (and failed attempts) I have done thus far has already ruled out 32feet.net as the library currently does not provide support for the bluetooth low-energy stack.
However, if there is another 3rd party library (preferably open source, or at least one with a trial version) that provides BLE support, I would be open to using that in lieu of the Windows 8 Runtime.

A: It is possible to call WinRT APIs from Win32 desktop apps on Windows 8.x, but this is not a well-tested or more importantly well-documented scenario.
With C#, you have to manually add the project and runtimes references to get this to work. This blog post covers it in detail. In short, to get the "Core" tab to appear in your project settings you need to manually add this to your Visual Studio project per MSDN.
<PropertyGroup>
    <TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

Then manually add a reference to both System.Runtime.dll and System.Runtime.InteropServices.WindowsRuntime.dll.
BTW, for C++, you can make use of ABI namespaces to call WinRT functions (such as I'm doing in one case in DirectXTK for Audio) or you can use C++/CX extensions.
#if defined(__cplusplus_winrt)

    // Enumerating with WinRT using C++/CX (Windows Store apps)
    using Windows::Devices::Enumeration::DeviceClass;
    using Windows::Devices::Enumeration::DeviceInformation;
    using Windows::Devices::Enumeration::DeviceInformationCollection;

    auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender);
    while (operation->Status != Windows::Foundation::AsyncStatus::Completed)
        ;

    DeviceInformationCollection^ devices = operation->GetResults();

    for (unsigned i = 0; i < devices->Size; ++i)
    {
        using Windows::Devices::Enumeration::DeviceInformation;

        DeviceInformation^ d = devices->GetAt(i);
...
    }
#else

    // Enumerating with WinRT using WRL (Win32 desktop app for Windows 8.x)
    using namespace Microsoft::WRL;
    using namespace Microsoft::WRL::Wrappers;
    using namespace ABI::Windows::Foundation;
    using namespace ABI::Windows::Foundation::Collections;
    using namespace ABI::Windows::Devices::Enumeration;

    RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
    HRESULT hr = initialize;
    ThrowIfFailed( hr );

    Microsoft::WRL::ComPtr<IDeviceInformationStatics> diFactory;
    hr = ABI::Windows::Foundation::GetActivationFactory( HStringReference(RuntimeClass_Windows_Devices_Enumeration_DeviceInformation).Get(), &diFactory );
    ThrowIfFailed( hr );

    Event findCompleted( CreateEventEx( nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS ) );
    if ( !findCompleted.IsValid() )
        throw std::exception( "CreateEventEx" );

    auto callback = Callback<IAsyncOperationCompletedHandler<DeviceInformationCollection*>>(
        [&findCompleted,list]( IAsyncOperation<DeviceInformationCollection*>* aDevices, AsyncStatus status ) -> HRESULT
    {
        UNREFERENCED_PARAMETER(aDevices);
        UNREFERENCED_PARAMETER(status);
        SetEvent( findCompleted.Get() );
        return S_OK;
    });

    ComPtr<IAsyncOperation<DeviceInformationCollection*>> operation;
    hr = diFactory->FindAllAsyncDeviceClass( DeviceClass_AudioRender, operation.GetAddressOf() );
    ThrowIfFailed( hr );

    operation->put_Completed( callback.Get() );

    (void)WaitForSingleObjectEx( findCompleted.Get(), INFINITE, FALSE );

    ComPtr<IVectorView<DeviceInformation*>> devices;
    operation->GetResults( devices.GetAddressOf() );

    unsigned int count = 0;
    hr = devices->get_Size( &count );
    ThrowIfFailed( hr );

    if ( !count )
        return list;

    for( unsigned int j = 0; j < count; ++j )
    {
        ComPtr<IDeviceInformation> deviceInfo;
        hr = devices->GetAt( j, deviceInfo.GetAddressOf() );
        if ( SUCCEEDED(hr) )
        {
            HString id;
            deviceInfo->get_Id( id.GetAddressOf() );

            HString name;
            deviceInfo->get_Name( name.GetAddressOf() );
...
        }
    }

#endif

This of course is code that is only compatible with Windows 8.0 or later and will not run on Windows 7 or earlier.

A: Create a Portable Class Library and put all your BLE code there then reference the library in your desktop/console application.