Prove that convex function on $[a,b]$ is absolutely continuous

Question: In the book Roberts, Varberg, Convex functions, on pp.9-10 is proved that

If $f:(a,b)\rightarrow \mathbb R$ is continuous and convex then $f$ is absolutely continuous on each $[c,d]\subset (a,b)$.

How can this be extended to the case when the domain of $f$ is instead $[a,b]$?
Edit
I wish to prove the following theorem:

If $f:[a,b] \rightarrow \mathbb R$ is continuous and convex then $f(b)-f(a)=\int_a^b f'(t)dt$.

Thanks
Comment: First of all, if $f$ is convex on $(a,b)$ then it is automatically continuous.
http://math.stackexchange.com/questions/258511/proof-of-every-convex-function-is-continuous
Comment: If you explicitly require the continuity on $[a,b]$, it is okay, the absolute continuity of $f$ on $[a,b]$ follows. If not, $f$ could be discontinuous at $a$ and/or $b$.
Comment: Yes, I know, but some authors by convex function mean Jensen convex function, which need not be continuous.
Comment: I guess it is not true on the whole domain $[a,b]$.
Answer: Suppose that $f\colon (a,b)\to \mathbb{R}$ is convex. Consider the function
$$F(x,t) = \frac{f(x+t) - f(x)}{t}\quad(t\neq 0).$$
Then $F$ is increasing in each variable. So $F$ is uniformly bounded on each compact subinterval $[c,d]\subset (a,b)$. In particular, $f$ is Lipschitz on $[c,d]$ hence absolutely continuous.
Comment: Thanks, but I need absolutely continuity also on the whole $[a,b]$.
Comment: @Richard: But $f$ is not even defined on the whole $[a,b]$!
Comment: In my question $f:[a,b] \rightarrow \mathbb R$.
Answer: Hint.  It should be enough to use the case from the book, together with:
If $\phi$ is nondecreasing, then
$$
\int_a^b \phi(t)\,dt = \lim_{\alpha\searrow a, \beta \nearrow b} \int_\alpha^\beta \phi(t),dt
$$
Comment: Does there always exist integral $\int_a^bf'(t)dt$  for convex $f$ ? In general the values $f'(a)$, $f'(b)$ can be in finite for convex continuous $f$.
Comment: But the limit of $f(\beta) - f(\alpha)$ is finite, right?
Comment: Ok, this limit is $f(b)-f(a)$, what is needed. Many thanks for explanation.


Calculating the resultant of two forces and angle?

