text:
Q: C function that removes comments from input I am new to C and trying to write my own function in C that would clean the comments out of a given input code. However there is some error with my logic as the result is not even close to desired.
My code is as follows:
char *removeComments(char *in)
{
    int i;
    int multipleLineFlag = 0;
    int singleLineFlag = 0;
    int n = strlen(input);
    char* output = malloc(n * sizeof(char));

    for (i=0; i<n; i++)
    {
        if (in[i] == '/' && in[i+1] == '*')
        {
            i++;
            multipleLineFlag = 1;
        }
        else if (multipleLineFlag == 1 && in[i] == '*' && in[i+1] == '/')
        {
            i++;
            multipleLineFlag = 0;
        }
        else if (in[i] == '/' && in[i+1] == '/')
        {
            i++;
            singleLineFlag = 1;
        }
        else if (singleLineFlag == 1 && in[i] == '\n')
        {
            singleLineFlag = 0;
        }
        else if (multipleLineFlag == 0 && singleLineFlag == 0)
        {
            out[i] = in[i];
        }
        i++;
    }
    free(in);
    return out;
}

Anybody else able to find my error in the code?

A: One obvious problem with your code is with this line:
out[i] = in[i];

You need to use 2 different variables to track where you are in the input and output strings as they'll be different. For example if the input string contains "foo /* test */ bar", then the output should contain "foo  bar", but what you'd actually get currently is "foo [10 undefined characters] bar". If you're lucky those undefined characters would be NULs.
The other problem is you're not adding a NUL to the end of the output. Which you'd be hard pressed to do if the input contains no comments as you're not allocating enough space - so as well as added the NUL at the end, you also need to allocate 1 more char than you are currently.

A: Beyond the problem identified by Chris and Antti, you should be aware that you cannot just parse the comment syntax to remove comments from C source code, you must also parse the string syntax to avoid false matches occurring inside string literals.
There is also this special case:
// this is a single line comment\
broken on 2 lines

And this one:
/\
*\
This is a block comment
*\
/

A state machine seems a correct approach for this problem, but state machines can be very tricky to polish.
Another point that is important to remember: block comments should be replaced with a single space character, otherwise you may have old style token pasting which is incorrect:
int/**/res; should expand to int res;, not intres;

A: You're sharing the same index for input and output - it means the out[0] to out[strlen("/* Hello World program */" - 1] will be uninitialized, and probably malloc just gives zeroed memory - thus the first character in your out would be a NUL character that terminates the string.
Actually you shouldn't be using indexes at all here, just use pointers.
char *result = malloc(n);
char *out = result;

...
    * out++ = in[i];
...
// finally terminate the output
*out = '\0';
return result;

Likewise, I'd prefer writing the in part of the code using just pointers.

A: Typically I would approach such a task with a state machine.
Here is an untested example of what I am talking about:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum {
  CODE,
  SLASH,
  SINGLELINE,
  MULTILINE,
  MULTILINE_ASTER
} state_t;

char* remove_comments(char const*in) {
  size_t len = strlen(in);
  char *out = malloc(len + 1);
  memset(out, 0, len+1);
  char c;
  state_t state = CODE;
  size_t opos = 0;
  while ((c = *in++)) {
    switch (state) {
    case CODE:
      if (c == '/') {
        state = SLASH;
      } else {
        out[opos++] = c;
      }
      break;
    case SLASH:
      switch (c) {
      case '/':
        state = SINGLELINE;
        break;
      case '*':
        state = MULTILINE;
        break;
      default:
        // this is a syntax error
        break;
      }
      break;
    case SINGLELINE:
      if (c == '\n') {
        state = CODE;
      }
      break;
    case MULTILINE:
      if (c == '*') {
        state = MULTILINE_ASTER;
      }
      break;
    case MULTILINE_ASTER:
      switch (c) {
      case '/':
        state = CODE;
        break;
      case '*':
        break;
      default:
        state = MULTILINE;
      }
    }
  }
  return out;
}

int main() {
  printf("%s", remove_comments("/********************************\n\
        * main function\n\
        * argc - number of arguments passed\n\
        * argv - pointer tgo arguments array\n\
        ********************************************/\n\
        int main(int argc, char **argv) {\n\
          // return number of arguments as return code\n\
          return argc;\n\
        }\n"));
  return 0;
}

Forgot to mention this code won't play along with string literals, these need to have their own states.


text:
Q: android CollapsingToolbarLayout scrolling
How can i create layout like this with CollapsingToolbarLayout and Toolbar?
First,
HEADER2 and CONTENT scroll up.
When top of CONTENT reach HEADER's bottom make HEADER scroll up.
Then HEADER_PIN is visible and only CONTENT scroll.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proof of a point beween two different points. (Geometry) I'm struggling with some of the logic writing this proof. This is the question:
Prove that if X is in AB (AB is a line segment) with X =/= B, then dist(AX) < dist(AB).
Logically this makes perfect sense.  The problem is that I struggle with putting it into words.  This is my attempt.
Proof:
Towards a contradiction, suppose that the distance AX >= AB.  Then by definition, AX + XB >= AB.  This implies that X is not in the line segment AB.  =><=
Am I close or should I use a different approach?

A: Since $X \ne B$,
$dist(X, B) > 0$.
Since
$dist(A, X) + dist(X, B)
=dist(A, B)
$,
$dist(A, X)
=dist(A, B)- dist(X, B)
< dist(A, B)
$.


text:
Q: How do i integrate a browser in my tk application? I am writing a Python program and want at some point to load HTML pages from the web and display them, in particular the support forum section/news section of my program. How can I easily integrate that into my program?

A: It would be easier to switch toolkits - Gtk+/Qt both have support for WebKit rendering engine. Both toolkits also have Python bindings support.

