text:
Q: Preserve row and column order of data frame when converting data frame to matrix I have a dataframe:
 df<- data.frame(lep= c("Tarchon", "Tarchon", "Tarchon", "Tarchon", "Tarchon",
               "Gonodonta","Gonodonta","Gonodonta", "Apatelodes"),
               plant=c("Amphimoea","Desmotrichia", "Paches", "Neoxeniades",
                       "Desmotrichia","Neoxeniades","Amphimoea", "Acribia","Sychesia"),
               freq=c(2,5,1,3,4,2,1,1,4))

That I convert to a matrix using:
mat1<-acast(df, plant~lep, value.var="freq", sum)

The output alphabetizes the names of the plant and lep however I want the order in the data frame to be maintained in the matrix.
Here is the desired output:
 mdat <- matrix(c(2,5,1,3,0,0,1,0,0,2,0,0,0,0,0,0,0,4), nrow = 6, ncol = 3, byrow = TRUE,
           dimnames = list(c("Amphimoea","Desmotrichia", "Paches", "Neoxeniades",
                             "Acribia","Sychesia"),
                           c("Tarchon","Gonodonta", "Apatelodes")))

I am not partial to using acast for this, I have just found this function helpful for the type of data frame I have. I am not able to find an argument in acast that preserves the order i the data frame.

A: Factors will are sorted by the order of their levels, which is alphabetical by default. You can specify a different order using the levels argument of factor. unique will return the unique values in the order they occur, which we can use here:
df$lep = factor(df$lep, levels = unique(df$lep))
df$plant = factor(df$plant, levels = unique(df$plant))

reshape2::acast(df, plant~lep, value.var="freq", sum)
#              Tarchon Gonodonta Apatelodes
# Amphimoea          2         1          0
# Desmotrichia       9         0          0
# Paches             1         0          0
# Neoxeniades        3         2          0
# Acribia            0         1          0
# Sychesia           0         0          4


text:
Q: Console error "Uncaught TypeError: Cannot read property 'style' of null" He puesto la opción de añadir la app PWA desde varios botones en mi web, pero la consola de google me da el error "Uncaught TypeError: Cannot read property 'style' of null".
Mi intención es que se pueda instalar la app PWA desde el menú, el header y al final en el footer. Funcionan los botones, pero el error en la consola persiste...
Paso el código que tengo en footer.php:

El código de un botón, el resto son parecidos, cambiando el contenido de class:
<a style="position: fixed;bottom:117px;left: 10px;z-index:9999;" class="add-button-footer mobile-menu añadirapp" title="pulsar para añadir a tus aplicaciones" href="#" onclick="javascript:return alert('<?php echo osc_esc_js(__('LEALES.ORG EN TUS APLICACIONES

• Pulsando Añadir en el siguiente mensaje se añadirá a tus aplicaciones, para que accedas cómodamente.

• Si no se muestra el mensaje, actualiza e inténtalo nuevamente.', 'beta')); ?>')">

Gracias por adelantadas!
Esto me dice que añada más detalles, pero no hay mucho más que añadir...Esto me dice que añada más detalles, pero no hay mucho más que añadir...Esto me dice que añada más detalles, pero no hay mucho más que añadir...Esto me dice que añada más detalles, pero no hay mucho más que añadir...

A: está solucionado, el error está en que el botón con class="add-button-footer" estaba mostrado únicamente cuando detectaba un móvil y al buscarlo en la versión de ordenador no aparecía.

redpajama_set_name: RedPajamaStackExchange


text: Q: Uploading NGS data I was wondering how you upload (or reach) sequencing data located on your computer. I'm trying to use Canu to analyse my fastq.gz files, but it seems like ubuntu can't reach them. (They are currently lokaded on my desktop.


text:
Q: Permalink coming from the Front Matter I'm working in Jekyll, and I want to customize the permalink of my posts, so I add this line in config.yml:
permalink: /:category/:title/

The category is the category of the post and title is its name as .md file. But suppose I want to get info from the from matter of the post: imagine the front matter of file.md is
---
title: my_title
lang: en
---

Now I want to get this title (my_title, not file) and this lang, so that I gent .../en/my_title.md. So in config.yml I should have
permalink: /page.lang/page.title/

Obviously that does not work because I'm mixing different languages. How should I do?

A: You cannot use variables in the front matter.
But you can put your post in an en/ folder and have a default permalink for posts like :path/:title.


text:
Q: large directory file echo Are there any tools out there that will echo one-way changes from one large directory (5+ million files) to another across a Windows network?  I also need it to be a fairly quick sync after the initial build up.  I've played around with a few tools like Microsoft SyncToy and Cobian backup but they don't seem to be built for this kinda of size.
Less than 1% of the files change every 1 hour but the problem with the design of the directory system I've inherited is that the changes can be at any position in the directory tree and there is no log of the changes so a full scan was being preformed in the past which would take about 4-5 hours.
I built a custom tool to do the sync much faster than these others but I just don't have the time to build in all the bells and whistles so I'm looking for something to do the trick in the mean time.  I do plan on changing the system but at this point I'm just looking to get them synced with less lag time.
[Update]
-My files are pretty small ranging from 10-30kb each
-The directory tree is pretty shallow.

A: When you say 'windows network', do you mean you have a Windows network with an Active directory?  One possibility that you should be looking at DFS-R.  Newer versions of DFS-R watch the filesystem and only transmit changes.  If you do have 5 million files, you may be getting close to the DFS limits though.

A: You could try one of these:
cwrsync - Rsync for Windows
Robocopy


text:
Q: Get the texts from div with same class and display them on another div What I want to achieve is if this
Display Code
 is clicked, I want to get the texts inside from each div with class 'codes' if .bet class has .open class and display them on

.

$(function() {
  $('.btn').each(function() {

    $(this).on('click', function() {

      var theClass = $('span', this).attr('class');

      $('.bet-' + theClass).each(function() {

        if ($('.bet-' + theClass + ' .bet').hasClass('open')) {

          // GET the text inside code and display them on #display-results
          // Results example =
C, D
r
        }
      });
    });
  });
});

A

Lorem Ipsum

B

Lorem Ipsum

C

Lorem Ipsum

D

Lorem Ipsum

E

Lorem Ipsum

Display Code

Display Code

A: Several issues

*

*Far too convoluted access to the elements. Rarely use for .each in jQuery

*You seem to want the sibling-div's letter of the open element

$(function() {
  $('.btn').on('click', function() {
    var theClass = '.bet-'+$('span', this).attr('class');
    $('#display-results').text(
      $('.bet.open',theClass)
        .map(function() {
          return $(this).prev(".code").text() // grab the letter from the sibling - ".code" is optional
        }).get().join(', ') // return an array and join it
    )
  });
});

A

Lorem Ipsum

B

Lorem Ipsum

C

Lorem Ipsum

D

Lorem Ipsum

E

Lorem Ipsum

Display Code

Display Code


text:
Q: How to open Open XML with Linq Hi i want to get the conection by filterin the atribute Enviroment from my xml
but im gettin some errors can anyone helpme.
here is my code :

XElement xelement = XElement.Load(xml);
var Connections = from conn in xelement.Elements("Conections")
                  where (String)conn.Element("Conection").Attribute("Enviroment") == "Test"
                  select conn;

foreach (XElement conection in Connections)
{
    MessageBox.Show(conection.Element("Conection").Value);
}

and Here is my xml

<?xml version="1.0" encoding="utf-8"?>
<Config>
  <General>
    <FormaInicial></FormaInicial>
    <DiasRecordatorioBuro></DiasRecordatorioBuro>
    <EnviarSMSDomiciliacion>rue</EnviarSMSDomiciliacion>
    <SimularDeathLock></SimularDeathLock>
    <IsProductionEnviroment></IsProductionEnviroment>
    <WaitingTimeBetweenExecutions></WaitingTimeBetweenExecutions>
    <NumberTriesBeforeRestartService></NumberTriesBeforeRestartService>
  </General>
  <Conections>
    <Conection Enviroment="Production">
      <Servidor></Servidor>
      <BaseDatos>==</BaseDatos>
      <Usuario></Usuario>
      <Password></Password>
    </Conection>
    <Conection Enviroment="Test">
      <Servidor></Servidor>
      <BaseDatos></BaseDatos>
      <Usuario></Usuario>
      <Password></Password>
    </Conection>
  </Conections>
</Config>

A: The problem you are facing (most likely) is that "Connections" is a collection of "Connection" elements, and when you are trying to filter them by attribute - you will check only the first element. You need to flatten the collection first, using SelectMany:
var connections = xelement.Elements("Conections")
            .SelectMany(c => c.Elements("Conection"))
            .Where(c => c.Attribute("Enviroment").Value == "Test");

And then in your result you will have a collection of XElements of type "Connection":
foreach (var conection in connections)
{
    Console.WriteLine(conection); //a full element with Servidor, BaseDatos, Usuario and Password
    Console.WriteLine(conection.Element("Servidor").Value);
}


text:
Q: WAMP Server phpmyadmin not working My WAMP server installation, which has been working fine up until this point, has started throwing a phpMyAdmin error.
When I go to localhost/phpmyadmin/ I get
phpMyAdmin - Error
The mysqli extension is missing. Please check your PHP configuration.

I have double and triple checked that extension=php_mysqli.dll is uncommented, and restarted all WAMP services several times after altering php.ini.
In addition, I have tried a fresh install of WAMP server, which produced the same result.

A: Turns out I had to delete the PHPRC environment variable from a previous installation in: System Properties > Advanced > Environment Variables > System Variables


text:
Q: Angularjs component state Hello I have few questions with using components in state. So i have tried doing ui-routing using templates and it works fine. but instead when i try to route it to a component, i get this error.
in my app.js
angular.module('app', ['ui.router'])
    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise('/');
        $stateProvider
            .state('home', {
                url: '/home',
                component: 'home'
        });
}]);

and in my index.html

        <link rel="stylesheet" href="Content/lib/bootstrap/bootstrap.css">
        <link rel="stylesheet" href="index.css">
        <link rel="stylesheet" href="Content/lib/bootstrap/bootstrap.css">
        <link rel="stylesheet" href="Content/app/components/redditAnalyzer.css">

        click me

and in my home.html

    "some stuffs"

and in my home.js
angular.module('app', ['chart.js'])
    .component('home', {
        templateUrl: 'Content/app/components/home.html',
        bindings: {},
        controller: ['$http',
            function ($http) {
                var vm = this;

"some more stuffs"

            }]
    });

but when i click on click me in my index.html, i get this error
Error: [$injector:unpr] http://errors.angularjs.org/1.6.6/$injector/unpr?p0=homeDirectiveProvider%20%3C-%20homeDirective
    at angular.js:88
    at angular.js:4826
    at Object.d [as get] (angular.js:4981)
    at angular.js:4831
    at Object.d [as get] (angular.js:4981)
    at getComponentBindings (angular-ui-router.js:sourcemap:8144)
    at TemplateFactory.makeComponentTemplate (angular-ui-router.js:sourcemap:8135)
    at Ng1ViewConfig.getTemplate (angular-ui-router.js:sourcemap:7938)
    at Object.<anonymous> (angular-ui-router.js:sourcemap:9719)
    at angular.js:1385 "
