text:
Q: Slow bulk_save_objects in Sqlalchemy So I'm having an issue with a very slow insert, I'm inserting 223 items and it takes 20+ seconds to execute. Any advice on what I'm doing wrong and why it would be so slow? Using Postgresql 9.4.8
Here's the table schema:
                                   Table "public.trial_locations"
   Column    |          Type          |                          Modifiers
-------------+------------------------+--------------------------------------------------------------
 id          | integer                | not null default nextval('trial_locations_id_seq'::regclass)
 status      | character varying(255) |
 trial_id    | integer                |
 location_id | integer                |
 active      | boolean                |
Indexes:
    "trial_locations_pkey" PRIMARY KEY, btree (id)
    "trial_locations_unique_1" UNIQUE CONSTRAINT, btree (trial_id, location_id)
Foreign-key constraints:
    "trial_locations_location_id_fkey" FOREIGN KEY (location_id) REFERENCES locations(id)
    "trial_locations_trial_id_fkey" FOREIGN KEY (trial_id) REFERENCES trials(id)

The line of code
for key, unique_new_location in unique_locations_hash.iteritems():
        trial_location_inserts.append(TrialLocations(trial_id = current_trial.id, location_id = unique_new_location['location_id'], active = True, status = unique_new_location['status']))

LOG_OUTPUT('==========PRE BULK==========', True)
db_session.bulk_save_objects(trial_location_inserts)
LOG_OUTPUT('==========POST BULK==========', True)

And here's the log from sqlalchemy echo
2016-12-23 07:37:52.570: ==========PRE BULK==========
2016-12-22 23:37:52,572 INFO sqlalchemy.engine.base.Engine INSERT INTO trial_locations (status, trial_id, location_id, active) VALUES (%(status)s, %(trial_id)s, %(location_id)s, %(active)s)
2016-12-22 23:37:52,572 INFO sqlalchemy.engine.base.Engine ({'status': u'Completed', 'active': True, 'location_id': 733, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 716, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 1033, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 1548, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 1283, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 1556, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 4271, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 1567, 'trial_id': 126625}  ... displaying 10 of 223 total bound parameter sets ...  {'status': u'Completed', 'active': True, 'location_id': 1528, 'trial_id': 126625}, {'status': u'Completed', 'active': True, 'location_id': 1529, 'trial_id': 126625})
2016-12-23 07:38:14.270: ==========POST BULK==========

EDIT:
Also for comparison I rewrote it in Sqlalchemy core
if len(trial_location_inserts) > 0:
LOG_OUTPUT('==========PRE BULK==========', True)
engine.execute(
  TrialLocations.__table__.insert().values(
    trial_location_core_inserts
  )
)
# db_session.bulk_save_objects(trial_location_inserts)
LOG_OUTPUT('==========POST BULK==========', True)

and it ran in 0.028 seconds
2016-12-23 08:11:26.097: ==========PRE BULK==========
...
2016-12-23 08:11:27.025: ==========POST BULK==========

I'd like to keep it in session for transaction sake but if Core is the only way I guess that's it
Help appreciated!


text:
Q: How to invert the pentagon created using CSS? I want to create pentagon which is pointing downward (reverse). But I don't how to mentions points.

#pentagon {
 margin:70px 0 5px 20px;
 position: relative;
 width: 110px;
 border-width: 100px 36px 0;
 border-style: solid;
 border-color: #abefcd transparent;
}
#pentagon:before {
 content: "";
 position: absolute;
 height: 0;
 width: 0;
 top: -170px;
 left: -36px;
 border-width: 0 90px 70px;
 border-style: solid;
 border-color: transparent transparent #abefcd;
}

A: TL;DR: (Solution)
The simplest way to invert that pentagon would be to invert the borders that are used in creating it like in the below snippet:

#pentagon {
  margin: 0px 0 5px 20px;
  position: relative;
  width: 110px;
  border-width: 0px 36px 100px;
  border-style: solid;
  border-color: #abefcd transparent;
}
#pentagon:before {
  content: "";
  position: absolute;
  height: 0;
  width: 0;
  top: 100px;
  left: -36px;
  border-width: 70px 90px 0px;
  border-style: solid;
  border-color: #abefcd transparent transparent;
}

How is the pentagon shape in question created?
The pentagon shape that you have shown in question is created as follows:

*

*The main element has a border-top of 100px whose color is #abefcd, it has border-left and border-right as 36px but they are transparent. This produces a trapezoid which is wider at the top and shorter at the bottom.

*The pseudo element has a border-bottom of 70px whose color is #abefcd, it has border-left and border-right as 90px but they are transparent. This produces a triangular shape which is then placed on top of the main element using absolute positioning.

Both these together produce the pentagon. I have changed the border colors in the below snippet so that you can see it visually.

#pentagon {
 margin:70px 0 5px 20px;
 position: relative;
 width: 110px;
 border-width: 100px 36px 0;
 border-style: solid;
 border-color: red transparent;
}
#pentagon:before {
 content: "";
 position: absolute;
 height: 0;
 width: 0;
 top: -170px;
 left: -36px;
 border-width: 0 90px 70px;
 border-style: solid;
 border-color: transparent transparent blue;
}

How do I invert it?
It is very simple to do once we have the understanding of how the shape is created.

*

*Change the trapezoid such that the bottom is wider than the top. That is, make border-bottom as 100px and set its color as #abefcd.  Change border-top to 0px. The color of border-top doesn't matter because it is anyway 0px wide.

*Similarly for the triangular part, set the border-top as 70px and its color as #abefcd. Change the border-bottom to 0px. This will make the triangle point down.

*Adjust the top value such that the triangle (pseudo-element) is below the trapezoid (which is 100px tall).

A: An alternative would be just to keep the same code but add rotate the pentagon using a transform like so.

#pentagon {
  margin: 70px 0 5px 20px;
  position: relative;
  width: 110px;
  border-width: 100px 36px 0;
  border-style: solid;
  border-color: #abefcd transparent;
  transform: rotate(180deg);
}
#pentagon:before {
  content: "";
  position: absolute;
  height: 0;
  width: 0;
  top: -170px;
  left: -36px;
  border-width: 0 90px 70px;
  border-style: solid;
  border-color: transparent transparent #abefcd;
}

A: Just inverse your div content by adding few new styles as mentioned below. Rest HTML/CSS keep as it is of yours.

#pentagon {
     margin:70px 0 5px 20px;
     position: relative;
     width: 110px;
     border-width: 100px 36px 0;
     border-style: solid;
     border-color: #abefcd transparent;
     -moz-transform: scale(1, -1);
     -webkit-transform: scale(1, -1);
     -o-transform: scale(1, -1);
     -ms-transform: scale(1, -1);
     transform: scale(1, -1);
    }
    #pentagon:before {
     content: "";
     position: absolute;
     height: 0;
     width: 0;
     top: -170px;
     left: -36px;
     border-width: 0 90px 70px;
     border-style: solid;
     border-color: transparent transparent #abefcd;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement server-side sorting on a data table I am planning to implement server-side sorting and paging for a data table to be shown on the webpage. The data table is a Javascript managed HTML table with external CSS. Data will be pulled from the server-side by Ajax. I am thinking about creating a class on the server-side to represent the data table but have no idea how to implement the sorting on different columns. The sorting should be general enough for any class that backs up the table.
Edit: a backup class such as this:
public class Inventory
{
   private int itemsLeft = 0;
   private float price = 0.0f;
   private boolean status = false;
   private int itemsSold = 0;

   public int getItemsSold()
   {
       return itemsSold;
   }
   public void setItemsSold(int itemsSold)
   {
       this.itemsSold = itemsSold;
   }
   //... and other getters and setters
}

Each of the private field will be one of the column for the data table and the whole table will be represented as an ArrayList of Inventory. Each instance of the back up class consists of one database table row.
When the header of any sortable column is clicked, the index or name of the column will be sent to the server for sorting data according to the selected column.
I am now stuck at how to make a general sorting function for any back up class. Your suggestions will be much appreciated.

A: Implement different Comparators for the columns you want to sort on. You can then use Collections.sort or similar to sort on the server.

A: Thanks to Amir and cuberoot, after some work, I finally come up with this:
import java.util.Comparator;
import java.lang.reflect.Method;

public class ObjectComparator<T> implements Comparator<T>{

   private String field;
   private String order;
   private Method method;
   private Class<T> cls;

   public ObjectComparator(String field, String order, Class<T> c){
       this.field = field;
       this.order = order;
       this.cls = c;
       init();
   }

   private void init(){
       String field_name = "get"+field.substring(0,1).toUpperCase()+field.substring(1);
       try{
          method = cls.getDeclaredMethod(field_name,new Class[]{});
       }
       catch(Exception ex){
          System.err.println("No Such Method Found!");
       }
   }
   @SuppressWarnings("unchecked")
   public int compare(T o1, T o2) {
        try{
          Object o1_ = method.invoke(o1,new Object[]{});
          Object o2_ = method.invoke(o2,new Object[]{});
          //Move all objects with null field values
          //to the end of the list regardless of sorting order.
          if(o1_== null) return 1;
          else if(o2_== null) return -1;
           //////////////////////////////////
          if (order.equalsIgnoreCase("asc"))
              return ((Comparable<Object>)o1_).compareTo(o2_);
          else
              return ((Comparable<Object>)o2_).compareTo(o1_);
       }
       catch (Exception ex)
       {
           System.err.println("error sorting");
           return 0;
       }
   }
}

This can be used as:
List<Inventory> list = new ArrayList<Inventory>();//populate list
Collections.sort(list, new ObjectComparator<Inventory>(field_name, order, Inventory.class));

Here field_name is the name of the field to be sorted on. It is sent to the server as a request parameter when the header of the table is clicked. There is a requirement with this approach: all the sortable fields in the domain object must implement Comparable interface. Also there must be JavaBean style getter and setter methods for the fields of interests.


text:
Q: What limitations does converting question links to links with titles have? On this question there are more than 50 links to Stack Overflow questions. However, the last 6 links aren't converted to titles (http://facebook.stackoverflow.com/questions/6530420/control-the-image-that-facebook-shows-when-i-like-a-url should be converted to http://facebook.stackoverflow.com/questions/6530420/control-the-image-that-facebook-shows-when-i-like-a-url).
However: changing all http://facebook.stackoverflow.com/... into http://stackoverflow.com/... fixes this, both in the preview and the final result. Also, the preview won't show any title for http://facebook.stackoverflow.com/... links.
My question is, what limitations does this converting have? How are these question titles retreived? Via API? Through database?
I'm not sure about title, feel free to edit that