A: Tkinter has no native support for displaying HTML. With a little bit of work you can download the raw html, do a little text manipulation (assuming it's mostly plain text and a few tags for bold, headers, etc), and display it in a text widget. If it's well formed xhtml you can use an xml parser to pull out the relevant data and give it appropriate formatting.
If the pages have embeded images, or use css or javascript, the problem becomes exponentially harder to the point of not being practical.


text:
Q: Is every smooth function from $\mathbb{R}^n \to \mathbb R$ with compact support the laplacian of some function? Given a smooth function $g:\mathbb R^n \to \mathbb R $ with compact support, is it true that there exists a function $u$ such that $g=\Delta u$?

A: Yes. A solution is given by the convolution of g with the fundamental solution (see http://en.wikipedia.org/wiki/Newtonian_potential).
The solution $u$ is not unique because one could always add to $u$ a harmonic function $h$ (satisfying $\Delta h = 0$).
If you specify some sort of boundary data for $u$, then there is a unique solution. For example, suppose the support of $g$ is contained in some open set $\Omega$ (you may need some sort of boundary regularity on $\Omega$). Then there is a unique solution $u$ to $\Delta u = g$ satisfying $u = 0$ on $\partial \Omega$. (Now the solution is unique by the maximum principle.)


text:
Q: How do I activate SSL for my AppEngine with java application? Please let me know the process to configure my custom domain (http://www.myapp.in) with SSL. If i do follow the below process, Does it guaranteed to be secure my application? As i know that the process Google gives us...
    "https://developers.google.com/appengine/docs/ssl" in this doc, i found the process is below to Activating heading.
And also please let me know that "Is it free of cost?"
Any reply can welcome,
Thanks in advance.
Satyarao

A: *

*Theres nothing special about java here. Enabling SSL is always the same on GAE, regardless of the language used.

*SSL on https://appid.appspot.com is always available and free of charge.

*SSL on custom domains costs money. The connection itself is secure (if you use a valid certificate and keep this secret). However its up to your application to enforce the usage of SSL, and doing the whole other security related stuff.

A: It's free to enable. Add the secure:always line in your configuration file (app.yaml): https://developers.google.com/appengine/docs/python/config/appconfig#Secure_URLs


text:
Q: Programmatically reading wall posts / stream of facebook "pages" My application is taking in various streams of data from social media / rss and combining it into one feed on the service that I will offer to businesses.
So, I'd like to read facebook page streams and process them.. do I need to get permission from the owner of the facebook page? Or is this publicly accessible somehow? since these are public pages for businesses and not the stream of private facebook users.
I don't care about WRITING to a stream at this point.. just READING.

A: If it is public you can read through graph API using:
https://graph.facebook.com/%page_id%/feed

But you need to be logged in, even with a user that does not manage that page.

A: Read the Facebook API documentation. I think the Graph API and Social plugins can be used for your purpose.


text:
Q: USB_modeSwitch doesnt detect my huawei dongle as modem automatically Problem:
I am using a Huawei dongle with me.
On my current kernel version, I have installed usb_modeswitch.
As soon as I insert my Huawei dongle, it detects as mass storage instead of the modem.
lsusb
Bus 001 Device 005: ID 12d1:1506 Huawei Technologies Co., Ltd. Modem/Networkcard

Experiments

*

*made DisableSwitching=1 in usb_modeswitch.conf file.
this also doesn't work.

*Issued usb_modeswitch -v 0x12d1 -p 0x1506 -M "55534243123456780000000000000a11062000000000000100000000000000"
At this time it will work and my device get detects as the modem and I an able to get wwan0 interface along with that.
But if I remove my dongle and insert it again, it again detects it as the storage device.
--> I want this to happen automatically, that no matter how many time I remove my dongle, it should always be get detected.
All these changes having below settings in kernel
CONFIG_USB_SERIAL_WWAN=m
CONFIG_USB_SERIAL_OPTION=m

Thanks,
Ashish

A: After installing the latest version of usb_modeSwitch 2.5 its works fine.


text:
Q: Interaction energy of two brownian spherical particle in liquid Let us consider two hard sphere in finite volume. Their motion is Brownian. What can we say about interaction energy? Is it less then $kT$?
I know that we can describe this system by Langevin equation. Of course, the process of interaction hard to describe because each of particles creates elastic waves, so we need to use acoustic equations. But I don't understand how I can estimate interaction.

A: After immersion each of particles get maximum $\frac{3}{2}kT$. So, they can interact with $3kT$ maximum.


text:
Q: Solving recurrence relation with exponential generating function Attempting to solve the recurrence relation $$a_{n+1} = 2na_n+a_n+2$$
with $a_0=1$ (solution in summation form, closed form not necessary)
Let $E(x)=\sum^{\infty}_{n=0}a_n\frac{x^n}{n!}$, and multiply each time in the relation by $ \frac{x^n}{n!}$ and take the sum.
$$\sum^{\infty}_{n=0}a_{n+1}\frac{x^n}{n!}=\sum^{\infty}_{n=0}(2n+1)a_n\frac{x^n}{n!}+2\sum^{\infty}_{n=0}\frac{x^n}{n!}$$
notice that $\sum^{\infty}_{n=0}a_{n+1}\frac{x^n}{n!}=E'(x)$, and $\sum^{\infty}_{n=0}\frac{x^n}{n!}=e^x$. But I'm not sure what I can do with the middle sum, differentiating/integrating it doesn't seem to help, nor does substitutions like $m=2n+1$

A: Hint: The middle term is $2 \sum a_n\frac {x^{n}} {(n-1)!}+E(x)$. You can write this as $2x\sum a_{n+1}\frac {x^{n}} {n!} +E(x)=2xE'(x)+E(x)$


text:
Q: How to use a SAS drive as an external hard disk? I am not a server guy. I have few external hard disks lying around. Googling around I found those are SAS drives. I want to convert it into an external hard drive for personal use (I'm planning to connect it to the router that has USB 3.0 ). How to connect these drives to the router through USB or ethernet? Any help would be welcome. The hard disk is in the image.

A: I came across two SAS to USB adapters that seem to have the necessary SAS controller as well as physical connectors; however the cost is going to be prohibitive for many.
Ebay $600
https://www.ebay.com/itm/Reader-Cable-SAS-to-USB-3-0-Adapter-Universal-Converter/192743009670?hash=item2ce060ed86:g:VeIAAOSwcOZcAV3g:rk:1:pf:0
Other  ?$
https://letmelinkusb.com/sas-to-usb-converter/
https://www.youtube.com/watch?v=e6eh9kgaWy0

A: Just got my converter for $5.50 from aliexpress SFF-8482 SAS 22 Pin to 7 Pin - not work for anybody when read comments

*

*is not working only detect drive but when init try change MBR GTP
failed (Win)

*drive spin - make whining noise

*ended up with my laptop power supply stop working and run on battery. After restart connect different power supply and then back to main original its working again

Found this one maybe its work:
https://www.youtube.com/watch?v=e6eh9kgaWy0
https://letmelinkusb.com/sas-to-usb-converter/
___ UPDATE _____
Connected to different HDD Enclosure but this time partition are not detected

A: You can use pretty much any HDD enclosure, which you can find on sites such as Newegg or Amazon. The keyword to search for is "External Hard drive enclosure".
Just make sure to choose SAS interface rather than SATA.
Here is a sample: https://www.newegg.com/Product/ProductList.aspx?Submit=ENE&IsNodeId=1&N=100008040%20600006291

A: Startech make a $30 drive bay to turn anything into SATA, ie load SAS drive in the front and takes standard SATA out the back. That will speak fluent PC. Then you can do SATA to USB 3.0. Crazy I know, but very doable despite what other people have said. No judgement on whether you really want to be doing this and for what cost.


text:
Q: Complex polynomial division proof Proof left as an exercise for the reader: For a non-trivial complex polynomial and any given input value $a$, there is a unique integer $k\geq1$ so that $$p(z)-p(a)=(z-a)^kq_k(z), q_k(a)\neq0.$$
My intuition here is to use something similar to proof by induction and Taylor expansion, but I'm not sure if this would be a proof of the exercise.

A: Sketch of induction proof.  By the Factor Theorem we have
$$p(z)-p(a)=(z-a)q(z)$$
for some $q(z)$.  If $q(a)\ne0$ we are finished.  If $q(a)=0$ we can use induction, since $q$ has smaller degree than $p$, and we get
$$q(z)=q(z)-q(a)=(z-a)^kr(z)\ ,\qquad r(a)\ne0\ .$$
Substituting back completes the proof.
Will leave you to supply details :)
For uniqueness, if
$$(z-a)^kq_k(z)=(z-a)^lq_l(z)\ ,\quad q_k(a)\ne0\ ,\quad q_l(a)\ne0$$
with $k\ne l$, then we can assume $k>l$, so $z-a$ is a factor of $q_l(z)$.  But this contradicts $q_l(a)\ne0$.


text:
Q: Download a file programmatically I have a Google Sheets application that generates a file that needs to be uploaded to the HMRC Government Network. They only accept an open document format (.ods) in a file originally formatted and generated by HMRC.
The only way I can currently do this is to manually download the data into my PC as an .ods file. I had hoped to be able to directly upload to HMRC a file that is in my Google File Drive Stream which I had thought would be a real file but it turns out not to be so! HMRC will not look at it.
So has anyone any idea whether DriveApp or any other Google Apps Script method can download the file, as you can do manually?

A: One possibility would be using Advanced Drive Service in Google Apps Script and use Drive API in your script. Using files.get method you can access export links from a file and select the one you need.
You will also need to prompt a dialog to click on the link because I believe you cannot directly open an URL from Google Apps Script.
This code could work for you:
function exportToODS(fileId){
  var file = Drive.Files.get(fileId);
  var openOfficeURL = file.exportLinks["application/x-vnd.oasis.opendocument.spreadsheet"];
  showDialog('Click here to export',openOfficeURL);
}

function showDialog(name,url) {
  var html = ''+name+'';
  var ui = HtmlService.createHtmlOutput(html)
  SpreadsheetApp.getUi().showModelessDialog(ui,"Export to ODS");
}

Remember that you need to enable Advanced Google Services before using them:

To use an advanced Google service, follow these instructions:

*

*In the script editor, select Resources > Advanced Google services....

*In the dialog that appears, click the on/off switch next to the service you want to use.

*At the bottom of the dialog, click the link for the Google API Console.

*In the console, click into the filter box and type part of the name of the API (for example, "Calendar"), then click the name once
  you see it.

*On the next screen, click Enable API.

*Close the API Console and return to the script editor. Click OK in the dialog. The advanced service you enabled is now available in
  autocomplete.

I hope it helps!


text:
Q: QML: Event which triggers when document was completly loaded I work now on an application witch loads QML file and makes screenshot of a window.
That's how it looks now:
QQmlApplicationEngine engine;
engine.loadData(data);
QQuickWindow *rootObject = qobject_cast<QQuickWindow *>(engine.rootObjects().first());

QImage image = rootObject->grabWindow();
image.save("window.png","PNG",90);

In this case data is just simple QML structure:
import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true
    width: 360
    height: 360

    Text {
        anchors.centerIn: parent
        text: "Hello, world!"
    }
    MouseArea {
         anchors.fill: parent
         //onClicked: someSingleton.makeScreenshot();
    }
    Component.onCompleted: someSingleton.makeScreenshot();
}

But image I get from QQuickWindow::grabWindow() is empty and not saved. So I tried to make it in another way through Component.onCompleted and it still not works. (someSingleton.makeScreenshot() is a function with call to QQuickWindow::grabWindow() like the code above). The only way to get it work is to call to this function in MouseArea .onClicked when a window completely loaded. So I came to conclusion that in 2 first attempts QML tree was not fully loaded.
I also tried this code:
connect(rootObject,&QQuickWindow::afterRendering,[=] () {
    QImage image = rootObject->grabWindow();
    image.save("window.png","PNG",90);
});

But program's execution just hungs up on first line.
So my question - is there some event witch triggers when a QML document completely loaded?
P.S. In real app I cannot modify QML source so all functionality have to be in C++ part. Component.onCompleted and MouseArea .onClicked here are just for test purposes.

A: Ok, after long search, I've found the solution.As usual I just had to read the Qt documentation more carefully.
QImage QQuickWindow::grabWindow()

http://doc.qt.io/qt-5/qquickwindow.html#grabWindow
Warning: This function can only be called from the GUI thread.
void QQuickWindow::afterRendering()

http://doc.qt.io/qt-5/qquickwindow.html#afterRendering
Warning: This signal is emitted from the scene graph rendering thread.
So, the slot was executed in scene graph rendering thread and hangs up due to conflicts. I've just changed the example above to be sure the slot executes in GUI thread as described here.
connect(rootObject,&QQuickWindow::afterRendering,this,[=] () {
    QImage image = rootObject->grabWindow();
    image.save("window.png","PNG",90);
},Qt::QueuedConnection);

A: I'm not sure why the following doesn't work:
#include <QtQuick>
#include <QtGui>

class Object : public QObject
{
    Q_OBJECT
public slots:
    void save() {
        QQuickWindow *window = qobject_cast<QQuickWindow*>(sender());
        QImage image = window->grabWindow();
        image.save("window.png", "PNG", 90);
    }
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    QByteArray data = "import QtQuick 2.3\n"
        "import QtQuick.Window 2.2\n"
        "Window {\n"
            "visible: true\n"
            "width: 360\n"
            "height: 360\n"
            "Text {\n"
                "anchors.centerIn: parent\n"
                "text: \"Hello, world!\"\n"
            "}\n"
            "MouseArea {\n"
                 "anchors.fill: parent\n"
            "}\n"
        "}";
    engine.loadData(data);

    QQuickWindow *rootObject = qobject_cast<QQuickWindow *>(engine.rootObjects().first());

    Object object;
    QObject::connect(rootObject, SIGNAL(afterRendering()), &object, SLOT(save()));

    return app.exec();
}

#include "main.moc"

It could be that the usage is incorrect, or there's actually a bug somewhere. I'm not sure. It's worth asking on the mailing list, or creating a bug report if you're unsure.
However, if you use frameSwapped() instead, it works:
    QObject::connect(rootObject, SIGNAL(frameSwapped()), &object, SLOT(save()));


text:
Q: Plotly.js Axis Click/Drag Event I have multiple y-axis in a line chart. Only the last y-axis related grid lines are shown by default. If the user clicks on any other y-axis, grid lines for that y-axis should be shown. But I am unable to find any event in plotly.js which triggers when the axis is clicked or dragged.

A: Sorry, I can't comment yet. Here's a rather hacky way of registering clicks on yaxis labels. Not sure if that's helpful.

var trace1 = {
  x: [1, 2, 3],
  y: [40, 50, 60],
  name: 'yaxis data',
  type: 'scatter'
};

var trace2 = {
  x: [2, 3, 4],
  y: [4, 5, 6],
  name: 'yaxis2 data',
  yaxis: 'y2',
  type: 'scatter'
};

var data = [trace1, trace2];

var layout = {
  title: 'Double Y Axis Example',
  yaxis: {title: 'yaxis title'},
  yaxis2: {
    title: 'yaxis2 title',
    titlefont: {color: 'rgb(148, 103, 189)'},
    tickfont: {color: 'rgb(148, 103, 189)'},
    overlaying: 'y',
    side: 'right'
  }
};

Plotly.newPlot('chart', data, layout);

var myPlot = document.getElementById('chart');
myPlot.on('plotly_afterplot', function(){
    Plotly.d3.selectAll(".nsdrag.drag.cursor-ns-resize")
          .on("click", function() {
              var target = Plotly.d3.event.target;
              console.log('clicked on', target.dataset.subplot);
          });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.49.5/plotly.min.js"></script>
<div id="chart">
</div>


text:
Q: jQuery each() restriction Is it possible to restrict where it looks for the certain text?
$(data,'table tr').each(function(){

});

Is what I have right now. Am I any where near right?

A: See jQuery() (aka the $() function) and see the supported forms.
It would likely be $(selector, context) where context is "A DOM Element, Document, or jQuery".
Alternatively, create a jQuery object and then apply the appropriate traversing function(s).
Happy coding.

A: I believe this is what you're looking for: How to skip to next iteration in jQuery.each() util?
var arr = [ "one", "two", "three", "four", "five" ];
$.each(arr, function(i) {
    if(arr[i] == 'three') {
        return true;
    }
    alert(arr[i]);
});

You can check certain conditions on the tr, like, does it have children? And if so, skip to the next iteration.


text:
Q: How to recursively iterate for dynamic data I've Json data in PHP which is:
{
  "module": [
    {
      "jhooq-webserver-1": [
        {
          "source": ".//module-1"
        }
      ]
    },
    {
      "jhooq-webserver-2": [
        {
          "source": ".//module-2"
        }
      ]
    }
  ],
  "provider": [
    {
      "aws": [
        {
          "access_key": "var.access_key",
          "region": "var.web_region",
          "secret_key": "var.secret_key"
        }
      ]
    }
  ]
}

All i wanted is to use recursive function to convert it to the below format (output):
provider "aws" {
  region     = "var.web_region"
  access_key = "var.access_key"
  secret_key = "var.secret_key"
}

module "jhooq-webserver-1" {
  source = ".//module-1"
}

module "jhooq-webserver-2" {
  source = ".//module-2"
}

Any help will be greatly appreciated.
I've tried using recursive function in php which i failed unfortunately failed. I'm unclear to use recursive function for my scenario.

A: You don't really need a recursive function to do this:
foreach($array as $blockName => $level2) {
    foreach($level2 as $level3) {
        foreach($level3 as $title => $level4) {
            echo "$blockName \"$title\" {\n";
            foreach($level4 as $level5) {
                foreach($level5 as $key => $value) {
                    echo "  $key = \"$value\"\n";
                }
            }
            echo "}\n";
        }
    }
}


text:
Q: Is there a way to make PipEnv install in whatever Python environment is currently active? If you have no virtualenv active, PipEnv will create a virtualenv and then activate it before installing packages. If you have a virtualenv active, PipEnv will use that and not create a new virtualenv. Those are the normal use-cases for PipEnv.
But what if I'd like to totally disregard virtualenv? Quite often I work out of Docker Containers. I'd like to install a PipEnv based project, but not in a virtualenv. When I pipenv sync from within a Docker container I want everything installed into the container's global Python interpreter.
It simply wouldn't make sense to put a virtualenv inside a container - that's one more layer of virtualization than I actually need.


text:
Q: I thought views/layouts/application.html.erb was meant to apply to all layouts? I am trying to design my ruby on rails app at the moment. I created views/layouts/posts.html.erb which styled my PostsController's views.
I want to add a main bar that is always at the top of the page no matter what view the user is looking at. I thought this was what the views/layouts/application.html.erb was for.
This seems to agree with me:
http://jacqueschirag.wordpress.com/2007/08/02/rails-layout-and-nested-layout-basics/

*

*The entire Rails application (all views of all controllers) will
  use this layout:
views/layouts/application.rhtml

*All views within a single controller will use this layout. For
  example, the layout for
  weclome_controller.rb will use this
  layout. Notice, the '_controller' is
  left off for the layout:
views/layouts/welcome.rhtml

What am I doing wrong?
Here is what I have in the body of my application.html.erb

        <% if current_user %>
          <%= link_to "My Profile", current_user %>
          <%= link_to "Logout", logout_path %>
        <% else %>
          <%= link_to "Register", new_user_path %>
          <%= link_to "Login", login_path %>
        <% end %>

    <%= yield %>

A: Both your layouts, application.html.erb and posts.html.erb should render the main bar as a partial:
<%= render :partial => 'layouts/main_bar' %>

All layouts contain the  element that wraps your page; you don't have one layout wrapping around the other.

A: Well the information is correct - 'views/layouts/application.html.erb' should be working just fine.Have you included the "main bar" content using <%= ..... %> (i.e. are you missing the = sign in your layout file?)
And, have you included the <%= yield %> statement somewhere in the layout file?

Also, what version of Rails are you using?
You should find this Layouts and Rendering in Rails very helpful in getting to the basics of rails views and layouts

A: I'm confused… do you still have views/layouts/posts.html.erb ? If that's the case all views rendered from PostsController will use this layout and not views/layouts/application.html.erb


text:
Q: Jquery prevent html list going over multiple lines I want to prevent my users on a cms from making their menu item go over multiple lines as it doesn't look to good and can cut off their content.  I so far have this.

Home

About

Contact

Sub contact

Register

Info

Share

Extra Info

Extra Info

If the width of the nav goes onto a second line I want the menu to look like this.

Home

About

Contact

Register

                More

Share

Extra Info

Extra Info

I am trying to achieve this with Jquery but am stuck. See Fiddle (the second list in the fiddle is how I would want it to look)
I can count the width of the list items. But I want to say if the width is > 300 add all li that come after li = 300 to a sub ul of more like I have shown above in how I want it to look like. Any help here would be appreciated.

A: try something like this, FIDDLE
    $(document).ready(function() {
        var listWidth = [];
        var total = 0;
         // new li to append
        var li = $('
more
')
         // new ul to be appended to ul
        var ul = $('
')

        // variable to store index of element after which new li(more) will be added
        var $index = true;

        // variable to state that index vaiable is set, no more index need to be set
        var $value_set = true;
        $('#wrap ul li').each(function() {
            total += parseInt($(this).width());
            if (total > 300){
                if($value_set){
                    $index = $(this).index() - 2;
                    $value_set = false;
                }
            }

        });
        $( "#wrap ul li:gt("+$index +")").each(function() {
            ul.append(this);
        });

        if(ul.length){
             $('#wrap ul').append(li.append(ul));

         }

    });


text:
Q: How can I declare a matrix in Polymer? I gotta pass this as parameter in a polymer element:
[
  ["id", "nome",     "idade"],
  [1,    "matheus",  16],
  [2,    "cristian", 16],
  [3,    "pedro",    10],
  [4,    "henrique", 10]
]

how can I declare this variable (a matrix) in the polymer propertie field?
How I declare my element:
<script>
        Polymer({
            is: "table-element",
            properties: {
                id: String,
                matrixdata: Array
            },

            ready: function() {
               document.getElementById(this.id).appendChild(criarTabela(this.matrixdata));
            }
        });

    </script>

A: I think this should work
<my-comp matrix='[
  ["id", "nome",     "idade"],
  [1,    "matheus",  16],
  [2,    "cristian", 16],
  [3,    "pedro",    10],
  [4,    "henrique", 10]
]'></my-comp>

if the type of the matrix property is Array
matrix: {
  type: Array
}

See also the rows or data example in https://elements.polymer-project.org/elements/google-chart


text:
Q: SlidingMenu and Samsung open in pop-up view (The specified child already has a parent. Exception) I have a problem with Samsung's 'Open in pop-up view' option.
My app uses jfeinstein10/SlidingMenu lib (not updated in 4 years) and the problem described below affects only the activty that uses it.
SlidingMenu messes with android's DecorView and I know (from the stacktrace below) that Samsung's 'Open in pop-up view' uses DecorCaptionView which I suppose has something to do with the DecorView.
The problem is that every time a user on Samsung device (namely Galaxy S7) presses 'recents button' and moves the app to the 'Open in pop-up view' box as in the photo below:

the following exception is thrown:
Fatal Exception: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
   at android.view.ViewGroup.addViewInner(ViewGroup.java:4656)
   at android.view.ViewGroup.addView(ViewGroup.java:4497)
   at com.android.internal.widget.DecorCaptionView.addView(DecorCaptionView.java:358)
   at android.view.ViewGroup.addView(ViewGroup.java:4469)
   at com.android.internal.policy.DecorView.onConfigurationChanged(DecorView.java:2053)
   at com.android.internal.policy.PhoneWindow.onMultiWindowModeChanged(PhoneWindow.java:747)
   at android.app.Activity.dispatchMultiWindowModeChanged(Activity.java:7177)
   at android.app.ActivityThread.handleMultiWindowModeChanged(ActivityThread.java:3212)
   at android.app.ActivityThread.-wrap16(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1866)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6692)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

and my app crashes.
After some code investigation I found out that this block of SlidingMenu lib code causes the problem:
    case SLIDING_WINDOW:
        mActionbarOverlay = false;
        ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
        ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
        // save ActionBar themes that have transparent assets
        decorChild.setBackgroundResource(background);
        decor.removeView(decorChild);
        decor.addView(this);
        setContent(decorChild);
        break;

but I cannot debug it when while this opening in pop-up happens.
Does anybody have any suggestions how to fix this ?
I have already tried switching off Samsung's multiwindow options explicitly in the AndroidManifest:
    <meta-data
        android:name="com.samsung.android.sdk.multiwindow.enable"
        android:value="false" />
    <meta-data
        android:name="com.samsung.android.sdk.multiwindow.multiinstance.enable"
        android:value="false" />
    <meta-data
        android:name="com.sec.android.multiwindow.STYLE"
        android:value="fixedRatio" />
    <meta-data
        android:name="com.sec.android.support.multiwindow"
        android:value="false" />

but with no success.

A: You can try these two solutions:

*

*after decor.addView(this);, add this block:

try {
  Field field = decor.getClass().getDeclaredField("mContentRoot");
  field.setAccessible(true);
  field.set(decor, this);
} catch (Exception e) {
  // do something
}

*add android:resizeableActivity="false" to 'application' element in AndroidManifest.xml, to disable multiwindow.


text:
Q: Get path relative to executed flask app In my flask app I recreate a sqlite database at every start.
For this I use code as shown on the official webpage
My project structure looks like this
project_dir/
|-README.md
`-app/
  |-StubbyServer.py (contains the flask root)
  |-schema.sql
  `- (all the other files)

Now my StubbyServer.py contains:
def get_db():
    db = getattr(Flask, '_database', None)
    if db is None:
        db = Flask._database = sqlite3.connect(DATABASE)
        with open('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
        db.row_factory = sqlite3.Row
    return db

If my working directory is /path/project_dir/app the command python StubbyServer.py works fine
If my working directory is /path/project_dir the command python app/StubbyServer.py fails with:

File "app/StubbyServer.py", line 43, in get_db
      with open('schema.sql', mode='r') as f:
  FileNotFoundError: [Errno 2] No such file or directory: 'schema.sql'

I know why this happens but I don't know how I can work around this.
I want my flask app to work fine independent from my current working dir, how can I achieve this?

A: This exact use case happens to be the example used in the documentation for flask's open_resource API call as well as the blueprint documentation linked in your question.
Specifically, the reference doc says:

To see how this works, consider the following folder structure:
/myapplication.py
     /schema.sql
     /static
         /style.css
     /templates
         /layout.html
         /index.html

If you want to open the schema.sql file you would do the following:
 with app.open_resource('schema.sql') as f:
     contents = f.read()
     do_something_with(contents)


text:
Q: why protege appears blue arrow automatically? when I followed the official document of protege to set up a pizza ontology,it is OK,but when I open this ontology after saving,I found each class has a grey arrow ahead and some blue arrows (refer the picture1).I take class Pizza and PizzaBase as an example,we know that the relationship between  Pizza and PizzaBase is hasBaase,that is Pizza hasBase some PizzaBase,so I click the Pizza and in class Description,I set that(refer secong picture2),then the class Pizza automatically becomes the subclass of PizzaBase,and a blue arrow appears. there are many blue arrows.I don't know what is the matter,so please help me,thanks very much!  enter image description here
enter image description here


text:
Q: Converting WEBM to MP3 I'm aware there are a couple of other questions here related to this, but the answers provided don't seem to work.
I'm trying to convert a webm to mp3 with avconv. Here's how I tried to do it:
 $ ls
test.webm
 $ avconv -acodec libmp3lame -i test.webm test.mp3
avconv version 9.18-6:9.18-0ubuntu0.14.04.1, Copyright (c) 2000-2014 the Libav developers
  built on Mar 16 2015 13:19:10 with gcc 4.8 (Ubuntu 4.8.2-19ubuntu1)
test.webm: End of file
 $ ls -l
total 4
-rw-rw-r-- 1 user user 439 Apr 28 09:16 test.webm

As you can see, I don't appear to get an error but my file is not created. Please note that I did install ubuntu-restricted-extras.
EDIT:
 $ avprobe test.webm
avprobe version 9.18-6:9.18-0ubuntu0.14.04.1, Copyright (c) 2007-2014 the Libav developers
  built on Mar 16 2015 13:19:10 with gcc 4.8 (Ubuntu 4.8.2-19ubuntu1)
test.webm: End of file
# avprobe output

 $ avprobe -encoders|grep mp3
avprobe version 9.18-6:9.18-0ubuntu0.14.04.1, Copyright (c) 2007-2014 the Libav developers
  built on Mar 16 2015 13:19:10 with gcc 4.8 (Ubuntu 4.8.2-19ubuntu1)
A... libmp3lame           libmp3lame MP3 (MPEG audio layer 3) (codec mp3)

A: The proper way to converting is :
avconv -i test.webm -c:a libmp3lame test.mp3

or even shorter, without telling to avconv that you want use libmp3lame encoder.
avconv -i test.webm test.mp3

A: I have found you need to specify that -acodecd parameter after the inpout and before the output.    personally i also throw in  -b:a "256k" to set the  bitrate to 256k for the mp3.
avconv -i Mozart.webm -acodec libmp3lame -b:a "256k" Mozart.mp3

A: You can convert through this script:
for FILE in *.webm; do
    echo -e "Processing video '\e[32m$FILE\e[0m'";
    ffmpeg -i "${FILE}" -vn -ab 128k -ar 44100 -y "${FILE%.webm}.mp3";
done;

Save it into a .sh file and execute it. It will automatically convert all the .webm into .mp3

A: You can convert WEBM videos to MP3 file using VLC Media Player. The open-source media player converts WEBM files for free.
Steps to convert WEBM to MP3 in VLC Media Player:

*

*Open VLC Media Player on your computer

*On the top menu bar, click Media > Convert/Save.

*In Open Media, click Add to insert WEBM files.

*Click Convert/Save.

*Across Profile, select MP3 format.

*In the Convert box, browse to select location and name to save the MP3 audio file.

*Click Start to convert WEBM to MP3 file.

Once the conversion process completes, access your MP3 file from the saved location.


text:
Q: How to prove this formula $ \sum_{k=2}^n k(k-1)\binom{k}{n} = n(n-1) \cdot 2^{n-2}$? $$ \sum_{k=2}^n k(k-1)\binom{k}{n} = n(n-1) \cdot 2^{n-2}$$

A: Observe that for all $ n\geq 2 $, $ k\in\left[\!\left[2,n\right]\!\right] $, we have : $$ k\left(k-1\right)\binom{n}{k}=n\left(n-1\right)\binom{n-2}{k-2} $$
Thus : \begin{aligned} \sum_{k=2}^{n}{k\left(k-1\right)\binom{n}{k}}&=n\left(n-1\right)\sum_{k=2}^{n}{\binom{n-2}{k-2}}\\ &=n\left(n-1\right)\sum_{k=0}^{n-2}{\binom{n-2}{k}}\\ &=n\left(n-1\right)2^{n-2} \end{aligned}

A: Hint: show that $k(k-1) \binom{n}{k}  = n(n-1) \binom{n-2}{k-2}$.


text:
Q: Parent table always inserted Duplicate rows I have following codes with transaction block.When i place a order my base table (TBL_T_Orders) always inserts 2 identical rows (duplicate rows with different OrderId's). Details table TBL_T_OrderItems correctly inserted the items.
My code
public CartTotal InsertNewOrder(CartTotal cartTotal)
{
            try
            {
                con.Open();

                transaction = con.BeginTransaction();

                string orderQuery = @"INSERT INTO [dbo].[TBL_T_Orders] ([OrderCode],[OrderReceivedDate])
                                      OUTPUT INSERTED.OrderId
                                      VALUES (@OrderCode, @OrderReceivedDate)";
                cmd = db.GetSqlStringCommand(orderQuery);
                cmd.Transaction = transaction;

                db.AddInParameter(cmd, "OrderCode", DbType.Int32, cartTotal.OrderCode);
                db.AddInParameter(cmd, "OrderReceivedDate", DbType.DateTime,DateTime.Now);

                db.ExecuteNonQuery(cmd, transaction);

                int OrderId = (int)cmd.ExecuteScalar();

                foreach (var item in cartTotal.items)
                {
                    string orderItemsQuery = @"INSERT INTO [dbo].[TBL_T_OrderItems] ([OrderId], [ItemId]
                                               VALUES (@OrderId, @ItemId)";

                    cmd = db.GetSqlStringCommand(orderItemsQuery);
                    cmd.Transaction = transaction;

                    db.AddInParameter(cmd, "OrderId", DbType.Int32, OrderId);//temp
                    db.AddInParameter(cmd, "ItemId", DbType.String, item.ItemId);

                    db.ExecuteNonQuery(cmd, transaction);
                }

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex;
            }
            finally
            {
                con.Close();
            }

            return cartTotal;
}

A: You are getting duplicate entries because you are executing query twice. First time with db.ExecuteNonQuery and then second time with cmd.ExecuteScalar();.
Remove first one db.ExecuteNonQuery line. Then it will work perfectly.


text:
Q: Kryonet/LibGdx received not called on client using android emulator, but works on device I'm using KryoNet with LibGdx to implement some network logic.
It works fine when running desktop client, and it also works when I test it on some Android devices, but on some others it does not work. It also does not work on an Android Emulator.
What exactly does not work is the received method in the Listener for client. Every other method in the Listener gets called, (connected, disconnected) so I know for sure the connection is up, but not received(Connection c, Object o).
It does work the other way around though, when the client sends a message to the server.
Please help, and if there is some specific code that could help, tell me and I'll gladly post it.
Edit: I was sending using UDP, but I changed it to TCP just to test, and then it worked fine. However, I'm making a game and I'm sending data quite frequently so I'd love to be able to use UDP. Anything I can do to try to understand what the issue is?


text:
Q: Android Geofencing with play-services-location 11.0.2 I'm trying to implement Geofencing on Android with the GooglePlayServices latest version.
I decided to use Geofencing because I need to know the user's location only when he moves, and I need something very low power consumption because my apps run in background 24/7.
In my code, the geofencing is not triggered if I don't implement the "requestLocationUpdates" of LocationServices. It is really weird because I read that normally we don't need to use this, and it is not low power consumption anymore with that.
Is someone ever implement geofencing with latest GooglePlayService and without implementing "requestLocationUpdates"?
My code :
Manifest:
<service
        android:name=".gps.GeofencingService"
        android:enabled="true"
        android:exported="true" />
    <receiver
        android:name=".gps.GeofenceReceiver"
        android:exported="true"
        >
        <intent-filter>
            <action android:name="android.location.MODE_CHANGED" />
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            <action android:name="android.location.PROVIDERS_CHANGED" />
        </intent-filter>
    </receiver>

Service :
public class GeofencingService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

//My singleton
private static GeofencingService mInstant;
public static GeofencingService getInstant(){
    return mInstant;
}

@Override
public void onCreate() {
    super.onCreate();
    mInstant = this;
    mFusedLocationClient = getFusedLocationProviderClient(this);
    mGeofencingClient = LocationServices.getGeofencingClient(this);
    buildGoogleApiClient();
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

public void addGeofence() {
    if (mGoogleApiClient.isConnected()) {

        LocationRequest mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(100); // Update location every second

        //use to initiate the geofence region on my position
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location != null) {
            mGeofenceList = new ArrayList();
            mGeofenceList.add(new Geofence.Builder()
                    // Set the request ID of the geofence. This is a string to identify this
                    // geofence.
                    .setRequestId(idGeofence)
                    .setCircularRegion(
                            location.getLatitude(),
                            location.getLongitude(),
                            Constantes.GEOFENCE_RADIUS_IN_METERS
                    )
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build());
            mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.d(TAG, "Geofence added");
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            // Failed to add geofences
                            Log.d(TAG, "Failed to add geofences");
                            e.printStackTrace();
                        }
                    });

    //if this line is removed, geofence is not triggered anymore
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //super.onStartCommand(intent, flags, startId);
    mGoogleApiClient.connect();
    return START_STICKY;
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "GoogleApiClient connected");
    addGeofence();
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "GoogleApiClient connection has been suspend");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i(TAG, "GoogleApiClient connection has failed");
}

public void getCurrentLocation() {
    //mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
    FusedLocationProviderClient locationClient = getFusedLocationProviderClient(this);
    locationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            // Got last known location. In some rare situations this can be null.
            if (location != null) {
                Log.d(TAG, location.getLatitude() + "/" + location.getLongitude());
            } else {

            }
        }
    });

}

 private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