Question: A force of $256 N$ and a vertical load of $537 N$. Trying to work out the resultant of the two forces and the angle at which it acts to the horizontal?
Comment: Welcome to Math.SE! Can you please clarify your question, I think we are lacking information here. In what direction does the force act?
Comment: The only information I have is that (A parting tool is fed into a work piece, in this case a component for a vehicle, with a force of 256N and the vertical load on the tool tip is 537N. Attempting to calculate the resultant of the two forces and the angel at which it acts to the horizontal.
Comment: Looks to be solved
Comment: This is what we have worked out, in the end we calculated it as 537N as 90 degrees and 256N at 0 degrees, the question was from a college assignment which was poorly written and since scrapped.
R² = 537² + 256²
= 353905
R = 594.9N

tan(theta)=opposite/adjacent
tan(theta)=(537/256)
theta=tan^-1(537/256)
theta=64.512 degrees above horizontal
Answer: HINT:
The resultant ($R$) of any two forces say $P$ & $Q$ having angle $\alpha$ between them is given as $$R=\sqrt{P^2+Q^2+2PQ\cos \alpha}$$
The acute angle $\theta$ between the resultant & the force $P$  is given as
$$\theta=\tan^{-1}\left|\frac{Q\sin \alpha}{P+Q\cos \alpha}\right|$$


Bash shell: Count occurrences of pattern (in one file) listed in arrays (array elements loaded from different file)

Question: Hi I have loaded patterns of pattern.txt file into array and now I would like to grep count of each array element from second file (named as count.csv)
pattern.txt
abc
def
ghi

count.csv
1234,abc,joseph
5678,ramson,abc
2231,sam,def
1123,abc,richard
2521,ghi,albert
7371,jackson,def

bash shell script is given below:
declare -a myArray

myArray=( $(awk '{print $1}' ./pattern.txt))

for ((i=0; i < ${#myArray[*]}; i++))
do
   var1=$(grep -c "${myArray[i]}" count.csv)
   echo $var1
done

But, when I run the script, instead of giving below output
3
2
1

It gives output as
0
0
1

i.e. it only gives correct count of last array element.
Answer: grep + sort + uniq pipeline solution:
grep -o -w -f pattern.txt count.csv | sort | uniq -c

The output:
  3 abc
  2 def
  1 ghi

grep options:

-f - obtain pattern(s) from file
-o - print only the matched parts of matching lines
-w - select only those lines containing matches that form whole words

The alternative awk approach:
awk 'NR==FNR{p[$0]; next}{ for(i=1;i<=NF;i++){ if($i in p) {p[$i]++; break} }}
     END {for(i in p) print p[i],i}' pattern.txt FS="," count.csv

The output:
2 def
3 abc
1 ghi

p[$0] - accumulating patterns from the 1st input file (pattern.txt)
for(i=1;i<=NF;i++) - iterating though the fields of the line of the 2nd file (count.csv)
if($i in p) {p[$i]++; break} - incrementing counter for each matched pattern
Comment: @RomanPerekhrest #     grep -o -f pattern.txt count.csv | sort | uniq -c
          1 abc
          1 def
          1 ghi
Comment: @laxmansharma, check again - it works fine for your input. Otherwise, you have posted nonactual input. Besides, it should  be executed as one
independent  line, without any loop
Answer: It is better to use awk for processing text files line by line:
awk -F, 'NR==FNR {wrd[$1]; next} $2 in wrd{wrd[$2]++} $3 in wrd{wrd[$3]++}
END{for (w in wrd) print w, wrd[w]}' pattern.txt count.csv

def 2
abc 3
ghi 1

Reference: Effective AWK Programming
Comment: It gives output: ef, ghi and bc
Comment: You probably have DOS line ending in your files. Run `dos2unix` on both files before you run this `awk` command.
Comment: If `dos2unix` is unavailable then `awk -v RS='\r\n' -F, 'NR==FNR {wrd[$1]; next} $2 in wrd{wrd[$2]++} $3 in wrd{wrd[$3]++} END{for (w in wrd) print w, wrd[w]}' pattern.txt count.csv` will also work.
Answer: Try using this command instead:
mapfile -t myArray < pattern.txt
for pattern in ${myArray[*]}; do
  echo $(grep -o $pattern count.csv| wc -l)
done

Output:
3
2
1

mapfile will store every pattern in pattern.txt into myArray
The for loop will iterate through each pattern in myArray and print the number of occurrence of pattern in count.csv
Comment: It gives output '0'
Comment: i m getting strange output. It gives count value of **abc** as 1 but when i put all the field **abc** of 3 rows in third column (pattern.txt file), it gives correct output.
Comment: @laxmansharma Not quite sure what you mean, but it works for both cases where your patterns are on one line (`abc def ghi`) or on separate lines like in your example pattern.txt
Answer: You could also skip the array and just loop over the patterns:
while read -r pattern; do
    [[ -n $pattern ]] && grep -c "$pattern" count.csv
done < pattern.txt

grep -c outputs just the counts of the matches
Comment: It is not giving count value of third pattern (ghi)--only count of abc and def i m getting. Further, i m getting strange output. It gives count value of abc as 1 but when i put all the field abc of 3 rows in third column (pattern.txt file), it gives correct output.


Slow text rendering with many text boxes

Question: I am a Windows Forms developer and I am currently toying around with WPF. To do a quick performance comparison of the two technologies regarding text rendering in text boxes, I wrote a little program that creates a huge number of text boxes in a window and updates their text every 100ms.
To my surprise, the WPF version of the test application renders much slower than the WinForms version. Most of the time the application does not respond at all, for example when I try to resize the window. The WinForms version of the application runs smoothly.
So my question is: Is there something wrong with the way I use the WPF controls (I use a WrapPanel as controls container in WPF and a FlowLayoutPanel in the WinForms)? Or is text rendering really slower than in WinForms?
WPF:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace PerformanceTestWPF
{
    public partial class MainWindow : Window
    {
        DispatcherTimer _timer = new DispatcherTimer();
        Random _r = new Random();

        public MainWindow()
        {
            InitializeComponent();

            for (int i = 0; i < 400; i++)
                this.wrapPanel.Children.Add(new TextBox {Height = 23, Width = 120, Text = "TextBox"});

            _timer.Interval = new TimeSpan(0,0,0,0, 100);
            _timer.Tick += _timer_Tick;
            _timer.Start();

        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            foreach (var child in wrapPanel.Children)
            {
                var textBox = child as TextBox;
                if (textBox != null)
                {
                    textBox.Text = _r.Next(0, 1000).ToString();
                }
            }
        }
    }
}

WinForms:
using System;
using System.Windows.Forms;

namespace PerformanceTestWinforms
{
    public partial class Form1 : Form
    {
        Timer _timer = new Timer();
        Random _r = new Random();

        public Form1()
        {
            InitializeComponent();

            for (int i = 0; i < 400; i++)
                this.flowLayoutPanel1.Controls.Add(new TextBox { Height = 23, Width = 120, Text = "TextBox" });

            _timer.Interval = 100;
            _timer.Tick += _timer_Tick;
            _timer.Start();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            foreach (var child in flowLayoutPanel1.Controls)
            {
                var textBox = child as TextBox;
                if (textBox != null)
                {
                    textBox.Text = _r.Next(0, 1000).ToString();
                }
            }
        }
    }
}

Comment: Wouldn't jump to conclusions here. Maybe it's the dispatcher cycles that are expensive. Can't do profiling on my machine (requires higher credentials); see if you can do that to find out which functions actually are the bottleneck.
Answer: I think the problem is the explicit dispatching, try this binding based example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfPerfTest
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        Timer _timer;
        Random _r = new Random();

        private readonly List<ValueViewModel<string>> _values = new List<ValueViewModel<string>>();

        public MainWindow()
        {
            InitializeComponent();

            for (int i = 0; i < 400; i++)
            {
                var value = new ValueViewModel<string>();
                var tb = new TextBox { Height = 23, Width = 120 };
                tb.SetBinding(TextBox.TextProperty, new Binding("Value") { Source = value });
                this.wrapPanel.Children.Add(tb);
                this._values.Add(value);
            }

            _timer = new Timer(o =>
            {
                foreach (var value in this._values)
                    value.Value = _r.Next(0, 1000).ToString();
            }, null, 0, 100);
        }
    }

    class ValueViewModel<T> : INotifyPropertyChanged where T : class
    {

        private T _Value = default(T);
        public T Value
        {
            get { return _Value; }
            set
            {
                if (value != _Value)
                {
                    _Value = value;
                    OnPropertyChanged("Value");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string name)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}

During resizing it's still choking quite a bit, but other than that it performs much better.
Comment: Thanks, this really works much better. But why is dispatching faster here (I guess some kind of implicit dispatching is happening here, since the timer is now a System.Threading.Timer which executes the callback asynchronously)?
Comment: If you use bindings the dispatching happens implicitly and is thus presumably scheduled more efficiently or the update is merged into the existing loops. The WPF dispatcher internals are fairly complex, would recommend [this article](https://msdn.microsoft.com/en-us/library/ms741870%28v=vs.100%29.aspx) for details.


How to call javascript in MVC3 pattern

Question: I'm new to the ASP.NET MVC 3 pattern and I want to call a JavaScript function in view (or controller), to display the result in a div or span object.
My solution

I create a new ASP MVC3 Solution (using Razor)
Add a new JavaScript in Script folder
Add a simple script function in the new JavaScript file, like this:
function HolaMundo(){
return "hola desde javascript";
}

Add a reference from the JavaScript in the index.csHTML file from my default controller.
@section JavaScript
{

}

Finally add a call for the function:

        result from Javascript

Result
Doesn't work

So, can any help me? I appreciate your help.
Comment: Welcome to StackOverflow Raymundo, I've edited your post to use lists and code blocks, you should be able to do this in the future, and it greatly improves the readability of your post, and allows users to provide better quality answers.
Comment: @Raymundo I'd bet there is a javascript error occuring somewhere that will help you debug the problem.  If you are using Chrome you can find the javascript console (CNTR-SHIFT-I).  If you are using FireFox then use the developer tools in the menu (not sure where they are).  I also think IE has similar javascript debugging.  Try that and post your error here to improve your question.
Answer: You should remove the <text> tags from your script so that the view looks like this:

        result from Javascript

The <text> tag is used by the Razor interpreter to indicate a literal value to be rendered as-is without processing. It's useful when you are mixing server side code with client side markup or script. For example:

Also make sure that the section that you have defined in your Index.cshtml view:
@section JavaScript
{

}

you should make sure that is registered in your _Layout.cshtml somewhere. For example in the . Also make sure that you have included the jQuery script to your page:

    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

    @RenderSection("JavaScript")

...

or even better before the closing  tag which is where it is recommended to place scripts to avoid blocking the browser loading the DOM while fetching them:
    ...

    @RenderSection("JavaScript")

Comment: Thank you very much Darin, i have more clarity now, My problem was resoved, i have a error in my JS but i can see under Kingdago show me the shortcut for the javascript console. I'm very grateful to you. =D

How to call javascript in MVC3 pattern


MySql subquery extraction as per number of days and other criterias

Question: We are facing some problems in building a mysql Query.
Let suppose we save two columns col1 and col2 . Let suppose col1 value is abcd. So we need to find all those rows whose col1 = abcd and after 10 days col2 value is product1 .
Let me try to elaborate with example.

Let me try to break out it into parts
1) All rows whose col1 = abcd and extract there wlid,date
2) Match wlid and date with other rows and col2 = product1 . and date should be more then 10 days. So In this case only 4th row should be output
EDIT Our desired output is 4th Row since by extracting all wlid whose col1 = abcd, so we get row1 and our 2nd condition whose date is more than date which is extracted in 1st condition and col2  value is product1 . So extracted output is only 4th Row
Table  in Text form
Sr.No  wlid  col1  col2      date
1      1     abcd  product1  2017-06-10 04:16:28
2      2     abc   product2  2017-06-12 04:16:28
3      1     ab    product1  2017-06-17 04:16:28
4      1     a     product1  2017-06-21 04:16:28
5      1     a     product2  2017-06-21 04:16:28
Comment: update your question and add the expected  result please (and use text and not image only SO is not a fre coding service)
Comment: hi @scaisEdge I update the question
Answer: You may use:
<code>mysql> select * from demo;

+-------+------+------+-----------+---------------------+
| sr_no | wlid | col1 | col2      | date                |
+-------+------+------+-----------+---------------------+
|     1 |    1 | abcd | product 1 | 2017-06-10 04:16:28 |
|     2 |    2 | abc  | product 2 | 2017-06-12 04:16:28 |
|     3 |    1 | ab   | product 1 | 2017-06-17 04:16:28 |
|     4 |    1 | a    | product 1 | 2017-06-21 04:16:28 |
|     5 |    1 | a    | product 2 | 2017-06-21 04:16:28 |
+-------+------+------+-----------+---------------------+
5 rows in set (0.00 sec)

mysql> select d1.* from demo d1 inner join demo d2 on d1.col2 = d2.col2 where datediff(d1.date,d2.date) >= 10;
+-------+------+------+-----------+---------------------+
| sr_no | wlid | col1 | col2      | date                |
+-------+------+------+-----------+---------------------+
|     4 |    1 | a    | product 1 | 2017-06-21 04:16:28 |
+-------+------+------+-----------+---------------------+
</code>
Comment: Thanks @yusuf but you forget to add a condition where d2 col2 needs to be product 1
Comment: Yes. This is a more generic query which'll give you where ever `col1 = col2`. What you say is a simple statement in `where` condition. Do you want me to structure that query as well? Also, feel free to accept the answer if it helped you :)
Comment: your query is absolutely correct and thanks for help. I am just saying  in your query that part is missing. By the ways thanks a lot, exact this query we are looking for
Comment: Hi this query runs well on small data but our data is more than 3 lakh rows and we index col1,col2,date columns but still performance is very very poor is there anyway to improve it
Comment: your answer contains duplicate rows
Comment: 1. Duplicates can be easily addressed by using `distinct` or `group by` depending upon how your dataset is.
2. The above query is slow because it's not using the `index` because of the datediff function.
Learnings - (a) specify the table structure (PKs / indexes before hand). (b) Execute `explain [your query]` to check the execution plan and usage of keys (I cannot do that because I don't have access to your data). (c) Issues like duplicates etc can be handled at run-time.
Answer: Try this one :
select * from table as t
inner join (select * from table as t2 where t2.col1 = 'abcd') on t2.Sr.No = t.Sr.No
where t2.wlid = t.wlid and t.col2 = 'product1' and t.date >
DATE_ADD(t2.date, INTERVAL 10 DAY);
I have not tested though, let me know if it works for you.


Javascript Function Passing in as parameter

Question: I want to pass some lines of code as parameter.

        function t_1()
        {
            var t6 = '';
            ////
            t_2(d1,d2,d3)
        }

        function t_2(c1, c2, c3)
        {
            var t1 = 12;
            if( t1 >12 )
            {
                // some code here
            }

        }

    </script>

Here in function t_2(), if conditions is static. But can i pass from t_1(). Like, condition in t_2() depends on t6 value in t_1().
Can i pass if condition code or any dynamic variable from t1 that can be executed in t2?
Comment: Outside of your function you can declare a variable? Like var t6 = ''; and then set it in the t_1 function like t6 = 'something'
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function
Comment: You can pass `t6` as parameter while calling `t_2(d1,d2,d3)` and use it inside `t2`.
Comment: i am okay with negative marking, but at least tell the reason for this marking. so i wont make same mistake again.
Answer: You can create anonymous function and pass it as an argument.
function t1()
{
    var x = 17;
    var f = function(a) { return a > x; }; // value of x is captured here inside f
    //                           ^^^^^^ here is expression you can pass around
    t2(f);
}

function t2(f)
{
    var y = 4;
    if(f(x)) {  //  ->  if(f(4))  ->  if(4>17)
        ...
    }
}

Answer: eval() could be a  possible solution.
Eg.
function t_1(){
  var a=5, b=10;
  //make you statement a string, any type of statement can be made string
  var c = "a+b";
  t_2(a,b,c);

}

function t_2(a,b,c){
  var res = eval(c); // here c can be any js statements in String form
}

eval() should be used with high precaution as it can make our application vulnerable to hacking. It should be used very selectively in case where we are getting input from the user.


What will the average amount be by year 2025 and 2050?

Question: The HDI for Burkina Faso is $0.388$. Annually, its average HDI increases by $2.6090\%$. If this continues what will the HDI be by $2025$ and again by year $2050$?
Comment: Instead of thinking how much is added to the HDI, what can you multiply 0.388 by to get next year's HDI?
Answer: If this year's HDI is $x$, next year it will be
$$x + \frac{2.6090}{100}x = \left(1 + \frac{2.6090}{100}\right)x = 1.026090x$$
If you repeat the above reasoning (for example, call the result $y$ and calculate again), you will obtain that, after $n$ years, the HDI will be
$$1.026090^nx$$
Therefore, by $2025$ it will be
$$1.026090^{2025-2014}\cdot0.388 \approx 0.5150765$$
You can repeat the calculation with $2050$.


Why is this coroutines demo crashing?

Question: import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

fun main() {
    coroutines()
    while (true) {
    }
}

fun coroutines() {
    val jobs = 1..100000
    jobs.forEach {
        GlobalScope.launch(Dispatchers.IO) {
            val request = getRequest()
            val client = getClient()
            call(request, client)
        }
    }
}

I am running this on 16GB RAM, High Sierra.
I want to understand what's wrong I am doing here.
My intention is to create a program to understand how many coroutines we can create.
Before the program ends my machine gets restarted.
Answer:
My intention is to create a program to understand how many coroutines we can create.

The program you wrote does not provide you with that answer. Rather, it puts a thin layer on top of the classic Java ExecutorService with up to 64 concurrent threads executing your call(). The reason why your computer reboots is entirely outside the code you posted in the question. It is probably related to what exactly your call() does.
If you want to observe the overhead the Kotlin coroutines introduce, you must write code that doesn't involve any heavyweight operations whose overhead dwarfs that of coroutines. Here's an example:
var maxConcurrentCalls = 0

fun main() {
    runBlocking {
        coroutines()
    }
    println("You launched %,d concurrent coroutines".format(maxConcurrentCalls))
}

fun CoroutineScope.coroutines() {
    var concurrentCalls = 0
    val jobs = 1..1_000_000
    jobs.forEach {
        launch {
            concurrentCalls++
            maxConcurrentCalls = max(concurrentCalls, maxConcurrentCalls)
            delay(1000)
            concurrentCalls--
        }
    }
}

On my computer it ran for about 3 seconds and printed
You launched 1,000,000 concurrent coroutines

Note that all these coroutines executed on the main thread, which is why I had no need for thread-safe counters.

Why is this coroutines demo crashing?


python run apschedule BlockingScheduler only once

Question: I am using the apscheduler to schedule a specific task with an interval of 10 minutes in another thread. This works fine and I can extract also this information in the loggers that I am initiating both in the initial scheduler as well as in the other task. My problem now is when I am trying to execute the scheduler only once and then terminate it together with the application which for some reason it does not happen and the application seems to be still running (waiting for something) and thus without exiting/terminating. Below is the code snippet that I am using:
import os
import sys
import logging
from datetime import datetime
from subprocess import Popen, PIPE
from apscheduler.schedulers.blocking import BlockingScheduler

import recorder
import threading

def run_daily_sessions(thelogger):
    thelogger.info("[{}] - Trigger triggered".format(datetime.now()))
    thelogger.info("[{}] - Going to run daily scheduler script".format(datetime.now()))
    r = recorder.Recorder() # start recorder on another thread
    r.start()

    thelogger.info("[{}] - Ran daily scheduler script".format(datetime.now()))

def main():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler('scheduler.log')
    handler.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    logger.info("[{}] - scheduler.py was run".format(datetime.now()))

    sched = BlockingScheduler()
    logger.info("[{}] - blocking scheduler was created".format(datetime.now()))
    sched.add_job(run_daily_sessions, args=[logger])
    # sched.add_job(run_daily_sessions, 'interval', minutes=10, args=[logger])
    logger.info("[{}] - everyday task added, going to start the scheduler".format(datetime.now()))
    sched.start()
    # sched.shutdown()
    #logging.root.removeHandler(handler)
    return 0

if __name__ == '__main__':
    STATUS = main()
    print("terminating application!!!")
    sys.exit(STATUS)

I have tried to add max_instances=1 as a parameter to the sched.add_job() or add a sched.shutdown() but both did not work either. Then I thought that might be due to the logger instance so I've tried to remove the handler no success with that as well. So I am trying to understand why the application never reaches to print("terminating application!!!") and to exit since the scheduler has completed his task or any child tasks. My experience with threads is limited but I think that I have done things correctly following also some examples in the web thus any idea what I might be doing wrong or missing?

Solution:
thanks to @Alex Grönholm and his feedback using a job function did the trick. Snippet code:
def terminate_scheduler(thesched, thelogger, should_exit=False):
    if should_exit:
        thelogger.info('[{}] - finished scheduler... going to exit'.format(datetime.now()))
        thesched.shutdown(wait=False)

def main():
...
...
...
    sched.add_job(run_daily_sessions, args=[logger])
    sched.add_job(terminate_scheduler, args=[sched, logger, {"should_exit": True}]) # add job function for terminating scheduler
...
...
    sched.start()
...
...
    return 0

if __name__ == '__main__':
    STATUS = main()
    print("terminating application!!!")
    sys.exit(STATUS)

Answer: You seem to be under the impression that the scheduler should terminate on its own, implicitly, once it has no jobs left. This is an incorrect assumption. If you wish to shut down the scheduler, you must do so explicitly from another thread.
Comment: If you put it after `sched.start()`, it will only be called *after* the scheduler has shut down, which makes no sense at all. So you need to call it from either a job function or an event listener.
Comment: but calling `sched.shutdown()` shouldn't terminate the scheduler once all jobs are done?
Comment: The `shutdown()` method will shut down the scheduler regardless of whether the schedules have finished or not. But I don't see you calling this method in the snippet.
Comment: it is below the `sched.start()` commented. As I stated I have used it but still did not allowed me to exit the app.
Comment: I see, indeed using a job function did the trick thanks. I also updated my question with a possible solution. As I said I am new to the subject so couldn't get it in first place.
Comment: Is there something I should add to the documentation of BlockingScheduler to make it more clear that `sched.start()` blocks until the scheduler has been shut down? I would like to avoid confusion like this altogether.
Comment: If I look at the documentation at the moment what is says is that "By default, the scheduler shuts down its thread pool and waits until all currently executing jobs are finished." so here I would say that you might add that it needs to be called from either another job function or an event listener. That should be clear enough then :-).


How can I strengthen the floor above a crawl space in pier and beam construction?

Question: what are the steps  to strengthen pier and beam (sometimes called post and beam) foundation?
i will be installing a 3-5 ton Rocket heated cob bench mass heater in a rambler home in the living room over 8' length of floor space  that has no beams beneath it.
i was told "If you have a suspended floor, the extra weight will probably need additional structural support so your floor doesn't sag."
my research suggests that to reinforce beneath this heater, we would add 1 or 2   6' 4x4 beams going N to S beneath the joists (which go E to W.  these would be nailed into posts nailed into pier blocks which would support the beam which would support joists.
how do i know where the spot i need to reinforce is when i'm in the crawl space?
how much weight can floor w/crawl space beneath, support ?  the rocket heated cob bench mass heater shouldn't be more than 135 lbs/sf.  i asked the local code officials what weight the floor itself is rated for but they didn't give me a clear answer .
Answer: The new support structure with a beam that you are proposing sounds fine.
If you are concerned, then overdo it by doubling the materials for the beam, or placing a steel L-rod 3/8" thick around the beam. Using an L-rod will reduce the number of bolts that you need to put through it into the beam, and will add structural support due to the angle.
The more important thing to remember here is what the pier block sits on. If you have bedrock or a similar rocky aggregate under the house, then you may be able to safely rely on it not shifting or changing over time.
If it is just soil, you can expect that you will get some compacting due to the weight of the heater. Even if you are able to bring in a tamper and pack the soil, you can still expect that over time it will change through natural cycles in the ground.  Instead, place the broad flagstones under the peers to distribute the weight.
Make sure that the flagstones are thick enough that the weight will not crack them – since the breadth of the flagstone is being used to distribute that weight across the soft soil. Do not use metal, as it will rust and deteriorate.
Answer: A typical residential first floor would be built to a minimum live load of 40 PSF. A dead load of 135 (plus any live loads) will stress things just a bit. There's no particular guarantee that your floor meets this standard, it's just a typical one. The odds that it comes anywhere near supporting 135 PSF without help are essentially zero.
Fundamentally, you add more posts and piers to transfer the additional load to the ground. You may also add more joists in parallel with the joists you have. Beams are somewhat optional, but can be useful. You know where to put things by measuring. You know how many you need and the correct sizes by hiring a structural engineer. Or just cut the floor out and build your mass heater from a foundation on, or more typically in, the ground (aligning with typical practice for masonry heaters and removing the excess load from the wooden structure.)
Here's a link to a nice bit from a structural engineer about placing fishtanks (another high load object, though a bit smaller in scale) that might shed a bit of light on floor loads, what we might know about the loads a floor should hold, a great deal of things we don't know about residential floors as built, and even why nobody will tell you what yours will hold.


Orientation of 3 vertices on GUI

Question: I am trying to find the orientation of 3 ordered points in space. I am using the algorithm that I found from this site. https://www.geeksforgeeks.org/orientation-3-ordered-points/
I want to print out the orientation updated on GUI whether it is Clockwise or CounterClockwise when I play with coordinates by slider.
You can view what I did so far in below fiddle.
https://jsfiddle.net/ewLkta45/48/
So to implement this, I added this function.
function findOrientation(){

var Orientation;

var x1=geometry.vertices[0].x;
var y1=geometry.vertices[0].y;
var x2=geometry.vertices[1].x;
var y2=geometry.vertices[1].y;
var x3=geometry.vertices[2].x;
var y3=geometry.vertices[2].y;

Orientation=(y2 - y1)*(x3 - x2) - (y3 - y2)*(x2 - x1);

}

But I do not know how to refresh a text controller. My question is how can I display orientation as CW or CCW  on temp controller whenever I move slider?
Answer: I think dat.GUI is a interface for changing variables not for showing variables, there are many other ways to show the text, e.g. ,
 HTML tag.
You can listen events on dat.GUI controllers:
gui.add(geometry.vertices[0], 'x').name("v1.x").min(-800).max(800).step(5).onChange(function() {
    var text = document.getElementById('text');
    if (findOrientation() < 0) text.innerHTML = 'The orientation of points : CW';
    else text.innerHTML = 'The orientation of points : CCW';
});

Here is my example.
Comment: thank you for the answer. This is a great way to show something on the screen.
Answer: You can use .listen() of a controller to display changes of its value:

var camera, scene, renderer;
var geometry, material, mesh;
var controller;
var orientation = {
  value: 'Sam'
};

init();
animate();

function findOrientation() {

  let Orientation = 0;

  var x1 = geometry.vertices[0].x;
  var y1 = geometry.vertices[0].y;
  var x2 = geometry.vertices[1].x;
  var y2 = geometry.vertices[1].y;
  var x3 = geometry.vertices[2].x;
  var y3 = geometry.vertices[2].y;

  Orientation = (y2 - y1) * (x3 - x2) - (y3 - y2) * (x2 - x1);
  return Orientation;
}

function addDatGui() {
  var gui = new dat.GUI();

  gui.add(geometry.vertices[0], 'x').name("v1.x").min(-800).max(800).step(5).onChange(onFinishChange);
  gui.add(geometry.vertices[0], 'y').name("v1.y").min(-800).max(800).step(5).onChange(onFinishChange);
  gui.add(geometry.vertices[1], 'x').name("v2.x").min(-800).max(800).step(5).onChange(onFinishChange);
  gui.add(geometry.vertices[1], 'y').name("v2.y").min(-800).max(800).step(5).onChange(onFinishChange);
  gui.add(geometry.vertices[2], 'x').name("v3.x").min(-800).max(800).step(5).onChange(onFinishChange);
  gui.add(geometry.vertices[2], 'y').name("v3.y").min(-800).max(800).step(5).onChange(onFinishChange);

  gui.add(orientation, 'value').name("orientation").listen();
}

function onFinishChange() {
  if (findOrientation() < 0) {
    orientation.value = 'CW';
  } else {
    orientation.value = 'CCW';
  }
}

function init() {

  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.z = 1000;

  scene = new THREE.Scene();

  geometry = new THREE.Geometry();
  geometry.vertices = [
    new THREE.Vector3(-94, -200, 0),
    new THREE.Vector3(92, 68, 0),
    new THREE.Vector3(-105, 180, 0)
  ];
  geometry.faces = [new THREE.Face3(0, 1, 2)];
  mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
    color: 0xffff00,
    side: THREE.DoubleSide,
    wireframe: true
  }));
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);

  document.body.appendChild(renderer.domElement);
  renderer.render(scene, camera);
  addDatGui();

}