A: You had to ask – well, here goes.
The restrictions are currently as follows, but note that they do look a bit contrived, resulting from the fact that they have grown over time (from single site to cross-site, from "there are no subsites" to "facebook.SO", etc.), so it's not unlikely that we'll revisit them.

*

*Links to questions on the same site are unlimited.

*Links to other sites are limited to

*

*a) 5 linked-to sites and

*b) N questions per target site, where N is 200 on meta sites (was 40 at the time this question was asked) and 10 on non-metas (this is about the site that the post containing the link is posted on, not the site that is being linked to)

*While same-site links always work, which other sites work depends on where you're posting:

*

*a) On all subsites (currently none), links to the master site work, and vice versa.

*b) On all meta sites, links to the corresponding main site work, and vice versa.

*c) On Meta Stack Exchange, all sites work.

*d) On all meta sites, links to Meta Stack Exchange work.

*e) Anything else does not work.

*For the purpose of 2 (in contrast to 1 and 3a), facebook.SO and SO were considered separate sites.

The reason that removing the facebook. part from links caused the auto-title to suddenly work, as you observed, is 2b in combination with 4: forty links to fb.so work; the 41st doesn't.
Point 4 is also the rule that makes the least sense, so don't expect that to stick around forever.
This will also work identical in the preview from the next build on, with the exception of 2a. That one is only applicable to Meta SO anyway (because of 3), it's non-trivial to add to the preview because of slight differences in the implementation, and it's a pathology to begin with.
To answer your other question in addition to what Arjan said: on the server-side, same-site links are retrieved from the database, cross-site links use an HTTP API. The latter used to happen via cross-DB queries, but this was dropped at some point, because having multiple database connections lying around is just crying for issues.

A: I'm not an authoritative source, but:

*

*While editing, Ajax calls to the API are used to fetch the data that is needed to change raw links into clickable links with their title.

*When saving, the HTML is "pre-cooked" (including sanitation and tag-balancing) from the Markdown source. This includes creating the clickable links, just like it includes creating <img> elements and so on. So, upon loading the page, the HTML fragment is simply fetched from a database or something like that. This implies that changes in a title are not visible in a post that links to it, unless the post that links to it is edited and saved too. (That applies to tags too.)
From this very Meta, this seems to work for links to all Stack Exchange sites:  Why did my "goat cheese espuma" flop? But some titles might look odd, lacking MathJax on the linking site: Integrating $\int \frac{1}{1+e^x} dx$.
On other sites (and their Metas) it seems only links to that specific site work:

Bugs† aside, there shouldn't be any other limitations. Apparently the facebook.stackoverflow.com subdomain causes some issues in your example (which you already tested works fine when removing that subdomain). That is a bug.

† Like:

*

*Bare links in parenthesis: (URL inside parenthesis are not automatically hyperlinked). That can be fixed by adding <...>, and thus using (<http://...>), like: (URL inside parenthesis are not automatically hyperlinked).

*Multiple URLs separated by just whitespace: Jon Skeet Facts The Many Memes of Meta


text:
Q: update height of element after a resize How can i know the height of an element after a resize event? I use the function .height() of jQuery and i have a timer of 500ms before use my resize function but the function .height() still return the height before the resize.
$(window).resize(function() {
    window.clearTimeout(timerResize);
    timerResize = setTimeout(recalculateAll, 1000);
});

function recalculateAll() {
    console.log('resize');
    setOpenClose('.auteurs .block');
}

function setOpenClose(target) {
    $(target).each(function() {
        $(this).data('height', $(this).height());
        $(this).height($(this).height() - ($(this).find('p').height() + 45));
    });
    sameHeights(target);
}

function sameHeights(target, locus) {
    if (locus === undefined) {
        locus = target;
    }
    var heightMax = 1;
    $(target).each(function() {
        if ($(this).height() > heightMax) {
            heightMax = $(this).height();
        }
    });
    $(target).each(function() {
        $(this).height(heightMax);
    });
}

Hoping my question is understandable because of my approximate english, and the fact i'm new in development.

A: You should be able to call the retrieve the height of the element in the resize callback.
$(window).resize(function(){
    var itemHeight = $('.item').height();
});

See https://jsfiddle.net/cvwf0pra/


text:
Q: detecting if the button onclick event is attached I have the button and i am trying to detect through jquery that if the button has a click event attached and has a specific message please hide it..
as of now i have nothing which comes up:
Here is the code i have:
<button name="submit" type="submit" class="iuttons" onclick="alert('The number of pages in your results is too long for us to print.');"><img height="16" alt="Submit" src="mall.png" width="16" align="center"></button>

I am trying something like this: but not sure how:
$("#iuttons").on('submit').length() {
   hide the button [same button]
}else{
show the button
}

This needs to be running on the doc ready so it can know what to do

A: I'm not sure what exactly you want to do but if you are trying to hide the button on click use this :
$('.iuttons').click(function() {
     $(this).hide();
});

A:  function hasClickEventAttached(id){
jQuery.each($('#' + id).data('events'), function (i, event) {

            jQuery.each(event, function (i, handler) {

                if(handler.type == 'click') return true;

            });

        });
     return false;
}

now you can use it like:
if(hasClickEventAttached('iuttons'))
      alert('onclick event is attached');
else
      alert('onclick event is not attached');

A: If you're using jQuery < 1.8.3, you can use something simple like this:
// your element
var $el = $('.iuttons');

// set listener
$el.on('submit', function() { alert('hi'); });

// check events
var hasListener = !!($el.data('events') || {})['submit'];

// print to console
console.log( "Submit listener: ", hasListener );

Just throwing this in the mix since it's related; it's not a sufficient answer.
Chrome, Firefox, and Safari have built-in support for a function called getEventListeners. https://developer.chrome.com/devtools/docs/commandline-api#geteventlistenersobject
getEventListeners(myElement);

// output:
// Object {mouseover: Array[1]}


text:
Q: Split text into two sentences in C# I want to divide a text into sentences.the sentence contains whitespace characters
For example:
Orginal sentence: 100 10 20 13
the result:
first sentence:100 10 20
second sentence:13

I tried split but the result was :
first:100
second:10
third:20
fourth:13

How can I do that?

A: You can use Linq for this;
// This splits on white space
var split = original.Split(' ');

// This takes all split parts except for the last one
var first = split.Take(split.Count() - 1);
// And rejoins it
first = String.Join(" ", first);

// This gets the last one
var last = split.Last();

Note: This is assuming that you want the first result to be every word except for the last and the second result to be only the last... If you have different requirements please clarify your question

A: You want all before the last space and the rest? You can use String.LastIndexOf and Substring:
string text = "100 10 20 13";
string firstPart = text;
string lastPart;

int lastSpaceIndex =  text.LastIndexOf(' ');
if(lastSpaceIndex >= 0)
{
    firstPart = text.Substring(0, lastSpaceIndex);
    lastPart = text.Substring(lastSpaceIndex).TrimStart();
}


text:
Q: scanf not waiting for input Although it is an extremely simple question, I am writing a program that is getting stuck in an infinite "while" loop because the argument that breaks the loop is determined by a switch statement that requires user input. The problem is that the program never stops for input so it constantly chooses the default case, causing an infinite loop.
This is my code thus far:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    float nickels, dimes, quarters, total, price;
    char input;
    price = 1.00;
    total = 0;

    while(total < price){
        printf("n = nickel, d = dime, q = quarter: ");
        scanf("%c", &input);

        switch(input){
        case 'n': case 'N':
            total += 0.05;
            printf("\nTotal: %f\n", total);
            break;
        case 'd': case 'D':
            total += 0.10;
            printf("\nTotal: %f\n", total);
            break;
        case 'q': case 'Q':
            total += 0.25;
            printf("\nTotal: %f\n", total);
            break;
        default:
            printf("\nWrong input\n");
            break;
        }
    }

    printf("You're done! Total is %f", total);

    return 0;
}

I know this is an extremely simple question. I apologize for that. It could quite possibly be something I'm just overlooking.

A: In short, scanf() as you've used it consumed the user's input character, but did not consume the newline he also had to type, leaving it for the next iteration of the loop to trip over. The easiest workaround is to just ignore newline characters from the user's input, by adding
    case '\n': break;

to the switch statement so that they are silently consumed rather than triggering the default case.
That said, here is a more verbose explanation of what is going on under the hood:
In general, I/O operations are more complicated then beginner books and courses make them out to be. The natural form of I/O that the C runtime library promotes has the benefit that it hides most of the details of access to data behind the flexible concept of a "stream".
A stream is usually buffered, meaning that reads and writes to a stream actually act on an in-memory buffer so that the expensive system calls that actually move data to and from memory can happen less often and on more bytes at a time. When processing a large file, this is a huge benefit, and makes it practical to process entire files apparently a character at a time.
A fully buffered stream is really inconvenient for interactive use, however, so a typical implementation will make the stdin, stdout, and stderr streams be "line buffered" when they are associated with an interactive terminal. When an output stream is line buffered, it flushes the buffer to the terminal when a newline is printed. When an input stream is line buffered, it fills the input buffer a line at a time.
That means in particular that the first call to scanf() (or getchar() or any other read operation on stdin) will apparently block execution until the user has typed a newline, then proceed to return what it is expected to return.
In your case, scanf("%c", &input); will block until the user typed a newline, then copy the first character typed to input, leaving any additional characters and the newline in the buffer. The next time around the loop,  scanf("%c", &input); will take the next character from the buffer without waiting for any further input. We know there is at least one such character, because the first loop waited for say "d\n" to be typed but then consumed only the "d", leaving the "\n" for later.
The generally accepted best practice today would be to not use scanf() at all. It would be much better to use fgets() and then parse the entire line of input appropriately. For your example, you could read a line, then count all of the 'n', 'd', and 'q' occurrences. The details, of course, would depend on the specification of what you are supposed to implement.
I mentioned "buffered" and "line buffered" streams. There is a third kind of stream that is more suitable to interactive use. It is usually possible to make the stream itself be "unbuffered", such that every call to a stdio function takes effect immediately in the device or file. Unbuffered operation is only recommended for interactive programs, so to use it you should verify that stdin really is attached to a terminal and not redirected from a file. You also need to deal with the fact that the terminal device driver itself is almost certainly going to try to at minimum line buffer its input. There will be a system-specific way to put the terminal driver into a raw mode where each character types will cause an immediate return from the read(2) system call allowing a program to respond to individual keypresses without waiting for the carriage return key to be pressed. Actually configuring this mode of operation is tricky, platform specific, and well beyond the scope of this question.