//Call a BroadcastReceiver
    mGeofencePendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, GeofenceReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
    return mGeofencePendingIntent;
}

private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "Location Changed : " + location.getLatitude() + "/" + location.getLongitude());
}

}
Receiver :
public class GeofenceReceiver extends BroadcastReceiver {

protected static final String TAG = "GeofenceReceiver";

protected Context applicationContext;

@Override
public void onReceive(final Context context, final Intent intent) {
    applicationContext = context;
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        String errorMessage = GeofenceErrorMessages.getErrorString(context, geofencingEvent.getErrorCode());
        Log.e(TAG, errorMessage);
        return;
    }

    // Get the transition type.
    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    // Test that the reported transition was of interest.
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

        // Get the geofences that were triggered. A single event can trigger
        // multiple geofences.
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

        // Get the transition details as a String.
        String geofenceTransitionDetails = getGeofenceTransitionDetails(geofenceTransition, triggeringGeofences);
        Log.d(TAG, geofenceTransitionDetails);
        Toast.makeText(context, geofenceTransitionDetails, Toast.LENGTH_LONG).show();
        // Send notification and log the transition details.
        sendNotification(geofenceTransitionDetails);
        Log.i(TAG, geofenceTransitionDetails);
    } else {
        // Log the error.
        Log.e(TAG, context.getString(R.string.geofence_transition_invalid_type,
                geofenceTransition));
    }
}

}
Thanks for your help