"

what am i doing wrong?
thank you!

A: You are registering the  module named "app" twice. A second module with same name will overwrite the first
Only use the dependency injection array on one of them when they have the same name. When there is no dependency array argument it acts as a getter not setter
Change:
// register new module with dependencies
angular.module('app', ['ui.router']).config...
// register new module with dependencies ... but will overwrite the first due to same name
angular.module('app', ['chart.js']).component...

To:
// register new module with dependencies
angular.module('app', ['ui.router','chart.js']).config...
// references an existing module to add component to
angular.module('app').component...

Also switch order of


text:
Q: mvc 4 razor uploaded image view I can upload image files using mvc 4 razor. Now I want to show/view those images. I am using images for products. So, I want to show images for particular product. How can I show images related to that product?
Here is my Model:
namespace Online_Shopping_Management.Models
{
  public class Product
  {
    [Key]
    public int ProductId { set; get; }
    public int? CategoryId { set; get; }
    public virtual Category Category { set; get; }
    public int? SubCategoryId { set; get; }
    public virtual SubCategory SubCategory { set; get; }
    public int? ModelId { set; get; }
    public virtual Model Model { set; get; }

    public IEnumerable<HttpPostedFileBase> Files { get; set; }
  }
}

Here is my controller part:
 public ActionResult Create(Product product)
    {
        foreach (var file in product.Files)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
                file.SaveAs(path);
            }
        }
        if (ModelState.IsValid)
        {
            db.Products.Add(product);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.CategoryId = new SelectList(db.Categorys, "CategoryId", "Name", product.CategoryId);
        ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", product.SubCategoryId);
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName", product.ModelId);
        return View(product);
    }

Here is my view part:
@model IEnumerable<Online_Shopping_Management.Models.Category>

@{
    ViewBag.Title = "Index";
}

Index

 Select from @Model.Count() categories:

@foreach (var categories in Model)
{

@Html.ActionLink(categories.Name, "Browse", new { categories = categories.Name })

}

A: I also face same problem some days ago. Check this link. I also answer there :
Upload,Save and Retrieve Image from database by using their Id in Code First Method


text:
Q: Detect memory leaks in dbx with new and delete operators I'm very interested in using Sun Studio to detect memory leaks in C++ applications with dbx debugger but I think this debugger only shows memory leaks produced by malloc/realloc and free; I'm not sure about this but I've tried with a C++ program and I've obtained no memory leaks. In this case, I'd try Valgrind. If I've done something wrong (high possibility) How do I debug C++ applications?
Thanks.

A: Well some points which you need to make sure,first,the application you traces do have any memory leak.if not then profiler won't show anything.If there is a leak and profiler is not capturing then need to check how you doing it. So valgrind is another best option you can try.So when you say "something wrong (high possibility) How do I debug C++ applications?" do you mean only relevant to debugging memory leak issue or in general debugging of C++ application?If its memory leak related then you can rely on valgrind,else you can also look at AIX malloc trace as well.Here is the URL for it:
http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=/com.ibm.aix.genprogc/doc/genprogc/malloc_trace_debug.htm


text:
Q: Search-wrapping: restart from pos1 when reaching EOF Given a situation like this:
 [1] abc
 [2] foo
 [3] ghi
 [4] foo
 [5] more
 ...
 EOF

When searching for "foo" and the match in line #4 is highlighted, I'd like  search to auto-wrap and restart ot the beginning of the file. (I may have been editing in #3 when I started the search and so "Find next" should take me #2, possibly with a small no-clicks-requiring message that it restarted at top).
I can't find a way to achieve this - but I also can't believe it shouldn't be possible. Surely I can't be the only searcher around ;-)  What am I missing?

A: That's already what happens, at least on a fresh installed Visual Studio Code 1.31.1. Your search does wrap-around after the end of the file.
(Actually... I came across this answer since I am searching for a way to DISABLE this feature. Sadly, after days of searching this question is all I found.)


text:
Q: What do rationals represent? While learning about the construction of number systems, I realized that I had many misunderstandings of crucial concepts which I was learning intuitively. I recently learned about the construction of the rationals as a set of equivalence classes of ordered pairs of integers (m,n), with n ≠ 0. Also I know how additon and multiplication are defined on that set. I know that the rationals exhibit good mathematical properties but what I wonder is what is their interpertation? What do they represent? For example what a half represents? Should I be content with the explanation that is given to 5 year olds about dividing pizza in half and taking one piece of them? Is there a defined real world meaning for rationals?

A: The rigorous mathematical definition of rational numbers is that they are equivalence classes of ordered pairs of integers $(m,n)$ with $n\neq 0$ for the equivalence relation $$(m,n)\equiv (o,p)\iff mp = no.$$
I don't really understand how you first wrote the rigorous mathematical definition of $\mathbb Q$, then asked is there a rigorous mathematical definition of rational numbers...
Another way you can look at the rational numbers is that they are, given the set of natural numbers and the operations of addition and multiplication, the smallest set containing $\mathbb N$ and satisfying all the axioms for a field (they are the "smallest field containing the natural numbers").

As for the real world meaning of rationals... In a strict sense of the word, no mathematical concept has a direct "meaning" in nature, but I think that generally, the natural use of fractions comes from the fact that nature itself contains them. Your example with a pie is a completely legitimate way of justifying why rationals are used in real life: it is because there exists such a thing as "half a pie."

A: I differ slightly from the other comments and answers in that I don't think the real-world meaning you gave is different from the formal meaning. Maybe we can break it into steps. What I hope is that each step can be deduced from the next.

*

*Two-thirds of a pizza is what you get when you divide a pizza into three equal pieces, then take two of them.

*Two-thirds of a pizza has the property that, given three of them, you have two pizzas altogether. This property characterizes "two-thirds of a pizza." That is, if you have some percentage of a pizza, such that when you take three, you can make exactly two whole pizzas, then you have two-thirds of a pizza.

*"Two-thirds of a pizza" is the unique solution to the equation 3x = 2 when x is interpreted as "numbers of pizzas."

*Whatever formal model (I am using the word "model" in its everyday sense, not its mathematical sense) you have in mind for the integers, you can extend it to a model in which all equations of the form ax = b with $a \neq 0$ have solutions by using the "equivalence class trick" that you mentioned. In that larger model, the equation $3x = 2$ has a unique solution which we call 2/3.
In summary, I wouldn't take (the equivalence class of the pair (2, 3)) to be very different from (the unique solution to $3x = 2$) which is directly linked to pizza-land when $x$ is interpreted as pizza.


text:
Q: Fastest way to clamp a real (fixed/floating point) value? Is there a more efficient way to clamp real numbers than using if statements or ternary operators?
I want to do this both for doubles and for a 32-bit fixpoint implementation (16.16). I'm not asking for code that can handle both cases; they will be handled in separate functions.
Obviously, I can do something like:
double clampedA;
double a = calculate();
clampedA = a > MY_MAX ? MY_MAX : a;
clampedA = a < MY_MIN ? MY_MIN : a;

or
double a = calculate();
double clampedA = a;
if(clampedA > MY_MAX)
    clampedA = MY_MAX;
else if(clampedA < MY_MIN)
    clampedA = MY_MIN;

The fixpoint version would use functions/macros for comparisons.
This is done in a performance-critical part of the code, so I'm looking for an as efficient way to do it as possible (which I suspect would involve bit-manipulation)
EDIT: It has to be standard/portable C, platform-specific functionality is not of any interest here. Also, MY_MIN and MY_MAX are the same type as the value I want clamped (doubles in the examples above).

A: For the 16.16 representation, the simple ternary is unlikely to be bettered speed-wise.
And for doubles, because you need it standard/portable C, bit-fiddling of any kind will end badly.
Even if a bit-fiddle was possible (which I doubt), you'd be relying on the binary representation of doubles. THIS (and their size) IS IMPLEMENTATION-DEPENDENT.
Possibly you could "guess" this using sizeof(double) and then comparing the layout of various double values against their common binary representations, but I think you're on a hiding to nothing.
The best rule is TELL THE COMPILER WHAT YOU WANT (ie ternary), and let it optimise for you.
EDIT: Humble pie time. I just tested quinmars idea (below), and it works - if you have IEEE-754 floats. This gave a speedup of about 20% on the code below. IObviously non-portable, but I think there may be a standardised way of asking your compiler if it uses IEEE754 float formats with a #IF...?
  double FMIN = 3.13;
  double FMAX = 300.44;

  double FVAL[10] = {-100, 0.23, 1.24, 3.00, 3.5, 30.5, 50 ,100.22 ,200.22, 30000};
  uint64  Lfmin = *(uint64 *)&FMIN;
  uint64  Lfmax = *(uint64 *)&FMAX;

    DWORD start = GetTickCount();

    for (int j=0; j<10000000; ++j)
    {
        uint64 * pfvalue = (uint64 *)&FVAL[0];
        for (int i=0; i<10; ++i)
            *pfvalue++ = (*pfvalue < Lfmin) ? Lfmin : (*pfvalue > Lfmax) ? Lfmax : *pfvalue;
    }

    volatile DWORD hacktime = GetTickCount() - start;

    for (int j=0; j<10000000; ++j)
    {
        double * pfvalue = &FVAL[0];
        for (int i=0; i<10; ++i)
            *pfvalue++ = (*pfvalue < FMIN) ? FMIN : (*pfvalue > FMAX) ? FMAX : *pfvalue;
    }

    volatile DWORD normaltime = GetTickCount() - (start + hacktime);