text:
Q: Question over induction, suppose $P(n)$ is true for all positive integers $n$ that is a power of 2. Suppose, that $P(k+1) \Rightarrow P(k)$ for all positive integers $k$. How would I prove $P(n)$ is true?
I am getting confused since this is going the 'other way'. Usually $P(k)\Rightarrow P(k+1)$

A: If $P(n)$ is sometimes false, let $a$ be a positive integer such that $P(a)$ is false. Let $2^n$ be the smallest power of $2$ (or any power of $2$) which is $\ge a$. Let $k$ be the largest positive integer $\le 2^n$ such that $P(k)$ is false. Note that $k\lt 2^n$.
It follows that $P(k+1)$ is true, which implies that $P(k)$ is true, and we have reached a contradiction.


text:
Q: The limit of iterated square root with multiplication under the root, $\sqrt{ a \sqrt{ a \sqrt{a \cdots}}}$ $$
\sqrt{ a  \sqrt{ a  \sqrt{a \cdots}}}=\text{ ?}
$$
options were given as

*

*$0$

*$-a$

*$a$

*$1$

i did not know how to solve it or what it was related to. Could anyone please explain the concept and/or provide helpful references or links?

A: That's just $a^{1/2}\cdot a^{1/4} \cdots = a^{1/2+1/4+1/8+\cdots}$.
You can use the summation $\sum_{i=1}^{\infty} \frac{1}{2^i} = 1$ to get the answer.

A: Let $x_1=\sqrt{a}$, and $x_n=\sqrt{ax_{n-1}}$, for $n\ge 2$ if the limit $$x:=\lim_{n\to \infty}x_n$$
If that limit exist. We have
\begin{align*}
x^2&=a\lim_{n\to\infty}x_n\\
&=ax
\end{align*}
So, $x=0$ or $x=a$.

A: Supposing that $x=\sqrt{a\sqrt{a\sqrt{a\sqrt{\cdots}}}}$, then squaring both sides, we have $x^2 = a\sqrt{a\sqrt{a\sqrt{a\sqrt{\cdots}}}} = ax$. If we assume $x$ is nonzero, we may divide both sides by $x$ yielding $x=a$. Otherwise, $x=0$; this occurs when $a=0\;(=x)$, so both possible cases are encapsulated in the response $x=a$.


text:
Q: using TCL command line, is there a way to stop showing characters? I'm building a tool were a command with a password needs to be entered.
I want when I enter this command with the password, the command line replaces each character with "*" or " ", so the command and the password will not be observable !
is there such a command that tells the TCL interpreter "from this point, show each character entered as *", and then switch back to regular mode ?
any other suggestion will be valuable too.

A: In your case, you shall take "full control" over your terminal and disable its default echoing behavior (In UNIX the likes the terminal should be entered into the so-called raw mode)
Then, you can read the characters one-by-one (till max password size or till Enter is pressed) and echo '*' per each pressed character.
You got working code examples both on UNIX and Windows how doing so here
You may want reading also this link echo-free password entry TCL wiki
proc enableRaw {{channel stdin}} {
   exec /bin/stty raw -echo <@$channel
}
proc disableRaw {{channel stdin}} {
   exec /bin/stty -raw echo <@$channel
}

enableRaw
set c [read stdin 1]
puts -nonewline $c
disableRaw

package require twapi
proc enableRaw {{channel stdin}} {
   set console_handle [twapi::GetStdHandle -10]
   set oldmode [twapi::GetConsoleMode $console_handle]
   set newmode [expr {$oldmode & ~6}] ;# Turn off the echo and line-editing bits
   twapi::SetConsoleMode $console_handle $newmode
}
proc disableRaw {{channel stdin}} {
   set console_handle [twapi::GetStdHandle -10]
   set oldmode [twapi::GetConsoleMode $console_handle]
   set newmode [expr {$oldmode | 6}] ;# Turn on the echo and line-editing bits
   twapi::SetConsoleMode $console_handle $newmode
}

enableRaw
set c [read stdin 1]
puts -nonewline $c
disableRaw

A: (Assuming Linux.) By far the easiest way to handle passwords in a terminal is to turn off echoing of input but leave the terminal otherwise in cooked mode. It won't show a * for each entered character, but it does mean that you don't have to handle things like backspace (when a user realises they typed the last couple of characters wrong before hitting Return), etc.
exec /bin/stty -echo <@stdin
set password [gets stdin]
puts ""
exec /bin/stty echo <@stdin

If you've got Tcl 8.6, you can easily make this more robust with this procedure:
proc getPassword {{prompt "Password: "}} {
    exec /bin/stty -echo <@stdin
    try {
        puts -nonewline $prompt
        flush stdout
        return [gets stdin]
    } finally {
        puts ""
        flush stdout
        exec /bin/stty echo <@stdin
    }
}

(It's possible to use catch and some scripting to emulate try…finally but it's really annoying.)
If you have a GUI and prefer that, you make a password entry box by setting the -show option to something non-empty (e.g., * to show an asterisk).


text:
Q: How to determine date grouping? Month or weekday? I have a data set listing activities over a year (in logistics context).
I can see that the loads are much more different across day of the week (e.g. Wednesdays are super busy while Sundays are very empty), but a teammate argue that grouping by month is a better idea (e.g. Jan vs Dec).
I wonder if there is any appropriate statistical analysis to prove which grouping is more appropriate?
Thanks,


text:
Q: C# - How do I set NULL to an instance method that cannot be NULL? How do I set NULL to an instance method that cannot be NULL?
Error message: Der Delegat einer Instanzenmethode kann kein "this" von NULL haben.
The problem is, that I have a method creating a MenuItem click event to run anything. But in one case there is no click event needed, so I need to set the parameter to NULL. C# does not like that. Do you know why?
public MenuItem SetMenuitem(string IconSource, RoutedEventHandler Click, string Header, string IGT, string Name)
    {
        Image Icon = new Image();
        Icon.Source = new BitmapImage(new Uri(IconSource, UriKind.Relative));
        Icon.Height = 16;
        Icon.Width = 16;
        Icon.Stretch = Stretch.None;

        MenuItem MenuItem = new MenuItem();
        MenuItem.Click += new RoutedEventHandler(Click);
        MenuItem.Header = Header;
        MenuItem.Icon = Icon;
        MenuItem.InputGestureText = IGT;
        MenuItem.Name = Name;
        MenuItem.Padding = new Thickness(5);

        return MenuItem;
    }

Here is an example, where the second parameter is set to null cuz a click event is not needed:
MI_Layout = SetMenuitem(@"IMAGES\icon.png", null, MI_Layout_Header, null, MI_Layout_Name);

A: Do a check for your Click parameter
if(Click != null)
 MenuItem.Click += new RoutedEventHandler(Click);

Personally, there is something wrong with the design if you are passing in the required parameters for the Click event, I would define an Action to attach it on the calling method.

A: You should just make another function of the same name that doesn't include the parameter and then doesn't set the click event. Instead of passing in NULL, call this function instead.
Example:
public MenuItem SetMenuitem(string IconSource, string Header, string IGT, string Name)
{
    Image Icon = new Image();
    Icon.Source = new BitmapImage(new Uri(IconSource, UriKind.Relative));
    Icon.Height = 16;
    Icon.Width = 16;
    Icon.Stretch = Stretch.None;

    MenuItem MenuItem = new MenuItem();
    MenuItem.Header = Header;
    MenuItem.Icon = Icon;
    MenuItem.InputGestureText = IGT;
    MenuItem.Name = Name;
    MenuItem.Padding = new Thickness(5);

    return MenuItem;
}


text:
Q: getting rid of file commited and pushed two commits behind HEAD I have a situation where two commits past I have reverted changes from another commit, on that revert commit I also committed package.json and package-lock.json, and now I need to get rid of those before I will rebase to master and have my PR approved. How can I achieve that without overnighting currently committed files, I mean without reverting to the commit where I have committed those unwanted files?
Many thanks

A: The simplest solution is to create a new commit where you are, deleting those files.
git rm package.json package-lock.json
git commit

If having so many commits is a problem, you can use rebase -i to re-order and/or squash commits. But in most cases, the simple solution is fine.  You can then rebase your branch to master, and your PR can just include all the commits, including the one where you deleted the unwanted files.
In some projects, the upstream maintainer (the one who approves and merges your PR) will do the work of squashing and/or reordering commits instead of asking you to do it.


text:
Q: direct sum and singular value Suppose that $A$ is an $n \times n$ complex matrix, and $A$ can be written as direct sum of matrices $\Gamma_i$ for $i=1,\ldots,n$ (i.e.: $A = {\Gamma _1} \oplus {\Gamma _2} \oplus  \cdots  \oplus {\Gamma _n}$). What relationship (if any) exists between singular values of $A$ and singular values of $\Gamma_i$ for $I=1,\ldots,n?$

A: If $\Gamma_i=U_i\Sigma_iV_i^T$ are SVD's of $\Gamma_i$ ($i=1,\ldots,n$), then obviously $A=U\Sigma V^T$, where $U=U_1\oplus\cdots\oplus U_n$, $\Sigma=\Sigma_1\oplus\cdots\oplus \Sigma_n$, and $V=V_1\oplus\cdots\oplus V_n$.


text:
Q: csv file create with exceljs not accept special charecters I am using the excelJS library to create CSV files. I am facing a problem. the problem is when I create a CSV file there are two characters that are not shown perfectly in the CSV file. for e.g...
the celsius and triangle symbols are shown in CSV file like  and  insted of (°C) and ▽ .
how to solve this problem?


text:
Q: Is this process optional? I have a rightcontinuous adapted $\bar{\mathbb{R}}$-valued stochastic process $(X_t)_{t\geq 0}$ with $X_s=\infty$ implies $X_t=\infty$ for $t>s \geq 0$. Since $\bar{\mathbb{R}}$ is homeomorph to $[-1,1]$ it makes sense to talk about rightcontinuity for the process $X$ that may also take the value $\infty$ or $-\infty$.
Is it true that $X$ is an optional process, i.e. is it measureable w.r.t. the optional $\sigma$-algebra? As $X$ can take the value $\infty$ I don't know how to check this. I would be grateful for hints or a solution.