A:
You don't have to call requestLocationUpdates for adding geoFence.

You only need a geofence with Location(Latitude,Longitude) to monitor.  And no need to use service (GeofencingService) for this. Use simple activity and attach mGeofencePendingIntent which will receive in GeofenceReceiver
It will notify you in GeofenceReceiver when you enter the fence with Geofence.GEOFENCE_TRANSITION_ENTER


text:
Q: Google Trusted Stores - confirm order without refresh page is it possible to confirm order on Google Trusted Stores without page refresh?
Conversion code looks like this:

MERCHANT_ORDER_ID
MERCHANT_ORDER_DOMAIN
CUSTOMER_EMAIL
CUSTOMER_COUNTRY
CURRENCY
ORDER_TOTAL
ORDER_DISCOUNTS
ORDER_SHIPPING
ORDER_TAX
ORDER_EST_SHIP_DATE
ORDER_EST_DELIVERY_DATE
HAS_BACKORDER_PREORDER
HAS_DIGITAL_GOODS

ITEM_NAME
ITEM_PRICE
ITEM_QUANTITY
ITEM_GOOGLE_SHOPPING_ID
ITEM_GOOGLE_SHOPPING_ACCOUNT_ID
ITEM_GOOGLE_SHOPPING_COUNTRY
ITEM_GOOGLE_SHOPPING_LANGUAGE

