Get curved result set rather than angular in JavaScript (maths help needed)

Question: I've got a script that creates a gradient by shading cells based on their distance from a set of coordinates. What I want to do is make the gradient circular rather than the diamond shape that it currently is. You can see an en example here: http://jsbin.com/uwivev/9/edit
<code>var row = 5, col = 5, total_rows = 20, total_cols = 20;

$('table td').each(function(index, item) {

    // Current row and column
    var current_row = $(item).parent().index(),
        current_col = $(item).index();

    // Percentage based on location, always using positive numbers
    var percentage_row = Math.abs(current_row-row)/total_rows;
    var percentage_col = Math.abs(current_col-col)/total_cols;

    // I'm thinking this is what I need to change to achieve the curve I'm after
    var percentage = (percentage_col+percentage_row)/2;

    $(this).find('div').fadeTo(0,percentage*3);

});
</code>
If you can give me hand with the right maths function to get the curve I'm after that would be great! Thanks!
Darren
Comment: Why are you doing it like this? Why not use canvas?
Answer: You can use the square of the distance formula:
((current_row - row)*(current_row - row) + (current_col - col)*(current_col - col))
then multiply it by whatever scale factor you need.
Answer: Here is a circle drawing procudure I wrote many moons ago in Pascal which you can use as pseudo code to understand how to color pixels at the radius from an (X,Y) and work your way in. Multiple shrinking circles should cover the entire area you need. The code also gives you the formula for accessing the radius.
<code> PROCEDURE DrawCircle(X,Y,Radius:Integer);
 VAR A,B,Z:LongInt;
 BEGIN
  Z:=Round(Sqrt(Sqr(LongInt(Radius))/2));
  FOR A:=Z TO Radius DO
   FOR B:=0 TO Z DO
     IF Radius=Round(Sqrt(A*A+B*B)) THEN
      BEGIN
       PutPixel(X+A,Y+B,8);
       PutPixel(X+A,Y-B,9);
       PutPixel(X-A,Y+B,10);
       PutPixel(X-A,Y-B,11);
       PutPixel(X+B,Y+A,12);
       PutPixel(X+B,Y-A,13);
       PutPixel(X-B,Y+A,14);
       PutPixel(X-B,Y-A,15);
      END;
 END;
</code>
NB: "Longint()" is a compiler typecast for larger numeric computations so don't let that worry you.
NB: Inner-most brackets are executed first.
Answer: <code>// Current row and column
var current_row = $(item).parent().index(),
    current_col = $(item).index();

// distance away from the bright pixel
var dist = Math.sqrt(Math.pow(current_row - row, 2) + Math.pow(current_col - col, 2))

// do something with dist, you might change this
var percentage = dist / total_cols;

$(this).find('div').fadeTo(0,percentage*3);
</code>
Comment: If I wanted to increase the severity of the curve, like in easeInQuart how could I do that to the gradient? Thanks!
Comment: Not exactly sure what you mean but you could try squaring *dist* or *1 - dist* to get a quicker or slower light dropoff.
Comment: Thanks, in the end I went with fade = percentage-(0.5-percentage);


mod_rewrite to correct directory rather than root directory

Question: I need to use mod_rewrite to redirect
http://www.site.com/new_cars/cars.php?make=brandname
to have a friendlier url of
http://www.site.com/new_cars/brandname.html
I've tried
RewriteRule ^([^/]*)\.html$ /new_cars/cars.php?make=$1 [L]
but this redirects to the root rather than the /new_cars/ direcory.
Can anyone explain how to resolve this please?
Answer: You need to add the PT (pass-through) flag to your RewriteRule.  Read more in the mod_rewrite documentation.
RewriteRule ^([^/]*)\.html$ /new_cars/cars.php?make=$1 [L,PT]

Comment: Thanks, that was what I was missing


How to interpret polychoric correlation matrix with reverse scored items?

Question: I'm currently working with a dataset with a sample size of 174 from a questionnaire that measures 6 types of personality traits with 5 response options per item (Strongly Agree, Agree, Neutral, Disagree, Strongly Disagree)
I've generated a polychoric correlation matrix to inspect each item and I need some assistance with the interpretation.
Specifically I'm looking at the correlation between two items: Item 1 reads "Compares their successes to other's" and another reads "questions things learned."
During my reliability analysis, R recommended that item 1 be reverse scored, so that's the scoring reflected in the polychoric matrix:

Given the strong positive correlation between these two items, my question is, given the reverse scoring, could we interpret the correlation between items 1 and 3:
As people DO compare themselves to others (reverse scored), the more they feel like they are questioning things learned
OR
As people DON'T compare themselves to others, the more they feel like they are contributing. I'm just not sure on how to interpret the direction of the relationship in this case.
Answer: Given that you recoded the item, the "original" (pre-recoding) correlation should have a negative sign, indicating a negative relationship. You can easily verify this by looking at a bivariate scatterplot with the original (unrecoded) variable.
Comment: From your description of your original variables, that interpretation sounds correct to me. Good luck with your work!
Comment: Yes you are correct. The original pre-coded item does indeed indicate a negative relationship. Would it be fair to say (if we're looking at the pre-coded item) to say that the less often people compare themselves to others, the more they question things (or vice versa)?


Success message after successful query not showing up but form data still sent to DB

Question: I am working on a code right now that allows for the user to input their email and another user's email to add them as a "friend" into the table "friends"
So far my code works in terms of posting the form data into the DB / table "friends" however the message I would like to appear is not showing up at all.
My HTML form:
<form class="form-signin" action="FriendLookup.php" method = "POST" enctype="multipart/form-data">

Add a Friend

        Your Email
        <input type="text" id="inputEmail1" name = "self_email" class="form-control" placeholder="Friend's Username" >

        Your Friend's Email
        <input type="text" id="inputEmail2" name = "friend_email" class="form-control" placeholder="Your Username" >

        <button class="btn btn-lg btn-primary btn-block" name = "submit" type="submit">Search</button>
      </form>

PHP script:
<?php
include_once('support.php');
//connect_database.php contains your connection/creation of a PDO to connect to your MYSQL db on bmgt406.rhsmith.umd.edu/phpmyadmin
include_once('connect_database.php');
ini_set("display_errors","1");
error_reporting(E_ALL);

// Initialize $title and $body.
$title = "Add User";
$body = "<fieldset><legend> $title </legend>";

$name_of_table = "friends";

// Check if the table exists in the db.
if (tableExists($db, $name_of_table)) {

    $inputemail1 = $_POST['self_email'];
    $inputemail2 = $_POST['friend_email'];

        // Prepare a SQL query and bind all 6 variables.
        $sqlQuery = "INSERT INTO $name_of_table ( self_email, friend_email)
        VALUES ( :self_email, :friend_email)";

        $statement1 = $db->prepare($sqlQuery);

        $statement1->bindValue(':self_email', $inputemail1, PDO::PARAM_STR);
        $statement1->bindValue(':friend_email', $inputemail2, PDO::PARAM_STR);

        // Execute the SQL query using $statement1->execute(); and assign the value
        // that is returned  to $result.
        $result = $statement1->execute();

        if(!$result) {
                // Query fails.
                $body .= "Inserting entry for friend failed.";
        } else {
                // Query is successful.
                   $body .= "Success";
        }

        // Closing query connection
                $statement1->closeCursor();

           }

$body .= "</fieldset>";
echo generatePage($title,$body);
?>

Any help is greatly appreciated. I am a novice programmer.
Comment: Where is your generatePage method you're calling?
Comment: what's the status of your previous questions?
Comment: function generatePage($title, $body) {
$page = <<
Answer: My function generatePage was wrong. I added HTML into the function and now it works!


Sulu cmf get referrer

Question: I have two pages in my content tree n sulu 1.0.13. On page "A" I set a reference to page "B" with a field of the content type "single internal link".
When I am on page "B" I want to get the referring page "A". I have tried following code in my controller:
$dm  = $this->get('sulu_document_manager.document_manager');
$doc = $dm->find('992758cf-1da4-4e45-9ee4-ca9c4ec3998e'); // UUID of page "B"
$di  = $this->get('sulu_document_manager.document_inspector');
$node = $di->getNode($doc);

$refs = $di->getReferrers($doc); // $refs is an empty collection
$refs = $node->getReferences(); // $refs is an empty collection
$refs = $node->getWeakReferences(); // $refs is an empty collection

$refs is always an empty collection.
What is the right way to get the referring page?
Update: I now use version 1.1.0 RC2
Comment: Your question is not at all clear.  Please describe your issue more clearly and show an attempt to solve the problem on your own.
Answer: Sadly the SingleInternalLink content type is currently just saving the UUID as a string, and not as a proper reference in PHPCR. This is also described in this GitHub Issue. I will reevaluate this issue, and see if we can fix that in the near future.
As a workaround you could use the InternalLinks content type, which already saves its values as references, although it is possible to add more than one link.
Comment: I have tried InternalLinks and now it works, But I get two elements if I call `$refs = $di->getReferrers($doc);`. One of type `Sulu\Bundle\ContentBundle\Document\RouteDocument` and the other one of type  `Sulu\Bundle\ContentBundle\Document\PageDocument`.
Comment: I have the issue with version 1.1.0 RC2
Comment: Yeah, the issue isn't fixed yet in any version... And that's right, I didn't think about that... You probably have to check if the document is from type `PageDocument`. Routes have its own tree, and are also referencing pages, this is why you get two referrers.

Sulu cmf get referrer


How to convert percentile rank into z score in R

Question: I have a vector of percentile ranks. I want to convert them into z-scores, so it will be interval scale. I have to do it in R, but I could not find a function or package that can do this. Does anyone have any idea?
Comment: Why do you think something that converts percentile ranks into something that's nominally a z-score will leave you with an interval scale?
Comment: Title changed to "convert". I doubt OP was trying for word play here.
Comment: Use the `qnorm` function.
Comment: @Glen_b is right about this, although in this case the title of your question may be quite accurate; and this is a COVERT action. Can you share, or do you have any information on the raw data as far as distribution?
Answer: You would apply the inverse cdf to the percentile ranks to convert them to quantiles, so if you want standard normals, $z=\Phi^{-1}(p)$ should do what you seem to be asking for.
However, this transformation won't of itself make an ordinal scale into an interval scale.
In R, you would do this as:
z <- qnorm(p)

Answer: x <- c(1 , 1.1 , 1.2) #your z-values in a vector

pnorm(x) will give the area to the left of the Z-value, which is the percentile. This function can take a vector as an input.
Comment: This seems to be the opposite of what is being asked for: the *input* is supposed to be the percentile ranks and the *output* will be the Z-scores.


How to display Media image with alt attribute in paragraph twig template

Question: I'm trying to access alt attribute as in given example Get Media Image URL in Paragraphs Twig Template - Drupal 8
But there is an example how to access alt and title...

That's easy, too. You should use the following syntax, switching out the bold for the machine name of your image field: {{ content.field_custom_image['#items'].alt }}

this is not worked for me
Answer: Digging in Twig certainly works, though it does have limitations (such as translation support).
If you need custom output, you could try:
function getMediaFieldImage($mediaField = NULL, $imageStyle = NULL) {

  if ($mediaField && $mediaField->entity) {

    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();

    // Get image.
    $mediaImage = $mediaField->entity
      ->get('field_media_image');

    // Check for translation.
    if ($mediaField->entity->hasTranslation($langcode)) {

      // Get translated image field.
      $mediaImage = $mediaField->entity->getTranslation($langcode)->get('field_media_image');
    }

    // Get image attributes.
    $alt = $mediaImage->alt;
    $width = $mediaImage->width;
    $height = $mediaImage->height;
    $title = $mediaImage->title;

    // Get image entity.
    $mediaImageEntity = $mediaImage->entity;

    // Get image mime type.
    $mediaImageMimeType = $mediaImageEntity->getMimeType();

    // Get image file URI.
    $mediaImageEntityUri = $mediaImageEntity->getFileUri();

    // Set image URL.
    $url = \Drupal::service('file_url_generator')->generateString($mediaImageEntityUri);

    // Set image style URL if not .svg.
    if ($imageStyle && $mediaImageMimeType !== "image/svg+xml") {
      $url = \Drupal::service('entity_type.manager')
        ->getStorage('image_style')
        ->load($imageStyle)
        ->buildUrl($mediaImageEntityUri);
    }

    return [
      'url' => $url,
      'alt' => $alt,
      'width' => $width,
      'height' => $height,
      'mimeType' => $mediaImageMimeType,
      'title' => $title,
    ];
  }

  return NULL;
}

Set it like:
function MYTHEME_preprocess_paragraph(&$variables) {
  $variables['mediaImage'] = getMediaFieldImage($paragraph->get('field_name'), 'medium');
}

And in Twig:

Answer: I have worked out this i have access to alt in my case its:
 {% if paragraph.field_media_image is not empty %}

  {% endif %}

So solution is:
{{ content.field_media_image[0]['#media'].field_media_image[0].alt }}

Comment: You just add a twig file for the field and media type that has no extraneous markup then.
Comment: You should just render the media item properly and all of this will 'just work'. `{{ content.field_media_image }}` - the rest is controlled from Manage Display on this particular media type. There is no need to manually write out img tags.
Comment: Thank you @Kevin In my case i need to do in that way.  Also it renders lots undesirable divs as fields templates in action when you use {{ content.field_media_image }} in my project i need to avoid this ...
Comment: @Kevin it will change all media files ... which i no need ... but this is usable for other tasks ... you are right :)
Comment: If you want to translate in twig, just add `|t` and use `{{ content.field_media_image[0]['#media'].field_media_image[0].alt|t }}`


How to prove that $3x^5-12x^4+21x^3-9x+2$ is irreducible over the rationals?

Question: Prove that the polynomial $3x^5-12x^4+21x^3-9x+2$ is irreducible over the rationals
$p=2: f(x)=x^5+x^3+x$..this has root..So this is not irreducible over $Z_2$
so Can I conclude $f(x)$ is irreducible over the rationals?
Comment: Why would you expect that demonstrating a polynomial is *reducible* in one context would imply that it is *irreducible* in a different context?
Answer: Try Eisenstein's criterion on $x^5 P(1/x)$.
Comment: Ooh, clever! +1
Answer: Hint: Try $p=3$ instead. Remember to appeal to Gauss's lemma at some point.
Comment: Using Eisntein's irreducibility Criterion P must not divide $a_n$ and $P^2$ must not divide $a_0$ for $f(x)$ to be irreducible over the field of rational numbers but $a_n=3$ which is divisible by 3. I am trying to figure this out so please do let me know if I am wrong.


How to change youtube video's player settings using javascript

Question: I am writing a simple Chrome extension to change the speed of a video on youtube. The code can be found here.
In essence, I am using the following code to change the speed:
document.getElementsByTagName("video")[0].playbackRate = 2;

This works well, but doesn't affect the settings on the player. Which also cause some issues, especially when you switch videos.
Is there a better approach to interact directly with the player?
Answer: You may try Youtube Player API iframe embeds, Iframe API allows you to control the speed of the video.
The default playback rate is 1, which indicates that the video is playing at normal speed. Playback rates may include values like 0.25, 0.5, 1, 1.5, and 2.
Here is a sample code for Iframe API:
function onYouTubeIframeAPIReady() {
    var player;
    player = new YT.Player('player', {
        videoId: 'M7lc1UVf-VE',
        playerVars: { 'autoplay': 1, 'controls': 0 },
        events: {
            'onReady': function(e){
                // e.target = player
                e.target.setPlaybackRate(0.5); // set to half speed
                e.target.playVideo(); // watch lolcats in slow motion :)
            },
        }
    });
}

Comment: Doesn't this create a new player?


In wordpress, how to show next and previous post

Question: I am able to display next and previous post in worspress but unable to show second-previous or third-previous || second-next or third-next like
1 - I want to show this too
2 - this is showing
3 - My Current post
4 - This is showing
5 - I want to show this too
any help would be appreciated.
In the and I am showing you my code so you can judge.
CODE:
<?php $next = get_permalink(get_adjacent_post(false,'',false)); if
($next != get_permalink()) { ?><a href="<?php echo $next; ?>">

            <?php $nextPost = get_next_post(true); $nextthumbnail = get_the_post_thumbnail($nextPost->ID); echo $nextthumbnail; ?>

                        <?php echo get_cat_name(1);?>
                        <?php the_time('M j, Y') ?>

                        <?php next_post_link('%link', "%title", TRUE); ?>

                        <?php
                        $Nextpost = get_next_post($id);
                        echo apply_filters('the_content', $Nextpost->post_content);
                        ?>

<?php } ?>
<?php $prev = get_permalink(get_adjacent_post(true,'',true)); if
($prev != get_permalink()) { ?><a href="<?php echo $prev; ?>">

            <?php $prevPost = get_previous_post(true); $prevThumbnail = get_the_post_thumbnail($prevPost->ID); echo $prevThumbnail; ?>

                        <?php echo get_cat_name(1);?>
                        <?php the_time('M j, Y') ?>

                        <?php previous_post_link('%link', "%title", TRUE); ?>

                    <?php
                        $Prevpost = get_previous_post($id);
                        echo apply_filters('the_content', $Prevpost->post_content);
                        ?>

<?php } ?>

Answer: WordPress provides several navigational template tags to make it easy for visitors to surf your pages. There are basically two different types of template tags used for chronological post navigation:
posts_nav_link() – for navigating various archive (non-single) pages
previous_post_link() & next_post_link() – for navigating single-post pages

<?php $posts = query_posts($query_string); if (have_posts()) : while (have_posts()) : the_post(); ?>

    <?php previous_post_link(); ?> | <?php next_post_link(); ?>

<?php endwhile; endif; ?>

Answer: try this:
    global $post;
    $post_curr = $post;

    //get last post
    $post_last1 = get_previous_post();
    setup_postdata($post_last1);
    //get second last post
    $post_last2 = get_previous_post();

    setup_postdata($post_curr);
    //get next post now
    $post_next1 = get_next_post();
    setup_postdata($post_next1);
    //get second next post
    $post_next2 = get_next_post();

    //reset current post data
    setup_postdata($post_curr);

Comment: Hi I did as you said but nothing happend


Setting std::io_base flags for custom stream class

Question: I have a custom class called Stream
class Stream
public:
    Stream& operator<<(int i) { stream_ << i; return *this;}
            template <typename CustomClass>
            Stream& operator<<(const CustomClass& c) { stream_ << c.toString() /* assume this template always have toString(); return *this; }
private:
    std::stringstream stream_;
};

This is a very basic example of what I actually have. And I am trying to set std::ios_base flags like following:
Stream() << 1 << std::hex << 2;

using operator;
Stream& operator<<(std::ios_base& b) { stream_.setf(b.flags()); return *this; }

from what I understand, because std::hex returns std::ios_base so it should call this and set streams' flag. But it always call the template. Note: If i remove this template, everything works just as good as you would expect but is there a way to have both?
Please feel free to ask further if you need more clarification
Comment: Just to clarify a bit more what I am trying is to make **ios_base** overloaded operator !important over template. I believe this is very weird behaviour since templates should be put at the very last if no other type could be resolved at compile time it should be used. and I believe std library is linked before all other libraries.
Comment: btw even if i return `std::ios_base&` and return stream, this does not do the job i mean it still calls template over typed overload
Answer: IOStream manipulators are not objects of type std::ios_base, they are functions that take and return std::ios_base references. So when you want to do stream insertion regarding these objects, you have to overload for function pointers:
Stream& operator<<(std::ios_base& (*manip)(std::ios_base&))
//                 ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
{
    manip(this->stream);
    return *this;
}


How can I get the unique nested lists of a python list?

Question: My question is related to the uniqueness of lists nested in a main list. Specifically, I have the following structure which is a list which includes lists:
lst = [  [
            [14], ['walk'], [69], ['walk'], [7]
         ],
         [
           [14], ['walk'], [69], ['walk'], [7]
          ],
        [
          [30], [948], [75], [947], [10]
        ],
        [
          [14]
        ]
   ]

In order to get the unique elements of the list I tried το implement the following:
unique_data = [list(x) for x in set(tuple(x) for x in lst)] but I am getting the following error:
TypeError: unhashable type: 'list' .
The expected output is the following:
[[[14], ['walk'], [69], ['walk'], [7]],
[[30], [948], [75], [947], [10]],
[[14]]]
Any suggestions?
Answer: Try:
lst = [
    [[14], ["walk"], [69], ["walk"], [7]],
    [[14], ["walk"], [69], ["walk"], [7]],
    [[30], [948], [75], [947], [10]],
    [[14]],
]

out, seen = [], set()
for subl in lst:
    t = tuple(tuple(i) for i in subl)
    if t not in seen:
        seen.add(t)
        out.append(subl)

print(out)

Prints:
[
    [[14], ["walk"], [69], ["walk"], [7]],
    [[30], [948], [75], [947], [10]],
    [[14]],
]

Answer: if you create a dict, and saving the values as key, so if order matter than you can solve this problem as
lst = [[[14], ['walk'], [69], ['walk'], [7]], [[14], ['walk'], [69], ['walk'], [7]], [[30], [948], [75], [947], [10]], [[14]]]

unique = {}
for sublist in lst:
    key = ''
    for sub_sublist in sublist:
            for value in sub_sublist:
                    key += '_' + str(value)
    unique[key] = sublist

print(unique)
# output -> {'_14_walk_69_walk_7': [[14], ['walk'], [69], ['walk'], [7]], '_30_948_75_947_10': [[30], [948], [75], [947], [10]], '_14': [[14]]}

result = list(unique.values())
print(result)
# output. -> [[[14], ['walk'], [69], ['walk'], [7]], [[30], [948], [75], [947], [10]], [[14]]]

Answer: In order to use set(), you need to convert all the lists (and sub-lists) to tuples.
Try this code:
unique = tuple([tuple([tuple(x) for x in y]) for y in lst])
unique = set(unique)

Comment: Though this removes duplicate inner collections; but it outputs Set of tuple. OP needs original List with given order. Please modify your answer to return List with given order.
Comment: You are right. I think it's obvious..
Here is the code:
list_again = [list([list(x) for x in y]) for y in unique]


Clarinet losing air

Question: I have a clarinet that I've been using recently, but whenever I try and play it, I can hear a sound like air coming out from somewhere besides the usual note.
I'm using a 3 1/2 reed, but when I switch to a 2 reed, the noise lessens by quite a bit.
Why is that?
Comment: Perhaps your clarinet has developed a leak in its joints, and your clarinet requires service by a qualified repair person.
Comment: @WheatWilliams Actually, I just found out that when I use a 2 reed, the noise is considerably lessened.  Updating comment.
Answer: If you hear an air-rushing sound, it's almost certainly due to reed strength, as you are finding out.  Leaks in pads or body joints are more likely to produce squeaky notes, or make it difficult/impossible to play notes which expect the given pad to be closed.
But far more important: please take some lessons from a qualified instructor.  It's all too likely that you are using the wrong embouchure (sp) in an attempt to compensate for lack of breath control.  While picking a proper reed strength is a good idea, the last thing you want is to pick up bad muscle habits.  They're very difficult to cure.

Clarinet losing air


How to upload and read PDF files in Django

Question: I am trying to create a simple django application which takes some PDF files from user and then read its contents. So far I have written the code as mentioned below, But it doesn't seem to work. It's producing an error at this line PyPDF2.PdfFileReader(open(filename))

TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile

index.html
<input type="file" name="fupload" multiple>

view.py
if request.method == 'POST':
        files = request.FILES.getlist('fupload')

        pdf_data = []
        for filename in files:
            read_pdf = PyPDF2.PdfFileReader(open(filename))
            page = read_pdf.getPage(0)
            page_content = page.extractText()
            pdf_data.append(page_content)

Can any body tell me what I am doing wrong. Thanks in advance
Comment: You probably need to use `open(filename.temporary_file_path())`. [See docs](https://docs.djangoproject.com/en/2.0/ref/files/uploads/#django.core.files.uploadedfile.TemporaryUploadedFile.temporary_file_path)
Answer: You need to modify your views.py to this:
if request.method == 'POST' and request.FILES['myfile']:

        pdfFileObj = request.FILES['myfile'].read()
        pdfReader = PyPDF2.PdfFileReader(io.BytesIO(pdfFileObj))
        NumPages = pdfReader.numPages
        i = 0
        content = []
        while (i<NumPages):
            text = pdfReader.getPage(i)
            content.append(text.extractText())
            i +=1


About the one point compactification

Question: I have a question about the one-point compactification, given an arbitrary topological space $(X,\tau)$, does the one-point compactification always exist?
Thanks!
Answer: No. A compactification of a space $X$ is an embedding of $X$ as a dense subset of a compact Hausdorff space, so if $X$ isn't already Hausdorff, it has no compactification. And if $X$ is compact and Hausdorff, it will be closed in any Hausdorff space, so the only compact Hausdorff space in which it is dense is itself. It turns out that $X$ has a one-point compactification if and only if it is a locally compact, non-compact Hausdorff space.
However, one can start with any non-compact space $X$ and form the Alexandroff extension $Y$ by adding a single point in such a way as to get a compact space in which the original space is a dense subspace. (Specifically, the open nbhds of the added point are the complements in $Y$ of closed, compact subsets of $X$.) It is an actual compactification, however, if and only if you start with a locally compact, non-compact Hausdorff space, in which case it's the one-point compactification of that space. (Note that some people do call it the one-point compactification, not requiring compactifications to be Hausdorff.)
Answer: Yes (provided that the word "compactification" does not involve Hausdorffness, see @Brian M. Scott's answer. For me, a compactification of $X$ is just a compact space containing $X$ as a dense subspace. Under this definition, the one-point compactification of $X$ is a compactification if, and only if, $X$ is not already compact). As a set, it is $X \cup \{\infty\}$ and its open sets are the open sets in $X$ and the complements of closed compact subsets of $X$, where you add $\infty$ to each one of them. In some applications you want the compactification to be Hausdorff, in which case you need to add more assumptions, namely that $X$ itself is Hausdorff and locally compact.
Comment: why can't you just add one open set which is $X\bigcup\left\{ \inf\right\} $?
Comment: Because this is only compact in pathological cases.
Comment: why? any open Cover will need to contain the set $X\bigcup\left\{ \inf\right\} $  (in order to contain inf) and then you can take this set as a finite cover
Comment: You're totally right. I guess this is the reason why people require Hausdorffness, then?
Comment: I think so. I'm not sure this new topology gets any  of the properties of the original one, so maybe that is why people are not interested in it
Comment: This seems like a reasonable explanation. I still stand by my answer, however, since "one-point compactification" and "Alexandroff extension" are synonyms (at least on Wikipedia), and the above construction always yields a compactification (provided the original space is not closed in its compactification, i.e., if $X$ is not cmpact).
Comment: The reason is that if you define the compactification by adding just $X\cup \infty$ then you change all closed sets of the original topology.
Comment: The reason for it being uninteresting or for it not being a compactification?
Comment: You are right. The reason to not be interesting. The new space does not retain important information of the original space, i.e., the closed compact sets.

About the one point compactification


Is setMainFrameURL really defined in webView

Question: I'm new to programming with cocoa. I was going to experiment with the webkit View class. According to this page:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/WebKit/Classes/WebView_Class/index.html
a web view should have a method called "setMainFrameURL". However, when I try to use it, I get an error message saying that the method is not defined. How is this possible? Does this method really exist?
Answer: setMainFrameURL is an Objective C method. The equivalent Swift syntax would be
webView.mainFrameURL = "http://www.google.com"

Comment: Thanks, it works. Is that the only thing I need to make the webView show the page? If so, it looks like it doesn't work :(
Comment: Yes, it should be. If you're still stuck, please open a new question (it is a new question after all) and don't forget to include all relevant code.


How can I tell if the results of an MCMC data-model fit are reasonable?

Question: I'm using an MCMC Python package (emcee) to fit observed data to a 4-dimensional ($A, B, C, D$) model. After a run with 100 walkers and 5000 steps (1000 burn-in period) I get a result that looks like the image below.
The 2-parameters density maps look horrible and the (16th, 84th) percentiles (dashed blue lines) around the median (red line) enclose an enormous region. Does this mean that the 5000 steps I'm using are not enough? Do I need more walkers? Could it be that this is the best results I can hope for?
Comment: In the few tests that I have run, emcee is a pretty inefficient sampler (despite being quite widespread for a number of reasons). 5000 steps are probably not enough for your problem. To check this, do several independent runs and compare them. Run a bunch of diagnostics on the chains. Do posterior predictive checks. See Chapters 6 and Part III of _Bayesian Data Analysis_ by Gelman et al.
Answer: 5000 steps is typically little for MCMC. Some applications need to go to 1M - I would say 100K is a better starting point.
Comment: Can you expand your answer and provide more evidence in support of your statement?


Gradle - 'flatten' default resource directory

Question: in my project I've the following directory setup:

src/main/resources/common
src/main/resources/local
src/main/resources/release

My goal is to override the default resources elaboration and to "flatten" this directory tree in the final archive.
At the moment I found only this ugly solution:
resources {
  exclude 'release'
  exclude 'common'
  exclude 'local'
  srcDir 'src/main/resources/common'
  srcDir 'src/main/resources/local'
  srcDir 'src/main/resources/release'
}

With this solution I think that the files in src/main/resources will be copied in the final archive. Is there a way to exclude the resources default directory?
Is there any better way to solve my problem?
Answer: A better approach is to override the default locations:
sourceSets {
    main {
        resources {
            srcDirs = [
                'src/main/resources/common',
                'src/main/resources/local',
                'src/main/resources/release'
            ]
        }
    }
}

It's a common idiom for Gradle APIs to offer a property (such as srcDirs) that allows to set a collection (thereby overriding any defaults), and a similarly named method (such as srcDir) that allows to add to the collection (thereby adding to the defaults).

My goal is to [...] "flatten" this directory tree in the final archive.

Not sure what you mean by that.
Answer: What if we don't wish to explicity give each directly..can flatten happen as in ant it is happens with flatten attribute as in
https://alvinalexander.com/blog/post/java/flatten-directories-during-copy-with-java-ant-task/
Comment: This is so hard to read that it gives the impression of asking a question instead of trying to answer the question at the top of the page. You are try to answer, aren't you?


How to send variable to the javascript in Drupal?

Question: What is the easiest way to send a value from PHP to Javascript in Drupal form?
Comment: Referring to the answers, drupal_add_js is deprecated. You should use #attached for forwards-compatibility. See http://drupal.stackexchange.com/questions/90040/what-is-the-difference-between-using-drupal-add-js-and-attached
Answer: The standard way to do this in Drupal is with drupal_add_js(), using the "setting" type, e.g.:
drupal_add_js(array('variableName' => 'value'), 'setting');

That will make the variable available on the JS side at Drupal.settings.variableName.


Layout com listview dúvidas

Question: Estou enfrentando um problema em layout, nesse layout tenho um ListView e depois do tenho mais 3 Buttons só que quando a lista é muito grande ela usa todo tamanho da tela e não consigo ver o Buttons, alguem pode me ajudar?
Como está o layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="match_parent"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/edtPesquisa"
        android:drawableLeft="@drawable/ic_lupa"
        android:layout_marginTop="15dp"
        android:hint="Pesquisa rápida"
        tools:ignore="HardcodedText,RtlHardcoded,UnusedAttribute"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:elevation="1dp"
        android:layout_height="40dp" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listDebitosPendentes"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"
        tools:ignore="NestedScrolling"
        android:footerDividersEnabled="false"/>

    <Button
        android:text="Enviar boleto por e-mail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/enviaBoletoEmail"
        tools:ignore="HardcodedText" />

    <Button
        android:text="@string/enviar_linha_digit_vel_por_sms"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/enviaLinhaDigitavel" />

    <Button
        android:text="@string/mostrar_linha_digit_vel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/mostraLinhaDigitável" />

</LinearLayout>

Answer: Adicione no ListView o peso android:layout_weight="1" desta forma o layout vai se reorganizar.
Comment: Deu certo aqui, muito obrigado.
Comment: Só uma pergunta, teria como eu adicionar esse peso pelo código java?
Comment: Acredito que tenha como sim, para fazer uma pesquisa como esta, vc pode pesquisar mais ou menos assim "layout_weight android programmatically" no google.
Answer: Você precisa usar um componente chamado ScrollView
<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include layout="@layout/minha_tela_"> </include>
    </ScrollView>

Você basicamente vai ter dois xmls... um que representa o layout inteiro, e outro com esse componente. Na activity use setContentView nesse layout que tem o scrollview.
(Detalhe: nesse layout que tem o scrollview SÓ vai ter ele. Todo o resto vai estar no layout que chamei de "minha_tela")
Comment: Eu adicionei da forma que me falou, mas ficou estranho meu listView, ele só mostra um item por vez.
Comment: Na verdade é só setar o layout "pai" para match_parent...

Layout com listview dúvidas


How do I add CSS classes to all the form elements?

Question: How can I add the same CSS class (form__text) to form elements in Drupal 8?
Answer: You can do it using template_preprocess_form_element something like:
use Drupal\Component\Utility\Html;
function [YOURTHEME]_preprocess_form_element(&$variables) {
  $input_types = ['search', 'textfield', 'password'];
  $type = $variables['element']['#type'] ?? NULL;
  if (in_array($type, $input_types)) {
    $variables['element']['#attributes']['class'][] = Html::cleanCssIdentifier('form__text');
  }
}

Update
If the below doesn't work try the following using hook_preprocess:
/**
 * Implements hook_preprocess().
 */
function [YOURTHEME]_preprocess(&$variables, $hook) {
  if ($hook == 'input') {
    $variables['attributes']['class'][] = Html::cleanCssIdentifier('form__text');
  }
}

To exclude submit button ?
change the condition to $hook == 'input' && $variables['element']['#type'] !== 'submit' instead of $hook == 'input'
Comment: It doesn't work for me
Comment: https://www.thirdandgrove.com/insights/theming-form-elements-drupal-8/ check this out
Comment: Thank you. It works. But how to exclude submit button?
Comment: you can easily overwrite to not load the css for the submit button despite the effort on overwriting the button, I would go with that route


rsync ignores --chown/--usermap

Question: I'm running ansible with the synchronize module, which underneath runs rsync.
My problem is not ansible-related, as I took the rsync command from the debug output and ran it manually - still the same issue.
The command I ran is:
/usr/bin/rsync --delay-updates -F --rsync-path="sudo rsync" --compress --delete-after --archive "/local/path" "firstname.lastname@example.com:/remote/path" --chown=myuser:myuser
Whatever I try - I end up with the directory belonging to root:root.
I therefore now rsync successfully runs as root, so it should have all neccessary permissions. I also tried using --usermap=*:myuser --groupmap=*:myuser - nothing.
I added --chmod=750 - not being applied.
In the debug output (-vvvv), I can see my parameters again, but that's it.
No warning, no error, but also no later mention of anything containing "user", "group", "chown" etc...
rsync is 3.1.1 on Debian 8.
Any help would be appreciated...
Answer: The chown system call (and, by extension, the chown and rsync --chown commands) may only be used by root. You're connecting to the remote system as the ansible user, so the remote system will not permit the operation. The rsync command recognizes that it's not running as root on the remote system, so it silently ignores the --chown option and others like it (e.g., --mapuser).
The rsync manual is not really explicit about this behavior, but if you specify the --super option as well, it will cause rsync on the remote system to assume it is running as root, even if it is not. This will allow it to attempt the chown operation, and to produce an error if or when it fails.
EDIT:
If you do manage to execute rsync on the remote system as root (e.g., using --rsync-path="sudo rsync"), you will still need to add a couple options for --chown to be usable. The manual states:
--chown=USER:GROUP
    This option forces all files to be owned by USER with group GROUP.
    This is a simpler interface than using --usermap and --groupmap
    directly, but it is implemented using those options internally, so
    you cannot mix them.

And here's what the manual says for --usermap and --groupmap:
--usermap=STRING, --groupmap=STRING
    ...
    For the --usermap option to have any effect, the -o (--owner)
    option must be used (or implied), and the receiver will need to
    be running as a super-user (see also the --fake-super option).
    For the --groupmap option to have any effect, the -g (--groups)
    option must be used (or implied), and the receiver will need to
    have permissions to set that group.

In addition to using --rsync-path to run it under sudo, try adding the -o and -g options as well.
Comment: I read something like that too, but... via `--rsync-path="sudo rsync"`, it actually runs as root, as I can see because the files are afterwards owned by root. Also, adding `--super` doesn't change anything - I tried that before.
Comment: Your question doesn't make it clear that your invocation of `rsync` causes it to run as root on the remote system. That being the case, you probably need the `-o` and `-g` options as well; I've updated my answer to explain why.
Comment: Yeah, it's only implicitely mentioned by the directory ending up belonging to root:root. I added the `--rsync-path` to the question, I removed it by error.

I tried adding `-o` and `-g`, and also `-p` (although they should be included in `--archive`) - didn't help.
Comment: My mistake, I missed that you had `--archive` specified. Perhaps the invocation under `sudo` is losing some options. Does the sudo log (not sure where it goes in Debian) show the correct options being applied?
Comment: `sudo` wasn't the offender... it was partially me, and maybe it's also a bug.
Answer: sudo wasn't the offender... it was partially me, and maybe it's also a bug/feature working differently than expected.
My ansible task added the source folder name to the destination path, which resulted in that path being created, and than the source folder being created inside that folder, effectively doubling the folder structure to /destination/path/source/source/...
--chmod is being applied to the second source folder, but not to the one created as part of the destination structure. Therefore, the top source belongs to root, but the second source belongs to the user it should belong too.
Fixed my ansible task to use the proper path, and therefore also this issue.
I wonder if one should expect rsync to also chown/chmod folders that it creates as part of the destination path?

rsync ignores --chown/--usermap


jqGrid - cells with TD elements inside

Question: I seem to have an issue where with jQuery Grid (jqGrid) if I have loaded data where one of the cells has a table inside, it throws an error when onSelectRow() is fired and I call $(grid).getRowData(rowid).
jqGrid seems to be enumerating ALL of the TD elements in the selected row (including those which are children of the table within a given cell).
Is there a proper way to do this or to prevent jqGrid from enumerating those elements? :(
EDIT: In my particular case, the HTML was hidden until needed, so I was able to replace the TD's with "xtd" on the server until sent out to the client. On the client-side, when I needed them HTML, I just replace "xtd" to "td". Still wish there was a better way.
EDIT: I want to clarify, I desire a method of doing this that doesn't modify the plugin. An well-written modification would still be nice.
Answer: Old but yet not solved.
Hi. Yes jqGrid has problem with inner table and td but there is a quick and useful fix. In file jquery.jqGrid.min (jqGrid  3.8.2 - jQuery Grid). Put file into js-beutifier or get not minified version and find getRowData function. Then you have to add extra condition to lookup foreach b("td", r).each(function (t) { to code b("td[id!='-1']", r).each(function (t) {. In your inner table you should declare . In this case you exclude your td from searching in colModel.
Copy/Paste this code:
getRowData: function (f) {
            var j = {},
                i, c = false,
                e, k = 0;
            this.each(function () {
                var n = this,
                    a, r;
                if (typeof f == "undefined") {
                    c = true;
                    i = [];
                    e = n.rows.length
                } else {
                    r = n.rows.namedItem(f);
                    if (!r) return j;
                    e = 2
                }
                for (; k < e;) {
                    if (c) r = n.rows[k];
                    if (b(r).hasClass("jqgrow")) {
                        b("td[id!='-1']", r).each(function (t) {//fix
                            a = n.p.colModel[t].name;
                            if (a !== "cb" && a !== "subgrid" && a !== "rn") if (n.p.treeGrid === true && a == n.p.ExpandColumn) j[a] = b.jgrid.htmlDecode(b("span:first", this).html());
                            else try {
                                j[a] = b.unformat(this, {
                                    rowId: r.id,
                                    colModel: n.p.colModel[t]
                                }, t)
                            } catch (B) {
                                j[a] = b.jgrid.htmlDecode(b(this).html())
                            }
                        });
                        if (c) {
                            i.push(j);
                            j = {}
                        }
                    }
                    k++
                }
            });
            return i ? i : j
        }

Finally where you want to put inner table do this:

            Now It's working!

            Yeah

Of course you can change id attribute but I recommend fix this with html id attribute due to jQuery performance against class attribute.
Comment: Thank you for solving this! :) I will use this or similar solutions in the future. Much cleaner than what I had before.
Answer: There is one more option that I implemented. Instead of, manipulating the jqGrid core javascript, why not use th  tags instead of td tags in the Cell that you are creating a Table.
I had a similar requirement and did go ahead with the above implementation (jqgrid.min.js manipulation). But then what happens is there is a mismatch with the Column# and the Cell# that we are trying to fetch. For example, I had to set a cell dynamically, Though the column-id was correct, it was editing/ changing a different cell (as there were extra td tags in one of the Cells).
I went ahead and used th instead of td tags for the custom table that I am creating within a Cell. Works so far.

jqGrid - cells with TD elements inside


Global variables in Apache Server

Question: I'm writing some apache (2.2) modules in C and I'm pretty new at it, so I was wondering:
I need to know if it's possible to create a global variable that will be initiated whenever the apache server starts to run.
See, I need to have a list of host names (that will be "privileged"), so that every request I get, I need to check if the host name appears in the list (to check if it's "previleged").
So the list should be global (so that every server instance will have the same instance of the list), and I need to initialize it at the beginning.
How do I do that, if it's at all possible?
Thanks!
Comment: Is the list static, or is it loaded from some external source?
Comment: I would like the list to be loaded from a simple text file when it is initiated.
Answer: Although not a complete answer, I did manage to find a way to have global variables.
I used the apr_pool_userdata_get and apr_pool_userdata_set methods with the process's global pools (pconf and pool).
For further reference:
http://apr.apache.org/docs/apr/0.9/group_apr_pools.html
Examples:
attach static global data to server process pool
char *data = "this is some data";
apr_pool_userdata_setn ((void*) data, "myglobaldata_key", NULL, request->server->process->pool);

attach malloced heap data to server process pool
char *data = strdup("this is some data");
apr_pool_userdata_setn ((void*) data, "myglobaldata_key", (apr_status_t(*)(void *))free, request->server->process->pool);

Now retrieve the global data:
char *data;
apr_pool_userdata_get ((void**)&data, "myglobaldata_key", request->server->process->pool);
if (data == NULL) {
    // data not set...
}

Answer: This link indicates one can use static/global variables in a module, they do require care in accessing from multiple threads.  My observation is that given there may be multiple processes (the global variable would live in a process, shared by many threads), the static should not be counted on to be initialized. Ie initializing once probably is not enough.
http://httpd.apache.org/docs/2.2/developer/thread_safety.html#variables

Global variables in Apache Server


How do I cancel previous PPK file of amazon ec2?

Question: I am in a big problem. actually I have given server details to third party extension support, in which I have provided them SFTP host xx.xx.xx.xx and username as ubuntu and PPK file.
Now I want to cancel the previous PPK file or some alternate way using which no one can misuse my server using those credentials. My Network administrator is responding negative on that. He said Nothing can be done now, Please let me know the solution for this problem, if possible.
Thanks!
Comment: Generate a new key pair. Put its public key in `~/.ssh/authorized_keys`. Check that it works. Remove the old public key from that file.
Answer: Your problem seems to be that you have have given the third party a copy of the private key that is used to access the server.
You could just disable access for that private key, but it would seem that other people are also using it, so your Network Administrator doesn't want to do that.
You really should have asked the 3rd party to generate their own key pair and provide you with the public key. You could then have permitted that for a short period of time and removed it, which would not have impacted on anyone else.
There isn't much you can do.
One option is to restrict access to the server by using the limit features of the authorized_keys files. If you know the ip addresses from which access is allowed, you can configure OpenSSH to only allow access from those addresses, even if the correct key is provided.
eg
https://debian-administration.org/article/685/Restricting_SSH_logins_to_particular_IP_addresses
You could also experiment with the "Match" options in sshd_config to prevent access from users who match certain criteria.
Bottom line: never share private keys. Every user should be using their own key pair.
Comment: Thanks for your kind help. IP restriction is a good trick there.
Answer: This will be slightly complicate process. AWS has a full page talking about keypair

The public key is stored under <code>/home/ubuntu/.ssh/authorized_keys</code>or ubuntu. If you use other OS, please check AWS documentation on the location of the public key.
Make snapshot backup before you do anything
Launch the backup snapshot (to another IP), make changes, test whether you can login
Then make another snapshot on the current server before you make changes
Make the changes

You may use some guide here Change key pair for ec2 instance
Always create extra snapshot if you want to make changes, it is the final fallback if you mess stuff up.
UPDATE:
Actually there is a CATCH here. If your AWS EC2 instance is using instance-storage(e.g. m3, c3), you cannot change the keypair. What you can do is create snapshot from it, make changes on the snapshot, launch a new instance from there .


How can I remove the hardcoded menus from the Navin subtheme?

Question: I'm using Navin, a subtheme of Omega. I'm trying to hide the main menu, so that I can add a superfish menu, but I don't know where it's been hardcoded. It's not in a block (admin/structure/blocks). I've checked the theme settings page (admin/appearance/settings/theme_name) The region--menu.tpl.php looks like this:
<?php
  $main_links = menu_tree_page_data(variable_get('menu_main_links_source', 'main-menu'));
  $main_links = menu_tree_output($main_links);
  $secondary_links = menu_tree_page_data(variable_get('menu_secondary_links_source', 'user-menu'));
  $secondary_links = menu_tree_output($secondary_links);
?>
<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <?php if ($main_links): ?>

      <?php print render($main_links); ?>

    <?php endif; ?>
    <?php if ($secondary_links): ?>

      <?php print render($secondary_links); ?>

    <?php endif; ?>
    <?php print $content; ?>

I appreciate any help or suggestions.
Answer: <?php
  $main_links = menu_tree_page_data(variable_get('menu_main_links_source', 'main-menu'));
  $main_links = menu_tree_output($main_links);
  $secondary_links = menu_tree_page_data(variable_get('menu_secondary_links_source', 'user-menu'));
  $secondary_links = menu_tree_output($secondary_links);
?>

Get rid of that bit for starters.
If you're not using that, then you can probably also strip out the following:
<?php if ($main_links): ?>

      <?php print render($main_links); ?>

    <?php endif; ?>
    <?php if ($secondary_links): ?>

      <?php print render($secondary_links); ?>

    <?php endif; ?>

Which (for reference) should just leave you with the following:
<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <?php print $content; ?>

Comment: Best explanation is the documentation: [`menu_tree_page_data`](https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_tree_page_data/7), [`menu_tree_output`](https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_tree_output/7). But basically, the first function says "Get the menu data for menu x", and then the second part says "Cool, thanks for that - time to make it look like a menu ready to put on the screen".
Comment: That was the trick - thanks. What did those 4 lines do that locked the menu in? What are the `$main_links` and `$secondary_links` variables?
Answer: Go here: /admin/appearance/settings/THEME
uncheck main menu
Comment: I tried that - I put the wrong link in the post

Thanks anyway
Comment: did you clear the cache after you disabled the menu?
Comment: I did do that - still no dice


A simple jquery change() is not working on safari

Question: I am trying to set the dropdown option by using a simple jquery code:
$('option[value="1"]').attr('selected', 'selected').change();

and its working fine on Chrome and Firefox but not on Safari.
Anyone, please help in solving this strange issue. Thanks in advance.

$(document).ready(function(){
  $('#btn').click(function(){
    $('option[value="1"]').attr('selected', 'selected');
  });
});

<select id="dd">
   <option value="">Select</option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
 </select>

 <input type="button" value="click me" id="btn" />
Comment: Events are not supported cross on `` tag. You will have the same issue in IE also and potentially other browsers
Comment: You haven't `change`d the option's `value`, **so no change to report.** The only `value` that changed is `dd.value`.
Comment: @connexo you can still trigger a change event even  when value hasn't changed. By doing it on `` I think OP was counting on it bubbling
Comment: @charlietfl Ofc you can, but it's pointless if the `value` of the element `change` is dispatched on hasn't changed at all.
Answer: Events are not supported cross browser on <option> tag. You will have the same issue in IE also and potentially other browsers. The same is true of trying to hide <option>
Set the value of the <select> and trigger change on that

$('#btn').click(function() {
  $('#dd').val('1').change();
});

$('select').change(function() {
  console.log(`Select #${this.id} was changed to ${this.value}`)
})

<select id="dd">
  <option value="">Select</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

<input type="button" value="click me" id="btn" />


Inserir Option com javaScript

Question: Tenho um formulário dinâmico. Com um campo radiobutton e um select. De acordo com o valor que seleciono na opção eu populo o campo lista com valores selecionados.
Exemplo.
Opção 1
Opção 2
Ao selecionar a opção 1, o campo select é populado com
Item A
Item B
Item C
Ao selecionar a opção 2, o campo select é populado com
Item X
Item W
Maior maior problema é como faço para inserir options dentro do select com JavaScript.
Comment: Bem-vindo ao StackOverflow Samuel. Por favor, poste um trecho do código que você já tem para termos uma ideia melhor do problema, sugiro que leia esse artigo da ajuda do site: [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve).
Comment: você pode utilizar jQuery no seu projeto? ou tem de ser em JavaScript nativo sem bibliotecas.
Comment: Olá Paulo. Não posso usar Jquery. Pois é um form dinâmico, e criou scripts com os elementos que criei na tela.  O João resolveu na resposta mais abaixo. É basicamente daquela forma, só falta descobrir para ele não ficar somando enquanto eu alterno entre as opções.
Answer: Segue um exemplo amigo.. Após você selecionar uma opção, os options são criados dinamicamente. A cada alteração do radio os options mudam, refletindo somente os valores desejados para aquela seleção.

function populateOptions(opt) {
  let select = document.querySelector("select[name='selecao']");

  while (select.children.length) {
    select.removeChild(select.lastChild);
  }

  // Cria option "default"
  let defaultOpt = document.createElement('option');
  defaultOpt.disabled = true;
  defaultOpt.selected = true;
  defaultOpt.textContent = 'Selecione uma opção';
  select.appendChild(defaultOpt);

  opt.forEach(function(option) {
    let optEl = document.createElement('option');
    optEl.value = option.value;
    optEl.textContent = option.text;

    select.appendChild(optEl);

  });
}

document.querySelectorAll("input[type='radio']")
  .forEach(function(radio) {
    radio.addEventListener('change', function(evt) {

      switch (parseInt(this.value)) {
        case 1:
          populateOptions([{
              value: "A",
              text: "Opção A"
            },
            {
              value: "B",
              text: "Opção B"
            }
          ]);
          break;

        case 2:
          populateOptions([{
              value: "C",
              text: "Opção C"
            },
            {
              value: "D",
              text: "Opção D"
            }
          ]);
          break;
      }
    });
  });

  Opção 1
  <input type="radio" name="opt" value="1">

  Opção 2
  <input type="radio" name="opt" value="2">

<select name="selecao">
  <option disabled selected>Selecione uma opção</option>
</select>
Comment: Obrigado meu amigo!!! Testei os códigos e funcionaram também.
Answer: Fiz um pequeno exemplo aqui utilizando somente JavaScript. Veja:

[...document.getElementById('form').elements].forEach((field) => {
  field.addEventListener('change', () => {
    if (field.value === 'opcao2') {
      createOptions(2);
    } else {
      createOptions(3);
    }
  });
});

function createOptions(quantidade) {
  let fieldSelect = document.getElementById('select');
  cleanOptionsSelect(fieldSelect);
  for (let i = 0; i < quantidade; i++) {
    let option = document.createElement('option');
    option.text = 'Opção ' + i;
    fieldSelect.append(option);
  }
}

function cleanOptionsSelect(fieldSelect) {
  fieldSelect.innerHTML = '<option value="valor1">Selecione uma opção</option>';
}
<form id="form">
    <input type="radio" id="opcao1" name="opcao" value="opcao1" />
    Opção 1
    <input type="radio" id="opcao2" name="opcao" value="opcao2" />
    Opção 2
</form>

<fieldset>
  <legend>Campo select</legend>
  <select name="select" id="select">
    <option value="valor1">Selecione uma opção</option>
  </select>
</fieldset>

Observações:

O algoritmo possui compatibilidade com a maioria dos navegadores, mas provavelmente não funcionará no IE por usar ES6.
Comment: Ah que legal cara. É isso mesmo!!!!. Só teria que descobrir como faz pra ele não ficar somando as opções ao ficar alternando entre as opções.
Comment: Uma dica é colocar o valor do atributo `value` no html dos `input[type=radio]` como `2` e `3` e na terceira linha do código javascript você chamar diretamente a função `createOptions(this.value)` :D
Comment: Vou fazer aqui agora :D
Comment: @samueltomkelski alterado! Se a minha resposta te ajudou ou serviu como resposta não esqueça de marcar como resposta!
Comment: recomendo utilizar o evento `change` ao invés do evento `click` por vários motivos.
Comment: Resolvido, o algorimo se adapta facilmente. Obrigado pelo lembrete :) Não tinha reparado

Inserir Option com javaScript


Why this OLS fitting will converge to (0,-0.5)?

Question: In this AR1 model, if we fit y with diff(y), regardless the true coefficient, when N is large, it seems the model will converge to (0,-0.5), why?
> set.seed(0)
> ts.sim <- arima.sim(list(order = c(1,0,0), ar = c(0.1)), n = 1e6)
> x= diff(ts.sim)
> y=ts.sim[-1e6]
> lm(y~x)

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x
 -4.376e-05   -5.000e-01

> ts.sim <- arima.sim(list(order = c(1,0,0), ar = c(0.9)), n = 1e6)
> x= diff(ts.sim)
> y=ts.sim[-1e6]
> lm(y~x)

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x
  -0.003551    -0.500002

Comment: @JarleTufto, you probably misunderstood the OP. Based on his recent posts, he is not trying to recover the autoregressive coefficient using the model here. He is wondering why the estimate is always 0.5 regardless of what AR coefficient is used when the underlying time series is generated. And could you please explain the result that is easy for you?
Comment: @JarleTufto, please see my comment above.
Comment: Are you sure you want `y[-1e6]` rather than `y[-1]`? This will hardly make a numerical difference, but the interpretation of the model will be different. Now you are fitting $y_t\sim\Delta y_{t+1}$, after the correction you would be fitting $y_t\sim\Delta y_{t}$.
Comment: Your results can easily be explained (from the well known autocovariance function of the AR(1) process).  But it's unclear why are you regressing $y_t$ on $y_{t+1}-y_t$ so I vote to close.  To recover the autoregressive coefficient via OLS you should regress $y_t$ on $y_{t-1}$.
Comment: @RichardHardy Then what _is_ he trying to do?
Answer: This is a law of large numbers in action.
Let $\rho$ be the parameter (the lag-1 correlation) and let $\varepsilon_i$ be a sequence of iid standard Normal variables, so that for $i=1, 2, \ldots,$ the model is
$$y_{i+1} = \rho y_i + \varepsilon_{i+1}$$
and $y_0=0.$  Therefore the first differences are
$$x_{i+1} = y_{i+1} - y_i = (\rho-1)y_i + \varepsilon_{i+1}.$$
Because $y_0=0,$ inductively the $x_i$ and $y_i$ all have expectations of zero.
Because $\rho \lt 1,$ notice that $x$ and $y$ move in opposite directions: they must be negatively correlated.  You might (intuitively) think that the amount of correlation depends on $\rho.$  However, it also depends on the variances of the $x_i$ and $y_i.$  We need to examine these.
As in the question, stop the series at $n$ and regress $y$ against $x.$  The slope estimate is
$$\hat \beta = \frac{\sum_i (y_i-\bar y)(x_i - \bar x)}{\sum_i (x_i-\bar x)} \approx \frac{\sum_i y_i x_i}{\sum_i x_i^2}$$
because, for large $n,$ the means $\bar y$ and $\bar x$ will be close to their expectations, which are zero.
Again because $n$ is large, the empirical values in the fraction can be approximated by their expectations (a law of large numbers),
$$\frac{\sum_i y_i x_i}{\sum_i x_i^2} \approx \frac{E\left[\sum_i y_i x_i\right]}{E\left[\sum_i x_i^2\right]}.$$
Find those expectations from the definition of the series $(y_i).$  I will begin with a useful auxiliary calculation:
$$\begin{aligned}
E\left[\sum_i y_i^2\right] &= \sum_i E\left[y_i^2\right] = \sum_i E\left[(\varepsilon_{i+1} + \rho y_i)^2\right]\\
&= \sum_i E\left[(\varepsilon_{i+1})^2\right] + 2\rho \sum_i E\left[\varepsilon_{i+1} y_i\right] + \rho^2 \sum_i E\left[ y_i^2\right]\\
&= n + 0 + \rho^2 E\left[\sum_i y_i^2\right]
\end{aligned}$$
which is justified because the $\varepsilon_i$ have zero expectation, unit variance, and are independent of each other (whence, in particular, $\varepsilon_{i+1}$ is independent of $y_i$).  Solving this equation gives
$$E\left[\sum_i y_i^2\right] = \frac{n}{1-\rho^2}.$$
With this (standard) result in hand we obtain, using similar calculations,
$$E\left[\sum_i y_i x_i\right] = -\frac{n}{1+\rho}$$
and
$$E\left[\sum_i x_i^2\right] = \frac{2n}{1+\rho},$$
whence
$$\hat \beta \approx \left(-\frac{n}{1+\rho}\right)\,/\,\left(\frac{2n}{1+\rho}\right) = -\frac{1}{2}.$$
(You can carry out this analysis rigorously using the Delta method, which applies because  the denominator of $\hat\beta,$ $\sum_i x_i^2,$ will stay away from zero.)
Finally, because the linear regression passes through the point of averages and the means of the $x_i$ and $y_i$ are each close to $0,$ the constant term will be close to $0,$ too.


The Test Statistic of the Neyman - Pearson Lemma

Question: I cannot understand this statement from the book Robust Statistics:
The most powerful tests between two densities $p_0$ and $p_1$, are based on a statistic of the form
$$\int \psi F_n(dx) = \frac{1}{n}\Sigma \psi (x_i), \text{ where } \psi(x) = \log\left(\frac{p_0}{p_1}\right)$$
There are two densities $p_0$ and $p_1$ but in the integral $\psi$ is multiplied by empirical distribution $F_n$, why? Also, it looks like the integral is not over x but over density $f_n(x)$? And I cannot understand why the integral is equal to the average of the logarithm of the ratio of two densities? I guess, that makes sense, if $\int F_n(dx) = \psi f_n$, but then what is $f_n$?
Comment: $f_n$ is the empirical (observed) probability of seeing each observation $x_i$, which equals $1/n$.   We construct the test statistic based on the observed sample, and this is how we do it.
Comment: This is the same calculation explained at https://stats.stackexchange.com/a/73626/919.
Comment: @whuber I don't understand the explanation. the delta "function" and the indicator function have different arguments. Then how to interpret the $g(0)$ in that case? $I(0)$?
Answer: The integral can be understood in the Riemann-Stieltjes sense.
Background
This is a natural generalization of the usual (elementary) Riemann integral with respect to the variable $x.$  Recall that such an integral, when it exists, can be approximated as accurately as you might wish by Riemann sums: you partition the interval of integration (call it $[a,b]$) into sufficiently short pieces, which will be the bases of rectangles, and use the values of the integrand within those intervals for the (signed) heights of rectangles and add up all the rectangle areas.
More specifically, letting the points in the interval be
$$a = t_0 \lt t_1 \lt \cdots \lt t_N = b,$$
where every $t_{i+1} - t_i$ is smaller than some tiny value $\delta,$ you can select any points $t_i{*} \in [t_i, t_{i-1}]$ for computing the rectangle heights $\psi(t_i^*).$
The Riemann-Stieltjes integral, when it exists, is more often written in the form
$$\int_a^b \psi(x)\,\mathrm{d}F(x)$$
where $F$ is increasing and right-continuous (as are all probability functions).  This means that instead of using the interval widths $t_{i+1}-t_i$ for the bases of the rectangles, you will weight them by the values of $F,$ using $F(t_{i+1}) - F(t_i)$ for the bases.  In effect, $F$ is trying to tell you how much weight to assign to any possible interval $[t_i, t_{i+1}]$ in the integral.  When $F$ is a distribution function then, by definition, $F(t_{i+1}) - F(i)$ is the probability of the interval $(t_i, t_{i+1}]$ and the approximation is the familiar sum of values of $\psi$ multiplied by (approximate) probabilities: it's an expectation.
Application
A dataset $(x_1, x_2, \ldots, x_n)$ gives rise to a random variable $X$ in a natural, physical way: take $n$ slips of paper ("tickets"), write $x_i$ on the $i^\text{th}$ ticket, put them all into a box, blindly withdraw a single ticket from that box, and read its value.  Because (at least in theory) every ticket has an equal chance of being withdrawn, each ticket has a chance of $1/n.$
By definition, the distribution function of $X$ is
$$F_X(x) = \Pr(X \le x) = \left(\text{number of } x_i \text{ not exceeding } x\right)\times \frac{1}{n}.$$

The black dots and lines plot $F_X$ for the dataset $(1, 2, 2, 2, 4, 4).$  The dataset is depicted by the red points below the horizontal axis.
To evaluate a Riemann-Stieltjes integral we will be considering the weighted differences $F(t_{i+1}) - F(t_i)$ for arbitrarily short intervals $[t_i, t_{i+1}]\subset [a,b].$  These values equal (a) the number of data points less than or equal to $t_{i+1}$ (b) minus the number of data points less than or equal to $t_i$ (c) times their common probability of $1/n.$  Clearly the net of the counts (a) and (b) is *the number of data points in the interval $(t_i, t_{i+1}].$  Consequently,

The only intervals $(t_i, t_{i+1}]$ contributing to the Riemann-Stieltjes integral are those that include at least one of the data $x_j.$

The dotted vertical lines indicate a partition of the interval $[a,b]=[0,5].$
Thus, any approximation to this integral is a sum over tiny intervals surrounding the data points; and the value contributed by such an interval is (a) the count of data points in that interval (b) times $1/n$ (c) times the value of $\psi$ at some arbitrary point in that interval.

This figure plots the differences of $F$ against values of $t_i^*$.  In effect it reproduces the information given by the red points in the first figure: it shows where the data values occur and with what multiplicities.
Suppose, now, that $\psi$ is continuous.  This means the values of $\psi$ within tiny intervals do not vary much compared to the sizes of those intervals.  This assumption permits us to approximate the Riemann-Stieltjes approximation (!) by choosing the specific values $\psi(x_j)$ for $x_j\in(t_i,t_{i+1}].$
At this point we make an algebraic move to simplify everything.  Suppose $(t_i, t_{i+1}]$ is an interval that is so small it contains only one unique data value.  However, that value might appear multiple times in the dataset.  If it appears $s$ times, it will be the values of the data points $x_{j_1}=x_{j_2}=\ldots=x_{j_s},$ say.  Each of these is our chosen representative $t_i^*.$  The contribution of this interval to the integral therefore is
$$\psi(t_i^{*}) \left(F(t_{i+1}) - F(i)\right) = \psi(x_{j_1}) \times \left(s\times \frac{1}{n}\right) = \sum_{k=1}^s \psi(x_{j_k})\times \frac{1}{n}.$$
That is, each data point $x_j$ contributes a value of $\psi(x_j)$ times a probability of $1/n$ to the integral.
The resulting approximation to the integral is
$$\int_{a}^b \psi(x) \,\mathrm{d}F(x) \approx \sum_{j=1}^n \psi(x_j) \frac{1}{n} =  \frac{1}{n}\sum_{j=1}^n \psi(x_j).$$
In the limit of arbitrarily small intervals, this sum equals the integral (by definition).
Finally, the indefinite integral in the question is implicitly meant to extend over all real numbers.  This is defined to be the limit of the integrals over finite intervals $[a,b]$ as $a$ and $b$ (separately) tend to $-\infty$ and $\infty.$  It should be clear from the foregoing result that once $a$ is smaller than the minimum data value and $b$ is larger than the maximum data value, the integral no longer changes and its limiting value has been reached.


set app to iphone4 and up,and ios6

Question: I have 3 questions that i couldnt find an answer to.

How would i set my app to work ONLY with iPhones-4 and up ?
How can i install in my xcode  ios6 to check my app ?
do i need icon in 57x57 if my app is for iphone4 and up only ?

thanks .
Comment: Adding some random code does not make it a "quality question".
Comment: @MartinR and not adding the code, would not allow me to upload almost anything to this site . i dont think this question has some problem. its relevant,specific,and right.
Comment: I removed this random code :)
Answer: Ad 1. This is not possible, even if you detect iPhone model in your code, someone can buy your app on older iPhone (3GS if you build your app for iOS 6).
You should support all devices available on a given iOS version.
Ad 2. Install the newest XCode (4.5.1) from Mac AppStore
Ad 3. Yes, you do.

set app to iphone4 and up,and ios6


Topology - Fundamental group proof - Path homotopy

Question:
Hi,
I have been really stuck for a while on the following:
As you can see below, is part of the proof of the Fundamental group actually being a group. I am aware of the general idea behind the diagrams which 'show' the homotopy. Yet I am confused as to how you give the co-ordinates. As in, below you can see f(2s-t) is used in the left hand side, yet what method was used to know it was 2s-t. I have tried thinking of a general method, something along the lines of continous functions taking the interval [0,1/2] to [1/2,1] and then multiplying this function by t. Yet it didnt seem to work. I am asking as I am trying to find the explicit homotopy required to prove the RHS of the picture, where we need to show f is homotopic to the constant path glued with f.
Thank you for any help I have been stuck for a long time, much appreciated.
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Answer: I have written a short note on these proofs. Check it out.


Electric violin amplification problem

Question: I have a (cheap) electric violin I use for practice. The violin requires a 9V battery to be amplified. After a couple of times I left the violin on (and hence I consumed the battery in like one night) I decided to buy a small AC adapter capable of 9V output. I amplified the violin this way for a while, connecting the violin with the adapter with a simple wire (3 meters of cable are more than enough for my room).
Yesterday, for some reason, I was not able to amplify the violin any more. The LED on the violin still turns on when it is connected to the adapter, but there seems to be no line out and the violin is not amplified, neither if I plug the headphones on the violin nor if I connect the violin with an external amplifier. I also tried a new 9V battery  but the result is the same.
I'm not sure whether there is a difference between an AC adapter with 9V output and a 9V battery (I would say no, but I only have some notions in electronics, I'm definitely not an expert).
Did I actually ruin the electronic of the violin? What may be other problems that can cause this issue? I'm having some troubles in finding shops in my hometown that deal with electric violins, so I would appreciate if you could suggest some other test I can do myself to check whether the electronics is still working.
Comment: Post the specifications of the DC adaptor: Somewhere on it will be written its rated output voltage and amperage limit.
Answer: If depends on the adapter. A cheap adapter rated a fairly high power, say 9 Volts 1 Amp, will probably output 9 volts at 1 amp as it says on the box, but if your violin pickup only draws 0.1 amp (or even less, which is quite possible) the voltage may be more than 9 volts. It could be anything up to about 12.7 volts. That might or might not damage your violin - depending how "cheap" the violin electronics design is!
Another possibility is that you had a power surge (e.g. a lightning strike that hit the mains supply) which somehow "got through" you adapter and fried the violin electronics (but it left the LED working - that is probably independent of anything other electronics in the violin).
But the most likely cause is something mechanical, like a broken lead or loose connection from the violin pickup to the circuit board, or from the board to the output connectors, or the on/off switch is broken. Have a good look using a magnifying glass, and try waggling any wire connections about to see if that fixes it, or at least makes some clicking or crackling noises.
You could also try touching the connections to the pickup transducer (at both ends of the wires) with your finger - if you that produces a humming noise, the electronics is working but the connections are bad or the pickup itself may have failed.
A music shop that repairs electric guitars should be able to help. The basic principles are the same for an electric guitar (or an electronic pickup for an acoustic guitar) and an electric violin.

Electric violin amplification problem


Undefined variable: _SESSION

Question: help me please, I have my principal page php with a $_SESSION.
page1.php
<?php
session_start();
$consulta = "select t.num_ticketfrom sdg_ticket t where t.cod_tipo_incidente=2 and t.cod_usuario='".$_SESSION['sdg_usuario']."' ";
?>

                        <?php include("page2.php"); ?>

second page
page2.php
<?php
    include("conexion.php");
       $count="SELECT COUNT(*)
    FROM sdg_ticket t,
      sdg_usuario u,
      sdg_estado_ticket e
    WHERE u.cod_empresa      = t.cod_empresa
    AND u.cod_usuario        = t.cod_usuario
    AND e.cod_empresa        = t.cod_empresa
    AND e.cod_estado_ticket  = t.cod_estado_ticket
    AND t.cod_estado_ticket <>7
    and t.cod_usuario   ='".$_SESSION['sdg_usuario']."'";
?>

setInterval() in the page1.php refresh every 30000 time,
in the second load get this
"Notice: Undefined variable: _SESSION in /srv/www/htdocs/lite/page2.php on line 12"
Comment: Does page2 have `session_start();`?
Comment: `page2.php` has only 4 lines, how are you getting error on line 12? show us the full code man.
Answer: you are missing session_start(); in the page 2
Comment: conexion.php not contain session_start()
Comment: may be conexion.php contain `session_start()`
Comment: @user2956927 did you add `session_start();` at the top in page2 ?
Answer: page1 code is
<?php
session_start();
$consulta = "select t.num_ticketfrom sdg_ticket t where t.cod_tipo_incidente=2 and   t.cod_usuario='".$_SESSION['sdg_usuario']."' ";
?>

                    <?php include("page-2.php"); ?>

page2 code is
<?php
session_start();
include("conexion.php");
   $count="SELECT COUNT(*)
    FROM sdg_ticket t
    WHERE u.cod_empresa      = t.cod_empresa
    and t.cod_usuario   ='".$_SESSION['sdg_usuario']."'";

?>

Undefined variable: _SESSION


Suggestions to improve sem results

Question: I wish to check the assumption that physical and mental health for elders are affected by two main latent factors the physical burden (PHB) and the emotional burden (EMB). The measurement model is as follows:

AGE: Individual's age
CAR: Cardiac disorder
HYP: Hypertension
DIA: Diabetes
OTH: Other physical illness
OAS: Shame (Inner)
ESS: Shame (Outer)
CAQ: Cardiac anxiety
PHI: Physical health index (SF-36)
MHI: Mental health index (SF-36)
The results of the code
HEART.model <- '
# measurement model
# Physical burden factor is reflected on objective measures. Age: scale, Cardiac disorder, hypertension, diabetes, otherpd: binomal (0,1)
PHBURDEN =~ AGE + CARDIACDISORDER + HYPERTASIS + DIABETES + OTHERPHYSICALDISEASE

# Emotional burden factor is reflected on pessimism and shame (inner and outer)
EMBURDEN =~ OASTOTAL + ESSTOTAL + CAQTOTAL

# Physical health index (SF-36) is regressed on Objective and Subjective factors.
PHI2 ~ PHBURDEN + EMBURDEN

# Mental health index (SF-36) is regressed on Objective and Subjective factors.
MHI2 ~ PHBURDEN + EMBURDEN

# residual correlations
# the unexplained variance from two variables are correlated
# you can hypothesise the existence of a latent (unmeasured) variable
PHBURDEN ~~ EMBURDEN
PHBURDEN ~~ 1 * PHBURDEN
EMBURDEN ~~ 1 * EMBURDEN

#AGE ~~ 1 * AGE
OASTOTAL ~~ 1 * OASTOTAL
ESSTOTAL ~~ 1 * ESSTOTAL
CAQTOTAL ~~ 1 * CAQTOTAL
'

fit <- lavaan:::cfa(HEART.model, data = mydata, std.lv=TRUE, estimator = "MLM")
summary(fit, fit.measures = TRUE, standardized=TRUE)

is:
> fit <- lavaan:::cfa(HEART.model, data = mydata, std.lv=TRUE, estimator = "MLM")
Warning message:
In lav_data_full(data = data, group = group, group.label = group.label,  :
lavaan WARNING: some observed variances are (at least) a factor 1000 times  larger than others; use varTable(fit) to investigate
> summary(fit, fit.measures = TRUE, standardized=TRUE)
lavaan (0.5-20) converged normally after  71 iterations

                                              Used       Total
  Number of observations                           177         178

  Estimator                                         ML      Robust
  Minimum Function Test Statistic             9297.448      64.374
  Degrees of freedom                                34          34
  P-value (Chi-square)                           0.000       0.001
  Scaling correction factor                                144.428
    for the Satorra-Bentler correction

Model test baseline model:

  Minimum Function Test Statistic              499.052     494.253
  Degrees of freedom                                45          45
  P-value                                        0.000       0.000

User model versus baseline model:

  Comparative Fit Index (CFI)                    0.000       0.932
  Tucker-Lewis Index (TLI)                     -26.002       0.911

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)              -7632.485   -7632.485
  Loglikelihood unrestricted model (H1)      -2983.761   -2983.761

  Number of free parameters                         31          31
  Akaike (AIC)                               15326.970   15326.970
  Bayesian (BIC)                             15425.431   15425.431
  Sample-size adjusted Bayesian (BIC)        15327.260   15327.260

Root Mean Square Error of Approximation:

  RMSEA                                          1.241       0.071
  90 Percent Confidence Interval          1.220  1.262       0.069  0.073
  P-value RMSEA <= 0.05                          0.000       0.000

Standardized Root Mean Square Residual:

  SRMR                                           0.149       0.149

Parameter Estimates:

  Information                                 Expected
  Standard Errors                           Robust.sem

Latent Variables:
                   Estimate  Std.Err  Z-value  P(>|z|)   Std.lv  Std.all
  PHBURDEN =~
    AGE              -2.456    0.758   -3.238    0.001   -2.456   -0.337
    CARDIACDISORDE   -0.189    0.044   -4.344    0.000   -0.189   -0.395
    HYPERTASIS       -0.072    0.044   -1.659    0.097   -0.072   -0.145
    DIABETES         -0.080    0.034   -2.392    0.017   -0.080   -0.231
    OTHERPHYSICALD   -0.040    0.031   -1.277    0.202   -0.040   -0.109
  EMBURDEN =~
    OASTOTAL          7.281    0.647   11.252    0.000    7.281    0.991
    ESSTOTAL         12.939    0.885   14.613    0.000   12.939    0.997
    CAQTOTAL          0.382    0.055    6.981    0.000    0.382    0.357

Regressions:
                   Estimate  Std.Err  Z-value  P(>|z|)   Std.lv  Std.all
  PHI2 ~
    PHBURDEN          1.519    0.399    3.808    0.000    1.519    0.827
    EMBURDEN          0.037    0.331    0.112    0.911    0.037    0.020
  MHI2 ~
    PHBURDEN          0.679    0.249    2.727    0.006    0.679    0.514
    EMBURDEN         -0.263    0.181   -1.454    0.146   -0.263   -0.199

Covariances:
                   Estimate  Std.Err  Z-value  P(>|z|)   Std.lv  Std.all
  PHBURDEN ~~
    EMBURDEN         -0.446    0.139   -3.196    0.001   -0.446   -0.446
  PHI2 ~~
    MHI2              0.725    0.417    1.741    0.082    0.725    0.668

Intercepts:
                   Estimate  Std.Err  Z-value  P(>|z|)   Std.lv  Std.all
    AGE              74.192    0.549  135.053    0.000   74.192   10.180
    CARDIACDISORDE    0.356    0.036    9.862    0.000    0.356    0.743
    HYPERTASIS        0.531    0.038   14.118    0.000    0.531    1.064
    DIABETES          0.141    0.026    5.380    0.000    0.141    0.406
    OTHERPHYSICALD    0.158    0.028    5.751    0.000    0.158    0.433
    OASTOTAL         17.169    0.740   23.217    0.000   17.169    2.336
    ESSTOTAL         45.424    1.016   44.694    0.000   45.424    3.500
    CAQTOTAL          1.575    0.063   25.164    0.000    1.575    1.472
    PHI2              4.849    0.138   35.024    0.000    4.849    2.640
    MHI2              5.023    0.100   50.425    0.000    5.023    3.801
    PHBURDEN          0.000                               0.000    0.000
    EMBURDEN          0.000                               0.000    0.000

Variances:
                   Estimate  Std.Err  Z-value  P(>|z|)   Std.lv  Std.all
    PHBURDEN          1.000                               1.000    1.000
    EMBURDEN          1.000                               1.000    1.000
    OASTOTAL          1.000                               1.000    0.019
    ESSTOTAL          1.000                               1.000    0.006
    CAQTOTAL          1.000                               1.000    0.873
    AGE              47.085    5.408    8.707    0.000   47.085    0.886
    CARDIACDISORDE    0.193    0.018   10.665    0.000    0.193    0.844
    HYPERTASIS        0.244    0.007   36.664    0.000    0.244    0.979
    DIABETES          0.115    0.018    6.484    0.000    0.115    0.947
    OTHERPHYSICALD    0.132    0.019    7.110    0.000    0.132    0.988
    PHI2              1.114    0.797    1.399    0.162    1.114    0.330
    MHI2              1.057    0.245    4.312    0.000    1.057    0.606

For the above results it seems that the model is not the appropriate way to interpret the data.
Is this correct or I could make any modification in order to improve the outcome?
Thank you in advance for any suggestions.
Answer: The diagram is not a measurement model, since it appears that you are regressing the latent variables on two observed variables, PHI and MHI. This kind of recursive model looks like it might not be identified. However I don't see these regressions in the code, so I wonder if you have posted the correct diagram for the code ? The way I read your code, PHI and MHI are additional indicators for both latent variables.
I would have thought that there should be residual covariances between the indicators for each latent variable. For example, there should surely be covariance between age, cardiac disorder, hypertension and diabetes not explained by your model, and possibly between these and cardiac anxiety - as well as others (theory and clinical expertise should drive these modifications, although you could use modification indices to help).  This should improve the model fit.
Why are you fitting intercepts ? This isn't necessary in a measurement model, though it shouldn't affect model fit. Note that you can use meanstructure = TRUE in the fitting function to do this more conveniently.
Have you checked for normality of the observed variables (since you are using the MLR estimator) ?
Also, you could try standardising your data since the variance of AGE is very much larger than the variance of the others (though I doubt this will help model fit)
Edit:
Further to your comment, I would suggest adding CARDIACDISORDER~~HYPERTASIS, CARDIACDISORDER~~DIABETES, HYPERTASIS~~DIABETES as well as AGEand CAQTOTAL with those 3 variables.
Also, note that regressing an observed variable on a latent variable is equivalent to adding that variable as an indicator of the latent variable.  To see this you can run the following models with the built-in dataset HolzingerSwineford1939
# model with regressions of 2 observed variables on 2 latent variables

HS.model1 <- ' visual  =~ x1 + x2 + x3
               speed   =~ x7 + x8 + x9
               x4 ~ visual + speed
               x5 ~ visual + speed
'

# model with the same 2 observed variables as indicators
HS.model2 <- ' visual  =~ x1 + x2 + x3 + x4 + x5
               speed   =~ x4 + x5 + x7 + x8 + x9
               x4 ~~ x5
'

fit1 <- cfa(HS.model1, data = HolzingerSwineford1939, std.lv=TRUE, meanstructure=TRUE)

summary(fit1, fit.measures = TRUE)

fit2 <- cfa(HS.model2, data = HolzingerSwineford1939, std.lv=TRUE, meanstructure=TRUE)

summary(fit2, fit.measures = TRUE)

Note how the model fit statistics, and all the parameter estimates and standard errors are identical. The only difference is that in HS.model2 the regressions are now factor loadings.
Comment: Thank you very much for your answer and your effort. 1). The relations I wish to test are PHI2 ~ PHBURDEN + EMBURDEN and MHI2 ~ PHBURDEN + EMBURDEN thus I regress the two latent on the two observed. 2). Mardia's Multivariate Normality Test rejected multivariate normality and that is the reason that I applied MLR estimator. 3). I added residual covariances in the model (e.g. ESSTOTAL ~~ OASTOTAL) with no luck. 4). meanstructure = TRUE did not produce any difference. 5). I already standardised PHI and MHI in order to decrease the differences in variance but with no luck.
Comment: Sorry for not appropriate use of "measurement model" and thanks for the helpful update in your answer. I also tried the suggested residual covariances but with no luck. Further, I tried the model up to the definition of the latent variable but with no satisfactory results. I end to admit that the data are not appropriate for such an analysis. Thank you for your help.

Suggestions to improve sem results


Unitrends Work with LTO-6?

Question: Has anyone been able to get a Unitrends appliance to work with an LTO-6 drive?
I checked to compatibility matrix and while it does have a vague list of supported products is vague... and seemingly outdated...
I contacted support and they referenced the matrix.  I have heard from an SE that anything that supports MTX commands should work.
Any experience?
Comment: I can't quite understand your question. The `mtx` command is not used for communicating with tape drives. Rather it is used to communicate with the robot, that moves the tapes between drives and library cells.
Answer: That's about right. The interface to an LTO-1, LTO-4, LTO-6 doesn't really differ... The Unitrends software/appliance is likely Linux and it sees the same device regardless of LTO type. You should be fine as long as you adjust capacity to reflect the size of your LTO-6 cartridges.

Unitrends Work with LTO-6?


How to reset subset row positions to row position 0 in Python

Question: Say I have a dataframe:
DF = pd.DataFrame({'Number':np.arange(9)})

Which yields:
    Number
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8

I then want to subset it into 3 different chunks with the code:
V1 = DF.query('Number > -1 and Number < 3')
V2 = DF.query('Number > 2 and Number < 6')
V3 = DF.query('Number > 5 and Number < 9')

Giving 3 new tables of:
V1
    Number
0   0
1   1
2   2

V2
    Number
3   3
4   4
5   5

V3
    Number
6   6
7   7
8   8

How do I write the code as to reset the rows for each data frame back to position 0 so that:
V1
    Number
0   0
1   1
2   2

V2
    Number
0   3
1   4
2   5

V3 =
    Number
0   6
1   7
2   8

Thank you.
Comment: call `reset_index(drop=True)` on each slice
Comment: Excellent, that did it. Thank you.
Answer: You can try this, slicing the original dataframe into 3 new dataframes:
V1 = DF[(DF.Number > -1) & (DF.Number < 3)]
V2 = DF[(DF.Number > 2) & (DF.Number < 6)]
V3 = DF[(DF.Number > 5) & (DF.Number < 9)]

Then reset the index of the dataframes that you need:
V2 = V2.reset_index(drop=True)
V3 = V3.reset_index(drop=True)

* OP Edit *
Placing the reset code in line:
V1 = DF[(DF.Number > -1) & (DF.Number < 3)]
V2 = DF[(DF.Number > 2) & (DF.Number < 6)].reset_index(drop = True)
V3 = DF[(DF.Number > 5) & (DF.Number < 9)].reset_index(drop = True)

Comment: Yup! Thank you for this. Should have known it was easy.
Comment: Updated to accept this answer, `pd.DataFrame.query` is not the common strategy (and seems to be less efficient through testing). The above technique is regarded as the current best practice. I'll add an edit also to decrease the line count but just placing `reset_index` in line with the split.
Answer: As stated by EdChum, "call reset_index(drop=True) on each slice".
So:
DF = pd.DataFrame({'Number':np.arange(9)})

V1 = DF.query('Number > -1 and Number < 3')
V2 = DF.query('Number > 2 and Number < 6')
V3 = DF.query('Number > 5 and Number < 9')

V1.reset_index(drop=True)
V2.reset_index(drop=True)
V3.reset_index(drop=True)

Yields:
    Number
0   0
1   1
2   2

    Number
0   3
1   4
2   5

    Number
0   6
1   7
2   8


Passagem de parametros de uma lista para sub menu

Question: Eu tenho uma lista de usuários que é formada a partir de uma consulta no banco de dados. E os nomes estão em tag , que consequentemente ao ser clicado abrirá um submenu, porém quero passar os dados do usuários digitado para este sub menu. Estou utilizando o CodeIgniter.
<?php foreach($usuarios as $usuario): ?>

           <a title="Editar" href="<?php echo base_url() . 'menu/usuario/' . $usuario->id . $usuario->nome; ?>"><?php echo $usuario->nome; ?>

           <?php echo $usuario->nome; ?>

          <?php echo $usuario->id; ?>

<?php endforeach ?>

Answer: Você pode usar (por exemplo) jQuery para fazer isso:
<a title="Editar" class="campo" href="<?php echo base_url() . 'menu/usuario/' . $usuario->id . $usuario->nome; ?>" data-id="<?php echo $usuario->id; ?>"><?php echo $usuario->nome; ?>

...

//jQuery
$(document).ready(function(){
    $('.campo').click(function(){
        $('.campoid-nosubmenu').value();
        $('.camponome-nosubmenu').value();

        $('.campoid-nosubmenu').value($(this).data("id"));
        $('.camponome-nosubmenu').value($(this).value());
    });
});