A: If $f$ is a homeomorphism of $\bar{\Bbb R}$ onto $[-1,1]$ and $Y_t:=f(X_t)$, then $Y$ is real-valued, right-continuous and adapted, hence optional provided the filtration is right-continuous.


text:
Q: css3 animations frame by frame I need to do an animation frame-by-frame changing a background-position of an element. I need to do this WITHOUT easing or linear animation, just changing the background-position. Is it possible to achieve with css3 animation?

A: Yes it is via the new step-function easing curves property.
Instead of "ease-in" etc. use "step-start" or "step-end" which will make the transition happen instantaneously either at the beginning or end of the time period specified in transition-duration.
You can also have multiple steps: "steps(N, start | end ])" which will have the transition happen in equally spaced steps.
AFAIK this is only supported in Chrome to date.


text:
Q: Making a universal bundle in Mac OS I have a project whose target is a Bundle . Now I need to make this bundle universal for all architectures. Now I refered this and this SO Post
The post  says that Xcode 3.2 automatically makes the targets universal in Release mode
But it doesn't seem to work . I am using Xcode 3.2.6 and my Operating System is MAC OS X 10.6.8 . Can anyone please help me

A: Problem solved :
You just need to add the 3 architectures :
1)ppc
2)i86
3) x86_64
under the active architectures of the target


text:
Q: Exception Handling in N-Tier application I am writing a N-Tier application using ASP.Net Core.
In my service layer in logic tier I have an API which update the user's password. Here is the code from the service layer.
public IActionResult UpdatePassword([Required][EmailAddress] string email, [Required][DataType(DataType.Password)] string oldPassword, [Required][DataType(DataType.Password)] string newPassword)
{
    try
    {
        _userLogic.UpdatePasswordLogic(oldPassword, email, newPassword);
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }

    return Ok($"Password updated successfully. The new password is: { newPassword }");
}

basically it just gets the email, the current password, and the new given password by user and pass it to the "UpdatePasswordLogic" method in business layer. The "UpdatePasswordLogic" works as following:
public void UpdatePasswordLogic(string oldPassword, string email, string newPassword)
{
    // Take the user's password from the database
    string savedPassword = _context.Users
        .Where(x => x.Email == email)
        .Select(x => x.Password);

    if (!string.IsNullOrEmpty(savedPassword))
    {
        // Check if the oldPassword is equal to the password saved in the databank
        if (ComparePasswords(savedPassword, oldPassword))
        {
            // TODO: Set the new password
        }
        else
            // Throw exception when password is not correct
            throw new Exception("password does not match the one saved in the database");
    }
    else
        // If user does not exist, throw an exception
        throw new Exception("User does not exist in databank");
}

The "ComparePasswords" method check if the given password by user match the one that saved in the databank. If the password is not correct then it suppose to throw an exception. When I enter a wrong password the UpdatePasswordLogic does throw an exception but my API in service layer does not catch this exception and it returns the OKObjectResult. Does anyone know why it does not catch the exception?


text:
Q: Specific column selection from data.table in R I have a data.table in R. The table has column names.
I have a vector named colnames with a few of the column names in the table.
colnames<-c("cost1", "cost2", "cost3")

I want to select the columns whose names are in the vector colnames from the table.
The name of the table is dt.
I have tried doing the following:
selected_columns <- dt[,colnames]

But this, does not work, and I get an error.
However, when I try the following, it works:
selected_columns <- dt[,c("cost1", "cost2", "cost3")]

I want to use the vector variable (colnames) to access the columns and not the c("..") method.
How can I do so?

A: You can try like this:
dt[, .SD, .SDcols = colnames]

Meanwhile, data.table gives an alternative choice in recent version:
dt[, ..colnames]

A: Another nice alternatives is leveraging select from tidyverse/dplyr universe. select gives you a lot of flexibility when selecting columns from a data frame / tibble or data table.
library("data.table")
library("tidyverse")
df <- data.table(mtcars)
columns_to_select <- c("cyl", "mpg")
select(df, columns_to_select)

You can also skip quoting column names if you wish
select(df, c(cyl, mpg))

or leverage ellipsis and pass multiple quoted or unquoted names
Here, comparing multiple objects.
objs <- list(select(df, c(cyl, mpg)),
             select(df, cyl, mpg),
             select(df, "cyl", "mpg"))
outer(objs, objs, Vectorize(all.equal))

You may want to have a further look at dtplyr, which provides a bridge between data table and dplyr, if you want to go this route.


text:
Q: :SQL how to count the amount of distinct rows the have a multiple if column in common( that is joined from from another table) Ok, so here is my question. Maybe my brain is just fried, but im struggling to wrap my head around this
i have one table(lets say TableA with a set of columns, lets say there names are:
pk1, Pk2, a, b, c,APPLE(has 3 set values from another table), etc                  (the PK1 and PK2 are primary keys)
and then I have another table(lets say tableB)
PK1(is linked with PK1 on TableA), ag, DOG, sf, STAR(also has a set nr of values),etc
Ok, so now i want to join these 2 tables, thats the easy part.  the values in PK1 can repeat, as long as the combination of PK1 and PK2 are unique,and this is the case.
ok, here comes the tricky part.  i want get a list of of the distinct combinations of PK1+PK2+a
but i also want to know how many of them are of each type of STAR.
ok, this part is optional(for you bright sparks out there):
and just to really make it tricky, each type of star must then be sub divided into types of APPLES
1) how do i do this?
2) is it possible to do it with just 1 query, i will i have to use something like a cursor?

A: What have you tried? Maybe this can help?
select distinct pk1,pk2,a from tableA

,
select tableA.pk1,pk2,a,star,count(*)
from tableA join tableB on tableA.pk1 = tableB.pk1
group by tableA.pk1,pk2,a,star

,
select tableA.pk1,pk2,a,star,apples,count(*)
from tableA join tableB on tableA.pk1 = tableB.pk1
group by tableA.pk1,pk2,a,star,apples


text:
Q: Export content of a row into a text file with a certain structure I have a Google sheet linked to a Google form. I would like to export the content of each row into a new text file each time a new answer (row) is given like in the example (see picture attached). The additional complexity is that I would like the file to be structured like in the example using the text in the first row, specifying the value and adding a carriage return.

I am using as a starting point the attached script but I didn't manage to adapt it to my problem and make it work. Also, every time I launch this script, it runs for a very long time and creates a huge number of untitled files.
I hope you can help.
function export() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  for (var i in sheets) {
    var name = sheets[i].getSheetName();
    var fo = DriveApp.getFoldersByName(name);
    var folder = fo.hasNext() ? fo.next() :
    DriveApp.getRootFolder().createFolder(name);
    var values = sheets[i].getDataRange().getValues();
    values.shift();
    var filename, text;
    for (var j in values) {
      [filename, text] = values[j];
      folder.getFilesByName(filename).hasNext() ||
      folder.createFile(filename, text, MimeType.PLAIN_TEXT);
    }
  }
}

A: Your code does not provide a valid file name that's why unnamed files.
Use below code to install a onFormSubmit trigger to spreadsheet where the form responses are written. It'll then create a file everytime the form is submitted and save it in a folder named after the response sheet. Run the setup function once, and comment it out. Test by submitting the form.
function setup() {
  var sheet = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('myFunction')
    .forSpreadsheet(sheet)
    .onFormSubmit()
    .create();
}

// run this function one to setup formSubmit trigger
// then comment it out, like this
setup();

function myFunction(e) {
  var sheet = e.range.getSheet();
  var name = sheet.getName();

  var text = 'This file contains all the details of your purchase:\n';

  for (var key in e.namedValues) {
    text += key + ': ' + e.namedValues[key][0] + '\n';
  }

  var fo = DriveApp.getFoldersByName(name);
  var folder = fo.hasNext() ? fo.next() : DriveApp.getRootFolder().createFolder(name);

  folder.createFile(Date.now() + '', text, MimeType.PLAIN_TEXT);
}


text:
Q: Simple `Assert.IsAssignableFrom` failing Why does this simple assert statement fail? From what I've read I should be . Unfortunately, since the functionality is so basic there isn't much information out there.
public interface IDummy{}
public class Dummy : IDummy {}

Assert.IsAssignableFrom<IDummy>(new Dummy());

Running this test yields
Expected: assignable from <Application.Tests.ViewModels.IDummy>
  But was:  <Application.Tests.ViewModels.Dummy>

I have tried swapping the interface and objects side to no avail.

A: For the benefit of those who land here through Google (or Bing :-) )
Assert.IsAssignableFrom<T>(object actual) is meant to check if the object being examined can be substituted by the type T. Effectively, what this means is that the assertion is testing an "is-a" relationship between the object examined and the type T.
Let's see some code (intentionally simplified):
// The Base class
public class Employee
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfJoining { get; set; }
}

// The derived class
public class Manager : Employee
{
    public IList<Employee> EmployeesReporting { get; set; }
}

Now the assertion:
// NOTE: using Assert = NUnit.Framework.Assert;
[TestMethod]
public void Test_IsAssignableFrom()
{
    var employee = new Employee();

    // Manager is-a Employee, so the below is true
    Assert.IsAssignableFrom<Manager>(employee);
}

Whereas the IsInstanceOf<T>(object actual) is meant to check whether the object being tested is (like the name suggests) an instance of type T - simply put, if "actual" is the type T or a type derived from T
[TestMethod]
public void Test_IsAssignableFrom()
{
    var manager = new Manager();

    // Manager derives from Employee so the below is true
    Assert.IsInstanceOf<Employee>(manager);
}

EDIT
Turns out, these asserts work the same way as Type.IsAssignableFrom and Type.IsInstanceOf methods on System.Type

A: IsAssignableFrom works in reverse from what you are expecting.  It's asking: Is (the value) Assignable From IDummy.  Or: "Is  assignable to (value)?"
From the XML doc:
    /// Asserts that an object may be assigned a  value of a given Type.
You probably want Assert.IsInstanceOfType()