function animate() {

  requestAnimationFrame(animate);

  //mesh.rotation.y += 0.09;
  mesh.geometry.verticesNeedUpdate = true;
  //if(resultOfOrientation<0) text.val='cw';
  // else text.val='wc';

  renderer.render(scene, camera);

}
body {
  overflow: hidden;
  margin: 0;
}

Comment: Thank you for the answer. :)
Comment: @Applik You're welcome :) Mark the answer as accepted if it solved your problem.

Orientation of 3 vertices on GUI


Beta: Github Codespace, was getting SynatxError, now resolved; however now receiving ImportError

Question: EDIT:
After following xcodz-dot's suggestion, while it was helpful and I believed it has fixed one problem, I recieved an exception in client.py. Traceback:
Traceback (most recent call last):
  File "/workspaces/[repo_name]/resource.py", line 5, in <module>
    from discord_components import DiscordComponents, ButtonStyle, Button
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord_components/__init__.py", line 1, in <module>
    from .client import *
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord_components/client.py", line 3, in <module>
    from discord import (
ImportError: cannot import name 'Guild' from 'discord' (/opt/python/3.10.4/lib/python3.10/site-packages/discord/__init__.py)

Is this a seperate issue or is it in direct causation of changing asyncio.async to getattr(asyncio, "async") in both compat.py and compatibility.py?
Please help me, thx :)
===============================================================
BELOW: OLD QUESTION, LIKELY RESOLVED
I am using Github Codespaces, and in the process of programming my bot, when trying to import discord_components, a SyntaxError is raised. Traceback (bash terminal, linux vm):
@[username]➜ /workspaces/[repo_name] (main ✗) $ /opt/python/latest/bin/python /workspaces/SineBot/resource.py
Traceback (most recent call last):
  File "/workspaces/[repo_name]/resource.py", line 4, in <module>
    from discord_components import DiscordComponents, ButtonStyle, Button
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord_components/__init__.py", line 1, in <module>
    from .client import *
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord_components/client.py", line 3, in <module>
    from discord import (
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord/__init__.py", line 20, in <module>
    from .client import Client, AppInfo, ChannelPermissions
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord/client.py", line 38, in <module>
    from .state import ConnectionState
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord/state.py", line 36, in <module>
    from . import utils, compat
  File "/opt/python/3.10.4/lib/python3.10/site-packages/discord/compat.py", line 32
    create_task = asyncio.async
                          ^^^^^
SyntaxError: invalid syntax

I have tried all soloutions in create_task = asyncio.async: SyntaxError: invalid syntax, except for downgrading to Py3.5 and using rewrite.zip (because it doesn't even exist), but there are functionalities in Py3.10 that I need, and downgrading would be a nightmare, if not, impossible. Note that discord.py works on my local machine.
Here is combat.py for reference:
...
import concurrent.futures
import asyncio

try:
    create_task = asyncio.ensure_future
except AttributeError:
    create_task = asyncio.async # -> where the exception is happening

try:
    run_coroutine_threadsafe = asyncio.run_coroutine_threadsafe
except AttributeError:
...

The same exception is raised when discord.py is imported (before discord_components).
Please help :)
Answer: In python 3.10, async is a keyword just like any other keyword such as while, for, etc... So you cannot write it like that. As far as I can see you are trying to be backwards compatible so you can use getattr builtin function which will resolve the error
...
import concurrent.futures
import asyncio

try:
    create_task = asyncio.ensure_future
except AttributeError:
    create_task = getattr(asyncio, "async") # -> where the exception is happening

try:
    run_coroutine_threadsafe = asyncio.run_coroutine_threadsafe
except AttributeError:
...

Comment: Hi @xcodz-dot, thanks, but it for some reason didn't work. While it did resolve the issue in compat.py, it raised an exception in `/opt/python/3.10.4/lib/python3.10/site-packages/websockets/compatibility.py`, the same one. I tried changing that to `getattr(asyncio, "async")` too, but then I got `ImportError: cannot import name 'Guild' from 'discord' (/opt/python/3.10.4/lib/python3.10/site-packages/discord/__init__.py)`. Is this a seperate issue, or one caused by changing `asyncio.async` to `getattr(asyncio, "async")`?
Comment: That sounds just another issue, because import error likely means that their is something missing. As your question said, I just fixed the SyntaxError without really messing with other things. If you would like, you can open another Question for afformentioned issue. I am not experienced with discord.py and thus only focused on fixing error message.


How to limit my results to only the rows I need?

Question: This is the code I have currently that pulls the top 2 contacts but because every company has more than 2 contacts when I bring in the USERID into picture (that is required) it gives me rows with all Userids for a company although they are not my top 2 Contacts.
select companyid,
 userid,
(case when seqnum = 1 then username end) as  Contact1,
(case when seqnum = 2 then username end) as  Contact2,

from (
select *, row_number() over (partition by companyid order by username) as
seqnum from
( SELECT b.userid, username, a.companyid from [UsersInCompanies] a
JOIN [Companies] c on a.companyid = c.companyid
join [aspnet_Users] b on a.userid = b.userid ) t ) l

Result set I'm getting
CompanyID Userid  Contact1  Contact2
1         xyz-78  Jane Doe1  NULL
1         uik-90  NULL       JD2
1         jkl-70  NULL       NULL
1         abc-60  NULL       NULL

Desired result
CompanyID Userid  Contact1  Contact2
1         xyz-78  JaneDoe1  NULL
1         uik-90  NULL       JaneDoe2

Should I be using some sort of COUNT & TOP functions ?
Comment: Try filtering by `seqnum <= 2`
Comment: *Filtering in a `WHERE` clause at the end of your query: `WHERE seqnum <= 2`. Copy, paste, run, done.
Comment: You have an extra sub-query that isn't really necessary. [**This should get you there**](http://rextester.com/AHPYZ18908)
Comment: Possible duplicate of [Calculate top two performing product categories from Sales data](https://stackoverflow.com/questions/50009033/calculate-top-two-performing-product-categories-from-sales-data)
Answer: You need filtration (i.e. seqnum <= 2) , but i would rewrite it as :
with t as (
        SELECT b.userid, username, a.companyid,
               ROW_NUMBER() OVER (PARTITION BY a.companyid order by b.username) as seqnum
        FROM [UsersInCompanies] a INNER JOIN
             [Companies] c
             ON a.companyid = c.companyid INNER JOIN
             [aspnet_Users] b
             ON a.userid = b.userid
 )
select companyid, userid,
       (case when seqnum = 1 then username end) as  Contact1,
       (case when seqnum = 2 then username end) as  Contact2
from t
where seqnum <= 2;

Answer: I think this is cleaner
with cte as
(
    SELECT b.userid, username, a.companyid,
           ROW_NUMBER() OVER (PARTITION BY a.companyid order by b.username) as rn
    FROM [UsersInCompanies] a
    JOIN [Companies] c
      ON a.companyid = c.companyid
    JOIN [aspnet_Users] b
      ON a.userid = b.userid
)
select ct1.*, cte2.username
  from cte as cte1
  join cte as cte2
    on cte1.companyid = cte2.companyid
   and cte1.rn = 1
   and cte2.rn = 2


android- OnClickListener not work for views inside recycle adapter

Question: I've a recycle view adapter , I've implement addOnItemTouchListener to listen for each row and it works fine .
But I have two buttons in one of my rows and I've set on OnClickListener for them but it's not triggered . this is my code :
holder.register.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ctx.startActivity(new Intent(ctx,Register.class));
                }
            });