I have reactjs application. So if i put this code to DOM I need invoke api call to google. But I can't find any API for this.
Maybe triggering of window.onload but it could make very unexpected behaviour :(
Any ideas?
Thanks!

A: How about you create a popup instead, with iframe inside the popup? That iframe will contain the contents of Google Trusted Store codes.

A: A non iframe solution: If you dynamically reinject the google trusted stores html script tag, the script will search for the gts ids and invoke the pop up. For cleanliness, it is probably best to remove the current script tag before doing this. The script was not designed for SPAs.


text:
Q: sql view performance optimization I have a view which has the below definition
create view mydashboard as
SELECT distinct
       cu.CrimeID,
       ad.DeptID,
       ad.CrimeDate,
       cd.DeptIncidentID,
       ad.crime,
       u.username
from alldatescrimes ad
inner join crimeslist cl
on
ad.crime =  cl.crime
inner join users u
on
u.DeptID = ad.DeptID
left join crimelookup cu
on cu.CrimesListID = cl.CrimeListID
left join crimesdetail cd
on
ad.CrimeDate = cast(cd.CrimeDate as date)
and
ad.DeptID = cd.DeptID
and
cu.CrimeID = cd.CrimeID

My problem is that If I put a where clause outside the view, the query runs very slowly. See the below example
select *
from mydashboard
where

(username  = 'john'
or
DeptIncidentID is null
)
and
CrimeDate = '2014-06-16'

On the contrary If I put the same where clause inside the view, the query runs very fast..like in 2-3 seconds
My question is what steps can I take so that the query runs fast if I put the where clause outside view. I am using this view in a report and the query runs real slow
Regards
Arif

A: MySQL has two options to process a view that is used inside a query: MERGE or TEMPTABLE.

For MERGE, the text of a statement that refers to the view and the view definition are merged such that parts of the view definition replace corresponding parts of the statement.
For TEMPTABLE, the results from the view are retrieved into a temporary table, which then is used to execute the statement.

Because of the DISTINCT clause in the view definition, MySQL cannot use the MERGE algorithm. It must falback to the less efficient TEMPTABLE algorithm.
The temporary table has no index, therefore the whole table must be scanned to process your outer WHERE conditions.
You may want to remove the DISTINCT clause from the view definition, and put it in your outer query instead.

A: This is a bit long for a comment.
MySQL does a poor job of optimizing views.  In fact, one part of the documentation starts:

View processing is not optimized:

One possible issue is that MySQL has determined that a temporary table is needed for the view.  If so, all the processing needs to be done.  Then at the very last stage, the where clause is being added.  Here is more information on "merge" versus "temporary tables" for views.


text:
Q: How to exclude San and Sat from matplotlib graph? I have pandas DataFrame like this:
2013-09-13 20:51:00
2013-09-13 20:52:00
2013-09-13 20:53:00
2013-09-13 20:54:00
2013-09-13 20:55:00
2013-09-13 20:56:00
2013-09-13 20:57:00
2013-09-13 20:58:00
2013-09-13 20:59:00
2013-09-16 00:00:00
2013-09-16 00:01:00
2013-09-16 00:02:00
2013-09-16 00:03:00
2013-09-16 00:04:00
2013-09-16 00:05:00
2013-09-16 00:06:00
2013-09-16 00:07:00
2013-09-16 00:08:00

there is no Sun and Sat date. Matplotlib pyplot draws so:

Is it possible to crop the image except emty date? Like this:

A: If you plot a series with null values (or a masked array) in matplotlib, the line will be broken at the location of the nulls.
For example:
import matplotlib.pyplot as plt
import numpy as np

plt.plot([1, 2, 3, np.nan, np.nan, 6, 7, 8, 9])
plt.show()

Therefore, what you want to do is add NaN's for the weekend dates.  pandas offers a few different ways to do this.  There's an overview here, but basically you want to look at the asfreq and resample methods.
As an example with your dates:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dates = """2013-09-13 20:51:00
2013-09-13 20:52:00
2013-09-13 20:53:00
2013-09-13 20:54:00
2013-09-13 20:55:00
2013-09-13 20:56:00
2013-09-13 20:57:00
2013-09-13 20:58:00
2013-09-13 20:59:00
2013-09-16 00:00:00
2013-09-16 00:01:00
2013-09-16 00:02:00
2013-09-16 00:03:00
2013-09-16 00:04:00
2013-09-16 00:05:00
2013-09-16 00:06:00
2013-09-16 00:07:00
2013-09-16 00:08:00"""
dates = pd.to_datetime(dates.split('\n'))

# Generate some random y-data...
y = (np.random.random(dates.size) - 0.5).cumsum()

# Resample to a regular 1-minute interval series
# By default, this will put NaNs in where there isn't any data...
data = pd.Series(y, index=dates).asfreq('1Min')

data.plot().set(title='Resampled data')
plt.show()


text:
Q: Why doesn't infrared slavery provide a proof for quark confinement? It is well known how and why the running coupling of QCD grows as we reduce energy or equivalently increase distance. Hence, if the effective color charge increases with distance then why doesn't this infrared slavery fully explain quark confinement?

A: Confinement is not about the running coupling. By confinement we mean a qualitative change - a phase transition - in how the physics between two quarks works compared to e.g. two electrons.
In particular, confinement is the phenomenon that, in the confining phase, the force between two quark rises linearly with the distance between them, or at least that the energy required to separate two quarks is infinite. No amount of running coupling can explain this, since this is not related to the value of a coupling at all, but to the the functional form of the force law/free energy functional.
To see that a running coupling cannot explain this, consider the traditional force law in QED (i.e. Coulomb's law), then crank up the coupling. No matter how high the coupling goes, the energy required to separate two oppositely charged particles is finite.
The traditional lattice treatment (see also this answer of mine) identifies the Polyakov loop's expectation value as the order parameter of the confining/deconfining phase transition, and the Polyakov loop is essentially (and a bit handwavingly) the exponential of $-E$, where $E$ is the energy required to separate a two-quark system. As long as the Polyakov loop is zero, $E$ is infinite, i.e. the quarks are confined.

A: (I am reproducing and elaborating on my comments above here as an Answer at the request of @Diracology, and take the opportunity to clarify some other comments.)
We only know about that running of the QCD coupling in perturbation theory. It confirms the idea of asymptotic freedom which early experiments had indicated, and for which Noble prizes were awarded. That such a running is a physical phenomenon is summarised by data in this paper.
However, we do not know if the coupling will keep getting stronger at low energies (long distances) beyond the perturbative domain in which we can do reliable calculations.  If indeed the effective coupling keeps getting stronger, it is possible that strong interaction dynamics might lead to a dramatic change (phase transition) to a novel state of the system.
So to study the strong coupling domain we need non-perturbative tools, such as lattice gauge theory, or some toy models.
Indeed, lattice gauge theory indicates that QCD has a confining phase, characterised by a linear quark potential similar to what one finds in lower dimensional analytic models.
One physical picture for quark confinement is the t'Hooft-Mandelstam "monopole condesation" leading to a "dual superconductor" whereby colour electric flux forms strings between charges, leading to a linear confining potential (Recall that in the usual Meissner effect in superconductors the condensation of electric charges (Cooper pairs) leads to magnetic flux tubes).
Seiberg and Witten illustrated the monopole codensation idea for confinement in a SUSY model of QCD, adding support to a similar idea in usual QCD.
In summary, confinement in QCD seems to be associated with a different phase from that which we associate with the asymptotic freedom perturbative calculations. But it is unclear (to me at least) how much of a role the strong coupling dynamics plays in the transition to the confinement phase.
**As an aside, there are many ways of interpreting and calculating the beta function beyond what is done in textbooks which usually discuss it in the context of renormalisation (usual or Wilsonian). The running of the beta function with energy scale can be physically interpreted in position space (and also calculated, if you like. I am sure someone must have done it) as the effective interaction between a source charge and a probe charge, just like in Coulomb's law. The vacuum is polarised by virtual particles in QFT and so the effective interaction changes.
Indeed in this picture its easy to see that the effective charge will depend on the distance between the source and probe. So the beta function can also be interpreted as telling us how the effective charges vary with distance between the charges.
If you want to amuse yourself, you can also calculate the same beta function by looking at the interaction of the charge with an external magnetic field, which provides the clearest physical picture of why spin one is different from spin 1/2 or spin 0. See this paper by Nielsen.
The basic reason why all the different methods give the same beta function is that deep down it physically corresponds to the effective interaction between charges. It does not matter whether you calculate it in momentum space or position space or between a charge and a current carrying wire, or between a charge and a external field etc.


text:
Q: How to compare the value of two selects in Javascript with dynamic content using javascript I currently have these two conditions that must be met for a modal to display on screen:
if($("#id_form-0-calculated").val() === $("#id_form-0-modified").val()) {
  if($("#id_form-0-calculated").val() === $("#id_form-0-modified").val()) {
    $("#Modal").modal();
  }
}

This works perfectly for the first element (N = 0), the problem is that the web page I am editing can have N elements with the following pattern:
id_form-N-calculated / id_form-N-modified
How could I make the if statements dynamic and work for all existing N values instead of just one static value?

A: I don't know how will you do this, but I regularly use the following:
var N = 0;

if($("#id_form-"+N+"-calculated_ad_pathogenicity").val() === $("#id_form-"+N+"-modified_ad_pathogenicity").val()) {
   if($("#id_form-"+N+"-calculated_ar_pathogenicity").val() === $("#id_form-"+N+"-modified_ar_pathogenicity").val()) {
      $("#Modal").modal();
   }
}

Most of the time, N is used in either loops or functions.

A: You could write a function something like
function check(n){
    if($("#id_form-" + n + "-calculated_ad_pathogenicity").val() === $("#id_form-" + n + "-modified_ad_pathogenicity").val()) {
      if($("#id_form-" + n + "-calculated_ar_pathogenicity").val() === $("#id_form-" + n + "-modified_ar_pathogenicity").val()) {
        $("#Modal").modal();
      }
    }
}

Adding it to the checking flow. For example
const n = 4;

for(let i = 0; i < n; i++){
     check(i);
}


text:
Q: Using count for counting sets of values of integer column I am fairly new to the world of SQL. I would like to know how many stores are at each location based on the location_id. I know for a fact that count is going to be needed. When i run the query below i get no results due to an error?
SELECT COUNT(location_id) FROM stores
Table:
stores

ID Location_id Store_Name
-- ----------- ----------
1      1         Example1
2      1         Example2
3      2         Example3
4      2         Example4

A: select  Location_id,count(Store_Name)
from stores
group by Location_id

This query will return the Location_Id followed by number of stores in that location for each location.

A: You have to group the records by location and count them. You can use most aggregate functions with group by statement .
 SELECT LOCATION_ID, COUNT(*) FROM stores GROUP BY LOCATION_ID

A: SELECT Location_id, COUNT(Store_Name) as count FROM stores
group by Location_id


text:
Q: Messed-up GUI: Lot of Blank Space Please have a look at the following code
package email;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SendEmail extends JDialog
{
    private JLabel to, cc, bcc, subject, account;
    private JTextField toTxt, ccTxt, bccTxt, subjectTxt;
    private JTextArea messageTxt;
    private JButton send;

    private JComboBox accountBox;

    private JScrollPane scroll;

    private GridBagLayout gbl;
    private GridBagConstraints gbc;

    public SendEmail()
    {
        //Declaring instance variables
        to = new JLabel("To: ");
        cc = new JLabel("CC: ");
        bcc = new JLabel("BCC: ");
        subject = new JLabel("Subject: ");
        account = new JLabel("Select an Account: ");

        toTxt = new JTextField(20);
        ccTxt = new JTextField(20);
        bccTxt = new JTextField(20);
        subjectTxt = new JTextField(20);

        messageTxt = new JTextArea(500,500);
        scroll = new JScrollPane(messageTxt);

        accountBox = new JComboBox();
        accountBox.addItem("Yahoo");
        accountBox.addItem("GMail");
        accountBox.addItem("MSN");
        //accountBox.addItem("Yahoo");
        //accountBox.addItem("Yahoo");

        //Creating thr GUI
        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();

        this.setLayout(gbl);

        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(account,gbc);

        gbc.gridx = 2;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(accountBox,gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(to,gbc);

        gbc.gridx = 2;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(toTxt,gbc);

        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(bcc,gbc);

        gbc.gridx = 2;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(bccTxt,gbc);

        gbc.gridx = 1;
        gbc.gridy = 4;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(cc,gbc);

        gbc.gridx = 2;
        gbc.gridy = 4;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(ccTxt,gbc);

        gbc.gridx = 1;
        gbc.gridy = 5;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(subject,gbc);

        gbc.gridx = 2;
        gbc.gridy = 5;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(subjectTxt,gbc);

        gbc.gridx = 1;
        gbc.gridy = 6;
        gbc.fill = GridBagConstraints.BOTH;
        this.add(scroll,gbc);

        this.setSize(new Dimension(200,500));
        this.setVisible(true);

    }
}

In here, the GUI seems very bad. I need to have enough space for all the fields. In the JTextArea, you can see it is not even visible. I need it's height to be 2 columns; it seems like all these problems are occurring because it is trying to set the large JTextArea to one column. For your information, this is an "Compose Email" GUI, so you can be clear of what I am asking. I used this.pack() but it made everything worst!

A: As I mentioned above in the comments:

Don't call setSize(). Instead pack() the GUI and let the component's natural preferred sizes and the layouts dictate the size of the GUI. If pack() makes things worse, then you should fix the problem from that side of things, not by calling setSize().

For instance, I would

*

*make the JTextArea a reasonable size, not 500 rows by 500 cols!

*Don't set size of things

*Do call pack()

*Don't forget to use weightx and weighty (added to the code) and insets (not yet added).

*Avoid magic numbers.

*Consider nesting easier to use layouts and minimizing use of GridBagLayout.

*Give the JScrollPane extra gridwidth to allow it to fill up the bottom.  For instance:

SendEmail.java:
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;

@SuppressWarnings("serial")
public class SendEmail extends JDialog {
   public final static String[] LABEL_TEXTS = { "Select an Account:", "To:",
         "BCC:", "CC:", "Subject:" };
   public final static String[] ACCOUNT_TEXTS = { "Yahoo", "GMail", "MSN" };
   private static final int TEXT_FIELD_LENGTH = 20;
   private static final int T_AREA_ROWS = 20;
   private static final int T_AREA_COLS = 50;
   private static final int INSET_GAP = 1;
   private static final int RIGHT_INSET_GAP = 15;
   private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
   private JTextArea messageTxt;
   private JButton send;

   private JComboBox<String> accountBox;

   private JScrollPane scroll;

   public SendEmail(JFrame frame) {
      super(frame, "Dialog", true);
      messageTxt = new JTextArea(T_AREA_ROWS, T_AREA_COLS);
      scroll = new JScrollPane(messageTxt);
      accountBox = new JComboBox<String>(ACCOUNT_TEXTS);

      this.setLayout(new GridBagLayout());
      int ebGap = 5;
      ((JPanel) getContentPane()).setBorder(BorderFactory.createEmptyBorder(
            ebGap, ebGap, ebGap, ebGap));

      for (int i = 0; i < LABEL_TEXTS.length; i++) {
         JLabel label = new JLabel(LABEL_TEXTS[i]);
         addLabel(0, i, label);

         if (i == 0) {
            addField(1, i, accountBox);
         } else {
            JTextField tField = new JTextField(TEXT_FIELD_LENGTH);
            fieldMap.put(LABEL_TEXTS[i], tField);
            addField(1, i, tField);
         }
      }

      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = LABEL_TEXTS.length;
      gbc.gridwidth = 2;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.insets = new Insets(INSET_GAP, INSET_GAP, INSET_GAP, INSET_GAP);
      this.add(scroll, gbc);

      pack();
      this.setVisible(true);
   }

   private void addField(int x, int y, JComponent comp) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.weightx = 1.0;
      gbc.weighty = 0.0;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.insets = new Insets(INSET_GAP, INSET_GAP, INSET_GAP, INSET_GAP);
      gbc.anchor = GridBagConstraints.EAST;

      this.add(comp, gbc);
   }

   private void addLabel(int x, int y, JComponent comp) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.weightx = 0.0;
      gbc.weighty = 0.0;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.insets = new Insets(INSET_GAP, INSET_GAP, INSET_GAP, RIGHT_INSET_GAP);
      gbc.anchor = GridBagConstraints.EAST;

      this.add(comp, gbc);
   }

   public String getTextFieldText(String key) {
      JTextField tField = fieldMap.get(key);
      if (tField == null) {
         String text = "key, " + key + " not a valid argument for fieldMap";
         throw new IllegalArgumentException(text);
      }

      return tField.getText();
   }

   public String getAccountText() {
      return accountBox.getSelectedItem().toString();
   }

   public String getMessageTxt() {
      return messageTxt.getText();
   }

   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      new SendEmail(frame);
      frame.dispose();
   }
}