text:
Q: deviceready not fired - onFileSystemPathsReady I am creating a Cordova / Phonegap application and I am getting this issue occasionally and randomly
"deviceready not fired after 5 seconds.
Channel not fired: onFileSystemPathsReady"

My Cordova application is a Multi Page App (not a SPA).
I am using Cordova 5.4.1 with (Android Build 4.1.1)
I am using file plugin of version 4.3.0. (and also tried plugin version 3.0 and 4.2.0)
Issue comes mostly in devices with Android version 6.0.1.
I am using Android studio 2.1.1 with Java 1.8.0_101 (earlier was using 2.2 and 2.3)
I have kept the Gradle Instant Run off.
Mostly the issue comes when I move from one page to another i.e. when I call window.location.href
My Code:
/* It's working fine on the index.html page */
/* Index.html demo page (actual page has many css and js files) */
<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="cordova.js"></script>
    <script src="js/core/pages/index.js"></script>
  </head>
  <body onload="startExecution()">

  </body>
</html>

/* index.js page */

var d1 = $.Deferred();
var d2 = $.Deferred();

document.addEventListener('deviceready', deviceReady, false);

function deviceReady() {

  if (navigator) {
    if (navigator.splashscreen) {
      navigator.splashscreen.hide();
    }

  }

  // after some processing or API hit
  window.location.href = "page1.html";
}

function startExecution() {
  d2.resolve();
}

$.when(d1, d2).done(function () {
  console.log('Both resolved');

  window.location.href = "page2.html";
});

The problem comes when I go to page1.html
on page1 too I have attached the necessary files like cordova.js.
But occasionally I get the above error:
"deviceready not fired after 5 seconds.
 Channel not fired: onFileSystemPathsReady"
It used to work properly, but somehow suddenly I started getting this error. I don't understand why, please help me out.


text:
Q: Nameservers setup in CentOS 6 I have a domain registered externally from where I have my VPS, but I need to connect these two in order to have the domain forward to my host. I know that I have to take my host's nameservers and replace them at my Domain Registrar's website.
The question is: Where do I get my nameservers?...
I've read about /etc/resolv.conf and I actually added my nameservers there like this:
ns1.mywebsite.org 8.8.8.8
ns2.mywebsite.org 8.8.4.4

The IPs are actually like that, I didn't know with what to replace them.
So how do I set up my nameservers correctly and have the domain point to my host?
P.S: I'm using Webmin to manage my VPS.

A: Your assumption that you have to take your host's nameservers and replace them at your Domain Registrar's website  is not quite what you need to do.

First: You do not need to change the /etc/resolv.conf file on your host. That is the configuration file your host uses to resolve all internet domains/hostnames, not just your own. The ip-addresses 8.8.8.8 and 8.8.4.4 are public DNS servers provided by Google and suitable for most configurations. The configuration should look like:
# /etc/resolv.conf
nameserver 8.8.4.4
nameserver 8.8.8.8

Changing nameserver records is what you do when you run your own nameserver. Normally you do not need to run your own nameservers and you shouldn't try before improving your understanding of DNS.
I think that what you probably want to achieve is that people using for instance www.yourdomain.com end up at your VPS and e-mail addressed to <someone>@yourdomain.com also gets delivered to the mailserver you run on your host.
That is mostly updating the DNS records for www.yourdomain.com ftp.yourdomain.com etc. Typically your registrar provides a management console where you can do that yourself and your domain uses the nameservers from the registrar.
In that management console you enter the ip-address of your VPS as the A-record for www.yourdomain.com and  for all other DNS names you might want to use.

A: The correct syntax for /etc/resolv.conf is "nameserver $IP_ADDRESS", like, if you use Google's DNS, "nameserver 8.8.8.8". If you want to locally resolve ns1.mywebsite.org to a certain IP, edit /etc/hosts.


text:
Q: Laravel not yielding I had a look at other questions and the problem with them seems to be they are referencing the wrong blade file and not extending from the parent.
My yield('section') isn't working.
HomeController.php
class HomeController extends BaseController {
        public function home() {
        return View::make('login');
    }
}

home.blade.php
@extends('layout.slim')

@content('section')
    Some content
@stop

slim.blade.php (inside: views/layout)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>test</title>

    <!-- Stylesheets -->
    {{ HTML::style('css/bootstrap.min.css'); }}
    {{ HTML::style('css/animation.css'); }}
    {{ HTML::style('css/checkbox/orange.css'); }}
    {{ HTML::style('css/preview.css'); }}
    {{ HTML::style('css/authenty.css'); }}

    <!-- Font Awesome CDN -->
    {{ HTML::style('http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css'); }}

    <!-- Google Fonts -->
    {{ HTML::style('http://fonts.googleapis.com/css?family=Roboto+Slab:400,700,300'); }}
    {{ HTML::style('http://fonts.googleapis.com/css?family=Open+Sans:300,400,700'); }}

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    {{ HTML::script('https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js'); }}
    {{ HTML::script('https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js'); }}
    <![endif]-->
</head>

<body>
<section id="authenty_preview">
@yield('section')
</section>

    <!-- js library -->
    {{ HTML::script('http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'); }}
    {{ HTML::script('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js'); }}
    {{ HTML::script('js/bootstrap.min.js'); }}
    {{ HTML::script('js/jquery.icheck.min.js'); }}
    {{ HTML::script('js/waypoints.min.js'); }}

    <!-- authenty js -->
    {{ HTML::script('js/authenty.js'); }}

    <!-- preview scripts -->
    {{ HTML::script('js/preview/jquery.malihu.PageScroll2id.js'); }}
    {{ HTML::script('js/preview/jquery.address-1.6.min.js'); }}
    {{ HTML::script('js/preview/scrollTo.min.js'); }}
    {{ HTML::script('js/preview/init.js'); }}

    <!-- preview scripts -->
    <script>
        (function($) {

            // get full window size
            $(window).on('load resize', function(){
                var w = $(window).width();
                var h = $(window).height();

                $('section').height(h);
            });

            // scrollTo plugin
            $('#signup_from_1').scrollTo({ easing: 'easeInOutQuint', speed: 1500 });
            $('#forgot_from_1').scrollTo({ easing: 'easeInOutQuint', speed: 1500 });
            $('#signup_from_2').scrollTo({ easing: 'easeInOutQuint', speed: 1500 });
            $('#forgot_from_2').scrollTo({ easing: 'easeInOutQuint', speed: 1500 });
            $('#forgot_from_3').scrollTo({ easing: 'easeInOutQuint', speed: 1500 });

            // set focus on input
            var firstInput = $('section').find('input[type=text], input[type=email]').filter(':visible:first');

            if (firstInput != null) {
                firstInput.focus();
            }

            $('section').waypoint(function (direction) {
                var target = $(this).find('input[type=text], input[type=email]').filter(':visible:first');
                target.focus();
            }, {
                offset: 300
            }).waypoint(function (direction) {
                    var target = $(this).find('input[type=text], input[type=email]').filter(':visible:first');
                    target.focus();
                }, {
                    offset: -400
                });

            // animation handler
            $('[data-animation-delay]').each(function () {
                var animationDelay = $(this).data("animation-delay");
                $(this).css({
                    "-webkit-animation-delay": animationDelay,
                    "-moz-animation-delay": animationDelay,
                    "-o-animation-delay": animationDelay,
                    "-ms-animation-delay": animationDelay,
                    "animation-delay": animationDelay
                });
            });

            $('[data-animation]').waypoint(function (direction) {
                if (direction == "down") {
                    $(this).addClass("animated " + $(this).data("animation"));
                }
            }, {
                offset: '90%'
            }).waypoint(function (direction) {
                    if (direction == "up") {
                        $(this).removeClass("animated " + $(this).data("animation"));
                    }
                }, {
                    offset: '100%'
                });

        })(jQuery);
    </script>
</body>
</html>

The yield('section') doesn't work. Not sure what to do anymore. Any help? Thanks!

A: replace @content('section') to @section('section')
and check out http://laravel.com/docs/templates its well explained there


text:
Q: "from when he was younger" or "from the time he was younger" or "when he was younger" (1) Although I haven't seen him for years, I still remember how he looked from when he was younger.
(2) Although I haven't seen him for years, I still remember how he looked from the time he was younger.
(3) Although I haven't seen him for years, I still remember how he looked when he was younger.
(4) Although I haven't seen him for years, I still remember his younger face.
Which sentence is correct?

A: Although I haven't seen him for years, I still remember how he looked when he was younger. is correct
although I would have written
Although I haven't seen him for years, I still remember what he looked like when he was younger.


text:
Q: How to draw polyline arc with fixed radius giving three mouse loc(first, second and last) in 2D? I have got question how to draw arc or part of cricle in OpenGL/Glut giving only one point and current mouse location? In total, the order of the mouse click, is not important.
The answer is below but i have got issuse to proper calculate it.
Gods like admins and rest - could ypu move this topic to on-topic, please?
How it should looks like