A: The bits of IEEE 754 floating point are ordered in a way that if you compare the bits interpreted as an integer you get the same results as if you would compare them as floats directly. So if you find or know a way to clamp integers you can use it for (IEEE 754) floats as well. Sorry, I don't know a faster way.
If you have the floats stored in an arrays you can consider to use some CPU extensions like SSE3, as rkj said. You can take a look at liboil it does all the dirty work for you. Keeps your program portable and uses faster cpu instructions if possible. (I'm not sure tho how OS/compiler-independent liboil is).

A: Rather than testing and branching, I normally use this format for clamping:
clampedA = fmin(fmax(a,MY_MIN),MY_MAX);

Although I have never done any performance analysis on the compiled code.

A: Both GCC and clang generate beautiful assembly for the following simple, straightforward, portable code:
double clamp(double d, double min, double max) {
  const double t = d < min ? min : d;
  return t > max ? max : t;
}

> gcc -O3 -march=native -Wall -Wextra -Wc++-compat -S -fverbose-asm clamp_ternary_operator.c
GCC-generated assembly:
maxsd   %xmm0, %xmm1    # d, min
movapd  %xmm2, %xmm0    # max, max
minsd   %xmm1, %xmm0    # min, max
ret

> clang -O3 -march=native -Wall -Wextra -Wc++-compat -S -fverbose-asm clamp_ternary_operator.c
Clang-generated assembly:
maxsd   %xmm0, %xmm1
minsd   %xmm1, %xmm2
movaps  %xmm2, %xmm0
ret

Three instructions (not counting the ret), no branches.  Excellent.
This was tested with GCC 4.7 and clang 3.2 on Ubuntu 13.04 with a Core i3 M 350.
On a side note, the straightforward C++ code calling std::min and std::max generated the same assembly.
This is for doubles. And for int, both GCC and clang generate assembly with five instructions (not counting the ret) and no branches. Also excellent.
I don't currently use fixed-point, so I will not give an opinion on fixed-point.

A: Old question, but I was working on this problem today (with doubles/floats).
The best approach is to use SSE MINSS/MAXSS for floats and SSE2 MINSD/MAXSD for doubles.  These are branchless and take one clock cycle each, and are easy to use thanks to compiler intrinsics.  They confer more than an order of magnitude increase in performance compared with clamping with std::min/max.
You may find that surprising.  I certainly did!  Unfortunately VC++ 2010 uses simple comparisons for std::min/max even when /arch:SSE2 and /FP:fast are enabled.  I can't speak for other compilers.
Here's the necessary code to do this in VC++:
#include <mmintrin.h>

float minss ( float a, float b )
{
    // Branchless SSE min.
    _mm_store_ss( &a, _mm_min_ss(_mm_set_ss(a),_mm_set_ss(b)) );
    return a;
}

float maxss ( float a, float b )
{
    // Branchless SSE max.
    _mm_store_ss( &a, _mm_max_ss(_mm_set_ss(a),_mm_set_ss(b)) );
    return a;
}

float clamp ( float val, float minval, float maxval )
{
    // Branchless SSE clamp.
    // return minss( maxss(val,minval), maxval );

    _mm_store_ss( &val, _mm_min_ss( _mm_max_ss(_mm_set_ss(val),_mm_set_ss(minval)), _mm_set_ss(maxval) ) );
    return val;
}

The double precision code is the same except with xxx_sd instead.
Edit: Initially I wrote the clamp function as commented.  But looking at the assembler output I noticed that the VC++ compiler wasn't smart enough to cull the redundant move.  One less instruction. :)

A: Realistically, no decent compiler will make a difference between an if() statement and a ?: expression. The code is simple enough that they'll be able to spot the possible paths. That said, your two examples are not identical. The equivalent code using ?: would be
a = (a > MAX) ? MAX : ((a < MIN) ? MIN : a);

as that avoid the A < MIN test when a > MAX. Now that could make a difference, as the compiler otherwise would have to spot the relation between the two tests.
If clamping is rare, you can test the need to clamp with a single test:
if (abs(a - (MAX+MIN)/2) > ((MAX-MIN)/2)) ...

E.g. with MIN=6 and MAX=10, this will first shift a down by 8, then check if it lies between -2 and +2. Whether this saves anything depends a lot on the relative cost of branching.

A: Here's a possibly faster implementation similar to @Roddy's answer:
typedef int64_t i_t;
typedef double  f_t;

static inline
i_t i_tmin(i_t x, i_t y) {
  return (y + ((x - y) & -(x < y))); // min(x, y)
}

static inline
i_t i_tmax(i_t x, i_t y) {
  return (x - ((x - y) & -(x < y))); // max(x, y)
}

f_t clip_f_t(f_t f, f_t fmin, f_t fmax)
{
#ifndef TERNARY
  assert(sizeof(i_t) == sizeof(f_t));
  //assert(not (fmin < 0 and (f < 0 or is_negative_zero(f))));
  //XXX assume IEEE-754 compliant system (lexicographically ordered floats)
  //XXX break strict-aliasing rules
  const i_t imin = *(i_t*)&fmin;
  const i_t imax = *(i_t*)&fmax;
  const i_t i    = *(i_t*)&f;
  const i_t iclipped = i_tmin(imax, i_tmax(i, imin));

#ifndef INT_TERNARY
  return *(f_t *)&iclipped;
#else /* INT_TERNARY */
  return i < imin ? fmin : (i > imax ? fmax : f);
#endif /* INT_TERNARY */

#else /* TERNARY */
  return fmin > f ? fmin : (fmax < f ? fmax : f);
#endif /* TERNARY */
}

See Compute the minimum (min) or maximum (max) of two integers without branching and Comparing floating point numbers

The IEEE float and double formats were
  designed so that the numbers are
  "lexicographically ordered", which –
  in the words of IEEE architect William
  Kahan means "if two floating-point
  numbers in the same format are ordered
  ( say x < y ), then they are ordered
  the same way when their bits are
  reinterpreted as Sign-Magnitude
  integers."

A test program:
/** gcc -std=c99 -fno-strict-aliasing -O2 -lm -Wall *.c -o clip_double && clip_double */
#include <assert.h>
#include <iso646.h>  // not, and
#include <math.h>    // isnan()
#include <stdbool.h> // bool
#include <stdint.h>  // int64_t
#include <stdio.h>

static
bool is_negative_zero(f_t x)
{
  return x == 0 and 1/x < 0;
}

static inline
f_t range(f_t low, f_t f, f_t hi)
{
  return fmax(low, fmin(f, hi));
}

static const f_t END = 0./0.;

#define TOSTR(f, fmin, fmax, ff) ((f) == (fmin) ? "min" :       \
                  ((f) == (fmax) ? "max" :      \
                   (is_negative_zero(ff) ? "-0.":   \
                    ((f) == (ff) ? "f" : #f))))

static int test(f_t p[], f_t fmin, f_t fmax, f_t (*fun)(f_t, f_t, f_t))
{
  assert(isnan(END));
  int failed_count = 0;
  for ( ; ; ++p) {
    const f_t clipped  = fun(*p, fmin, fmax), expected = range(fmin, *p, fmax);
    if(clipped != expected and not (isnan(clipped) and isnan(expected))) {
      failed_count++;
      fprintf(stderr, "error: got: %s, expected: %s\t(min=%g, max=%g, f=%g)\n",
          TOSTR(clipped,  fmin, fmax, *p),
          TOSTR(expected, fmin, fmax, *p), fmin, fmax, *p);
    }
    if (isnan(*p))
      break;
  }
  return failed_count;
}

int main(void)
{
  int failed_count = 0;
  f_t arr[] = { -0., -1./0., 0., 1./0., 1., -1., 2,
        2.1, -2.1, -0.1, END};
  f_t minmax[][2] = { -1, 1,  // min, max
               0, 2, };

  for (int i = 0; i < (sizeof(minmax) / sizeof(*minmax)); ++i)
    failed_count += test(arr, minmax[i][0], minmax[i][1], clip_f_t);

  return failed_count & 0xFF;
}

In console:
$ gcc -std=c99 -fno-strict-aliasing -O2 -lm *.c -o clip_double && ./clip_double

It prints:
error: got: min, expected: -0.  (min=-1, max=1, f=0)
error: got: f, expected: min    (min=-1, max=1, f=-1.#INF)
error: got: f, expected: min    (min=-1, max=1, f=-2.1)
error: got: min, expected: f    (min=-1, max=1, f=-0.1)

A: If your processor has a fast instruction for absolute value (as the x86 does), you can do a branchless min and max which will be faster than an if statement or ternary operation.
min(a,b) = (a + b - abs(a-b)) / 2
max(a,b) = (a + b + abs(a-b)) / 2

If one of the terms is zero (as is often the case when you're clamping) the code simplifies a bit further:
max(a,0) = (a + abs(a)) / 2

When you're combining both operations you can replace the two /2 into a single /4 or *0.25 to save a step.
The following code is over 3x faster than ternary on my Athlon II X2, when using the optimization for FMIN=0.
double clamp(double value)
{
    double temp = value + FMAX - abs(value-FMAX);
#if FMIN == 0
    return (temp + abs(temp)) * 0.25;
#else
    return (temp + (2.0*FMIN) + abs(temp-(2.0*FMIN))) * 0.25;
#endif
}

A: Ternary operator is really the way to go, because most compilers are able to compile them into a native hardware operation that uses a conditional move instead of a branch (and thus avoids the mispredict penalty and pipeline bubbles and so on). Bit-manipulation is likely to cause a load-hit-store.
In particular, PPC and x86 with SSE2 have a hardware op that could be expressed as an intrinsic something like this:
double fsel( double a, double b, double c ) {
  return a >= 0 ? b : c;
}

The advantage is that it does this inside the pipeline, without causing a branch. In fact, if your compiler uses the intrinsic, you can use it to implement your clamp directly:
inline double clamp ( double a, double min, double max )
{
   a = fsel( a - min , a, min );
   return fsel( a - max, max, a );
}

I strongly suggest you avoid bit-manipulation of doubles using integer operations. On most modern CPUs there is no direct means of moving data between double and int registers other than by taking a round trip to the dcache. This will cause a data hazard called a load-hit-store which basically empties out the CPU pipeline until the memory write has completed (usually around 40 cycles or so).
The exception to this is if the double values are already in memory and not in a register: in that case there is no danger of a load-hit-store. However your example indicates you've just calculated the double and returned it from a function which means it's likely to still be in XMM1.

A: I tried the SSE approach to this myself, and the assembly output looked quite a bit cleaner, so I was encouraged at first, but after timing it thousands of times, it was actually quite a bit slower. It does indeed look like the VC++ compiler isn't smart enough to know what you're really intending, and it appears to move things back and forth between the XMM registers and memory when it shouldn't. That said, I don't know why the compiler isn't smart enough to use the SSE min/max instructions on the ternary operator when it seems to use SSE instructions for all floating point calculations anyway. On the other hand, if you're compiling for PowerPC, you can use the fsel intrinsic on the FP registers, and it's way faster.

A: As pointed out above, fmin/fmax functions work well (in gcc, with -ffast-math). Although gfortran has patterns to use IA instructions corresponding to max/min, g++ does not. In icc one must use instead std::min/max, because icc doesn't allow short-cutting the specification of how fmin/fmax work with non-finite operands.

A: My 2 cents in C++. Probably not any different than use ternary operators and hopefully no branching code is generated
template <typename T>
inline T clamp(T val, T lo, T hi) {
    return std::max(lo, std::min(hi, val));
}

A: If I understand properly, you want to limit a value "a" to a range between MY_MIN and MY_MAX.  The type of "a" is a double.  You did not specify the type of MY_MIN or MY_MAX.
The simple expression:
clampedA = (a > MY_MAX)? MY_MAX : (a < MY_MIN)? MY_MIN : a;

should do the trick.
I think there may be a small optimization to be made if MY_MAX  and MY_MIN happen to be integers:
int b = (int)a;
clampedA = (b > MY_MAX)? (double)MY_MAX : (b < MY_MIN)? (double)MY_MIN : a;

By changing to integer comparisons, it is possible you might get a slight speed advantage.

A: If you want to use fast absolute value instructions, check out this snipped of code I found in minicomputer, which clamps a float to the range [0,1]
clamped = 0.5*(fabs(x)-fabs(x-1.0f) + 1.0f);

(I simplified the code a bit).  We can think about it as taking two values, one reflected to be >0
fabs(x)

and the other reflected about 1.0 to be <1.0
1.0-fabs(x-1.0)

And we take the average of them.  If it is in range, then both values will be the same as x, so their average will again be x.  If it is out of range, then one of the values will be x, and the other will be x flipped over the "boundary" point, so their average will be precisely the boundary point.


text:
Q: Restful webservice call improper response I have written an Restful GET API call to get 10 records based on some condition. In that I am returning all records as a string, while executing that method from Workbench I am not getting proper format. But in debug logs I am getting proper JSON response. Did I missed something?
Method:
@RestResource(urlMapping='/meetings/*')
global with sharing class RestWebshowMappingscls {
 @HttpGet
    global static string getMeetInviteDetails(){
        List<Meeting__c> metLst=new List<Meeting__c>();
        List<Mainwrapper> mainWrapLst;
        string finalqryvalue;
        metLst=[select id,name,Event__r.name,Meeting_ID__c,Meeting_with__c,Meeting_UUID__c,(select Meeting__r.name,Attendee__r.name,Unique_ID__c,Attendee_Status__c,Attendee_Name__c from Invites__r) from Meeting__c where Meeting_ID__c!=null limit 10];
        system.debug('metLst value' +metLst.size());
        if(metLst.size()>0 && metLst!=null){
          try{
              for(Meeting__c met:metLst){
                mainWrapLst=new List<Mainwrapper>();
                Mainwrapper mainWrap=new Mainwrapper();

                List<meeting> meetingWrapLst=new List<meeting>();
                meeting meetingWrap=new Meeting();
                meetingWrap.mid=met.Meeting_ID__c;
                meetingWrap.meetingwith=met.Meeting_with__c;
                meetingWrap.eventName=met.Event__c;
                meetingWrap.meetinguuid=met.Meeting_UUID__c;
                meetingWrapLst.add(meetingWrap);

                List<invite> inwrap;
                List<invites__c> invlst;
                for(Invites__c inv : met.invites__r){
                    inwrap=new List<invite>();
                    invite invt=new invite();
                    invt.invitestatus=inv.Attendee_Status__c;
                    invt.inviteUniqueid=inv.Unique_ID__c;
                    inwrap.add(invt) ;
                }
                meetingWrap.invites=inwrap;
                mainWrap.data=meetingWrapLst;
                mainWrap.statusCode=200;
                mainWrap.status='Success';
                mainWrap.message='Details of Meetings';
                mainWrapLst.add(mainwrap);

                RestContext.response.responseBody = Blob.valueOf(JSON.serialize(mainWrapLst));
                finalqryvalue = JSON.serialize(mainWrapLst);
                system.debug('finalqryvalue @@' +finalqryvalue);

            }
           } catch(exception ex){
               System.debug('exception type' +ex.getTypeName());
             }
        }
        return finalqryvalue;
    }

//Wrapper to diplay values///
    global class Mainwrapper{
        public List<meeting> data;
        public integer statusCode;
        public string status;
        public string message;
    }
    global class meeting{
        public string meetingwith;
        public string eventName;
        public string mid;
        public string meetinguuid;
        public List<invite> invites;
    }
    global class invite{
        public string invitestatus;
        public string inviteUniqueid;
    }

}

Workbench screenshot:

A: Here is the issue:
RestContext.response.responseBody = Blob.valueOf(JSON.serialize(mainWrapLst));
finalqryvalue = JSON.serialize(mainWrapLst);
system.debug('finalqryvalue @@' +finalqryvalue);

What you're debugging is in fact JSON. But your service is returning (i.e., its actual return value) a string, which is escaped automatically by Salesforce to produce JSON. Your web service return value is converted to JSON by Salesforce automatically; when this happens, your string - which is already JSON - gets escaped, and Workbench shows you that escaped string.
You don't need to set the response body and also return a value, and you actually don't need to do any explicit serialization at all. Just return your serializable structure:
global static List<Mainwrapper> getMeetInviteDetails() {
    // ...
    return mainWrapLst;
}

Salesforce will take care of marshalling it into JSON for you.


text:
Q: Session variables not working in PHP after UBUNTU upgrade In error log, i get error on line 7 and 109 of header.php which says "on line 7 Undefined index: id in /var/www/ttm.com/public_html/include/header.php" and "Undefined index: fullname in /var/www/ttm.com/public_html/include/header.php on line 109". This same code was working fine before the upgrade.
Here is my code of header.php
<?php
    include('data/db.php');
    $base_url = "http://ttm.xceedance.com/";
    if(!isset($_SESSION['login'])){
        header("Location:login.php");
    }
    $user_id=$_SESSION['id'];
    $sql_works = "select  *  from items where work_status!='Start' AND account_id='$user_id'";
    $result_works = mysql_query($sql_works);
    $acco_data=mysql_fetch_array($result_works);
    if(!empty($acco_data))
    {
        $account_work_status=$acco_data['work_status'];
    }
    else
    {
        $sql_mett = "select  *  from meeting where work_status!='Start' AND account_id='$user_id'";
        $result_mett = mysql_query($sql_mett);
        $acco_mett=mysql_fetch_array($result_mett);
        if(empty($acco_mett))
       {
         $sql_client = "select  *  from client_email where work_status!='Start' AND account_id='$user_id'";
         $result_client = mysql_query($sql_client);
         $acco_client=mysql_fetch_array($result_client);
         if(empty($acco_client))
         {
             $sql_break = "select  *  from break where work_status!='Start' AND account_id='$user_id'";
             $result_break = mysql_query($sql_break);
             $acco_break=mysql_fetch_array($result_break);
             if(!empty($acco_break))
             {
                $account_work_status=$acco_break['work_status'];
             }  else {   $account_work_status='Start'; }
         }
         else
           {

         $account_work_status=$acco_client['work_status'];
           }
       }
       else
       {

        $account_work_status=$acco_mett['work_status'];
       }
    }
    //print_r($account_work_status);die;

?>

<!DOCTYPE html>

<meta http-equiv="refresh" content="120" >
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Xceedance Exposure Management Time Tracker</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/sb-admin.css" rel="stylesheet">
    <link href="css/mystyle.css" rel="stylesheet">
    <link href="css/jquery-ui.css" rel="stylesheet">

    <link href="css/plugins/morris.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    Toggle navigation

                </button>

<?php if($account_work_status=='Start') { ?><?php }  else { ?><?php }  ?>

                <?php if($account_work_status=='Start') { ?><?php }  else { ?><?php }  ?>Exposure Management Time Tracker

                     Welcome <?php echo $_SESSION['fullname'] ?>

                            Settings

                           Change Password

                           <?php if($account_work_status=='Start') { ?> <?php }  else { ?><?php }  ?> Log Out


text:
Q: What situation uses this syntax: thing.Foo().Bar(this) Can someone show me an example of where this syntax would show up in code?
thing.Foo().Bar(this)

From the looks of it, I see an object that calls a function that calls another function?
I obviously don't know how it works. If you have the slightest idea, I would appreciate a suggestion. Thanks!

A: This is one of many possible scenarios:
struct somethingelse
{
    void SomeOtherMethod()
    {
        thing.Foo().Bar(this);
    }
};

struct foo
{
    void Bar(somethingelse *pSomethingElse);
};

struct thing
{
    foo &Foo() {return m_foo;}

    foo m_foo;
};

What makes this a bit unusual is that the naming convention for the class and method naming is the opposite of the de-facto one in which classes are capitalised and methods camel-cased.

A: This code could be found in any non-static member function of a class. The Foo() function of thing returns an object of a class with a member function Bar that takes a pointer to the current object (this) as argument.


text:
Q: Need help updating PHP 5.2 to 5.3 (on Debian Lenny) I need to update 5.2 to 5.3 in one of our servers urgently. My unix skills are limited so please be as specific as possible.
Is there any way to do this easily with apt-get upgrade ?

A: There are instructions available that might work at http://www.debiantutorials.com/how-to-install-upgrade-to-php-5-3-on-debian-lenny/
But you need to first have working backups in place. Best to test this on another install somewhere else to make sure there aren't any "gotchas", and if this is a production server and something goes wrong,...
Your support documentation is up to date, yes?

A: PHP 5.3 Packages can be sourced from:

*

*for Debian 6.0 Squeeze : on the main Dotdeb repository

*for Debian 5.0 "Lenny" : on php53.dotdeb.org

Follow the instructions using aptitude or plain old apt


text:
Q: Converting Native Query Result To POJO : Error on boolean field I had a use case where I had to run a native query. I was able to run it successfully but when I am trying to convert the resultset to dto I am getting errors on boolean fields.
Since I am using MySQL, the boolean value column is bit(1) in the database.
Here is the code for the wrapper
public interface DownloadDetails {
   Boolean getBooleanField();  //Doesnot work but why?
   Integer getBooleanFieldAsInt(); //Works but needs explicit check to boolean in code
   Long getLongField();
}

Native Query :
@Query(nativeQuery = true, value = CUSTOM_QUERY)
List<DownloadDetails> getDownloadDetails();

Now when I try to do something like downloadDetails.getBooleanField() it does not work and gives  an error as

Projection type must be an interface!

Anything which I am missing here?

A: As a workaround I did something like this
public interface DownloadDetails {
   String getBooleanFieldAsString();
   Long getLongField();

   default Boolean getBooleanFieldAsBoolean(){
      return BooleanUtils.toBoolean(getBooleanFieldAsString());
   }

}
This is the best possible and the neatest way workaround I could think of. Also if you want to use this interface for directly sending the response back(which you might consider avoiding), use @JsonIgnore and @JsonProperty("customName")

A: Not sure why you need a native query exactly, but maybe you can do with using Blaze-Persistence Entity Views.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
@EntityView(DownloadEntity.class)
public interface DownloadDetails {
    @IdMapping
    Long getId();
    @Mapping("CAST_BOOLEAN(booleanStringAttribute)")
    String getBoolean();
    Long getLongField();
}

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
DownloadDetails a = entityViewManager.find(entityManager, DownloadDetails.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
Page<DownloadDetails> findAll(Pageable pageable);

The best part is, it will only fetch the state that is actually necessary!


text:
Q: Access Files for Custodian Account from Admin Account OneDrive SDK CSharp, is there a way to automate this? I am coding against the OneDrive C# SDK. I have set up a OneDrive for business where I have multiple global admins and a collection of users. I already have proofed out the ability for an admin to login and access a custodian (non-admin) accounts OneDrive files and folder.
The current workflow is as so:

*

*Admin signs into https://portal.office.com/adminportal/home#/homepage

*Navigate to "Users" on left navigation

*Expand "Active Users"

*Click a Custodian account

*Expand OneDrive Settings

*Click "Access Files" to grant permissions to manage this user's OneDrive
This is the only way currently that I am able to access a Custodian user's OneDrive files and folder from an Admin account.
My question is if there is a way to automate this process instead of having to have the Admin follow the workflow above?


text:
Q: How to initially center an image inside inline-block container when using panzoom? I want to set the initial position of the image as centered how can I do that? I don't want to do CSS centering as it will be applied always only at the first time I want the position to be set as centered of the container.
I need to keep the style #scene {display: inline-block;} or else the panning inside bounds breaks.
How can I center this image at load initially

    const element = document.querySelector('#scene');
    let panZoomController = panzoom(element, {
      bounds: true,
      boundsPadding: 0.1
    });
.image-outer-wrapper {
  border: 3px solid red;
  overflow: hidden;
  height: 500px;
}

img {
  cursor: move;
  display: flex;
  justify-content: center;
}

#scene {
  display: inline-block;
}

A: Found out a move to function Thanks to @Temani Afif for help

let element = document.querySelector('#scene');
var s = (document.querySelector('.image-outer-wrapper').offsetWidth /2) - (element.offsetWidth / 2);

let panZoomController = panzoom(element, {
  bounds: true,
  boundsPadding: 0.1
});

panZoomController.moveTo(s, 0);
.image-outer-wrapper {
  border: 3px solid red;
  overflow: hidden;
  height: 300px;
}

img {
  cursor: move;
}

#scene {
  display: inline-block;
}

A: You can use zoomAbs to set the initial position. The scale need to be different from 1 (not sure why) so I made it 0.9

let element = document.querySelector('#scene');
var s = (document.querySelector('.image-outer-wrapper').offsetWidth - element.offsetWidth) ;

let panZoomController = panzoom(element, {
  bounds: true,
  boundsPadding: 0.1
}).zoomAbs(
  6*s, // initial x position
  0, // initial y position
  0.9 // initial zoom
);
.image-outer-wrapper {
  border: 3px solid red;
  overflow: hidden;
  height: 300px;
}

img {
  cursor: move;
}

#scene {
  display: inline-block;
}

A: Here:

A: Try this

A: This will center the img inside its container :
#scene {
    display: flex;
    justify-content: center;
}


text:
Q: How to get the current date in DataTable.Compute I am trying to compute the string expression by DataTable.Compute.
A simple string like below is working:
        static void Compare()
        {
            var logicalExpression = "'2022-09-14' <= '2029-12-31'";
            DataTable dt = new DataTable();
            var result = (bool)dt.Compute(logicalExpression, "");
        }

But, the date 2022-09-14 is dynamic, it should be the date for now.
I have tried to replace '2022-09-14' with Now(),GETDATE(). None of them work.
Is there any function to get current date time in Compute?

A: You can do this like this:
var logicalExpression = "'" + DateTime.Now.ToShortDateString() + "' <= '2029-12-31'";

you can also specify in what format you want the date, see this post for an example.

A: var logicalExpression = $"#{DateTime.Now:MM/dd/yyyy}# <= #12/31/2029#";

This is the proper way to represent dates in this context. See here for more information.


text:
Q: Dynamic image width in ul/li I have code that sets li width dynamically on window resize. It divides 100% with the current number of li tags.
Code looks like this:
$(document).ready(function() {
    var num = $('li').length;
    var width_li = 100 / num;
    $('li').css('width', width_li + '%');
});

Test it here:
http://jsfiddle.net/jbew7/
How can I make it resize images that's inside the li tags to?

A: You can use CSS:
li img {
   width: 100%;
   height: auto;
}

A: li img {
   width: 100%;
   height: 100%;
}

100% percent will make sure that image width/height remains same as the width/height of li..


text:
Q: How to tell if Fisher information is well defined? I'm asked to determine whether the Fisher information is well defined for a number of distributions. I think I understand how to actually compute the fisher information, at least for the standard distributions, but I'm not sure exactly what "well defined" means or how to test for it?

A: It only means that it is a well-defined function:
https://en.wikipedia.org/wiki/Well-defined
There are cases where the Fisher information does not exist (or is $\infty$) at some points.


text:
Q: Extracting data from Plot I have a parametric matrix. I can solve the eigenvalue problem as a function of the parameter used in the matrix. I need to extract the solutions as a function of the parameter. Let me give an example: Suppose I have a parametric matrix as
m[c_] := {{1, -c + 1, 2}, {c, 5, c}, {2, 5, c}};

The eigenvalues can be plotted as a function of the parameter using
Plot[Eigenvalues[m[c]], {c, 0, 1}]

which results

Now I want to extract data of these plots. How can I do that functionally using Mathematica's commands?

A:
I want to extract data of these plots

There are many ways to extract data from plots (if you search you'll find good examples).
One method I like is EvaluationMonitor since one can then control what data to extract, and how to format it, even thought it might not be the most efficient?
ClearAll[m, c, x]
m[c_] := {{1, -c + 1, 2}, {c, 5, c}, {2, 5, c}};
data = Reap@
   Plot[Eigenvalues[m[c]], {c, 0, 1},
     EvaluationMonitor :> Sow[{c, Eigenvalues[m[c]]}]];
data = data[[2, 1]]

And now data contains what you want
 {{2.04082*10^-8, {5., 2.56155, -1.56155}},
  {0.0196287, {5.04462, 2.52608, -1.55108}},
  {0.0409084, {5.09137, 2.48926, -1.53972}},
  ....

The first value in each row is c and the second list in each row are the eigenvalues for that c.
For example
 Eigenvalues[m[0.0196286612015304`]]

Gives
 {5.04462, 2.52608, -1.55108}

Which you see is the second row in the output. etc..
The above is basically the same as doing
 Table[{c, Eigenvalues[m[c]]},{c,0,...}]

The only difference is that you are using Plot choice of the sample values of c it used to make the plot, which one does not know before hand.
Update

It is not possible to plot data of each line

All the data is there. One way to plot it from the extracted data is
p1 = ListPlot[Transpose[{data[[All, 1]], data[[All, 2, 1]]}], PlotStyle -> Red];
p2 = ListPlot[Transpose[{data[[All, 1]], data[[All, 2, 2]]}], PlotStyle -> Blue];
p3 = ListPlot[Transpose[{data[[All, 1]], data[[All, 2, 3]]}], PlotStyle -> Black];
Show[{p1, p2, p3}, AxesOrigin -> {0, 0}, PlotRange -> All]

There is probably a better way to plot the data back, but this becomes a question on plotting. The point is, all the data is there.

A: Perhaps you just want to create functions for each eigenvalue:
{eig1[c_], eig2[c_], eig3[c_]} = Eigenvalues[m[c]];

Plot:
Plot[{eig1[c], eig2[c], eig3[c]}, {c, 0, 1}]

The value of the second eigenvalue at $c=2$:
eig2[2]

4 - Sqrt[11]

A: Following this answer by @Jens:
plot=Plot[Eigenvalues[m[c]], {c, 0, 1}];
points=Cases[Normal@plot,Line[x_]:>x,\[Infinity]];
ListPlot[points]


text:
Q: Re-position MyLocation button inside Google Map fragment In the Google Maps API for Android there is button located at the top-right corner, served to locate you inside the map.
I would like to know if it is possible to relocate this icon that is by default in the API of Google Maps for Android, because at the top I plan to add an EditText as if it were floating.

A: I can suggest 2 options.
However, I strongly advise you to use the first one - much more classic and simple:

*

*Use Map Padding (recommended)

You can re-position any of the GoogleMap Controls by setting the Padding from the corners. In your case, I would set some padding from the top:
googleMap.setPadding(0, numTop, 0, 0); //numTop = padding of your choice
It would also change the center position of the Map Camera accordingly, which is great for that kind of use case (adding a title / other floating controls).

*Disable the button and create one of your own (less recommended)

Disabling it will be easy:
googleMap.getUiSettings().setMyLocationButtonEnabled(false)

However, creating a new one would be trickier - mostly because it is harder to set a fully-functional one.

*

*I would Create a FloatingActionButton that looks like the one on the Google Maps application (example).

*

*You can get the Icon from here (called "My Location")

*Color the Fab in Material Grey 300 (maybe 400, can't remember at the moment)

*Define an onClick Event that would move the camera to the user's current location (you're going to have to use Location Service for this.
Sample:
//Acquire a reference to the system Location Manager
LocationManager locationManager =
     (LocationManager)getSystemService(Context.LOCATION_SERVICE);

//Acquire the user's location
Location selfLocation = locationManager
     .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

//Move the map to the user's location
LatLng selfLoc = new LatLng(selfLocation.getLatitude(), selfLocation.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(selfLoc, 15);
googleMap.moveCamera(update);

*If you noticed, when you click the "My Location" button, it starts to track you and move the camera accordingly. In order to create that effect, you need to override googleMap.onCameraMove and googleMap.onCameraIdle, and code your app so whenever the camera is idle, the map will continue to follow the user, and whenever the user moved the camera, it will stop.
Sample for onCameraIdle:
//Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager)
                    getSystemService(Context.LOCATION_SERVICE);

//Acquire the user's location
Location selfLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
LatLng cameraLocation = googleMap.getCameraPosition().target;

float[] results = new float[3];
Location.distanceBetween(selfLocation.getLatitude(), selfLocation.getLongitude(), cameraLocation.latitude, cameraLocation.longitude, results);

if (results[0] < 30) //30 Meters, you can change that
    googleMap.moveCamera(...) //Move the camera to user's location

A:     View locationButton = ((View) findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
    locationButton.setVisibility(View.GONE);
    RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
    // position on right bottom
    rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
    rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    rlp.setMargins(0, 180, 180, 0);

You can set margin where you likely to locate the My location button.


text:
Q: Is CSS display property animatable using keyframes? I know I can't transition between display none and block, but I thought that I could do some kind of step animation by doing this:

li:nth-child(1) {
  -webkit-animation: winkle 1s linear;
  animation: winkle 1s linear;
}
li:nth-child(2) {
  -webkit-animation: winkle 1s linear 1s;
  animation: winkle 1s linear 1s;
}
li:nth-child(3) {
  -webkit-animation: winkle 1s linear 2s;
  animation: winkle 1s linear 2s;
}
li:nth-child(4) {
  -webkit-animation: winkle 1s linear 3s;
  animation: winkle 1s linear 3s;
}
li:nth-child(5) {
  -webkit-animation: winkle 1s linear 4s;
  animation: winkle 1s linear 4s;
}
@-webkit-keyframes winkle {
  0%, 100% {
    display: none;
  }
  1%,
  99% {
    display: block
  }
}
@keyframes winkle {
  0%, 100% {
    display: none;
  }
  1%,
  99% {
    display: block
  }
}

Item 1

Item 2

Item 3

Item 4

But actually this is not working. Can you confirm this is not possible? Is there any other solution? I thought of this but it doesn't work either. If you can come up with something better, it would be greatly appreciated.

li:nth-child(1) {
  -webkit-animation: winkle 1s linear;
  animation: winkle 1s linear;
}
li:nth-child(2) {
  -webkit-animation: winkle 1s linear 1s;
  animation: winkle 1s linear 1s;
}
li:nth-child(3) {
  -webkit-animation: winkle 1s linear 2s;
  animation: winkle 1s linear 2s;
}
li:nth-child(4) {
  -webkit-animation: winkle 1s linear 3s;
  animation: winkle 1s linear 3s;
}
li:nth-child(5) {
  -webkit-animation: winkle 1s linear 4s;
  animation: winkle 1s linear 4s;
}
li {
  overflow: hidden;
}
@-webkit-keyframes winkle {
  0%, 100% {
    height: 0;
    color: red;
  }
  1%,
  99% {
    height: auto;
    color: blue;
  }
}
@keyframes winkle {
  0%, 100% {
    height: 0;
    color: red;
  }
  1%,
  99% {
    height: auto;
    color: blue;
  }
}

Item 1

Item 2

Item 3

Item 4

A: That's right, you can't animate something that not exists anymore. So you have to use another way to hide this element, like height or opacity, look this eg to see the differences:
Winkle with Height
This example winkle the li but the list will move because the height changes.

li:nth-child(1) {
  -webkit-animation: winkle 1s linear;
  animation: winkle 1s linear;
}
li:nth-child(2) {
  -webkit-animation: winkle 1s linear 1s;
  animation: winkle 1s linear 1s;
}
li:nth-child(3) {
  -webkit-animation: winkle 1s linear 2s;
  animation: winkle 1s linear 2s;
}
li:nth-child(4) {
  -webkit-animation: winkle 1s linear 3s;
  animation: winkle 1s linear 3s;
}
li:nth-child(5) {
  -webkit-animation: winkle 1s linear 4s;
  animation: winkle 1s linear 4s;
}
@-webkit-keyframes winkle {
  0%, 100% {
    height:0;
  }
  1%,
  99% {
    height:20px;
  }
}
@keyframes winkle {
  0%, 100% {
    height:0;
  }
  1%,
  99% {
    height:20px;
  }
}

Item 1

Item 2

Item 3

Item 4

Winkle with Opacity
This example winkle the li but the list mantain the original height.

li:nth-child(1) {
  -webkit-animation: winkle 1s linear;
  animation: winkle 1s linear;
}
li:nth-child(2) {
  -webkit-animation: winkle 1s linear 1s;
  animation: winkle 1s linear 1s;
}
li:nth-child(3) {
  -webkit-animation: winkle 1s linear 2s;
  animation: winkle 1s linear 2s;
}
li:nth-child(4) {
  -webkit-animation: winkle 1s linear 3s;
  animation: winkle 1s linear 3s;
}
li:nth-child(5) {
  -webkit-animation: winkle 1s linear 4s;
  animation: winkle 1s linear 4s;
}
@-webkit-keyframes winkle {
  0%, 100% {
    opacity:0;
  }
  1%,
  99% {
    opacity:1;
  }
}
@keyframes winkle {
  0%, 100% {
    opacity:0;
  }
  1%,
  99% {
    opacity:1;
  }
}

Item 1

Item 2

Item 3

Item 4

A: No, it isn't.
Properties which are not animatable are not animatable period.
There is no state between display: none and display: block (as there is between height: 0 and height: 500px) so you can't animate between them.

A: CSS animations and transitions work by creating steps between two numeric values, for example:
height: 0px -> height: 100px;

In this case, given the amount of steps and timing, the browser can calculate a transition between both values. It comes down to math.
On the other hand, non numeric CSS properties only have 2 possible states (on / off), and therefore can't have any "inbetween" steps:
display: none -> display: block;

All CSS propeties can be used in an animation or transition, just take into account if that value can take progressive steps between two values.


text:
Q: Access violation when getting network adapters with GetAdaptersAddresses in C I don't know if the code from https://learn.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses is wrong but when I try to use it in my C project I keep getting the infamous

Access violation reading location 0xFFFFFFFFFFFFFFFF

I have tried increasing the buffer size but nothing seems to fix it. I think this happens after the first adapter is passed through the loop.
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <winsock2.h>
#include <iptypes.h>
#include <iphlpapi.h>
#include <windows.h>

#pragma comment(lib, "IPHLPAPI.lib")

#define MALLOC(x)       HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x)         HeapFree(GetProcessHeap(), 0, (x))

FILE* fLog = NULL;

void netinfo() {
    PIP_ADAPTER_ADDRESSES pAddresses = NULL;
    PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;

    DWORD dwRetVal = 0;
    ULONG outBufLen = 15000;
    ULONG iter = 0;
    do {
        pAddresses = (IP_ADAPTER_ADDRESSES*)MALLOC(outBufLen);
        if (pAddresses == NULL) {
            fwprintf(fLog, L"MALLOC error");
            break;

            dwRetVal = GetAdaptersAddresses(
                AF_UNSPEC,
                GAA_FLAG_INCLUDE_PREFIX,
                NULL,
                pAddresses,
                &outBufLen
            );

            if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
                FREE(pAddresses);
                pAddresses = NULL;
                fwprintf(fLog, L"GetAdaptersAddresses() error");
            } else {
                break;
            }

            iter++;
        }
    } while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (iter < 3));

    wchar_t netAddressLog[256];
    if (dwRetVal == NO_ERROR && pAddresses != NULL) {
        pCurrAddresses = pAddresses;
        while (pCurrAddresses) {
            // this is where the debugger stops !!!
            swprintf(netAddressLog, 256, L"Index: %u", pCurrAddresses->IfIndex);
            fwprintf(fLog, netAddressLog);
            pCurrAddresses = pCurrAddresses->Next;
        }
    } else {
        fwprintf(fLog, L"GetAdaptersAddresses() error");
    }

    if (pAddresses) {
        FREE(pAddresses);
    }
}

int main(int argc, char **argv) {
    errno_t error = _wfopen_s(&fLog, L"log.txt", L"a+");

    netinfo();

    fclose(fLog);
}

So, when trying to access pCurrAddresses->IfIndex it's where the program fails, after the first loop (in which it logs some weird large number for index). I am trying to compare mi slightly modified code to the one from MSDN but I can't figure it out.
I know my code needs better organization but for now this is a blocker

A: There is some problem in the while loop block:
do {
    pAddresses = (IP_ADAPTER_ADDRESSES*)MALLOC(outBufLen);
    if (pAddresses == NULL) {
        fwprintf(fLog, L"MALLOC error");
        break;
        /* a } is missing here*/

        dwRetVal = GetAdaptersAddresses(
            AF_UNSPEC,
            GAA_FLAG_INCLUDE_PREFIX,
            NULL,
            pAddresses,
            &outBufLen
        );

        if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
            FREE(pAddresses);
            pAddresses = NULL;
            fwprintf(fLog, L"GetAdaptersAddresses() error");
        } else {
            break;
        }

        iter++;
    }
} while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (iter < 3));

The good corrected code could be:
do {
    pAddresses = (IP_ADAPTER_ADDRESSES*)MALLOC(outBufLen);
    if (pAddresses == NULL) {
        fwprintf(fLog, L"MALLOC error");
        break;
    }
    dwRetVal = GetAdaptersAddresses(
        AF_UNSPEC,
        GAA_FLAG_INCLUDE_PREFIX,
        NULL,
        pAddresses,
        &outBufLen
    );

    if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
        FREE(pAddresses);
        pAddresses = NULL;
        fwprintf(fLog, L"GetAdaptersAddresses() error");
    } else {
        break;
    }

    iter++;
} while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (iter < 3));


text:
Q: MSBuild from Powershell I'm trying to run a Sync from MSBuild (From Powershell) that also includes Pre Sync Commands.
I am unable to get the commands right. I've tried multiple ways, but the final way I'm up to is :
[string[]]$msdeployArgs = @(
  "-verb:sync",
  "-preSync:runCommand='$preSyncCommand',waitInterval=30000",
  "-source:dirPath=$sourceFolder",
  "-dest:computerName=$serverName,userName=$username,password=$password,authType=basic,dirPath=$serviceFolder",
  "-postSync:runCommand=$postSyncCommand,waitInterval=30000"
)

& "C:\Program Files (x86)\IIS\Microsoft Web Deploy V3\msdeploy.exe" $msdeployArgs

I get the following error.

Error: Unrecognized argument
  '"-preSync:runCommand='F:\Projects\Unleashed\Release_Scripts\WindowsServices\deployTopShelfServicePreCommands.cmd
  Unleashed.Maintenance.JobScheduler
  C:\MyCompany\Services\MyCompany.Maintenance.JobScheduler',waitInterval=30000"'.
  All arguments must begin with "-".

Note that after the PreSyncCommand, is params that I want to pass to the CMD file (For it to know where to uninstall the existing service from etc.
I've ran that params via EchoArgs.exe, and the args are fine.
If it matters (It might), I'm running the powershell script from TeamCity.

A: I've found the issue. As it turns out, it isn't powershell with the issue, but MSDeploy. MSDeploy as far as I can see does not allow you to pass batch files with parameters. Removing the parameters works fine (But then you need to hardcode them in your batch file, or work out some other way of generating the bat files on the fly).


text:
Q: Writing a conditional mean argument The following is an example data frame that I am working on:
       Age   Exon.1    Exon.2   Exon.3    Exon.4 Tissue
1   8 pcw 1.069621  2.090989 2.815579  2.599460    HIP
2   9 pcw 0.359670  1.327652 0.997034  1.128186    HIP
3  12 pcw 1.170716  7.368116 4.855342  4.868139    HIP
4  12 pcw 0.618367  0.780580 1.564149  2.119555    HIP
5  12 pcw 0.592584  3.233361 1.750408  4.784493    HIP
6  13 pcw 1.634750  3.852918 5.822762  4.215661    HIP
7  13 pcw 1.076103  3.653933 4.616696  4.288468    HIP
8  13 pcw 0.530033  1.572620 1.643339  2.447955    HIP
9  16 pcw 0.607179  6.393372 4.284723  6.054567    HIP
10 16 pcw 1.649528  8.162135 6.258901  5.672448    HIP
11 17 pcw 3.857213  6.297120 2.644501  6.823737    HIP
12 19 pcw 2.025933  2.471025 3.151600  5.400733    HIP
13 21 pcw 3.666728 12.037541 8.605424 11.427137    HIP
14 24 pcw 0.569007  3.611914 2.728669  7.173590    HIP
15 37 pcw 0.153815  0.000000 0.622567  0.606804    HIP
16  4 mos 2.585179  1.980350 3.781297  4.898531    HIP
17  4 mos 0.760953  0.339324 1.501044  2.491687    HIP
18  1 yrs 2.003685  7.804700 8.027769  7.122507    HIP
19  2 yrs 0.000000  0.616036 0.000000  0.050892    HIP
20  3 yrs 0.302567  0.000000 0.000000  0.402933    HIP
21  8 yrs 0.765591  2.332778 1.736967  4.598780    HIP
22  8 yrs 1.157266  3.497623 2.591768  3.543247    HIP
23 11 yrs 0.337816  0.000000 0.000000  3.256239    HIP
24 13 yrs 0.082116  0.000000 0.000000  1.421612    HIP
25 18 yrs 0.243391  0.000000 0.000000  0.601639    HIP
26 19 yrs 0.716598  1.412251 2.421302  4.201108    HIP
27 21 yrs 1.742922  4.678306 3.216452  3.701010    HIP
28 23 yrs 0.158256  0.760269 0.220072  2.115750    HIP
29 30 yrs 1.303604  0.488246 2.493215  3.816740    HIP
30 36 yrs 0.367384  2.611151 2.322208  3.423121    HIP
31 37 yrs 0.643085  3.441538 3.193851  4.546699    HIP
32 40 yrs 0.145881  0.000000 0.000000  1.622436    HIP

In R, I want to write an argument that would compute the mean for all rows in Exon.1, only if the row contains the following ages: "4 mos", "1 yrs", "2 yrs", "3 yrs".
I attempted to subset the values for Exon.1 through a series of trial arguments.
birth.infant <- c("4 mons", "1 yrs", "2 yrs", "3 yrs")
mean(data.frame$Exon.1 | birth.infant) # error
mean(data.frame$Exon.1 | if(intersect(data.frame$Age, birth.infant) == TRUE))
if(intersect(data.frame$Age, birth.infant)==TRUE) mean(data.frame$Exon.1)

If these illustrations aren't clear, my goal is to use birth.infant as include certain Exon.1 values of interest for computing a mean.
How might I establish a conditional mean argument for this task?

A: Have you tried: mean(Data$Exon.1[which(Data$Age %in% birth.infant)]) ? This should solve your problem.

A: As Jealie said,
mean(Data$Exon.1[Data$Age %in% birth.infant])

except remove the which. It serves no purpose other than to slow down your code.


text:
Q: js url not working in android Hi In My application I am using this js file for getting the json response.that is under
xamp->htdoc->node-chat->node_modules->config->request this is path of the file
http://www.learn2crack.com/2014/11/android-chat-application-using-gcm-mysql.html
In Client side I am using path like this
UserFragment.java
public class UserFragment extends Fragment {
ListView list;
ArrayList<HashMap<String, String>> users = new ArrayList<HashMap<String, String>>();
Button refresh,logout;
List<NameValuePair> params;
SharedPreferences prefs;

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    View view =inflater.inflate(R.layout.user_fragment, container, false);
    prefs = getActivity().getSharedPreferences("Chat", 0);

    list = (ListView)view.findViewById(R.id.listView);
    refresh = (Button)view.findViewById(R.id.refresh);
    logout = (Button)view.findViewById(R.id.logout);
    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new  Logout().execute();

        }
    });
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.content_frame)).commit();
            Fragment reg = new UserFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, reg);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.addToBackStack(null);
            ft.commit();

        }
    });
    new Load().execute();

    return view;
}

private class Load extends AsyncTask<String, String, JSONArray> {

    @Override
    protected JSONArray doInBackground(String... args) {
        JSONParser json = new JSONParser();
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
        JSONArray jAry = json.getJSONArray("http://10.0.2.2:8080/node-chat/getuser",params);

        return jAry;
    }
    @Override
    protected void onPostExecute(JSONArray json) {
        for(int i = 0; i < json.length(); i++){
            JSONObject c = null;
            try {
                c = json.getJSONObject(i);
                String name = c.getString("name");
                String mobno = c.getString("mobno");
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("name", name);
                map.put("mobno", mobno);
                users.add(map);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        ListAdapter adapter = new SimpleAdapter(getActivity(), users,
                R.layout.user_list_single,
                new String[] { "name","mobno" }, new int[] {
                R.id.name, R.id.mobno});
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Bundle args = new Bundle();
                args.putString("mobno", users.get(position).get("mobno"));
                Intent chat = new Intent(getActivity(), ChatActivity.class);
                chat.putExtra("INFO", args);
                startActivity(chat);
            }
        });
    }
}
private class Logout extends AsyncTask<String, String, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParser json = new JSONParser();
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
        JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2:8080/node-chat/logout",params);

        return jObj;
    }
    @Override
    protected void onPostExecute(JSONObject json) {

        String res = null;
        try {
            res = json.getString("response");
            Toast.makeText(getActivity(),res,Toast.LENGTH_SHORT).show();
            if(res.equals("Removed Sucessfully")) {
                Fragment reg = new LoginFragment();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, reg);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.addToBackStack(null);
                ft.commit();
                SharedPreferences.Editor edit = prefs.edit();
                edit.putString("REG_FROM", "");
                edit.commit();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

After running this application getting this logcat error.
logcat
12-29 01:47:09.198: E/Buffer Error(1982): Error converting result java.lang.NullPointerException: lock == null
12-29 01:47:09.198: E/JSON Parser(1982): Error parsing data org.json.JSONException: End of input at character 0 of
12-29 01:47:58.818: D/AndroidRuntime(1982): Shutting down VM
12-29 01:47:58.818: W/dalvikvm(1982): threadid=1: thread exiting with uncaught exception (group=0xb2aa5ba8)
12-29 01:47:58.938: E/AndroidRuntime(1982): FATAL EXCEPTION: main
12-29 01:47:58.938: E/AndroidRuntime(1982): Process: com.example.androidchat, PID: 1982
12-29 01:47:58.938: E/AndroidRuntime(1982): java.lang.NullPointerException
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.example.androidchat.UserFragment$Load.onPostExecute(UserFragment.java:85)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.example.androidchat.UserFragment$Load.onPostExecute(UserFragment.java:1)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.Looper.loop(Looper.java:136)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.app.ActivityThread.main(ActivityThread.java:5017)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at java.lang.reflect.Method.invokeNative(Native Method)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at java.lang.reflect.Method.invoke(Method.java:515)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at dalvik.system.NativeStart.main(Native Method)
12-29 01:48:12.648: W/System.err(1982): org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused
12-29 01:48:12.658: W/System.err(1982):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
12-29 01:48:12.668: W/System.err(1982):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-29 01:48:12.678: W/System.err(1982):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-29 01:48:12.688: W/System.err(1982):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-29 01:48:12.698: W/System.err(1982):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-29 01:48:12.708: W/System.err(1982):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-29 01:48:12.718: W/System.err(1982):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-29 01:48:12.728: W/System.err(1982):     at com.example.androidchat.JSONParser.getJSONArray(JSONParser.java:81)
12-29 01:48:12.748: W/System.err(1982):     at com.example.androidchat.UserFragment$Load.doInBackground(UserFragment.java:79)
12-29 01:48:12.758: W/System.err(1982):     at com.example.androidchat.UserFragment$Load.doInBackground(UserFragment.java:1)
12-29 01:48:12.768: W/System.err(1982):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-29 01:48:12.778: W/System.err(1982):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-29 01:48:12.778: W/System.err(1982):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-29 01:48:12.788: W/System.err(1982):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-29 01:48:12.798: W/System.err(1982):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-29 01:48:12.808: W/System.err(1982):     at java.lang.Thread.run(Thread.java:841)
12-29 01:48:12.818: W/System.err(1982): Caused by: java.net.ConnectException: failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)
12-29 01:48:12.848: W/System.err(1982):     at libcore.io.IoBridge.connect(IoBridge.java:114)
12-29 01:48:12.858: W/System.err(1982):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-29 01:48:12.868: W/System.err(1982):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-29 01:48:12.878: W/System.err(1982):     at java.net.Socket.connect(Socket.java:843)
12-29 01:48:12.888: W/System.err(1982):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-29 01:48:12.898: W/System.err(1982):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-29 01:48:12.908: W/System.err(1982):     ... 15 more
12-29 01:48:12.918: W/System.err(1982): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
12-29 01:48:12.938: W/System.err(1982):     at libcore.io.Posix.connect(Native Method)
12-29 01:48:12.948: W/System.err(1982):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
12-29 01:48:12.958: W/System.err(1982):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-29 01:48:12.968: W/System.err(1982):     at libcore.io.IoBridge.connect(IoBridge.java:112)
12-29 01:48:12.968: W/System.err(1982):     ... 20 more

request.js
var request = require('request');
var mysql = require('mysql');

var connection = mysql.createConnection(
    {
      host     : 'localhost',
      user     : 'root',
      password : '',
      database : 'chat',
    }
);

connection.connect();

exports.login = function(name,mobno,reg_id,callback) {

var data = {

            name    : name,
            mobno :  mobno,
            reg_id   : reg_id

        };
var que = "SELECT * from users WHERE mobno =" + mobno;

 var query = connection.query(que, function(err, rows)
        {
          if(rows.length == 0){
            var query = connection.query("INSERT INTO users set ? ",data, function(err, rows)
        {

          callback({'response':"Sucessfully Registered"});

        });
          }else {

           callback({'response':"User already Registered"});

          }

        });

}

exports.getuser = function(mobno,callback) {

 var query = connection.query("SELECT * from users", function(err, rows)
        {
          if(rows.length == 0){
            callback({'response':"No Users Registered"});
          }else {

          callback(removeUser(rows, mobno));

          }

        });

}

exports.removeuser = function(mobno,callback) {

var que = "DELETE FROM users  WHERE mobno =" + mobno;

var query = connection.query(que, function(err, rows)
        {

             if(!err){

    callback({'response':"Removed Sucessfully"});
  }else{
    callback({'response':"Error"});
  }
        });
}

exports.send = function(fromn,fromu,to,msg,callback) {

var que = "SELECT * from users WHERE mobno =" + to;

 var query = connection.query(que, function(err, rows)
        {
          if(rows.length == 0){
            callback({'response':"Failure"});

          }else {

    var to_id = rows[0].reg_id;
    var name = rows[0].name;

request(
    { method: 'POST',
    uri: 'https://android.googleapis.com/gcm/send',
    headers: {
        'Content-Type': 'application/json',
        'Authorization':'xxxxxxx'
    },
    body: JSON.stringify({
  "registration_ids" : [to_id],
  "data" : {
    "msg":msg,
    "fromu":fromu,
    "name":fromn
  },
  "time_to_live": 108
})
    }
  , function (error, response, body) {

      callback({'response':"Success"});
    }
  )
}});

}

function removeUser(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i].mobno == val) {
            arr.splice(i, 1);
            return arr;
            break;
        }
    }
}


text:
Q: Loop not working in SQL stored procedure I have a database with multiple questionnaires, each questionnaire has related (multiplechoice) questions, and each question has related answers.
I'm trying to create a stored procedure that will delete all questions and related answers with only the ID of the questionnaire.
My stored procedure looks like this:
ALTER PROCEDURE [dbo].[DeleteQuestionnnaire]

    @EnqueteID bigint
AS

BEGIN
    SET NOCOUNT ON

    DECLARE @QID bigint

    DECLARE questionCursor CURSOR FOR
        SELECT ID FROM questions WHERE EnqueteID = @EnqueteID

    OPEN questionCursor;

    FETCH questionCursor INTO @QID

    WHILE(@@fetch_status=0)
    BEGIN

    -- this is not working correct, the related answers are NOT being deleted

        FETCH questionCursor INTO @QID
        DELETE FROM answers WHERE QuestionID=@QID

    END

    CLOSE questionCursor

        --  this works fine, the questions are being deleted
    DELETE FROM questions WHERE EnqueteID=@EnqueteID

END

the related questions are being deleted but the related answers not, so I'm doing something wrong in my loop, is there anybody out there who sees what it is?
Thanks in advance

A: Your cursor is slightly odd, in that FETCH NEXT is usually the last statement in the loop (see the example from the documentation), so in fact the first value you fetch is immediately replaced by the second one. Adding some PRINT statements into the cursor to check the current value of @QID would show this.
But the real answer is not to use a cursor at all, it's unnecessary here:
delete from dbo.answers where questionid in (
    select questionid from dbo.questions where EnqueteID = @EnqueteID
)
delete from dbo.questions where EnqueteID = @EnqueteID

A: The overall cursor looks good. I'd move the fetch statement (within the loop) to the bottom right before the end. Currently you're fetching the first value into the parameter, then fetching the second value as soon as you enter the loop; effectively tossing out the first value while never using it.
WHILE(@@fetch_status=0)
BEGIN

    --SELECT @QID and Answers to see if you're getting the right values
    SELECT @QID
    SELECT * FROM Answers WHERE QuestionID = @QID
    -- DELETE FROM answers WHERE QuestionID=@QID

    --Fetch should be right before the loop ends
    FETCH questionCursor INTO @QID
END

A: You are fetching in the first and then the second so the first does not get deleted
FETCH questionCursor INTO @QID

WHILE(@@fetch_status=0)
BEGIN

    DELETE FROM answers WHERE QuestionID=@QID
    FETCH questionCursor INTO @QID

END

or
delete answers
where QuestionID in (select SELECT ID FROM questions WHERE EnqueteID = @EnqueteID);
go
delete questions WHERE EnqueteID = @EnqueteID;


text:
Q: Share photo with full size on facebook useing GRAPH API Android i want to post look like below image but with full size image.

I allreay use graph api to share photo on facebook which is something like below.

i want some hyperlink like above image and big photo.
pls.....guide me for this question.
Thanks in advance.

A: Simple answer No you can't show full sized image.We will get only default size fixed by Facebook Graph API
Totally there are three types of Media attachments ,
1)  image
2)  flash
3)  mp3
For image Media type : You can't set user defined height and width , no such key/value pair for setting height and width.
For Flash Media type :  You can set Height and width , below are the key/value pair available for Flash type :
"width": "80",
"height": "60",
"expanded_width": "160",
"expanded_height": "120"

For mp3 no need to discuss.
Media attachments for Facebook post


text:
Q: When try to convert django dict to json object it says "'str' object has no attribute '_meta'" I need to update HTML table when dropdown vale change.I'm using Ajax to do this.
Here is the HTML code and Ajax code
HTML code
<form role="form" action="/surveys/viewsurveys/{{ survey_id }}"   method="post" >

{% csrf_token %}
    <input type="hidden" id="Surey_ID" name="Surey_ID" value="{{ survey_id }}">
    Select Department or Section
    <select id="dept" name="dept" class="form-control" onchange="allusers();">
      {% for items in dept_data  %}
         <option value="{{ items.id }}">{{ items.dept_name }}</option>
      {% endfor %}
    </select>

All &nbsp {{ counts.hr_count }}

           First Name
           Last Name
           Email
           Username
           Data join
           last login
           Is Active

          {% for items in allusers %}

                         <input name="{{ items.id }}" type="checkbox">

                 {{ items.first_name }}
                 {{ items.last_name }}
                 {{ items.email }}
                 {{ items.username }}
                 {{ items.date_join }}
                 {{ items.last_login }}
                 {{ items.is_active }}
                  Edit

           {% endfor %}

                First Name
                Last Name
                Email
                Username
                Data join
                last login
                Is Active

</form>

Ajax code
function allusers()
  {

    $.ajax({
          url : "/surveys/ajaxalldeptusers",
          type : "POST",
          dataType: "json",
          data : {
             csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
             dept: $('#dept').val(),
             Surey_ID:$('#Surey_ID').val(),

          },

          success : function(json) {
           //$('#result').append( 'Server Response: ' + json.server_response);
           $('#box').html(json.message),
           console.log('my message' + json)
          },
          error : function(xhr,errmsg,err) {
          alert(xhr.status + ": " + xhr.responseText);
          }

        });

  }

back-end
def ajax_all_dept_users(request):
    try:
        request.session['user_login_data']
        dept_data=SuUserDepartment.objects.filter(org=request.session['user_login_data']['org'])
        dept=request.POST.get('dept','')
        survey_id=request.POST.get('Surey_ID','')
        responce_data={}

        if request.method == 'POST':
            surey_data=SuSurey.objects.get(id=survey_id)
            allusers=SuUser.objects.filter(dept_id=dept)
            responce_data['allusers']=allusers
            responce_data['dept_data']=dept_data
            responce_data['surey_data']=surey_data
            responce_data['survey_id']=survey_id
            data = serializers.serialize('json', responce_data)
            return HttpResponse(json.dumps(data),content_type="application/json")
            #return HttpResponse(json.dumps({'allusers':allusers,'dept_data':dept_data,'surey_data':surey_data, 'survey_id':survey_id }),content_type="application/json")
            #return  render_to_response("pages/forms/publish.html",{'allusers':allusers,'dept_data':dept_data,'surey_data':surey_data, 'survey_id':survey_id },context_instance=RequestContext(request))

    except KeyError, e:
        messages={'alert':'You need to loging'}
        return render(request, 'index.html',{'messages': messages},context_instance=RequestContext(request))

I try to debug and try to figure out the problem.I found that when come to  serializers.serialize() it give this error

how can i fix this error? need a quick help

A: That is a common error with serializers.serialize
You're trying to serialize an object that is not a model queryset.
Your data object is a dictionary, so you don't need to serialize it, just return that dict with json dump.

A: responce_data['allusers']=allusers
responce_data['dept_data']=dept_data
responce_data['surey_data']=surey_data
responce_data['survey_id']=survey_id
data = serializers.serialize('json', responce_data)

Here your call passing dict response_data to serializer, rather you should pass list of objects that you want to serialize.
So create list of objects and also do not specify string survey_id in the list to serialize.
Update your code to
dept_data=list(SuUserDepartment.objects.filter(org=request.session['user_login_data']['org']))

allusers=list(SuUser.objects.filter(dept_id=dept))
responce_data = [ surey_data, ] + dept_data + allusers
data = serializers.serialize('json', responce_data)


text:
Q: MySQL select only the correct row with releationship I have several tables and have them connected to relationships.
Here is a picture like:

Since I have several entries in the table Addresses I get more rows while selecting.
This is the SQL-Statement:
SELECT * FROM Users, Infos, Addresses WHERE Users.User_TOKEN = "PMgzdI3T9ji-8waSGUJCfTp-IQBT061TIRF-YqSHuMRN4Zk-fS09BDov27l-D0lK2"

User-Table:

Infos-Table:

Adresses-Table:

How can I get it without working with join?

A: I still didn't get, why you don't want to use joins. But mybe this will help you:
Your original query already uses joins. But the way you did it, you will get all infos and all addresses for all users. To fix it you need to define join conditions:

SELECT * FROM Users, Infos, Addresses
WHERE Users.User_TOKEN = "PMgzdI3T9ji-8waSGUJCfTp-IQBT061TIRF-YqSHuMRN4Zk-fS09BDov27l-D0lK2"
    /* join conditions */
    AND Infos.Info_TOKEN = Users.User_Info_TOKEN
    AND Addresses.Address_TOKEN = Infos.Info_Address_TOKEN

The folowing query will do the same, but is more readable (imho):
SELECT *
FROM Users u
JOIN Infos i     ON i.Info_TOKEN = u.User_Info_TOKEN
JOIN Addresses a ON a.Address_TOKEN = i.Info_Address_TOKEN
WHERE u.User_TOKEN = "PMgzdI3T9ji-8waSGUJCfTp-IQBT061TIRF-YqSHuMRN4Zk-fS09BDov27l-D0lK2"


text:
Q: How to handle target decoder inputs for self attention transformer model during predict() My question is essentially a duplicate of this one, where I'm confused as to what to pass into the decoder during the predict() (i.e., call()) phase. I've modified tutorials found here and here in order to create this script. This is being used for the purposes of self-attention on a time series dataset for regression (not NLP).
There's too much boilerplate to provide the full model so I'll write in the pertinent script:
Transformer.py
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
# The following imports are my custom Layers/Functions
from Utilities.MachineLearning.Keras.Layers.Encoder import Encoder
from Utilities.MachineLearning.Keras.Layers.Decoder import Decoder
from Utilities.MachineLearning.Keras.Functions.etc import create_padding_mask, create_look_ahead_mask

def create_masks(input, target):
    # Encoder padding mask
    encoder_mask = create_padding_mask(input)

    # Used in the 2nd attention block in the decoder.
    # This padding mask is used to mask the encoder outputs.
    decoder_mask = create_padding_mask(input)

    # Used in the 1st attention block in the decoder.
    # It is used to pad and mask future tokens in the input received by
    # the decoder.
    look_ahead_mask = create_look_ahead_mask(tf.shape(target)[1])
    target_mask = create_padding_mask(target)
    encoder_decoder_mask = tf.maximum(target_mask, look_ahead_mask)

    return encoder_mask, encoder_decoder_mask, decoder_mask

class Transformer(Model):
    def __init__(
        self,
        num_inputs,
        num_outputs=1,
        num_heads=1,
        num_layers=1,
        num_embedding_inputs=None,
        num_ff_inputs=None,
        dropout=0,
    ):
        super().__init__()

        self.encoder = Encoder(
            num_inputs,
            num_heads,
            num_layers,
            num_embedding_inputs,
            num_ff_inputs,
            dropout,
        )

        self.decoder = Decoder(
            num_inputs,
            num_heads,
            num_layers,
            num_embedding_inputs,
            num_ff_inputs,
            dropout,
        )

        self.output_layer = Dense(num_outputs, name="Output")

    def call(
        self,
        inputs,
        targets,
        training=None,
    ):
        encoder_mask, encoder_decoder_mask, decoder_mask = create_masks(inputs, targets)

        encoder_output = self.encoder(inputs, encoder_mask, training)

        decoder_output, attention_weights = self.decoder(
            targets, encoder_output, encoder_decoder_mask, decoder_mask, training
        )

        output = self.output_layer(decoder_output)

        return output, attention_weights

    train_step_signature = [
        tf.TensorSpec(shape=(None, None), dtype=tf.int64),
        tf.TensorSpec(shape=(None, None), dtype=tf.int64),
    ]

    @tf.function(input_signature=train_step_signature)
    def train_step(self, data):
        x, y = data

        with tf.GradientTape() as tape:
            y_pred = self(x, y, training=True)
            loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)

        # Compute gradients
        trainable_vars = self.trainable_variables
        gradients = tape.gradient(loss, trainable_vars)
        # Update weights
        self.optimizer.apply_gradients(zip(gradients, trainable_vars))
        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, y_pred)
        # Return a dict mapping metric names to current value
        return {m.name: m.result() for m in self.metrics}

SelfAttention.py
# Don't worry about what Custom is, it's basically a modified Keras Model
from Utilities.MachineLearning.Keras.Models.Custom import Custom
from Utilities.MachineLearning.Keras.Models.Transformer import Transformer

class SelfAttention(Custom):
    def initialize(self):
        self.transformer = Transformer(
            self.batch_input_shape[-1],
            num_heads=self.attention_units,
            dropout=self.attention_dropout,
            name="Transformer",

        )

    def call(self, inputs, training=False):
        # TODO: What about `targets`?
        return self.transformer(inputs, training=training)

A: There was no point in using a decoder as all the relevant information for time series data is used by the encoder block.