I've set android clickable for my buttons but it didn't make any change :
 <TextView
        android:id="@+id/register"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_weight="1"
        android:clickable="true"
        android:textColor="#fff" />

How can I call on click listener for my buttons instead of recycle view TouchListener ?
Comment: show your xml and adapter class
Comment: post your entire adapter code and xml code.
Answer: First of all, as you said you have implemented TouchListener for each row. so your entire row listens to touch even, so another touch event in the same row gets affecting.
You need to override the onInterceptTouchEvent() for each child, otherwise, it will remain an onTouchEvent for the parent.
Better implement your onClick events in view holder itself. Use OnclickListener instead of TouchListener
Hope it helps :)
Answer: try below.
remove android:clickable from xml. and try setOnClickListener
<TextView
        android:id="@+id/register"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_weight="1"
        android:textColor="#fff" />

Comment: can i know why you set onTouchListner for your list item??
Answer: try this way and remove click event android:clickable="true" from xml file and add below code inside bindview holder
holder.detailimage.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(ctx, MainActivity.class);
        ctx.startActivity(intent);
    }
});

Answer: here is a snippet
// adaptor
    public class youradaptor extends RecyclerView.Adapter<youradaptor.ViewHolder>
    {

    // create variable

    OnItemClickListener mOnItemClickListener;

    @Override
    public void onBindViewHolder(Holder holder, int position)
    {
       holder.register.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v)
           {
               mOnItemClickListener.click(position);
           }
       });
    }

    //interface for Click-listener
    public interface OnItemClickListener
     {
       // method name which you can call in main class
       void click(int position);
     }
     public void setOnItemClickListener(OnItemClickListener onItemClickListener)
     {
         mOnItemClickListener = onItemClickListener;
     }
}

in the main class
youradaptorvarialble.setOnItemClickListener(new BrandProductGridAdapter.OnItemClickListener()
{
    @Override
    public void clcik(int position)
    {
    // write you action here
    // enter code here
    }
});


setTimeout stop scrolling function

Question: I have this scroll function that checks for when the end of a div id reached:
function loadOldPosts() {

        $.ajax({
            url: "https://www.example.com/go.php",
            method: "post",
            data:{
                postID: postID
            },
            dataType:"json",
            success:function(data)
            {
                if (data) {

                    setTimeout(loadOldPosts, 5000);

                }
            }

        });

    }

$(window).scroll(function() {

    var $this = $(this);

    if ($this.scrollTop() + $this.height() >= $('#wall_posts').offset().top + $('#wall_posts').height() ) {
        loadOldPosts();
    }

});

I'm trying to make it so that once loadOldPosts runs, it must wait 5 seconds before being able to run again. I though I could accomplish this with setTimeout function but it does not seem to work.
How can I make it to that the function can only run once every 5 seconds at most?
Thanks!
Answer: You can do it with wait for next calling until ajax success/error using following example:
var loading  = true;
function loadOldPosts(){
   if(loading){
     loading  = false;
     $.ajax({
      ...,
      success:function(data){
         loading  = true;
      },
      error:function(data){
         loading  = true;
      }
     })
   }
}

setTimeout stop scrolling function


ReactJS pass component as var (in ecma6)

Question: in one js file I have a component :
import React from 'react';
export default class ImageGrid extends React.Component {
  render(){
    return
ImageGrid1

  }
}

I want to render the above component from another component using a 'var', and I cant figure out the syntax:
import React from 'react';
import ImageGrid from 'components/imageGrid';
class HomePage extends React.Component {
  render() {
    var div1=ImageGrid;
    return (div1); // what is the proper syntax?
  }
}