A: Let $\vec{p}_1 = (x_1, y_1)$ be the first point and $\vec{p}_2 = (x_2, y_2)$ the second point of the half-circle arc, and $\vec{p}_0 = (x_0, y_0)$ be the previous point preceding the first point.
If we look from $\vec{p}_1$ towards $\vec{p}_2$, the arc and $\vec{p}_0$ will be on different sides (left or right). If $\vec{p}_0$ and $\vec{p}_1$ are collinear, or there is no $\vec{p}_0$, then you probably want to draw a line instead of an arc.
Since the arc is a half-circle, the center $\vec{c} = (x_c, y_c)$ of that circle is at the midpoint of the two points, and radius $r$ half their distance. However, instead of scalar $r$, it is easier to use vectors $\vec{u} = (x_u, y_u)$ and $\vec{v} = (x_v, y_v)$, as if semi-major axes of an elliptical arc, where $\vec{v}$ is $\vec{u}$ rotated 90°:
$$\begin{align}
\vec{c} &= \frac{\vec{p}_1 + \vec{p}_2}{2} \\
r &= \left\lVert \vec{p}_2 - \vec{p}_1 \right\rVert \\
\vec{u} &= \frac{\vec{p}_1 - \vec{p}_2}{2} \\
\vec{v} &= \mathbf{R} \vec{u}
\end{align} \; , \; \; \mathbf{R} = \begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}$$
i.e.
$$\begin{cases}
x_c = \frac{x_1 + x_2}{2} \\
y_c = \frac{y_1 + y_2}{2} \\
r = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} \\
x_u = \frac{x_1 - x_2}{2} \\
y_u = \frac{y_1 - y_2}{2} \\
x_v = y_u = \frac{y_1 - y_2}{2} \\
y_v = -x_u = \frac{x_2 - x_1}{2}
\end{cases}$$
The rotation by 90° is clockwise if using a left-handed coordinate system ($x$ increases right, $y$ down). If $\vec{p}_0$ is already clockwise from line from $\vec{p}_1$ to $\vec{p}_2$, we want it counterclockwise. (That just means negating $\vec{v}$, i.e. both $x_v$ and $y_v$ negated.)
Note that OpenGL uses left-handed coordinate system in normalized device coordinates, and most 2D graphics toolkits and file formats use left-handed coordinate systems too. This is why this answer assumes a left-handed coordinate system. Note that typically in mathematics a right-handed coordinate system is assumed (in 2D, $x$ increasing right, and $y$ up, not down as in left-handed).
That check if $\vec{p}_0$ is to clockwise or counterclockwise from $\vec{p}_1$ towards $\vec{p}_2$ is simple, if we use the 2D analog of vector cross product:
$$\left( \vec{p}_0 - \vec{p}_1 \right) \times \left( \vec{p}_2 - \vec{p}_1 \right) = x_0 ( y_2 - y_1) + x_1 (y_0 - y_2) + x_2 (y_1 - y_0) \\
\begin{cases}
\le 0, & \vec{p}_0 \text{ counterclockwise} \\
= 0, & \vec{p}_0 \text{ collinear} \\
\gt 0, & \vec{p}_0 \text{ clockwise}
\end{cases}$$
In other words, if $x_0 ( y_2 - y_1) + x_1 (y_0 - y_2) + x_2 (y_1 - y_0)$ is positive, negate $x_u$ and $x_v$; if zero, draw a line instead of an arc. (If negative, everything is fine.)
Drawing a polyline from $\vec{p}_1$ to $\vec{p}_2 = \vec{p}_1 + 2 \vec{u}$ using $N$ line segments is easy. The $N+1$ points $\vec{a}_0 = \vec{p}_1$ to $\vec{a}_N = \vec{p}_2$ are
$$\vec{a}_k = \vec{p}_1 + \left ( 1 + \cos\left(\frac{\pi k}{N}\right) \right ) \vec{u} + \sin \left(\frac{\pi k}{N}\right) \vec{v}, \; k = 0 \ldots N$$
(The $+1$ in the $\cos$ part just moves the center of the arc from $\vec{p}_1$ to $\vec{p}_1+\vec{u}$, where it should be.)
Note that even though I do assume a left-handed coordinate system for the explanation above, this works exactly as-is for right-handed coordinate systems, too: the only thing that changes, is swapping clockwise and counterclockwise in the explanations.

Depending on how you implement the above, the $\vec{u}$ or $\vec{v}$ might need to be negated. Here is a verified C function, which does the math correctly:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

typedef struct {
    float   x;
    float   y;
} vec2f;

static void line_to(const vec2f p)
{
   /* Draw a line from current location to p.
      Implement this yourself. */
}

/* Draw a half-circle arc from p1 to p2,
 * starting in direction (not opposite to) d.
 * Returns the final direction. Uses n segments.
 * Assumes the pen is at p1 already.
*/
vec2f arc_to(const vec2f p1, const vec2f p2, const vec2f d, const int n)
{
    if (n > 1 && (d.x != 0.0f || d.y != 0.0f)) {
        /* We should be able to draw an arc. */

        /* Center is midway between p1 and p2: */
        const vec2f  c = { 0.5f*(p1.x + p2.x), 0.5f*(p1.y + p2.y) };

        /* Constant semi-axis u is halfway from p1 to p2 */
        const vec2f  u = { 0.5f*(p2.x - p1.x), 0.5f*(p2.y - p1.y) };

        /* Semi-axis v is u rotated by +90 degrees */
        vec2f        v = { u.y, -u.x };

        /* f = v . d; positive if in the same direction,
           zero if perpendicular */
        const float  f = v.x*d.x + v.y*d.y;

        /* Loop variable */
        int          i;

        if (f == 0.0f) {
            /* d is perpendicular to v, parallel to p2-p1.
               We do not know which side the arc should
               bulge, so we draw a line instead.
            */
            line_to(p2);
            return d;

        } else
        if (f > 0.0f) {
            /* d and v point at the same direction. Reverse v.
               This test is > 0.0f, because we use -u and -v
               in the loop below! */
            v.x = -v.x;
            v.y = -v.y;
        }

        for (i = 1; i < n; i++) {
            const float t = (float)i * 3.14159265358979323846f / (float)n;
            const vec2f p = { c.x - cosf(t)*u.x - sinf(t)*v.x,
                              c.y - cosf(t)*u.y - sinf(t)*v.y };
            line_to(p);
        }

        line_to(p2);

        return v;

    } else {
        /* Parameters indicate no arc, so just draw
           a line segment from p1 to p2.
           Return that direction (p2-p1), too. */
        const vec2f delta = { p2.x - p1.x, p2.y - p1.y };
        line_to(p2);
        return delta;
    }
}

Note that the above function only draws arcs when $\vec{d}$ points in the direction the arc can bulge. Otherwise, it only draws a line segment.


text:
Q: While loop doesn't wait before displaying In this code section, the query gets all the teachers and appends their assigned classes within the object
The weird thing is it works perfectly on local but not online, it is almost it doesn't wait for the while loop
<?php
$SID = mysqli_real_escape_string($con, htmlspecialchars($_POST["SID"], ENT_QUOTES));

$allTeachersArr = [];
$test = [];
$q = "SELECT onderwysers.*,klasse.Klas,klasse.Datum,klasse.Vak FROM `onderwysers` LEFT JOIN klasse ON onderwysers.ID = klasse.Teacher WHERE `SID` = '$SID'";
// echo $q;
$result = $con->query($q);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $subjectItem = new stdClass();

        $filtered_array = [];
        $isIn = false;
        $var1 = $row['ID'];
        $var2 = $row['Teacher'];
        if (count($allTeachersArr) > 0)
            foreach ($allTeachersArr as $item) {
                if ($item->ID == $var1 && $item->Teacher == $var2) {
                    // do something
                    $filtered_array = $item;
                    $isIn = true;
                }
            }
        if ($isIn == true) {
            $notAdd = false;
            // echo "updates";
            $subjectItem->Klas = $row["Klas"];
            $subjectItem->Datum = $row["Datum"];
            $subjectItem->Vak = $row["Vak"];
            foreach ($filtered_array->displaySubjects as $item) {
                if ($item->Klas == $row["Klas"] && $item->Vak == $row["Vak"] && $item->Datum == $row["Datum"]) {
                    // do something
                    $filtered_array = $item;
                    $notAdd = true;
                }
            }
            if ($notAdd == false) {
                $temp = $filtered_array->displaySubjects;
                array_push($temp, $subjectItem);
                $filtered_array->displaySubjects = $temp;
            }
        } else {
            //add new entry
            $subjectItem->ID = $row["ID"];
            $subjectItem->Title = $row["Title"];
            $subjectItem->Name = $row["Name"];
            $subjectItem->Surname = $row["Surname"];
            $subjectItem->Afkorting = $row["Afkorting"];
            $subjectItem->IdentityNumber = $row["IdentityNumber"];
            $subjectItem->Geslag = $row["Geslag"];
            $subjectItem->ContactDetails = $row["ContactDetails"];
            $subjectItem->Email = $row["Email"];
            $subjectItem->RegKlas = $row["RegKlas"];
            $subjectItem->Status = $row["Status"];
            $subjectItem->UID = $row["UID"];
            $subjectItem->displaySubjects = [];
            array_push($allTeachersArr, $subjectItem);
        }
    }
}

echo json_encode($allTeachersArr);
$con->close();

THE EXPECTED RETURNED DATA(This is local, online returns nothing)


text:
Q: unable to get values from a login page in web.py I am using python web.py framework to create a small web application which has just

*

*Login screen (Authentication)

*Screen with list of records(After succesfull login)
Presently i am trying to create a login screen authentication
I have created an index.py file with code as below
index.py
import os
import sys
import web
from web import form
from web.contrib.auth import DBAuth

render = web.template.render('templates/')

urls = (
  '/',   'Login',
)

app = web.application(urls, globals())
db = web.database(dbn='mysql', db='Python_Web', user='root', pw='redhat')

class Login:

    login_form = form.Form(
        form.Textbox('username', form.notnull),
        form.Password('password', form.notnull),
        form.Button('Login'),
        )

    def GET(self):
        form = self.login_form()
        return render.login(form)

    def POST(self):
#        if not self.login_form.validates():
#            return render.login(self.login_form)
        post = self.login_form()
        username = post['username'].value
        print username,">>>>>>>>>>>>>>>>>>>>>>username"
        password = post['password'].value
        ident = db.select('user', where='user_login=$username', vars=locals())

if __name__ == "__main__":
    web.internalerror = web.debugerror
    app.run()

My login.html code
$def with (form)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Log in</title>

Log in Details

  <form action="" method="post" accept-charset="utf-8">

Username:
    <input type="text" name="username" id="username" maxlength="254" tabindex="1" />

Password:
    <input type="password" name="password" id="password" maxlength="254" tabindex="2" />

<button id="Login" name="Login">Login</button>

  </form>

When i run the above file with url www.localhost:9080 in browser i can see the screen with fields username, password and login button , but when i enter username and password and  clicked login button and tried to print the username i cannot fetch any data from the browser and the result showing is as below
None >>>>>>>>>>>>>>>>>>>>>>username
0.0 (1): SELECT * FROM user WHERE user_login=NULL

Can anyone let me why i am unable fetch the details entered through browser ?, am i missing anything in the above code and finally all my intention is
to create a login page and validate the user details by checking in the database
and redirect to the next page if user exits
I request to please help me out in writing the code for fetching the details from the browser and checking in the database and redirecting to another html page if user exists. I am really stuck and breaking my heads to complete this process

A: Make sure you validate the form before trying to access any of the inputs
def POST(self):
    post = self.login_form()
    post.validates()
    username = post['username'].value
    print username,">>>>>>>>>>>>>>>>>>>>>>username"
    password = post['password'].value
    ident = db.select('user', where='user_login=$username', vars=locals())