which when run would look like:


text:
Q: Stochastic dynamics of rotation intergral over $d\hat n$? I am looking into the stochastic dynamics of rotation in which we describe the orientation with a unit vector $\hat n$. If we let $p(\hat n',t)$ denote the probability that $\hat n=\hat n'$ at time $t$ then the mean value of $\hat n$ at $t$ is given by:
$$\int p(\hat n',t) \hat n' d\hat n'$$
Working in 3d - my question is should I interpret the integral over $d\hat n'$? Is it equivalent to an integral over solid angle? An explicit example would be useful.

A: I would personally express $\hat n$ using spherical coordinates and then consider the average of the angles:
$$\hat n = (\sin \theta \cos \phi,\sin \theta \sin \phi, \cos \theta) = n_1 \hat x + n_2 \hat y + n_3 \hat z $$
The integral over $\hat n$ is therefore replaced by an integral over $\theta$ and $\phi$, which is just an integral over the solid angle.
For a general quantity $Q$, you have
$$\langle Q (\theta, \phi) \rangle_{\theta, \phi} = \int_0^{2 \pi} d \phi \int_0^{\pi}  p(\theta,\phi) \ Q(\theta,\phi)\  \sin \theta d \theta$$
The average values of the components of $\hat  n$ are
$$\langle n_1 \rangle= \int_0^{2 \pi}\cos \phi d \phi \int_0^{\pi} p(\theta,\phi) \cdot \sin^2 \theta d \theta$$
$$\langle n_2 \rangle= \int_0^{2 \pi}\sin \phi d \phi \int_0^{\pi} p(\theta,\phi) \cdot \sin^2 \theta d \theta$$
$$\langle n_3\rangle = \int_0^{2 \pi} d \phi \int_0^{\pi} p(\theta,\phi) \cdot \sin \theta \cos \theta d \theta$$
In case the distribution is uniform, then
$$p(\theta, \phi) = \frac 1 {4 \pi}$$
In this case, $\langle n_{1,2,3} \rangle = 0$.


text:
Q: What is the way to prevent the cream from settling on the surface of hot milk with least manual labour? I have seen Cooling a cup of coffee with help of a spoon but that question has a restriction of using only a spoon.
My problem is that I have to boil the milk before pouring it in the bottle for the toddler and I don't want the cream to settle on the surface of the milk because then I have to put the cream aside and give plain milk to the toddler.
I saw that if I constantly keep on string the milk till it cools, I can prevent the cream from settling.
I have tried the spoon method. It works, but it takes a considerable amount of effort to cool 500 ml milk with a spoon.
What is the other way out provided we can all the kitchen utencils (i.e. spoons, spatulas, bowls etc.)?

A: Cream separates from milk because it forms large globules which rise to the surface.  You can prevent this by homogenizing the milk and cream so they form a colloid, in which smaller particles of cream are distributed evenly throughout the milk.
You can buy a hand-held homogenizer for $500.  Or, if that's too much to spend, try a home juicer to see if it can reduce the cream globules to colloid size and disperse them evenly throughout the milk.  If you run the milk and cream through a juicer prior to boiling, it may remain in a colloid state long enough to come to a boil without separating.  This should be tested to see if the juicer turns the milk fat to butter, or succeeds in reducing it to a colloid.
If the milk fat globules are ruptured, they may be partially digested by the enzyme lipase in the milk, which could lead to rancidity.  However, lipase is deactivated by heat, so the milk should be boiled either prior to or immediately upon homogenization.

A: This is an attempt at an answer to an older version of the question, where the focus lay only on cooling the milk as fast as possible.

This is only a partial answer - I have no idea whether my "method" is the fastest.
Heat transfer can be done in three ways: convection, conduction and radiation. We cannot really influence radiation, but it doesn't help much anyway (the temperatures are too small). Roughly, thermal conductivity is governed by Fourier's law, which tells us that the local heat flux $q$ is roughly
$$ q= k\nabla T$$
where $\nabla T$ is the temperature gradient and $k$ is a constant depending on the material where the flux occurs (thermal transmissivity).
Therefore, we can influence conduction by
a) bringing the milk into contact with a material with high thermal conductivity (such that conduction is accelerated)
b) cooling this contact material as far down as possible
c) making the contact surface as large as possible
The third is necessary, because we cannot really influence the thermal transmissivity of milk. Even if the material in contact with the milk has infinite thermal transmissivity, this would just mean that regions closest to that material would be cold immediately and regions far away would still be warm and cool according to the conductivity of milk. Of course, we can remedy this by introducing a current, therefore introducing convection (i.e.: we can stirr).
Based on a)-c) and the common sense assumption that you don't want to create a total mess and you don't want to contaminate the milk (albeit what that means can vary), here is a suggestion:
(Maybe) fastest method: Buy a baking tray (copper would be ideal, but I'm not sure these exist. It seems to be best from pure alluminium, if this is safe, but stainless steel seems fine - here is a list of thermal conductivities), put it in your icebox and when you want to cool your milk, get it out, pour the milk onto the baking tray and maybe stirr a little (however, if the baking tray is large enough, the surface area of the 500ml of milk should be enlarged enough) and then recollect the cooled milk in your bottle.
However, there is a problem: While the thermal conductivity of metal is pretty good, its thermal capacity is very low compared to water (and therefore milk). This means that while the temperature exchange will be mostly instantaneous, it might not be enough to cool the whole bottle. Here is a back-of-the-envelope calculation: Heat capacity of water is about four times that of stainless steel (link). Temperature of the ice box is maybe -15°C and the milk would maybe be at 90°C when you get it out of the bottle. Therefore, in order to cool it to 30°C, i.e. the gradient is 60° for the milk and 45° for steel. This would mean that you need more than five times the amount of milk in steel (i.e. 2.5-3kg), which seems too much for a baking tray - and this ignores the fact that the temperatures will not instantly equilibrate, since the flux depends on the gradient.
Thus, you'd maybe need to cool the steel - preferably with water, because this is available (supposedly) in larger cold quantities. One way seems to be to spray the baking tray with cold water from below, but this could create a mess. Another way would be to hold the lower side in a bath of cold water. Therefore, here is the second method:
Method with more cooling power: We use our baking tray as above, but we also have a second vessel (maybe a larger baking tray) with cold water and we hold the baking tray in the cold water and maybe even stirr the cold water.
This however might be very cumbersome. So here's another proposition:
Slower, but enough cooling power: Don't pour the milk into a bottle, put it into some vessel which is very narrow or somehow far away from cylindrical or round form such that the volume to surface ratio is large (maybe some flask or a small bag that you can close) and completely submerge the vessel in cold water. Wave it around a bit and it should be cold quite fast. With this method, you won't get the thermal gradient and conductivity of the baking tray (however, water is still way better at conducting heat than air - see the list linked above), but since you cool water with water, a few litres of cold water will definitely be sufficient to cool the milk without heating up too quickly.

A: The scientific process you need to complete is homogenization.
In your case when the fat {cream} separates from the water in the milk by boiling. Once boiled you want to break down the fat quickly so it re-emulsifies with the water. Homogenization breaks the fat into smaller sizes so it no longer separates from the water. A small hand held ultrasonic homogenizer would work best in your case. But since it is not in ones usual set of kitchen appliances I would try the following.
Try using egg beaters at a slow speed not fast because you don't want to put too much air into the liquids. Put the boiling whole milk in a bowl and beat it slowly to break down the fat. A whisk or spoon could also work. This will break up the fat\cream and keep it in suspension with the milk. Placing it in a cooling bowl will also cause the heat to dissipate more quickly due to the cold water heat sink. Just make sure you don't beat it too fast and probably don't want to cool it until fully emulsified. This should help you transfer the manual task of stirring to a more mechanized approach in shorter time frame. Once the milk is warm, fill your bottle, test for temperature and feed your toddler. Also make sure the toddler is 12 months or older. Whole Cow milk has a number of proteins and minerals that can damage a younger child's\babies kidneys and in turn lead to a number of unwanted health complications.
Using an egg whisk at slow speed could do the same but with a little more manual work. Certainly/Probably more effective than a spoon. You need to get the fat back emulsified in the solution. If it is too cold the fat won't break up efficiently so homogenization will work better when the liquids are hot to warm not cold.
Also another point you may not have thought of. You probably do not need to boil the whole milk to begin with since the whole milk was probably already pasteurized {and all of the pathogens and microbes killed} prior to sale. Just warm it up to a comfortable level for the toddler. This is usually what one wants to do.
Additional Information :
Homogenization or homogenisation is any of several processes used to make a mixture of two mutually non-soluble liquids the same throughout. This is achieved by turning one of the liquids into a state consisting of extremely small particles distributed uniformly throughout the other liquid. A typical example is the homogenization of milk, where the milk fat globules are reduced in size and dispersed uniformly through the rest of the milk.
In Kitchen Parlance :
Mixing is a general term that includes stirring, beating, blending, binding, creaming, whipping and folding. In mixing, two or more ingredients are evenly dispersed in one another until they become one product. Each mixing method gives a different texture and character to the baked good. The implements used, such as blades, whisks, spoons, etc., themselves make a difference. They have a great impact on what happens during mixing.
STIR: This method is the simplest, as it involves mixing all the ingredients together with a utensil, usually a spoon, using a circular motion.
BEAT: The ingredients are moved vigorously in a back and forth, up and down, and around and around motion until they are smooth. An electric mixer is often used to beat the ingredients together. {Just don't add to much air by beating to vigorously and fast.}
BLEND: Ingredients are mixed so thoroughly they become one.
One last suggestion. One might try cheese cloth to achieve an alternative homogenization process. A homogenization process usually tries to keep much of the air out and forces the fat globules through small screen like openings to break the fat down so it is small enough to stay in solution. Cheese cloth with small apertures may work as the screen. Placing the boiled milk in the cheese cloth shaped like a cone or pouring it over the cheese cloth and a bowl and paying attention not to get burnt one could conceivably squeeze or force the liquids the fat and milk water through the cloth {of proper size, it is usually available in a number of sizes} and then stir up the resultant mixture in the bowl into a suitable mixture to fill the baby bottle for feeding. Since the process would take some time to complete enough heat should dissipate so that the temperature is sufficiently warm. If not place the bottle in an ice bath till proper temperature is reached.

A: Use a magnetic stirrer and hotplate. That way you will not let the cream/fat separate out during heating. After heating and stirring at same time, once boiling is reached, place heated milk in bottle and place in ice water bath to cool quickly to appropriate temperature.
See link how to DIY http://www.instructables.com/id/Magnetic-Stirrer-w-Hotplate-for-30/


text:
Q: Layout theory for a thumbnail gallery I am in the process of creating a thumbnail gallery exactly like this (http://tmv.proto.jp/#!/destroyftw). Currently I am trying to work out the theory for the scripting. The actual script for the webpage is here (http://tmv.proto.jp/tmv_v3.js). As I am relatively new to javascript this has caused me some frustration.
I have already tried using plugins such as masonry and isotope, but they are unable to handle massive amounts of images. Not to mention that infinite scroll doesn't work with filtering, which I need. So I decided to try my hand at coding one myself.
The idea is that user submitted images will be resized to thumbnails with a set width (height will of course be scaled to maintain aspect ratio). Then those thumbnails will be used to create the gallery. The problem I'm having is that the layout, I find, is a little tricky.
It appears that the page is first divided into columns to form the first "row". After that the thumbnails are place into the shortest column that is furthest to the left (Specifically, I'd like to know the theory behind this particular image positioning technique.).  Ex: The numbers can also be understood as the image's id. (id="i_1",id="i_2"etc...)

This also causes the cascading fade-in effect that the page does onload and when new images are appended (they're simply fading in according to their id's).
I have tried to use the above script page as a reference to no avail. But if anyone would like to check for themselves the functions that I believe are responsible for the thumbnail positioning are under "ViewManager".
Just to reiterate, I am not looking for someone to do my work for me. I just need help working out the theory so I will have somewhere to start.
**Note**(In the script): cellSize= 100; cellMargin=1; doubleSize=201 (cellSize*2+cellMargin); totalCellSize=101 (cellSize+cellMargin);

A: The technique works exactly as you described:
fill the first (from the left or right, doesn't matter) shortest column

The part about finding the first shortest is necessary as a tie-breaker in case there are several columns of the same length and all of them are the shortest.
The part about filling in the shortest first is obvious: doing it otherwise would cause blank white space to randomly accumulate.
To understand why the columns are necessary you have to first understand how the  tag works in HTML:
The  tag
From the earliest days, HTML was supposed to be a way to format text. So when images was introduced it was designed to be placed inline with the text without any fancy layout (css later allows you to do fancy layout). The height of an image always occupies a line of text. So for example this:

  text text text
  text  text
  text text text

ends up looking like this:
text text text
     .------.
     | img  |
     |      |
text '______' text
text text text

Notice that the height of the second line is automatically increased to fit the image.
Image gallery layout problems and solutions
So, a series of image tags with different heights like this:

may end up looking like this:
 ______
|      |           ______
|      |  ______  |      |
|      | |      | |      |
'______' '______' '______'
          ______
 ______  |      |  ______
|      | |      | |      |
|      | |      | |      |
'______' '______' '______'
                   ______
 ______           |      |
|      |  ______  |      |
|      | |      | |      |
'______' '______' '______'

..with ugly gaps of blank space.
One solution to this is to use CSS floats. But experienced developers would recognize me typing the words "float" and "css" together and recall nightmares of trying to get multiple floats to play nice with each other.
Another solution (which I often use) is to fix the height of the images instead of the width and let the images flow normally. This often leads to layouts that looks something like this:
 _______   _______   ______
|       | |       | |      |
|       | |       | |      |
'_______' '_______' '______'
 ______   ____   ________
|      | |    | |        |
|      | |    | |        |
'______' '____' '________'
 _____   ______   ___________
|     | |      | |           |
|     | |      | |           |
'_____' '______' '___________'

Which is a lot better since it gets rid of a lot of the blank gaps. But the problem with this is the uneven right edge of the gallery which some people don't like.
The column solution
Which leads us to the solution you've come accross. Use HTML elements like
s or
s to group the images into columns and place the images into the columns using the above stated algorithm. You'll still end up with an uneven edge but at least it's at the bottom of the gallery which is preferable to some people.

A: Have a look at
var fixedwidth = 50 + 1, //the +1 is for 1px horizontal margin
    gallery = $('#gallery'), // cache a reference to our container
    imagelist = gallery.children(); // cache a reference to our image list

function layoutImages(){
    var columncount = parseInt(gallery.width()/fixedwidth,10),  // find how many columns fit in container
        columns = [];

    for (var i =0;i<columncount;i++){ // initialize columns (0 height for each)
        columns.push(0);
    }

    imagelist.each(function(i,image){
         var min = Math.min.apply(null, columns), // find height of shortest column
             index = columns.indexOf(min), // find column number with the min height
             x = index*fixedwidth; // calculate horizontal position of current image based on column it belongs

        columns[index] += image.height +1; //calculate new height of column (+1 for 1px vertical margin)
        $(image).css({left:x, top:min}).delay(i*200).animate({opacity:1},100); // assign new position to image and show it
    });
}

$(window).resize(layoutImages).trigger('resize');

Demo at http://jsfiddle.net/gaby/DL8Vr/6/

Assumptions

*

*50 pixels fixed width for each image (parameterized by the fixedwidth variable)

*all images are in a common container (with id gallery in this case)

The demo has some CSS animations, and also repositions the images when the window is resized..
Demo html

    ....

Demo css
#gallery{
    position:relative;
    width:100%;
}
#gallery img{
    position:absolute;
    -ms-transition:all 1s;
    -o-transition:all 1s;
    -webkit-transition:all 1s;
    -moz-transition:all 1s;
    transition:all 1s;
    opacity:0;
}


text:
Q: Run task before applying plugin build.gradle? Is it possible to run a task before applying a plugin in a build.gradle file?
Say I have the following code:
apply plugin: 'my-plugin'

task myTask(type: Exec) {

}

How do I ensure myTask runs before my-plugin is applied?


text:
Q: How to fetch data in background every hour in Swift even the app is terminated? I am making an app that provides functionality to fetch data every hour. It fetches data even when the app terminates. How can I implement this functionality?
After a lot searching I found background fetching using performFetchWithCompletionHandler. Will this function work even if my app terminates? What I mean is if my app is in closed or terminated state, can I call this function automatically?

A: You can't do anything if your app is in terminated state. Apple is not allowing anything (except receiving notification) in terminated or closed state.
You are also restricted for background execution also.
You can perform specific kind of task in background mode like : Location update,Music playing, VOIP, finite length task, Newsstand downloads, etc. You can refer apple documentation for more details about background execution.
Hope this will help :)

A: Once I needed this same when I was working on some project, unfortunately I didn't
find any solution for it.
You can run a task when your app is in Background state(that too with limited services) but apple doesn't allow to run a task when app is Terminated
Please go through the link.
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
and this is for background running.
Sending Latitude and Longitude to Server when app is in background

A: Your app is terminated once it will not do any kind of task related to it.
Apple Doesn't support it.
You can not call Functions when your app is not running.
So it's not possible Due to apple rules.
performFetchWithCompletionHandler is only work when your app is running if your application is terminated it will not perform any kind of task.

A: From what i have experienced:
First of all the timer will stop when the app goes to the background to stop fast battery drainage and expand the lifetime of the battery even to save network bundles quota consumption while you are not actively using the app.
You can do background fetch tasks by adding the following in the AppDelagate "as you mentioned":
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    //Do whatever you need
    //This will keep running for max 3 mins
}

But the same is for background fetch tasks. You have got maximum 3 min of background activity except for Locations services, Audio playing, VOIP and some other tasks.
I really don't know the use and the functionality of the app and why do you need to grab data from the server every 1hr if the app is already closed and the user is not concerned about seeing the updated data.
But if this data is important to be updated every hour and need to notify the user with the updates "for instance checking the status of a certain event on the server, like making a chat app and the user received a message".
Then it is better to send a remote push notification to the user from the server upon a certain event taking place and this will make the user get the app again on the foreground and the app will start fetching the updated data "in my case here the message".

A: you can find location in app terminated state, after significantly change in location like about 500 meter.
here is working example
http://mobileoop.com/getting-location-updates-for-ios-7-and-8-when-the-app-is-killedterminatedsuspended
but what I am stuck at is post location through webservice.

A: @Jack.Right you can call the method after every 1 hour so use NSTimeinterval it would be helpful!!
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication *app = [UIApplication sharedApplication];

    //create new uiBackgroundTask
    __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    //and create new timer with async call:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //run function methodRunAfterBackground
        NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(methodRunAfterBackground) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });
}