Comment: `return `, but you should capitalize the variable name, i.e. `var Div1 = ImageGrid` http://jsfiddle.net/69z2wepo/48005/
Comment: My god!!!!! all it needed was a capital letter
Comment: Yeah, because in JSX lowercase components are translated to DOM nodes and uppercase components to React elements. So you should use `var Div1`
Answer: This is what you want.
import React from 'react';
import ImageGrid from 'components/imageGrid';

class HomePage extends React.Component {
  render() {
    var SomeComponent = ImageGrid;

    return <SomeComponent />
  }
}

Comment: as pawel said: you should capitalize the variable name, i.e. var Div1 = ImageGrid


hyperlink isn't working in mac firefox browser

Question: I am facing an  issue on my site. On my site, the a tag text hyperlink isn't working in mac Firefox browser (whether you are giving target blank or not with the a tag, the issue is remain same). But its work fine in other mac browser like chrome, safari or opera. In windows machine, the link is working fine in all browsers. But its not working in mac Firefox. When there is an image link with the a tag, that time the link is working fine. But when the link is with a text, then its not working in mac Firefox browser. I really don't know whether anyone have encountered similar kind of situation before or not. It would be a great help for me if someone can give me an idea how to sort this out.
The code is like the following:

Click
here
to follow mts on Facebook

In the above code, the image is get hyperlinked in all the browser but the text "here" is hyperlinked all the browsers except mac Firefox browser.
Comment: Can you share a code snippet of what the link looks like?
Answer: This might be something to do with the configuration settings of Firefox in the problematic system

Open Firefox
In the URL, type about:config
If presented with a warning, click the button and proceed to next page
In the search text box on top, type 'dom.popup_allowed_events'. In the value column, make sure that it has following events 'change click dblclick mouseup reset submit touchend'
Close the browser and try your code

If the click event is not allowed to open a popup (i.e. _blank), it would be captured by Firefox as a popup and you'd see that yellow bar on top
Comment: @indy The default configuration is the one provided in this answer, your users will not likely face this issue. Also, if they had modified it, it's probably because they don't want to be bothered with popup windows, don't try to workaround this
Comment: @Kaiido actually the users are facing this issue. The default configuration is solving my problem but not all the users problem who are facing this issue.
Comment: Then remove the `target="_blank"` But your page might not be the only one where they're facing the issue so I would tell them to check their configuration.
Comment: @Kaiido its not a target="_blank" issue. I have removed the target blank but the behavior is still the same. Not working in mac firefox browser only. Also I have checked the configuration and in 39 version of Firefox, that option is already there 'change click dblclick mouseup reset submit touchend'..so there has to be something else.
Comment: Then go back to [first comment](http://stackoverflow.com/questions/31397119/hyperlink-isnt-working-in-mac-firefox-browser#comment-50769897)
Comment: @Kaiido In your first comment, you mentioned about the default configuration is the answer. But as I said in 39 version of Firefox, that option is already there. In about:config, under type 'dom.popup_allowed_events', the value column is already showing like this 'change click dblclick mouseup reset submit touchend'..so what to change in here. Its already there in firefox and still not working. Any other idea?
Comment: No I mean the first comment on your question, [follow the link](http://stackoverflow.com/questions/31397119/hyperlink-isnt-working-in-mac-firefox-browser#comment-50769897). Which is asking your for a code snippet, I would even add a working one, where we could reprodruce it (i.e http://jsfiddle.net/)


Grout gap - best way to fix?

Question: I just had a full bathroom reno done and Kerdi board was used on walls, floor, bench and shelves in fully tiled shower; however, I have a gap in the middle of the bottom of the bench where it meets the shower floor. It looks like clear silicone was used over grout but I can stick my nail in the gap so it isn't "sealed". I'm not so worried about water damage (maybe a little though) since kerdi board was used but aesthetically it is driving me mad. Anyway, could I just put some grout in the gap to make it less noticeable? Or would caulk work? All the work was just finished about a month ago so I have grout and matching caulk left over - just don't want to make anything look bad since job was very well done (just this small imperfection). Fixed! (Second pic)
Comment: Without a photo, its guess work.
Comment: Shoot, didn't realize I could add photos. Just updated my original post with image. Thx!
Answer: You can purchase color-matched silicone caulking in the same color of the grout. I'd lay that in to the gap.
Comment: It is always recommended to use elastomeric sealers (i.e. caulk) rather than grout at changes of plane (i.e. corners).
Comment: @kreemoweet thanks! Took that advice and closed it up just now. Added my after pic under original photo. I'm definitely a rookie caulker (maybe used caulk twice in my life) but I think this girl didn't do too bad of a job :) a little worried that the hole on the left was a weep hole though which I closed. There are a couple others though that are open.

Grout gap - best way to fix?


How to inject a message selector to message listener bean in jms-spring integration?

Question: I'm working with JMS API (with HornetQ) and i'm using spring beans for message listener container and message listener:
<bean id="messageListener" class="core.messaging.handler.MessageListener">
    <property name="postCommandService" ref="postCommandService" />
</bean>

<bean id="messageSender"
    class="lsn.messaging.sender.MessageSender">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="destination" />
</bean>

<bean id="msgListenerContainer"
  class="org.springframework.jms.listener.DefaultMessageListenerContainer"
  p:connectionFactory-ref="connectionFactory"
  p:destination-ref="destination"
  p:messageListener-ref="messageListener"
  p:concurrentConsumers="10"
  p:maxConcurrentConsumers="50"
  p:receiveTimeout="5000"
  p:idleTaskExecutionLimit="10"
  p:idleConsumerLimit="5" />

If i want my message listener, only consume specific messages (that have same StringProperty) what should i do? Where should i define selector?
I have below solution, but i don't have MessageConsumer and so i can't add selector to it:
     String redSelector = "color='red'";

     MessageConsumer redConsumer = session.createConsumer(queue, redSelector);
     redConsumer.setMessageListener(new SimpleMessageListener("red"));

     TextMessage redMessage = session.createTextMessage("Red");
     redMessage.setStringProperty("color", "red");

     producer.send(redMessage);

Answer: You should be able to add it to the MessageListenerContainer this way:
p:messageSelector="color='red'"
Comment: For more than 1 destination you can probably just register more messagelistenercontainers - regarding more than 1 messagelistener per container - you can essentially dispatch it internally within the messagelistener - get the message inside the messagelistener and delegate the message to more beans inside the messagelistener.
Comment: Thanks! Can MessageListenerContainer have more than one destination? or more than one messageListener?


Cannot add ggproto objects together

Question: I'm currently working on an Rshiny app. I had to make multiple boxplots with several select inputs and a checkbox input. I've almost finished my task and now I just need to make it so that every time I change the Species selected, the scale stays the same (unless other variables have been input of course).
My code looks like this:
library(shiny)
library(palmerpenguins)
library(dplyr)
library(ggplot2)

data <- na.omit(penguins)

colnames(data) <- c("Species",
                    "Island",
                    "Bill Length (mm)",
                    "Bill Depth (mm)",
                    "Flipper Length (mm)",
                    "Body Mass (g)",
                    "Sex",
                    "Year")

data.numeric <- data[, c(3:6, 8)]

data.categorical <- data[, c(1,7)]

ui <- fluidPage(
  headerPanel("Penguin boxplots"),
  selectInput("ycol",
              "Numeric Variable",
              names(data.numeric),
              selected = names(data.numeric)[3]),
  selectInput("xcol",
              "Categorical Variable",
              names(data.categorical),
              selected = names(data.categorical)[2]),
  checkboxInput("split",
                "Split levels by Island",
                value = FALSE),
  selectInput("species",
              "Species Type",
              c("Unspecified", levels(data$Species))),
  mainPanel(
    plotOutput("plot1")
  ))

# 4. Use a select input to allow the user to view separate plotting
# panels for each species, with each plot panel on the same scale.

server <- function(input, output){
  output$plot1 <- renderPlot({
    par(mar = c(5, 4.1, 0, 1))

    if (input$species == "Unspecified"){

      if (input$split) {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]], fill = Island)) +
          geom_boxplot(na.rm = TRUE) +

          if (input$ycol == "Bill Length (mm)"){
              coord_cartesian(ylim = c(30, 60))
          } else if (input$ycol == "Bill Depth (mm)"){
            coord_cartesian(ylim = c(12.5, 21.5))
          } else if (input$ycol == "Flipper Length(mm)"){
            coord_cartesian(ylim = c(170, 232))
          } else if (input$ycol == "Body Mass (g)"){
            coord_cartesian(ylim = c(2500, 6500))
          } else if (input$ycol == "Year"){
            coord_cartesian(ylim = c(2006, 2009))
          } +
          xlab(input$xcol) +
          ylab(input$ycol) +
          scale_x_discrete(labels = c("Female", "Male")) +
          theme(text = element_text(size = 15))

      } else {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]])) +
          geom_boxplot(na.rm = TRUE) +
          if (input$ycol == "Bill Length (mm)"){
            coord_cartesian(ylim = c(30, 60))
          } else if (input$ycol == "Bill Depth (mm)"){
            coord_cartesian(ylim = c(12.5, 21.5))
          } else if (input$ycol == "Flipper Length(mm)"){
            coord_cartesian(ylim = c(170, 232))
          } else if (input$ycol == "Body Mass (g)"){
            coord_cartesian(ylim = c(2500, 6500))
          } else if (input$ycol == "Year"){
            coord_cartesian(ylim = c(2006, 2009))
          } +
          xlab(input$xcol) +
          ylab(input$ycol) +
          theme(text = element_text(size = 15))
      }

    } else {

      data <- data %>%
        filter(data$Species == input$species)
      if (input$split) {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]], fill = Island)) +
          geom_boxplot(na.rm = TRUE) +
          xlab(input$xcol) +
          ylab(input$ycol) +
          scale_x_discrete(labels = c("Female", "Male")) +
          theme(text = element_text(size = 15))

      } else {
        ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]])) +
          geom_boxplot(na.rm = TRUE) +
          xlab(input$xcol) +
          ylab(input$ycol) +
          theme(text = element_text(size = 15))
      }
    }

  })
}

shinyApp(ui = ui, server = server)

The issue arises when I run the lines containing else if (input$ycol == "Year"){ coord_cartesian(ylim = c(2006, 2009))} as I get the following error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?
I'm not sure where I'm going wrong here or if I'm just overlooking some sort of syntax error.
p.s. The code isn't finished - I still need to add more code to control the scales for when the Species is not 'Unspecified', but I'm not doing that until this is figured out.
Comment: Try just `else` in the last ggplot statement instead of `if else`.
Comment: See I thought that before and tried it but it wasn't working. I've changed it back again to that and it's still not working. Still says the same error. Here's the line of code now:

else { coord_cartesian(ylim = c(2006, 2009))}
Answer: You can simplify things by creating a function that returns the desired coord_cartesian statement. The function can then be added to a ggplot chain with + as in the usual ggplot workflow.
The example below uses the hard-coded choices in your example. However, if you can provide more information on how these ranges are selected, it may be possible to get the y-range in a more automated way, rather than having to explicitly hard-code each possible case.
In the example below, the case_when statement returns the appropriate ylim values to feed to coord_cartesian. If input$ycol does not match any of the options, case_when will return ylim=c(NA,NA), which will result in ggplot keeping the default axis range.
# I've included only 3 choices. Add in as many additional choices as needed.
coord_fnc = function(x=input$ycol) {
  ylim = dplyr::case_when(
      x=="Bill Length (mm)" ~ c(30,60),
      x=="Flipper Length(mm)" ~ c(170, 232),
      x=="Bill Depth (mm)" ~ c(12.5,21.5)
  )
  coord_cartesian(ylim=ylim)
}

ggplot(data, aes(x = data[[input$xcol]], y = data[[input$ycol]], fill = Island)) +
  geom_boxplot(na.rm = TRUE) +
  coord_fnc() +
  xlab(input$xcol) +
  ylab(input$ycol) +
  theme(text = element_text(size = 15))

Try it with the built-in mtcars data frame:
ggplot(mtcars, aes(hp, mpg)) +
  geom_point() +
  coord_fnc("Bill Length (mm)")

Although the string of if else statements takes a lot of code, that approach can work and I'm not sure why you're getting an error (it might be some other part of the code). For example, this works:
input = list(ycol = "Year")

ggplot(mtcars, aes(hp, mpg)) +
  geom_point() +
  if (input$ycol == "Bill Length (mm)"){
    coord_cartesian(ylim = c(30, 60))
  } else if (input$ycol == "Bill Depth (mm)"){
    coord_cartesian(ylim = c(12.5, 21.5))
  } else if (input$ycol == "Flipper Length(mm)"){
    coord_cartesian(ylim = c(170, 232))
  } else if (input$ycol == "Body Mass (g)"){
    coord_cartesian(ylim = c(2500, 6500))
  } else if (input$ycol == "Year"){
    coord_cartesian(ylim = c(2006, 2009))
  }

Cannot add ggproto objects together


Server connecting with different sockets port

Question: I have read a question on a mock interview. Here is the question...

Code a C++ program to connect a server (ex. IP:192.168.10.131) on 2 different sockets on port 2345,4325, simultaneously..

My doubt is wheather it is saying create 2 sockets with common interface ip 192.168.10.131 and port 2345,4325 respectively.
Or it is saying connect a server having interface ip 192.168.10.131 to two different connection sockets on another server machine on different sockets port..
If i am guessing first one right then I just need to create two socket connection and start these on individual thread.
If 2 nd one is right how i need to do that.... Please help...
Comment: In a real interview, you should of course be able to seek clarification from the interviewer.  If you did, I think it likely that the answer would be that they want you to create two separate sockets, each connecting **to** a different port on the same remote server.  If you want a practice problem then try that.  But I don't see how anyone here can make more than an educated guess at what the question was intended to mean by whomever originally posed it.
Answer: The simplest interpretation (which is probably correct in the context of an interview, but of course you'd ask) is to create two sockets and connect one to each of the given ports on the given IP address.
A TCP connection is defined by the 4-tuple (source address, source port, destination address, destination port).  The source address and port are usually irrelevant to such questions because they'll be chosen automatically by default.  So when the question says "on 2 different sockets on port 2345,4325" the most likely interpretation is that those are the destination ports from the client's perspective.
So it's really two calls to socket(2) and two calls to connect(2) with perhaps a sprinkling of other functions like inet_pton(3).
As for "simultaneously," yes you could use threads, but a likely better solution is to multiplex them using select(2).  Being too quick to jump to a multithreaded solution can be a red flag in an interview.  Again, you'd want to ask about this.


jqm listview onclick still following href

Question: I have a Jquery Mobile listview with a delete button next to an  link in each list item. When I click the delete button, the onclick event fires, the delete function runs but then the href is also followed, even though the button isn't nested within the href. I have added return false to the button to see if that would help but it doesn't! HELP!
Here's the code I'm using to dynamically populate my list....
$('#roomsList').append('
' + currentRow.roomtype + '
');

Answer:
Append both  the a and the li to the parent [ put them on the same level]. In this way they it should work easily.
Comment: Do you mean put the image tag and the a tag on the same level? that's what's already happening. I tried taking the image out of the li tag as below but then it just disappears.

    Link
Answer: There shouldn't be any problems. Look at this example: http://jsfiddle.net/Gajotres/WEmNG/. I have created it two days ago for someone else but it is similar to your question. Instead of delete button I am showing custom checkbox on a listview. If you click a listview it will forward you to another page but if you click on the custom checkbox it will only activate event on chechbox.
Use my example to create a working delete button on a listview.
This is an example of event I am using on my custom checkbox:
$('.checkBoxLeft').bind('click', function(e) {
   if($(this).find('input[type="checkbox"]').is(':checked')){
       $(this).removeClass('checked').addClass('not-checked');
       $(this).find('input[type="checkbox"]').attr('checked' , false);
   } else {
       $(this).removeClass('not-checked').addClass('checked');
       $(this).find('input[type="checkbox"]').attr('checked' , true);
   }
});

Comment: I can see this is working for you but as soon as I replace the checkbox with an image, it follows the href. I am confused!
Comment: Wrap image inside a DIV. Set DIv with absolute position, float it to correct location. I think this will prevent your problem.


Swift change button background color and image color while pressed

Question: I have a UIButton that has a white image of an arrow.
What I want to do is to change the buttons background color and keep the image as white while the button is pushed down.
I have tried this:
@IBAction func backButtonDidTouch(sender: AnyObject) {

        backButton.backgroundColor = UIColor.blueColor()

    }

But this will give the button a blue color soon as I lift my finger. I want the background color to change soon as I touch/press down the button. And also keep the image white.
Thanks
Comment: how can you see the background color,if the button is covered with the image?
Comment: In storyboard I've set image to a image, and not background
Answer: you can change background color on UIButton
first you should create a util class.
class Color {
    class func imageWithColor(color: UIColor, size: CGSize = CGSizeMake(60, 60)) -> UIImage {
        var rect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContext(rect.size)
        var context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor);
        CGContextFillRect(context, rect);

        var image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext();

        return image;
    }
}

next you can set highlight color for UIButton

UIButton type must be 'Custom'

func viewDidLoad() {
    backButton.setBackgroundImageForState(Color.imageWithColor(UIColor.blueColor()), forState: .Highlighted))
}

Answer: Use setBackgroundImage(_:forState:) to change background for Selected state
Comment: Wont that just change the image and not the background color?
Comment: have two images with diff colors.
Comment: UIButton have a image and backgroundImage, you change backgroundImage for state Selected only
Answer: When creating the action method in the interface builder, you can choose the event type.
It's in the same dialog where you choose the name of your method.
You've chosen the default Touch Up Inside.
Choose event Touch Down instead.


How do I install osCommerce?

Question: Recently I've come across the osCommerce, an open-source e-commerce project, and I'd like to try it. Is it packaged in the repository (like Wordpress)? If not, how do I manually install and use it?
Comment: Dude, forget about OSCommerce, it's really old news.
There are a whole lot of better shopping platforms. Aside from the big names you can try Microweber for example which is PHP/MySQL of course, but way lighter than OSCommerce.
Answer: you need a LAMP solution, so you have to install Apache, MySQL (server version) and the required PHP version and it's modules for your software.
The path where you have to "install" your files is called "document root" and is defined in the Apache configuration file, which is usually /var/www/. You can open the file /etc/apache2/apache2.conf and simply read (and change) the location of the DR.
You can basically consider the PHP as a big plugin for Apache, so probably for all the settings regarding the organization of the files on the disk and the general setup you have to refer to apache2.conf file. But to manage the PHP functionality you can modify the file php.ini that is usually located under the /etc/php tree but it can easily be moved elsewere according to your version of Ubuntu, but in general you can find a php.ini under /etc/.
Always make a backup of these files if you are not sure about what you are really doing.
By default the address of your local webserver is localhost or 127.0.0.1 if you want to use an IP, you can type it as the address and reach your document root. If you have created a dir under the DR called test (as in /var/www/test/), navigate to the content of this folder simply by going to http://localhost/test/ or http://127.0.0.1/test/ in your web browser. In a nutshell every web address is relative to the DR.
Comment: I was hoping for a clear instructions on how set up an configure those to work with each other.
Comment: you probably do not need that, in many cases it's simply enough to install these packages from the repository, everything else is tuning, your LAMP works right after the installation.
Comment: The LAMP will, I know, but I need to configure osCommerce to use the PHP and whatever other backends it needs.
Comment: What do you mean with that? Apache recognize the use of php simply looking at the source code of the page, everything contained in the brackets  is php for Apache after you have installed the right modules. It's an automated process and you simply have to copy all the osCommerce files and paste this files in the DR.
Comment: Oh darn it! I'm so stupid! So you're saying that Apache handles everything, right? It makes sense. I still have a lot to learn.
Answer: osCommerce requires PHP and MySQL, in other words, a LAMP stack (Linux (operating system), Apache HTTP Server, MySQL (database software) and PHP). osCommerce need only to be copied to the document root, /var/www/.
Further, we need to create a database and user in MySQL for osCommerce to use.
Install LAMP and osCommerce
sudo tasksel install lamp-server

Now you need to download and "install" osCommerce (get the latest download URL @ osCommerce):
wget http://www.oscommerce.com/get/8 #this is osCommerce 3.0.2 download as of 21/11/2011
unzip oscommerce-3.0.2.zip
sudo cp oscommerce-3.0.2/oscommerce/ /var/www/

In order to avoid permission issues, the above commands downloads to the current shell, unzips and copies osCommerce to /var/www/. Never unzip it directly or move the files to the document root if you don't know the necessary permissions required for a web application to function properly.
osCommerce will now be accessible at http://ipaddress/osommerce/, where ipaddress is the IP address or the domain of your server. If you're installing osCommerce on the system you are currently on, you can replace ipaddress with localhost or 127.0.0.1.
Browsing to the osCommerce page will trigger the initial setup and ask for the details of MySQL database it will use and administrator user set up.

Create a MySQL database
First, you should create a MySQL user for osCommerce to use. It's bad practise to use the root user/pass (setup during LAMP installation) for a web application.
In a shell on the machine with the MySQL on it, do:
mysql -u root -p