After that change the code works for me. Good luck!


text:
Q: How to overlay Image to openstreetmap using leaflet.js I want to overlay a wide range satellite image onto openstreetmap using leaflet.js. The satellite image is in Equidistant Cylindrical Projection.
This is how I initiate the layer.
L.imageOverlay(imgUrl, [[-15, 75], [45, 145]], {opacity: 0.6, autoZIndex: true});

The overlay result is attached below. As you can see, the coastline of the satellite image (in purple color) is not aligned with that of openstreetmap. Is that something wrong with the image or map projection? or I should use other way to overlay the satellite to map ?

A: Unfortunately your satellite imagery is in equirectangular projection (aka "equidistant cylindrical projection"), whereas OpenStreetMap tiles are in Web Mercator (EPSG:3857) projection, which has a more pronounced vertical stretch.
I do not thing there is anything Leaflet can do to help you with this situation. You can try plotting the latitude parallels to see the discrepancy (top and bottom should match, since you have manually specified the image bounds, but intermediate parallels should be at different positions).
You should either look for a tile source that provides tiles in equirectangular projection as well (EPSG:4326), or have your image converted to Web Mercator.


text:
Q: I can't seem to make a Socket.io connection I'm new to Sockets.io and working on creating a real-time chat API. While using Sockets.io I can't seem to break into it.
const app = require("../app");
const debug = require("debug")("app:server");
const http = require("http");

/**
 * Get port from environment and store in Express.
 */

const port = normalizePort(process.env.PORT || "5000");
app.set("port", port);

/**
 * Create HTTP server.
 */

const server = http.createServer(app);

/**
 * Socket.io Connection
 */

const io = require("socket.io")(server, {
  maxHttpBufferSize: 1e8,
});
io.on("connection", function (socket) {

Down Here I'm expecting a console Log, but I get nothing.
I don't get what's wrong here.
  console.log("New Socket IO Connection!!");
});

/**
 * Listen on provided port, on all network interfaces.
 */
console.log("Serve Like a Server");
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);

A: Make sure that atleast one client is connected to socket. Your code doesn't seems to be wrong here. You can check the working code for socket below.
bin/www
/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('socketio:server');
var http = require('http');
var socket = require('socket.io');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Create Socket.io Connection.
 */

var io = socket(server, {
  cors: {
    origin: "*",
    methods: "*"
  }
});
require('../socket')(io);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

module.exports = io;

socket.js
module.exports = (io) => {
    let users = {}
    io.of('/test').on('connection', (socket) => {
        console.log('Connected', socket.id);
        socket.on('join', (data) => {
            socket.join(data.room);

            users[socket.id] = data;

            io.of('/test').to(data.room).emit('message', `${data.name} joined ${data.room} room!`);
        })

        socket.on('disconnect', (data) => {
            io.of('/test').emit('message', 'user disconnected ' + users[socket.id].name);
            delete users[socket.id];
            console.log('Disonnected', socket.id);
        })
    })
}

You can check the full implementation here


text:
Q: Google Talk over XMPP I am trying to establish a XMPP connection to talk.google.com on port 5222, however I am getting a 301 MOVED PERMANENTLY response redirecting me to hangouts.google.com.
I know Google abandoned GTalk, and what I could find is really inconclusive of whether the service is actually still up and running (although not maintained), or not.
I almost gave up thinking it is just not there anymore, however last try using external client (Adium...like Pidgin but for Mac) instead of my own library (XMPP-PHP), ended up actually connecting to the server and sending messages all fine.
Is there something I'm missing?

A: You want to do an DNS SRV record lookup to find the actual server to connect to, eg https://kingant.net/check_xmpp_dns/?h=gmail.com says that the client records for gmail.com's XMPP server are xmpp.l.google.com and alt{1..4}.xmpp.l.google.com
Alternatively, you could use a hangups-based solution to speak the native Hangouts protobuf format: https://github.com/tdryer/hangups/

A: I have found the right URL to be talk.l.google.com.


text:
Q: How to apply query on List objects in java I am doing some project in Java. I need some help regarding applying query/filter on List objects in Java. Like we can have query in C# i.e.
List<ReplicaManagerCustom> replicamanager;
replicamanager.where(x=>x.Id>6)

I want to make my searching easy in java on list objects. Kindly help me

A: You need to do it yourself, manually. I.e. using if-else structures in Java prior to Java 8. In java 8 u can use Stream with lambdas to filter them. Also you can use Google Collections, it have API for managing collections in functional style


text:
Q: Reset orders,invoices and shipping to 000001 How can i reset orders,invoices and shipping to 000001 in magento Comunnity 1.7.0.2 ?
What is the simplest and safest method ?

A: There is a table in the database which stored increment id of order.
It is called "eav_entity_store" table.
You can check which entity type id belongs to which entity by looking at eav_entity_type table.
You can run following query to update last increment id for the order.
update eav_entity_store
inner join eav_entity_type on eav_entity_type.entity_type_id = eav_entity_store.entity_type_id
set eav_entity_store.increment_last_id=000001
where eav_entity_type.entity_type_code='order';


text:
Q: How can I use a passive form of a gerund to replace the bold words? During studying the book of "Top Notch", I come across the below sentence. Who can help me use a passive form of a gerund to replace the bold words?

We can't tolerate their calling us While we are eating dinner.

A: It was two separate sentences:

1-     They call us While we are eating dinner.
2- We can't tolerate it.

After the combination of the two sentences, you have:

We can't tolerate their calling us while we are eating dinner.

Now for using a passive form of a gerund to replace with the bold words, you can have:

We can't tolerate being called by them while we are eating dinner.


text:
Q: how to display data in next line in ng-repeat? I need to display data in next line inside ng-repeat loop. But I am not able to find how to do it. Can anyone suggest me how to do it.
JS:
 $scope.array ={dates:[]};
 $scope.array ({display:display});
 var display = day+ "\n" + date;

Here day=mon, tue,  etc and date contains 4,5,6.. etc..
I want to display this as,
MON     TUE
5       6

HTML:

{{days.display}}

A:

angular.module('todoApp', []).controller('TodoController', function($scope) {
  $scope.array = {
    'date': ['Mon 5', 'Tue 6']
  };
});

{{date.split(' ')[0]}}

{{date.split(' ')[1]}}

Between {{ }} you can write javascript codes and angular will parse and run it.

A: HTML:

{{ k.split(' ')[0] }}
 {{ k.split(' ')[1] }}

Script:
angular.module('myapp',[])
 .controller('myctrl',function($scope){
    $scope.array ={dates:['MON 5', 'TUE 6']};
 });

A: Please check if this is what you need.
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.array = ['MON  5 10', ' TUE 6 11'];
    var data = {
        headers : [],
        rows : []
    };
    var array = $scope.array;
    for(var index in array){
        data['headers'].push(array[index].trim().split(/\s+/)[0]);
        data['rows'].push(array[index].trim().split(/\s+/).splice(1))
    }

    data['rows'] = data['rows'][0].map(function(col, i) {
      return data['rows'].map(function(row) {
        return row[i]
      })
    });

    $scope.data = data;
}

    {{header}}

        {{item}}

JS-Fiddle link


text:
Q: Is there a plugin to validate jQuery code? Is there a jQuery plugin which can check our code before launch it ?
Example:
I write this :
jQuery('.myclass')css('color','red');