text:
Q: Published content not displaying, getting not found message I am posting data in wordpress but after click on public it is showing

This is somewhat embarrassing, isn't it?
  It seems we can't find what you're looking for. Perhaps searching, or one of the links below, can help.

I dont have any idea how to resolve this. I am using wordpress4.1
Screenshots

After click on publish

A: Please reset your permalink. Go to http://yourdomain.com/wp-admin/options-permalink.php and just click Save Changes button.
Edited:
Try these steps:

*

*Make sure the homepage exists. Go to Settings > Reading options, see which page is used for homepage and check this page's status.

*Update WordPress. Keep backup before you proceed.

*Check each of the plugins. Deactivate and re-activate one by one and see what happens.

*It may happen that modSecuriy process is checking the wp-admin and
the input of data. Edit the modsecurity whitelist-

vi /usr/local/apache/conf/modsec2/whitelist.conf
Add this code
<LocationMatch "/wp-admin/*">
  SecRuleEngine Off
</LocationMatch>
then restart apache. /etc/init.d/httpd restart

A: This is can be because of following reasons.
1.Premalink problem.
Go to settings -> permalinks and set to default. save and check if post is now showing.
If its working fine then reset premalink structure to desired one (like postname), save and check.
2.rewrite problem in .htaccess file
Check if url is re-written in htaccess file or if it is then it rewrite rule is proper.
3.Url rewrite from functions.php file
Check if urls are overridden in function.php file.
4.Post is in draft or not set to public

A: Goto settings -> permalinks option and change the common settings. Check the post again.
If this does not work then check the .htaccess file.

A: Did you enable WP_Debug ?

*

*Go to File Manager.

*Locate the wp-config.php file for your WordPress website.

*Click Edit for the wp-config.php file.

*To enable WP_Debug, add the following code to the end of the file:
/**
* WordPress Debugging
*
* Set to "true" to enable wp_debug. Set to "false" to disable.
* Do not include quotes when setting to "true" or "false".
*/
define( 'WP_DEBUG', true );

A: Well i had something similar and i was banging my head why when i was editing an existing post it was fine but when i was doing one on my own it was simple ... " not found "
The "key" is the slug, since i am from Greece , using Greek letters for my posts and subsequently the slug was "getting" the Greek heading it would simply won't work.
Changing slug to Latin letters was the key to "success"