Enter the root password you previously specified. This gets you a prompt which has full access to your MySQL server.
Now, pick a database name - it doesn't matter what it is really so long as it's unique on the MySQL server (to see existing ones, SHOW DATABASES;)
CREATE DATABASE dbname;

For example, replacing dbname can be replaced with with oscommerce.
Now you have to give a new user access to that database. Pick a username and password (the username can be oscommerce again, but make a secure password) - replace dbname with the database name (in this example, oscommerce):
GRANT ALL ON dbname.* TO username IDENTIFIED BY 'password';

Done. Now you have the details to put into your webform; the Database Server is just localhost or 127.0.0.1, assuming the webserver is the same machine as the MySQL server, the Username and Password are the ones just created, and the Database Name is whatever you replaced dbname with. Port can be left empty.
Reference

MySQL database in tasksel LAMP stack for osCommerce

How do I install osCommerce?


iOS asset sizes and design method

Question: The code for my first iOS 2D game is written. Now, when it comes to assets I feel lost. One reason is the feeling of imperfection due to outdated articles.
I need to know the image sizes, to begin designing. The device orientation of the game is portrait only. The status bar is hidden (game). The devices is universal, primary iPhone but I have of course no objections if the sizes are well with iPads too. What is the best image size to start designing for this intention?
If I did not have your help, I would have started creating the background (fullscreen) image at 1242 x 2208 and 401ppi. Then, scale the final image down in Photoshop to 750 x 1334 (4,7") and to 640 x 1136 (4"). Am I right with my method? Especially, is it best to start with 1242 x 2208 or is 1080 x 1920 fine?
Comment: I would just scale down the final image, created at 1242 x 2208 and 401ppi. So it's the same image and does not vary based on the screen size. But I also don't know if there's a need to scale down or just add the 1242 x 2208 image to the @3x section and let iOS rescale it?
Answer: iPhone 5:
Display Size: 4 in
Screen Size: 320 x 568 points
Rendered Pixels: 640 x 1136 (@2x)
Pixels Per Inch (PPI): 326
Browser Size Portrait: 320 x 460 px (320 x 528* / 320 x 548**)
iPhone 6/7:
Display Size: 4.7 in
Screen Size: 375 x 667 points
Rendered Pixels: 750 x 1334 (@2x)
Pixels Per Inch (PPI): 326
Browser Size Portrait: 375 x 559 px (375 x 627* / 375 x 647**)
iPhone 6/7 Plus:
Display Size: 5.5 in
Screen Size: 414 x 736 points
Rendered Pixels: 1242 x 2208 (@3x)
Pixels Per Inch (PPI): 401
Browser Size Portrait: 414 x 628 px(414 x 696* / 414 x 716**)
So I would go for the rendered pixels sizes for the images.
Comment: As a quick and dirty cheatsheet, also look here: http://iosres.com (as said, quick and dirty, only rely on this once you figured all out and are sure you know the general direction)
Comment: 2 days already and this answer isn't accepted? That's kind of unfair, there's really not much else to say... @rashwan-l should get the bounty (not that he needs the rep :) )
Comment: Rashwan L answered already, but You may also refer [here](https://developer.apple.com/ios/human-interface-guidelines/graphics/app-icon/).
Comment: The title of my question is "iOS asset sizes **and design method**", you answered only the asset sizes...an information that is easily googleable. You would go for the rendered pixels, so should I create a 1242x2208 image and scale it down to 750x1334 and 640x1136? And, if so, are these three images copied into the universal image set?

iOS asset sizes and design method


Can I use a 200A main circuit breaker panel as a 100A subpanel?

Question: Short version:
Can I use a 200A MCB panel as a 100A subpanel?  Can I leave the 200A large-format breaker in the subpanel, or would I have to remove the 200A breaker and convert it to a MLO (obviously, there would be a 100A breaker in the main panel).
Longer version:
I currently have 200A service running into my single, 200A, 30-breaker, main circuit breaker panel.  I'm running out of breaker slots, and need to add on a sub panel.  I've run the calcs for my power loads (the energy.gov calculator that crunches the NEC formulae), and I'm at about 175A.  I don't think there's a reason to upgrade my residential service to 400A just yet, but who knows what new power-hungry toys humanity is going to need 20 years from now.  If I had 2 200A MCBs, if/when I upgrade, I'd be most of the way there with the two panels ready for new feeders.
I'd of course float my neutrals, and install a separate grounding bar in the subpanel.
A 125A MLO panel and cover is roughly $150.  A 200A MCB is roughly $250.  If it meets Code, $100 for me is worth it for a bit of future-proofing.
Comment: As long as the the feed breaker(in main panel) is at or less than the sub panel's rating it is good.  I think the breaker in sub panel must equal or be larger, so feeding a 200 amp breaker/panel from a 40 amp breaker is good(if you wanted).  The sub panel's breaker basically becomes a disconnect use.  Usually it is recommended to go big(200 amps) for sub panels, even if never expected to use that much.
Comment: The savings of using a 100A panel instead of a 200A panel are not worth it for the average DIYer IMHO. You can always use a smaller feed breaker and even obtain a smaller main breaker if you want. But a higher rate panel should cost under $100 more if you're already doing the work. Replacing it later with a bigger one is more heartache.
Answer: Yeah, that's fine. Nobody cares if a subpanel (in the same building) has a completely superfluous main breaker.  And for a 100A feeder, it's always better to use a 200A subpanel with plenty of spaces than a 100A subpanel with barely enough spaces.

who knows what new power-hungry toys humanity is going to need 20 years from now.

Well right now, the wind is actually blowing in the opposite direction, as appliances only get more efficient, and energy management is starting to exist.
Technology Connections has a 2-part series on this.
Answer: You certainly could use the 200A as is (and in this case should). The breaker feeding the panel has to be equal or smaller than the rating of the sub-panel, and breaker in the subpanel can remain even if oversized. The wire has to be rated large enough for the breaker feeding the sub-panel.
If it's in the same building you don't even need a main breaker in the sub-panel. If it's in a detached building the breaker satisfies the disconnect requiement, even if oversized since the requirement is  just for a disconnect as overcurrent protection is provided in the main panel.
Comment: I considered an MLO for the subpanel - in fact that's what I was going to go with first.  From my quick Google searching, anything reasonably priced maxes out at 125A for a MLO - at least for QO, which was the brand I want to go with. Thanks for the comment!


Store PDF in MySQL database

Question: I am developing an application and I need to create invoices in PDF. I'm using pdfbundle and PDF files are created correctly:
<code>public function helloAction()
{
    $format = $this->get('request')->get('_format');
    $name = "work!!!";
    return $this->render(sprintf('miomioBundle:Venta:helloAction.%s.twig', $format), array('name' => $name));
}
</code>
But how could I store that file in the database?
Answer: You'd be far better off storing them on disk as files and reference their location in your DB. So store:

/path/to/store/invoice_434992.pdf

in a relevant table, each with a unique filename and reference it where you need to.
Answer: Is there any particular requirement you want to store those pdfs in the database. Generally its a bad idea to store large binary content in the database.
Let the invoices be in files, with a unique filename, and store the just the path to file in the database table.
Comment: sorry I meant to save the pdf on the server. I first want to prove that the PDF is saved on the server and then I'll put the path in mysql. someone help me to save the pdf on the server? thanks
Answer: I've done this. There is avery good article on how to do it.
http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx
As others have said, it may not be a good idea to store binary data in a database.
Answer: You could create a table in your database that is:
<code>____________________________________________
| ID | TIME | QUERY | PDF_NAME | PDF_FILE  |
|----|------|-------|----------|-----------|
...
</code>
The type of the PDF_FILE would be BLOB, and the rest are self-explanatory. This way, if you wanted, you could search for the result of a query that happened a while back.

Store PDF in MySQL database


Good reference for method of characteristics

Question: I am in graduate school for chemical engineering and the method of characteristics appears in many journal articles.  Does anyone have a good reference: either online or a book that provides a good explanation with examples of the method of characteristics.
Comment: @J.M.: for some reason you just reminded me of [this](http://slashdot.org/story/10/12/06/0416250/Medical-Researcher-Rediscovers-Integration) :) I'll defer to our expertise in this case.
Comment: @Willie: Knowing the chemical engineering literature, they point to a handbook or textbook even if they're using something as simple as Newton-Raphson or Simpson's rule, so I'd think a paper would point to a proper textbook at the very least.
Comment: Method of characteristics should be common enough that one shouldn't have to give references to it when dealing with PDEs.
Comment: The journal articles you speak of give no references themselves?
Answer: Off the top of my head, I've found both of these to be well-written and easy to follow.  Cavet:  I don't have them in front of me, so my recommendation is based on general impressions rather than their particular treatment of characteristics.

Partial Differential Equations, by L. C. Evans. Aimed at the intro grad level.
Partial Differential Equations, by Walter Strauss.  Aimed at an advanced undergrad audience, but good for someone new to the field.

The External Links listed at the end of the wikipedia article on characteristics also look like they might be worth your time.
Comment: Evans's method of characteristics is good for the second time you've seen it.  I like Fritz John's PDE for the first time.  Same basic feel in both books.
Answer: Since you have more of an engineering background, I would suggest the textbook of Robert McOwen, Partial Differential Equations: Methods and Applications. Chapter 1 is about solving first order partial differential equations, where the method of characteristics is most applicable. Chapters 2 and 3 also contains some application of the notion of characteristics to higher order equations and to the wave equation.
Compare to the treatments in other standard, more theory-oriented textbooks, I find McOwen's treatment of the method of characteristics to be more detailed and complete, and easier to teach from. As a remark: section 1.3, the application to fully non-linear first order equations, is very difficult to wrap your head around. So don't worry if you feel like you suddenly hit a wall when you get to that section.


In a Hausdorff Space a set has an accumulation point only if the set itself is infinite

Question: Let $X$ be a Hausdorff topological space and let $S$ be a subset of $X$ that has an accumulation point $x_0$ in $X$. Then show that $S$ is infinite.
Try Since $x_0$ is an accumulation point of $S$, every deleted neighborhood of $x_0$ intersects $S$. Consider any neighborhood $V_1$ of $x_0$, then $V_1\setminus \{x_0\}\cap S\neq \emptyset$. Choose $x_1\in  V_1\setminus \{x_0\}\cap S$. Due to $X$ is Hausdorff, there exists a neighborhood $V_2$ of $x_0$ that excludes $x_1$. Also, $V_2\setminus \{x_0\}\cap S\neq \emptyset$. Choose $x_2\in V_2\setminus \{x_0\}\cap S$. Thus, we can recursively construct neighborhoods $V_k$ of $x_0$ such that for any distinct $m,n\in \mathbb{N}$, there exists $x_m\in V_m\cap S$, $x_n\in V_n\cap S$ and $x_m\neq x_n$. Therefore, $\{x_k:~k\in \mathbb{N}\}$ is a countably infinite set contained in $S$.
Query We only have used the $T_1$ property of $X$. So is this proof valid for even if $X$ is $T_1$?
Thanks in advance!!
Comment: Your title is imprecise: it should say "only if" the set itself is infinite! "$P$ if $Q$" means $Q \implies P$, while "$P$ only if $Q$" means "$P \implies Q$".
Comment: Thankyou@diracdeltafunk for pointing out that.
Answer: Yes, the claim is true for all $T_1$ spaces. Here's a proof by contrapositive:
Proof. Suppose that $S \subseteq X$ is finite, say $S = \{s_1, \dots, s_n\}$. Let $x \in X$ be arbitrary. Since $X$ is $T_1$, let $U_1, \dots, U_n$ be open neighborhoods of $x$ such that $s_i \notin U_i$ for all $i \in \{1, \dots, n\}$. Then $U := U_1 \cap \dots \cap U_n$ is an open neighborhood of $x$ such that $(U
 \setminus \{x\}) \cap S \subseteq U \cap S = \varnothing$, so $x$ is not an accumulation point of $S$. Since $x$ was arbitrary, $S$ has no accumulation points.
Your proof also works, but I recommend being more precise about the recursive construction of $x_m$. From what you wrote in your proof, it seems like you might try to define $x_m$ as an arbitrary element of $V_m \setminus \{x_0\}$ where $V_m$ is an arbitrary open neighborhood of $x_0$ which does not contain $x_{m-1}$. This would not work!


Does the water table replenish?

Question: Does the water table replenish? I keep running out of water. I'm looking for a sustainable city, but I keep running out of water.
Comment: You mean your actual water table is getting less and less blue?
Comment: @MathewFoscarini, I don't know if this is a boon, or a curse. ;)
Comment: @theUg yes and it eventually dries up
Answer: Yes - the water table does replenish
The water table in SimCity is replenished from the following sources;

Rain
Water from shorelines
Sewage treatment plants
Other cities
Outflow pipes from industrial buildings

Rain is not a reliable source of replenishment but does contribute. Due to its random nature (it never rains when you want it to) you should never rely on your water table being replenished by rain. Water from the shorelines however does replenish the water table a lot faster than water from rain, but seemingly not fast enough to cater for a sudden explosion in population.
The outflow pipes from industrial buildings will put polluted water back into the ground. This doesn't show up as blue but even so, it is still water. It will need treating before it gets to your Sims but it is still present on the water table.
Sewage Treatment facilities will replenish the water table during their normal operation. Sure they're pretty expensive to place but if you're heading towards a high population city you will need to cater for replenishing the water table just as much as getting garbage off your streets or keeping everything powered.
Some tips for managing your water

SimCity is not SimCity 4 - large cities are not supposed to be self sufficient. This is managed by the 'multi-city' game mechanic and if you want clean and efficient cities with large populations you are going to have to import some of your water
See water management as a challenge you're going to have to overcome along the way through proper planning and preparation
Slow down! The purpose of the game isn't to get a massive population in as little time as possible, the goal is to create a stable region consisting of multiple cities that compliment each other
Some cities may be your population centers and some cities may be mining hubs, and these cities are going to be thirsty, but other cities in the region may have an abundance of coal or oil, and these smaller cities can provide the water to your population centers

The best advice for a perpetual water supply
Build a water pump next to a sewage treatment plant. The sewage treatment plant will replenish the water table as fast as the water pump is depleting it, thus providing the effect of infinite water. It's also a good way to pick up germs and make your population sick in the instance of a sewage overflow, so filtration pumps at your water pump may be the way to go with this.
Comment: Wouldn't importing water merely delay, not solve, the problem? In other words, if a city drained its own water table, wouldn't it eventually drain the water tables of all other cities in the region?
Comment: No - imports do not "take away" from the resources in another city. The number of resources in the city that you're importing from are not affected.
Comment: I've found sewage treatment plants to be the best sustainable solution without a shoreline.
Comment: I have just tried the "perpetual water" tip you mentioned. The pumps still dry out after a while...

Does the water table replenish?


Is it normal to have visible lines below a second story room?

Question: Are these lines normal? Looks like frame from second story?
Comment: What are we looking at here? Drywall? Precast concrete? Please revise to add enough detail for us to answer.
Comment: Please take the [tour] so you know how to respond to answers here.
Answer: This looks like a poor taping job. The installer probably did butt joints instead of the taper joints. The butt joints are two pieces of drywall where the joints are the same thickness as the rest of the drywall. They are much harder to level out and match the rest of the ceiling. The tapered joints use dywall that has narrower edges where the they are joined so the tape and mud are slightly recessed. The results are a seam that's more hidden and blends in with the rest of the ceiling.
Comment: They are "normal", but like JACK said, it's a poor taping job.   If you want a DIY fix, get some light drywall mud and a wide taping knife (at least 10" wide) .  Slam on some mud over the joint and taper it out.   I find best results if I apply  slightly uneven pressure by putting more pressure on the side of the knife that's away from the joint.   You should be able to get it done with one coat, but for someone learning, it may take two.  Go to You-Tube university.  There are tons of vids there to give you more complete advice than I did.
Answer: Boring and normal drywall joints not done well.
You can go over them with joint compound and a wide knife and a wider knife and perhaps even a wider knife than that (letting each layer dry before moving to the next wider knife) to get a better blend, or you can put something like a brushed texture finish (or "popcorn" texture, if you'd like to hate yourself later when you tire of it) on the ceiling to disguise it, or both, or you can not worry about it at all as it's just cosmetic.
Comment: Or, of course, you can do something like a fake beam -- or go completely over the top to a mock-coffered ceiling treatment. (Which, since I like the look and have a 10' ceiling in the living room, I have been considering.)
Answer: They look like joins in the plasterboard, the width you see is the tape that is used on the joints, so that the plaster can bridge the boards.
A modern plasterer could do a much better job. Often the problem is that the joists an batons are not level. In older houses, they would put a pattern on the ceiling to disguise it.
Comment: Expanded my answer.  Unless there is dampness or cracking, it should be fine.
Comment: The protocol is to tick the answer if you consider it correct and/or to upvote it.
Comment: So this is normal? Is it something I should be worried about?
Comment: And to give a checkmark to the answer you find most helpful. Though it's good practice to wait a while to see if an answer you like even better shows up, since AFAIK you can't reassign that once you've made the choice.
Comment: @keshlam you most certainly _can_ reassign a check mark! It does (according to conventional wisdom) tend to deter future answers that one might like better.
Comment: Good to know; never tried doing it. Thanks, @FreeMan. (Maybe we need a system that once a year reminds authors to recheck whether a better answer has appeared?)


Limit question help

Question:
If $\tan(x_n \pi) = -x_n$ and $x_0=0$, show that $$\lim_{n\to \infty} (n-x_n)=\frac{1}{2}$$

I am not getting any idea from where to start this. Can you give me some hint?
EDIT: $x_n$ is the nth solution of $y=\tan(x_n\pi)$ and $y=-x_n$ starting from $n=0$ where $x_n=0$
Comment: I am not getting any idea from where to start this. Can you give me some hint?
Comment: $\tan(x_n \pi) = -x_n$? Is there a typo while specifying the recurrence relationship?
Comment: No, it is correct.
Comment: @sudddddd Are sure you've not forgotten to include $x_{n+1}$?
Comment: @sudddddd do you mean $(x_0,x_1,....)$ are the roots of the given equation in increasing order?
Comment: @PrathyushPoduval Even so, what does $\lim_{n\rightarrow \infty} x_n$ mean? Are the roots ordered?
Comment: @Prathyush yes the roots are in increasing order
Answer: Note that for $n\geq 1$, by the intermediate value theorem, $x_n\in (n-1/2,n)$ and therefore $n-x_n\in (0,1/2)$. It turns out that $n-x_n$ is increasing (prove it!). Then $n-x_n$ is convergent to some real number $L\in (0,1/2]$. Now, if $L<1/2$ then, as $n\to+\infty$,
$$+\infty\leftarrow x_n=-\tan(x_n \pi)=\tan(-x_n \pi)=\tan((n-x_n) \pi)\rightarrow \tan(L \pi)\in\mathbb{R}^+$$
which is a contradiction. Hence we may conclude that $L=1/2$.
Answer: Take $n>1$.
First I shall show that $x_n \in (n-1,n)$
Using the Intermediate value theorem, we have that $ x_m\in (n-\frac{1}{2},n)$ for some integers $m$. Since $(\tan(x\pi)+x)'=\pi\sec^2(x\pi)+x>0$ in that interval, we have $x_m$ is the only solution in that interval. Also, there exist no solution in $(n-1,n-\frac{1}{2})$ because $\tan(x\pi)>0$ in that interval.
Thus, $x_m$ is the only solution in $(n-1,n)$, and by induction we can show that $n=m$.
Let $k=n-x_n$, note that $0<k<1$. The given equation can be written as:
$$\tan((x_n -n)\pi) = -x_n$$
$$\Leftrightarrow \tan(-k\pi)=-(n-k)$$
$$\Leftrightarrow k\pi =\arctan(n-k)$$
Thus, as $n \to\infty$, $k\pi=\arctan(n-k)\to \frac{\pi}{2}$ (Note that $k<1$).
As a result, we have $k=\frac{1}{2}$, which was to be proved

Limit question help


Center DIV contents to viewport

Question: I'm trying to create a carousel similar to http://www.aprica.jp/, using jQuery and HTML. To do so, I need to be able to horizontally center the contents of a large (overflow-hidden) div to the viewport. Any ideas how I can do that?
Comment: You can use jcarousel - http://sorgalla.com/projects/jcarousel/
Answer: Ok Buzz, if i understand you need a way to center a div inside another 'overflow: hidden' div.
I imagine you don't know in advance the width of the inner div. You sead you want to use JQuery than ou have to calculate the left margin of the inner div with something like this:

<title>item List</title>

This is a very simple case, if you need more, please ask.
PS: you need JQuery and JQuery.UI.
Comment: Fantastic - exactly what I was looking for. I think I was trying to overcomplicate the issue, simple was the key :)
Answer: You can horizontally center a div with:
/*CSS*/
#divtocenter {
    width: 400px;
    margin: 0 auto; /*that's it*/
}

Comment: i don't understand you. i can set overflow: hidden; in this div too
Comment: I'm looking to horizontally center the contents of a 100% width DIV (even if the contents are 5000px wide).

For example, assuming the below is a super-wide UL, li '3' would be centered to my screen (as it's the center item), and anything left or right would disappear from my view (overflow hidden).

| 1 | 2 | 3 | 4 | 5 |

Center DIV contents to viewport