The plugin will show me some message like 'parse error line ...' because I forgot a period
Or:
function test() {
    alert('test');
...
tet();

Message: The tet() function doesn't exist.
EDIT: or maybe it could be some Firefox plugin ?

A: This can't be a plugin because if you have syntax errors in your code, the browser will stop execution and show an error. JSLint is an online service you could use to validate your javascript.

A: In addition to the above suggestions, you may also want to look at jQuery-lint - a script that checks your jQuery codes as they run and report incorrect or suboptimal usage usage of the jQuery API.

A: As 'Darin Dimitrov' said jQuery is not a language to have some special syntax but it is a javascript library so the syntax validation should be done against javascript
If you are using a IDE like Eclipse there are javascript plugins like spket, aptana which will help you to find out some syntax errors


text:
Q: Generalized unique nearest point problem for a compact, convex set in a strictly convex Banach space. If $X$ is a Real Banach space with strictly convex norm, it is known that for any non-empty compact, convex set $K$ and point $x_0\notin K$, there exists a unique point $z_0\in K$ minimizing the quantity $\|z-x_0\|$ in $z\in K$.
My question is whether it is known if the obvious generalization holds:

Given two (or n) points $x_0,x_1\notin K$ so that the set $\{x_0,x_1\}$ is separated from $K$ by an affine hyperplane, then there exists a unique point $z_0\in K$ minimizing the quantity $\|z-x_0\|+\|z-x_1\|$ in $z\in K$.

My feeling is that this should have been investigated somewhere in the literature, but in my inexperience navigating that landscape I had thus far been unable to find it.

A: The answer is YES.
The function $\mathrm{dist}_x$ is strictly convex at any point $y$ and any direction different $x-y$.
It follows that $f=\sum \mathop{\rm dist}_{x_i}$ is strictly convex at any point if $x_i$ do not lie on one line;
in this case uniquness is obvious.
If there is a line, say $\ell$ containing all $x_i$, then $f$ is strictly convex in any half-space not intersecting $\ell$. Hence the result.


text:
Q: Prove that $\lim_{n \to \infty}\bigg[\int_0^1f(t)^n \text{dt}\bigg]^{1/n}=M$ Suppose that $f$ is a continuous, non-negative function on the interval $[0,1]$. Let $M$ be the maximum of $f$ on the interval. Prove that $$\lim_{n \to \infty}\bigg[\int_0^1f(t)^n \text{dt}\bigg]^{1/n}=M$$
We wrote out some simple examples to show it worked for functions such as $x^2$. We are having trouble finding how to create a general proof. Thanks for any help!

A: Hint: Let $x_0$ be such that $f(x_0) = M$.  Fix $\epsilon > 0$.  There exists a $\delta > 0$ such that $f(x) > M - \epsilon$ whenever $x \in (x_0-\delta,x_0 + \delta)$. Conclude that
$$
\lim_{n \to \infty}\bigg[\int_0^1f(t)^n \text{dt}\bigg]^{1/n}\geq M - \epsilon
$$
However, $\epsilon$ was arbitrary.

A: A more general statement is that, if $0<\mu(X)<\infty$ and $f\in L^{\infty}(X)$, then $\lim_{p\rightarrow\infty}\|f\|_{L^{p}}=\|f\|_{L^{\infty}}$:
$\|f\|_{L^{\infty}}\\
=\lim_{\epsilon\rightarrow 0^{+}}(\|f\|_{L^{\infty}}-\epsilon)\\
=\lim_{\epsilon\rightarrow 0^{+}}\lim_{p\rightarrow\infty}(\|f\|_{L^{\infty}}-\epsilon)(\mu(S_{\epsilon}))^{1/p},~~~~S_{\epsilon}=\{|f|>\|f\|_{L^{\infty}}-\epsilon\}\\
\leq\liminf_{\epsilon\rightarrow 0^{+}}\liminf_{p\rightarrow\infty}\left(\displaystyle\int_{S_{\epsilon}}|f|^{p}d\mu\right)^{1/p}\\
\leq\liminf_{\epsilon\rightarrow 0^{+}}\liminf_{p\rightarrow\infty}\|f\|_{L^{p}}\\
\leq\limsup_{p\rightarrow\infty}\|f\|_{L^{p}}\\
\leq\limsup_{p\rightarrow\infty}\|f\|_{L^{\infty}}(\mu(X))^{1/p}\\
=\|f\|_{L^{\infty}}$


text:
Q: Should typescript infer 'this' to be of type 'any' for class instance methods? It seems that within an instance method for a typescript class, the typescript compiler believes that 'this' is the same type as the declaring class.
For example:
class Person {
    private name: string;

    constructor(name) {
        this.name = name;
    }

    public showName() {
        //Typescript believes 'this' is a 'Person', but it could be anything!

        var me: Person = this;

        alert("My name is " + this.name);
    }
}

class Introducer {
    public introduce(person: Person) {
        setTimeout(person.showName, 1);
    }
}

var introducer: Introducer = new Introducer();
var bob = new Person("Bob");

this.name = "Dave";

introducer.introduce(bob);

In the showName function, typescript things that 'this' is a 'Person'. However, that is not always guaranteed to be the case - as with the example shown by the Introducer class (the output is "My name is Dave", NOT "My name is Bob").
Given this possibility, why is the type of 'this' not 'any' within class instance methods?

A: The compiler has the reasonable assumption that you will be within the scope of the class that you created when the code runs. There are several tools available to you to make sure that your methods are called within that scope including arrow-functions () =>, call and apply. You can use these to bind the method calls to the class context in situations such as you describe.
Here is an example using the arrow-function, this gives you a class guarantee:
class Person {
    private name: string;

    constructor(name) {
        this.name = name;
    }

    showName = () => {
        //'this' is a definitely a 'Person'

        var me: Person = this;

        alert("My name is " + this.name);
    }
}

Although I prefer to resolve the scope from the caller when the caller is causing a change in scope, like this:
class Introducer {
    public introduce(person: Person) {
        setTimeout(() => person.showName(), 1);
    }
}


text:
Q: If X is uniformly distributed over $(-5,5 )$ find $P(|x|\gt 3)$ How I approached this question was taking the intergral from -5 to -3 of 3dx and then from 3 to 5 of 3dx to get 12. Did I do that wrong?
Also part b of this question says To find the density function of |x|, for this I just took the probability of -a <= X <= a. To do this I took the derivative of F(a)/da = 1 to get that it's uniformly distributed on (0,1).
I'm not sure if I'm correct, any help is appreciated.

A: You did a mistake. Note that $3$ is not the density of $X$. As $X$ is uniformly distributed, $X$ has a constant density $f_X(x) = c$, for some $c \in \mathbf R$. As we must have
$$ 1 = P(-5 \le X \le 5) = \int_{-5}^5 f_X(x)\, dx = \int_{-5}^5 c\,dx = 10c $$
we have $f_X(x) = \frac 1{10}$. Now continue as you did, we have
$$ P(|X| > 3) = \int_{-5}^{-3}\frac 1{10}\, dx  + \int_3^5 \frac 1{10}\, dx = \frac 25 $$
For the density of $|X|$, let $a \in (0,5)$, we have
\begin{align*}
   P(|X| < a) &= \int_{-a}^a f_X(x)\,dx\\
              &= \frac a5
\end{align*}
Taking derivatives, as you did correctly, we have
$$ f_{|X|}(a) = \frac 15, \qquad a \in (0,5)$$
Hence, $|X|$ is uniformly distributed on $(0,5)$.

A: $\int_{3}^{5}\frac{1}{10}dx + \int_{-5}^{-3}\frac{1}{10}dx= 4/10$


text:
Q: Getting error "a nonstatic member reference must be relative to a specific object" while both member are in the same class I know this question had been asked many times but I'm still stuck. I thought I got what this error was about what obviously I don't.
So, the error I am getting is
a nonstatic member reference must be relative to a specific object

My code is:
class theTranslator {
public:
    ros::NodeHandle nh;

    ros::Publisher pub = nh.advertise<sensor_msgs::Image>("camera/depth/image_raw", 100);

    static void getMessage(const sensor_msgs::Image::ConstPtr& recMmsg) {
        ROS_INFO( "I heard message" );
        pub.publish(recMmsg); //*** ERROR IS HERE ***
    }
};

since pub is part of the same class as getMessage(), shouldn't it work? How can I make a static member function use a variable member of the same class?
P.S. this is done in ROS (Robotics Operating System) but I believe this is a C++ mistake (not related to ROS).

A: In C++ you can not access a non static class member from a static method. Make it a normal method and try like below:-
 void getMessage(const sensor_msgs::Image::ConstPtr& recMmsg){
        ROS_INFO( "I heard message" );
        pub.publish(recMmsg); //*** ERROR IS HERE ***
    }

Else declare pub as static member
static ros::Publisher pub;

Also refer to the below answer
C++ static member functions and variables

A: You need to make getMessage non-static or you need to make pub static.
Probably what you really need to do is rethink your design. Why are you trying to make getMessage static? As a very general rule of thumb static is a mistake, especially for a newbie.


text:
Q: How to merge type signatures with type properties How does one merge types that have both call signatures and properties, without resorting to the intersection &?  Intersection & creates types that are shown as e.g. Foo & { a: string } & { ()=>void } & Bar which may be hard to understand and abstract.  When what one wants is {()=>void, a: string, b: string, c: number } which can be simpler to parse.
type Merge<T1, T2> = {
  [k in keyof T1 | keyof T2]: k extends keyof T1 ? T1[k] : k extends keyof T2 ? T2[k] : never;
}

type Foo = {
    (a: string): number;
    (a: number): number;
    foo1: string
}

type Bar = {
    bar1: number
}

type FooBar = Merge<Foo, Bar> // Merge excluding the call signatures - how does one include the call signatures?
/* end type should be:
type FooBar = {
    (a: string): number;
    (a: number): number;
    foo1: string
    bar1: number
}
and not be an intersection `Foo & Bar`
*/

code

A: No, there is currently (TS4.7) no way to do this programmatically without using intersection types.
Mapped types do not preserve call signatures; there is a feature request at microsoft/TypeScript#29261 asking for some way to do this (well, it technically asks about construct signatures, but this comment mentions pulling signatures out of a type).
You could try to do this by making the intersection and then teasing out the resulting multiple call signatures (i.e., overloads), but unfortunately there is no good programmatic way to do this, see this answer for more information.  Even if you could do this you'd probably have to resort to intersections to combine them again.
For now, I'd say that intersection types are the best you can do.


text:
Q: Why is custom ExpandableListView not displayed in android I am trying to make custom ExpandableListView having child or node. But some parents don't have children. I don't want to show anything. In other words
I need to display like that
Parent 1
parent 2
  child1
  child2
  child3
parent 3
parent 4
  child1

So I try like this  I make a xml route_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ExpandableListView
        android:id="@+id/expandableListView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
   >
    </ExpandableListView>

</RelativeLayout>

custom adapter
public class CustomExpendableListView extends BaseExpandableListAdapter {
    private String[] fatherName={"naveen","ravi","sharma","uncle","rahat"};
    String[] raviChildrenname={"abc","pqr","mnn"};
    String[] sharmaChildrenname={"zxa","yh","er"};
    Context context;
    public CustomExpendableListView(Context context) {
        this.context=context;
    }

    @Override
    public int getGroupCount() {
        return 0;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return 0;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return null;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return 0;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
          LayoutInflater mInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.parenttextview, null);
        }
        TextView item = (TextView) convertView.findViewById(R.id.parentTextView);
        item.setText(fatherName[groupPosition]);
        return item;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        return null;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return false;
    }

}

call main function
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.route_dashboard);
    expendablelistView = (ExpandableListView) findViewById(R.id.expandableListView1);
    adapter = new CustomExpendableListView(this);
    expendablelistView.setAdapter(adapter);
}

child.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/childTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

parenttextviewxml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/parentTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

I take three array
private String[] fatherName={"naveen","ravi","sharma","uncle","rahat"};
        String[] raviChildrenname={"abc","pqr","mnn"};
        String[] sharmaChildrenname={"zxa","yh","er"};

fatherName is the parents nodes.raviChildrenname is the child of ravi parent node .sharmaChildrenname is the child of sharma
could you please give some code.?

A: Your getGroupCount method must return value greater than zero. In this case only list view will display something
Something like that:
@Override
public int getGroupCount() {
    return fatherName.length;
}

@Override
public int getChildrenCount(int groupPosition) {
    if (fatherName[groupPosition].equalsIgnoreCase("ravi")) {
            return raviChildrenname.length;
    }

    if (fatherName[groupPosition].equalsIgnoreCase("sharma")) {
            return sharmaChildrenname.length;
    }

    return 0;
}

You also need to implement getChildView method for this listView:
@Override
public View getChildView(int groupPosition, int childPosition,
        boolean isLastChild, View convertView, ViewGroup parent) {
    View convertView, ViewGroup parent) {

     LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.childView, null);
    }
    TextView item = (TextView) convertView.findViewById(R.id.childTextView);

     if (fatherName[groupPosition].equalsIgnoreCase("ravi")) {
            item.setText(raviChildrenname[childPosition]);
    }

    if (fatherName[groupPosition].equalsIgnoreCase("sharma")) {
            item.setText( sharmaChildrenname[childPosition]);
    }

    return item;
}