text:
Q: Extracting Information From a CSV I am trying to create a program that will extract a certain type of cable from a CSV based upon the user's inputs.  With that cable I will use the specs of it to solve equations.
I am trying to make a dictionary out of each cable so that extracting it and using it to solve equations will be a lot smoother.  Here's the code.
import csv
import math

with open("origionalconductordata.csv", "r") as file:
    #read the file
    reader = csv.reader(file)

    cable = {}
    #creating a cable dictionary
    for column in reader:
        cable[column[1]] = {'Stock Number':column[2], 'Overall Diameter':column[49],
        'Diameter Over Conductor':column[40], 'Conductor Size': column[10]}

#Finding out what cable the user wants
def find_cable():
    spec = raw_input("Type the cable Spec Number below.  If you do not have a Spec Number, type 'no'.\n>")
    size = raw_input("Type the size of the cable.\n>")

    if spec and size in cable:
        print cable[spec][size]
        find_equation()

    elif spec == "no":
        next = raw_input("Type the Overall Diameter of the cable.\n>")

        if next in cable:
            print cable[next][size]
            find_equation()

        else:
            print "Diameter not found."
            find_cable()

    else:
        print "Unable to find request."
        find_cable()

The expected result is that the code will give you a cable that matches the users 'Spec Number' and 'Size'.  With the information that's in the cable's dictionary, it will solve equations.  The actual result in my code is when you type in a 'Spec Number' and 'Size' the else statement "Unable to find request" pops up.

A: You have a dictionary, cable, which has cable specifications as its keys, and the value for each key is a dictionary of data corresponding to the specification.
The expression spec and size in cable will evaluate to True if cable has keys which match spec and size.  I think you really want to check whether the value for spec has a value for "Conductor Size" equal to size:
if spec in cable and cable[spec]['Conductor Size'] == size:
    find_equation()

In the case where no spec is provided, you seem to be trying to find a cable with a given "Diameter Size" and the correct "Conductor Size".  Since the keys of cable are not diameter sizes, next in cable will never be true, except by coincidence.  You'll need to check each value in cable to see if it matches your requirements.
elif spec == "no":
    # Use meaningful variable names to show your intent.
    diameter_size = raw_input("Type the Overall Diameter of the cable.\n>")

    # Search for matches.
    for k, v in cable.items():
        if (v['Diameter Size'] == diameter_size
            and v['Conductor Size'] == size):
            find_equation()

    if next in cable:
        print cable[next][size]
        find_equation()

The usual way to handle repeatedly asking for input like this is to use a while loop, rather than having find_cable call itself recursively.  So the function would end up looking like this untested code:
def find_cable():
    while True:
        spec = raw_input("Type the cable Spec Number below.  If you do not have a Spec Number, type 'no'; type 'q' to quit.\n>")
        conductor_size = raw_input("Type the size of the cable.\n>")

        if spec in 'Qq':
            print('Bye!')
            break

        if (spec in cable
            and cable[spec]['Conductor Size'] == conductor_size):
            find_equation()

        elif spec == "no":
            diameter_size = raw_input("Type the Overall Diameter of the cable.\n>")

            # Search for matches.
            for k, v in cable.items():
                if (v['Diameter Size'] == diameter_size
                    and v['Conductor Size'] == size):
                    find_equation()
                    # Break out of the for loop once we find a match.
                    break
            else:
                # For loops have an else clause that is triggered if the code
                # doesn't break out of the loop
                print "Diameter not found."

        else:
            print "Unable to find request."

Finally, looping through all the dicts to find matching diameters would be slow if there are lots of different cables (say 1000s).  Consider loading the data into a database like sqlite instead.


text:
Q: Jmeter- Access log sampler: Increase load up to 5x from orignal logs For development purpose I am sole user of my application. So I used my application normally for an hour an take access logs of it via tomcat. Now I am using Jmeter to test against these logs according to this Tutorial.
When I define Number of Threads=1 in Thread Group , Jmeter only process Ist request  from log.
When I define Number of Threads=2 in Thread Group , Jmeter only process Ist 2 request  from log.
When I define Number of Threads=3 in Thread Group , Jmeter only process Ist 3 request  from log.
...
...
and so on.
My motive is to double(2x) or triple(3x) or nx the load from actual load and test it. How can I define my Test Plan in order to do it.
What I need to do for one user(I guess thread), Jmeter process all logs once. For n User Jmeter create n threads which individually process whole log simultaneously.

A: Check number of iteration value so that it as a sufficient value and add a Cookie Manager.
But access log sampler is not the best way to load test an application.
Why not use jmeter proxy:

*

*jmeter.apache.org/usermanual/jmeter_proxy_step_by_step.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find the height of the average person that is taller than $n$ people? Assume we have a population $X$ following a normal distribution.
We pick a random person $x_p$ and we fix him. We then pick a random person $x_1$. The probability that $x_p > x_1$ is 0.5.
We pick yet another person $x_2$ and once again $P(x_p > x_2) = 0.5$
Thus the probability that the picked person is higher than both the other people is $0.5^2$ and in general, for $n$ people it is $0.5^n$.
This is the probability of being taller than $n$ people labelled $p_n$. Now I am interested on finding the height $h_n$ of the average person that is taller than $n$ people. In other words, $p_n$ tells you how likely you are to be taller than $n$ people if you don't know your height. We now want to know what's your height likely to be if you are indeed taller than n people, (i.e you are taller than x cm).
Edit:
To the people saying the probabilities are dependent, I don't think that's correct. Assume the height of someone is $\mu$, the average of the population. If you sample one person at random, the probability that that person is taller than $\mu$ is 50% (by definition). If you do this whole process again, the probability is still 50%. Trivially if you pick $n$ people at random, the probability that all of them are of height $\mu$ is $0.5^n$
It's slightly different to calculate the probability of picking the tallest person among $n$ people, than it is to ask, what's the probability that someone with unkown height is taller than $n-1$ other people.

A: The distribution of heights does not matter for this argument.  All that matters is that they are strictly linearly ordered, that there are no ties.  The probability that a third person is taller than the first two is not $\frac 14$ but $\frac 13$ by symmetry.  Your calculation assumed that the chance the third person is taller than the first and taller than the second are independent, but it is not.  Generally, if you pick $n$ people, the chance that a specific one is tallest is $\frac 1n$.
We can ask what is your expected rank if you are the tallest of $n$ people.  I have seen that it is $\frac n{n+1}$ because all the intervals are expected to be the same size.

A: The issue here is whether you treat $x_p$ as a random variable, or as a fixed realization.  Your treatment is not clear or consistent in the description of your question, thus the confusion.
When you write $$\Pr[x_p > x_1],$$ you are writing an unconditional probability of an event on two iid random variables $x_p$ and $x_1$.  The resulting value will be a function of the parameters from which the distribution is drawn, but not of the random variables $x_p$ and $x_1$.  But if you had written instead $$\Pr[x_p > x_1 \mid x_p],$$ then this is a conditional probability in which the answer will in general be a function of $x_p$.  You seem to conflate the meaning of these two.
In particular, in the first case if $x_1, x_p$ are iid random variables following a $\operatorname{Normal}(\mu, \sigma^2)$ distribution, then their difference is $$x_p - x_1 \sim \operatorname{Normal}(0, 2\sigma^2).$$  Consequently, $$\Pr[x_p > x_1] = \Pr[x_p - x_1 > 0] = \frac{1}{2},$$ trivially.  However, in the second case, $$\Pr[x_p > x_1 \mid x_p] = \Phi\left(\frac{x_p - \mu}{\sigma}\right),$$ where $\Phi$ is the CDF of the standard normal distribution.  If by chance we had observed $x_p = \mu$, then $\Phi(0) = 1/2$, but otherwise, this probability is a strictly increasing function of $x_p$.
Now we can begin to see what's going on.  If you asked for $$\Pr[(x_p > x_1) \cap (x_p > x_2)],$$ this is not equivalent to $$\Pr[x_p > x_1] \Pr[x_p > x_2]$$ because the event $(x_p > x_1)$ is not independent of the event $(x_p > x_2)$ when $x_1, x_2, x_p$ are iid.  If you are not convinced, consider the explicit calculation for the simple case $\mu = 0$, $\sigma^2 = 1$:  $$\Pr[(x_p > x_1) \cap (x_p > x_2)] = \int_{y_1 = -\infty}^\infty \int_{y_2 = -\infty}^\infty \!\!\!\! \Pr[(x_p > y_1) \cap (x_p > y_2)] f(y_1)f(y_2) \, dy_2 \, dy_1$$ where $f$ is the PDF of the standard normal.  I will not show all the steps of the computation, but the answer to this is $1/3$; e.g. via Mathematica
Integrate[(1 - CDF[NormalDistribution[0, 1], Max[y1, y2]])
   PDF[NormalDistribution[0, 1], y1] PDF[NormalDistribution[0, 1], y2],
   {y2, -Infinity, Infinity}, {y1, -Infinity, Infinity}]

But whatever the exact value, it should have been obvious from the outset that independence of these events is not implied by independence of the sample.  Moreover, you can immediately see that $$\Pr[(x_p > y_1) \cap (x_p > y_2)] = \Pr[x_p > \color{red}{\max(y_1, y_2)}],$$ not $$\Pr[x_p > x_1]\Pr[x_p > x_2].$$  This clearly demonstrates the lack of independence. of events.
However, if we were to consider the conditional calculation, i.e. $$\Pr\left[\bigcap_{i=1}^n (x_i > x_p) \mid x_p \right],$$ it is correct that independence applies because $x_p$ is no longer random--you've conditioned on it, so the above is equivalent to $$\prod_{i=1}^n \Pr[x_i > x_p \mid x_p].$$


text:
Q: JTable Row Filter based on list of table model row integers I'm building a query screen for my data table. I've done the work and consolidated the rows I want to show on the table based on user criteria.
How can I apply a row filter to a table based on the rows of the model? For instance: I want to show rows 3,6,7,8,9 which are stored in an ArrayList<Integer> list.
I am currently not grasping the RowFilter class. I'm not sure what to do or how to use it here:
RowFilter<DefaultTableModel,Integer> rf = new RowFilter<>() {
    @Override
    public boolean include(Entry entry) {
        // TODO Auto-generated method stub
        return false;
    }
};

A: Perhaps you will find the provided method below somewhat useful. I use it to filter JTables. What you need to do is make use of the TableRowSorter class:
/**
 * Make sure the supplied JTable's DefaultTableModel already contains data
 * before calling this method.
 *

 * The JTable always retains the data it is currently filled with within its
 * Table Model. Knowing this we can theoretically fill the Table with all
 * database table records then use the Filter to display only the specific
 * table records we want. This way we don't have to pole the database
 * for different records all the time and records acquisition is greatly
 * increased.
 *

 * This method will pass the supplied Filter text across the supplied JTable
 * and will force that JTable to only display records (contained within that
 * JTable at the time) which contains that specific text. It reacts very
 * much like a search engine for the JTable.
 *

 * If you want to display all records again which were originally contained
 * within the supplied JTable then just pass a Null String ("") within the
 * searchCriteria parameter of this method.
 *
 * @param table          (JTable) The JTable to run filter on.

 *
 * @param searchCriteria (String) The text to filter JTable with. Passing a
 *                       Null String ("") will force the table to display
 *                       all records. Regular Expressions (RegEx) can also
 *                       be supplied within the criteria string. If the
 *                       wildcard characters ? or * are
 *                       supplied within the filter criteria String without
 *                       any RegEx meta characters then the functional
 *                       purpose of these two wildcard characters are
 *                       converted to RegEx when encountered. If actual
 *                       Regular Expressions are going to be used to make up
 *                       the search criteria string then be sure to set the
 *                       endorseWildcards optional parameter to
 *                       boolean false since the ? and *
 *                       wildcard characters have different meaning within a
 *                       Regular Expression and must be handled
 *                       differently.

 *
 * @param options        (optional - Integer/Boolean):

 *
 *     byColumnNumber - (Optional - Integer - Default is -1) By default
 *                       this method filters across all table columns but
 *                       you can be column specific if you pass a column
 *                       number to this optional parameter. This parameter
 *                       accepts only a Literal Column Number which
 *                       means that although the first column within a
 *                       JTable is considered column 0, to this method it is
 *                       considered as column 1.
 *
 *    endorseWildcards - (boolean) Default is true (allow wildcards). If true
 *                       then when a wildcard character is encountered within
 *                       a search criteria string it is automatically converted
 *                       to its RegEx equivalent. The two wildcard characters
 *                       are almost always more than enough to carry out any
 *                       search required and is usually much easier to use than
 *                       some complex regular expressions. If endorseWildcards
 *                       is true then upper or lower letter case is ignored as
 *                       well.
 *
 *                       If you provide a true of false to this parameter then
 *                       you must provide a value (or null) to the option
 *                       byColumnNumber parameter.

 */
public static void filterTable(JTable table, String searchCriteria, Object... options) {
    int column = -1;
    boolean endorseWildcards = true;
    if (options.length > 0) {
        if (options[0] != null) {
            column = (int) options[0] - 1;
        }
        if (options.length >= 2) {
            if (options[1] != null) {
                endorseWildcards = (boolean) options[1];
            }
        }
    }

    String criteria = searchCriteria;
    if (endorseWildcards) {
        criteria = "(?i)" + searchCriteria.replace("?", ".?").replace("*", ".*?");
    }

    try {
        TableRowSorter<TableModel> sorter = new TableRowSorter<>(((DefaultTableModel) table.getModel()));
        sorter.setRowFilter(column < 0 ? RowFilter.regexFilter(criteria)
                : RowFilter.regexFilter(criteria, column));
        table.setRowSorter(sorter);
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
}

A: After studying and trying to grasp how the RowFilter Class works, i got my table to sort the way i want it to, it seems. I still need to do more testing but it looks like it is working. I still do not fully grasp the RowFilter Class so i would love some feedback.
Here is my code: where ArrayList<Integer> filteredRows = new ArrayList<>(); contains the row numbers i want to show. To my understanding, the filter automatically iterates over my table model and the identifier is the row number the filter is currently processing. So at first glance if the identifier equals any of the row numbers i have stored, then show it.
RowFilter<DefaultTableModel,Integer> rf = new RowFilter<>() {

    @Override
    public boolean include(Entry<? extends DefaultTableModel, ? extends Integer> entry) {
        int entryRow = entry.getIdentifier();
        for (Integer i : filteredRows) {
            if (entryRow == i) return true;
        }
        return false;
    }

};
TableRowSorter<DefaultTableModel> sorter =  new TableRowSorter<DefaultTableModel>(myTableModel);
sorter.setRowFilter(null);
sorter.setRowFilter(rf);
table.setRowSorter(sorter);


text:
Q: Riemann and Lebesgue integrals coincide? Is it enough to say that the function $f(x,y)=x^4+\sin(\frac{1}{y}),-1\leq x \leq 1,\, -1\leq y \leq 1$ is Riemann integrable because the set of its discontinuities has measure zero ($y=0$)? Then the Lebesgue integral would coincide with the Riemann one

A: Since the number of discontinuities of $sin(\frac{1}{y})$ is finite (there is only one discontinuity) the function is Riemann integrable over the interval.


text:
Q: pagination without dataprovider Hi i tried to used pagination without dataProvider. Can I used this like:
 public function actionShowtest($id){
      $model = $this->findModel($id);
      $messages= \common\models\PrMessage::find()->where(['Rel_Dialog'=>$id])->all();
      $count = count($messages);
      $pagination = new Pagination(['totalCount' => $count, 'pageSize'=>10]);
        return $this->render('messages', [
                'model' => $model,
                'messages'=>$messages,
                'pagination'=>$pagination
            ]);
    }

And in my view:
<?php echo \yii\widgets\LinkPager::widget([
    'pagination' => $pagination,
]); ?>

My $count return me :

int 12

and in my view i can see pagination with 1,2 but it not work becosue it show me all 12 records but I want to see this 10 records. I have 2 buttons of page but it still show me all records. What can I do to fix that?
my view:
<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\widgets\ListView;
/* @var $this yii\web\View */
/* @var $model common\models\BlogPost */
$this->title = $model->Id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Konwersacje'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

?>
<div class="blog-post-view">
<?php foreach($model->prMessages as $msg): ?>

  <?=$msg->relSender->Name.' '.$msg->relSender->Surname;  ?>
  <?=$msg->CreatedAt; ?>
  <?=$msg->Text; ?>

<?php endforeach; ?>

</div>
<?php echo \yii\widgets\LinkPager::widget([
    'pagination' => $pagination,
]); ?>

A: Its becoz Your $messages variable contains all values , its not being limited according to your pagination
Try This
public function actionShowtest($id){
  $model = $this->findModel($id);
  $messagesQuery = \common\models\PrMessage::find()->where(['Rel_Dialog'=>$id]);
  $pagination = new Pagination(['totalCount' => $messagesQuery->count(), 'pageSize'=>10]);
  $messages = $messagesQuery->offset($messagesQuery->offset)
            ->limit($pagination->limit)
            ->all();
  return $this->render('messages', [
            'model' => $model,
            'messages'=>$messages,
            'pagination'=>$pagination
  ]);
}


text:
Q: How to install packages-dev defined in composer.json I am running a Symfony 2.8 based web app. Now I try to follow the docs to add PHPUnit support to the project:
$ composer require --dev symfony/phpunit-bridge

While this adds the symfony/phpunit-bridge requirement to the packages-dev of my composer.json file, not files are actually installed.
Running update manually does not change this either:
composer update --dev symfony/phpunit-bridge
You are using the deprecated option "dev". Dev packages are installed by default now.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update

Thus I get an error when trying to run a test
./vendor/bin/simple-phpunit -c app src/AppBundle/
-bash: ./vendor/bin/simple-phpunit: No such file or directory

There is not bin subdir in /vendor.
What am I doing wrong?
EDIT:
$ composer show symfony/phpunit-bridge

name     : symfony/phpunit-bridge
descrip. : Symfony PHPUnit Bridge
keywords :
versions : * v4.1.0
type     : symfony-bridge
license  : MIT License (MIT) (OSI approved) https://spdx.org/licenses/MIT.html#licenseText
source   : [git] https://github.com/symfony/phpunit-bridge.git b3451fc442baaf9169e50491a059ef17582c4424
dist     : [zip] https://api.github.com/repos/symfony/phpunit-bridge/zipball/b3451fc442baaf9169e50491a059ef17582c4424 b3451fc442baaf9169e50491a059ef17582c4424
names    : symfony/phpunit-bridge

autoload
files
psr-4
Symfony\Bridge\PhpUnit\ => .
exclude-from-classmap

requires
php >=5.3.3

suggests
ext-zip Zip support is required when using bin/simple-phpunit
symfony/debug For tracking deprecated interfaces usages at runtime with DebugClassLoader

conflicts
phpunit/phpunit <4.8.35|<5.4.3,>=5.0

A: After removing the vendor dir and re-running composer install I noticed the message:
Skipped installation of bin bin/simple-phpunit for package symfony/phpunit-bridge: name conflicts with an existing file

This problem does not occur anymore after removing the following config from composer.json
"config" : {
    "bin-dir" : "bin"
},

Without these lines the bin/ folder and the containing files are created correctly.


text:
Q: Stochastic integral with respect to discontinuous martingale in my research, I need to deal with a stochastic integral with respect to a compensated poisson process, namely,
$ \int_0^t f(X_t) dM_t,$
where $M(t) = N(t) - \int_0^t \lambda(s)ds$.
The integrand $f$ is bounded, and my question is do I still need $f$ to be predictable in order to make sure such integral is again a martingale.

A: Yes, you do need the integrand $f(X_t)$ to be predictable.  If it is merely adapted you may not get a martingale.
Intuitively, the stochastic integral $\int Y_t\,dM_t$ tells you the profit from a stock trading strategy.  $M_t$ is the share price at time $t$, and $Y_t$ is the number of shares you hold at time $t$.   Requiring that $Y$ be predictable means that in determining your holdings at time $t$, you can only use information about the stock prior to time $t$.  If $Y$ is adapted, you may also use the stock price at time $t$.  But since our compensated Poisson process $M_t$ moves by jumping up and drifting down, if $Y$ is adapted, you can buy shares at the instant the price jumps up to turn a quick profit, and sell them a short time later to lock it in.  That strategy gives you a guaranteed profit, so it can't be a martingale.
Formally, consider a time-homogeneous Poisson process ($\lambda(t) = 1$) and let $T$ be the time of the first jump: $T = \inf\{t : M_t > M_{t-}\}$.  $T$ is a stopping time, so if we let $X_t = 1_{\{T \le t < T+\epsilon\}}$ where $\epsilon < 1$, we can check that $X_t$ is adapted (but not predictable).  Thus our strategy is "buy 1 share when the stock jumps for the first time, sell it $\epsilon$ seconds later".
Let $I_t = \int_0^t X_t\,dM_t$ be the stochastic integral.  You can check that $I_t \ge 0$, and for any $t > 0$, we have $I_t > 0$ with positive probability ($I_t$ is positive, indeed at least $1-\epsilon$, on the event that $M_t$ has made a jump by time $t$).  So $I_t$ certainly is not a martingale.


text:
Q: How to determine if 6 elements are equal in a list with 100 elements So I have this exercise to do:
Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of head and tails and if there is a streak you add to to the variable number_of_streaks
I made the loop for adding H and T to the list but I don't know how to check if there is a streak in that list. I tried this code:
if th[experiment_number][z] == th[experiment_number][z+1]:

but I get this error:
IndexError: string index out of range
(Note I am new to programming, I am still learning)
import random

number_of_streaks = 0
th = []
for  experiment_number in range(10000):
    for x in range(100):
        if random.randint(0, 1):
            th.append('H')
        else:
            th.append('T')
    first = 0
    last = 5
    for x in range(100):
        for z in range (6):
            if th[experiment_number][z] == th[experiment_number][z+1]:
                number_of_streaks += 1

A: Walk the list, and keep a count of the length of the current streak. If the current item is equal to the previous item, increase the length. Otherwise, reset the counter to 0. When the counter reaches 6, you've found a streak.

A: The first half of your code works, the second half doesn't.
This code should work:
# The number of consecutive Heads or Tails needed to form a streak
streak_num = 6
# Iterate over the list th, excluding the last 5 (streak_num-1) elements of the list
for n in range(0,len(th)-streak_num+1):
    # Create a list to append values to
    list = []
    # Iterate streak_num times to check for a streak
    for m in range(0,streak_num):
        # Starting from the nth element in the list
        # Append that nth element to the list and the next streak_num-1 elements to the list
        list.append(th[n+m])
    # Check to see if all elements in list are the same
    if len(set(list)) == 1:
        # If they are all the same, a streak of size streak_num has been found
        # Therefore add it the count
        number_of_streaks = number_of_streaks + 1

The part you're having trouble with is the following portion:
# Iterate over the list th, excluding the last 5 (streak_num-1) elements of the list
for n in range(0,len(th)-streak_num+1):

If you are looking for a streak of 6, you have to stop checking the list the 6th last element.
Let me know if you have any questions.

A: Assumed that a streak is described as the least amount of consecutive identical outcomes. So, if it is 6 then a streak can be made of 6, 7, 8, ... outcomes.
from itertools import groupby
from collections import Counter
import random

# initialize the random number generator - for testing!
random.seed(121)

n_throws = 100
streak_threshold = 6 # exact value or more
outcomes = 'HT'

# flip the coin
experiment = [outcomes[random.randint(0, 1)] for _ in range(n_throws)]

# streaks ids
grps_by_streak = [grp_id for grp_id, grp in groupby(experiment) if len(list(grp)) >= streak_threshold]
print(grps_by_streak)
#['H', 'H', 'T']

# frequency for each result
cc = Counter(grps_by_ streak)
print(cc)
#Counter({'H': 2, 'T': 1})

number_of_streaks = sum(cc.values())
print(number_of_streaks)
#3

If a streak is not a threshold value but an exact one just smalls fixed are needed:

*

*replace streak_threshold = 6 to streak = 6 (just for consistency)

*use equality and change of variable: grps_by_streak = [grp_id for grp_id, grp in groupby(experiment) if len(list(grp)) == streak]


text:
Q: How can I use indices in the subset function New to R programming and have a simple question about the subset function. I am hoping to use indices instead of names of columns in the subset function.
In the airquality dataset for example, instead of
   subset(airquality, Temp > 80, select = c(Ozone, Temp))

I want to use the column indices of the Temp and Ozone columns

A: We can use
subset(airquality, Temp > 80, select = c(1,4))

Based on the comments by the OP, using get to subset the rows (provided by @Ananda Mahto in the comments) is needed
subset(airquality, get(names(airquality)[4]) > 80, c(1, 4))


text:
Q: Matlab: track all file handles that were opened/touched by script I want to find all dependencies of my script (and/or all subfunctions/subscripts), but not only functions that are called but also external files that are loaded or touched (fopen). matlab.codetools.requiredFilesAndProducts (documentation here) doesn't capture the touched filenames, my next idea, shadow the fopen function using something like below (to copy the filename to a log file), resulted in an unexpected recursive loop.
failed because of (unexpected) recursive loop, where somehow the 'builtin' fopen is not called, rather this function itself:
function varargout=fopen(varargin)
  %write opened filename to log file somewhere
  varargout=builtin('fopen',varargin{:}); %attempt to call built-in fopen() as usual
end

I also checked Mathworks depencey reports etc, to no use. Any ideas? Thank you.


text:
Q: Two VirtualHost websites do not work together under Apache 2.4 I'm running Apache 2.4 under Ubuntu 18.04
I'm having this problem where all addresses I type onto the browser bar get redirected to one of the two websites I have configured (in this case, whenever I type an address that should redirect to other-site, I get shown the website under jekyll only.)
For example:

*

*typing jekyll on the browser shows me the jekyll website, as expected

*typing other-site on the browser also shows me the jekyll website, even though there is another VirtualHost listening on that name

I have these two separate sites configured as VHosts under /etc/apache2/sites-available (both of them enabled via a2ensite)

*

*jekyll.conf
<VirtualHost *:80>
      DirectoryIndex index.html
      DocumentRoot /var/www/jekyll/_site
      LimitRequestFieldSize 48000
       <Directory />
              Options FollowSymLinks
              AllowOverride None
      </Directory>
      <Directory /var/www/jekyll/_site>
              AllowOverride All
              Order allow,deny
              allow from all
      </Directory>
      <Directory /var/www/jekyll/_site/>
              Order allow,deny
              allow from all
      </Directory>

      ServerName jekyll
      ServerName http://jekyll
      ServerName http://localhost/jekyll

      ServerAdmin webmaster@localhost
</VirtualHost>

*other-site.conf
<VirtualHost *:80>
      DirectoryIndex index.html
      DocumentRoot /var/www/other-site/_site
      LimitRequestFieldSize 48000
       <Directory />
              Options FollowSymLinks
              AllowOverride None
      </Directory>
      <Directory /var/www/other-site/_site>
              AllowOverride All
              Order allow,deny
              allow from all
      </Directory>
      <Directory /var/www/other-site/_site/>
              Order allow,deny
              allow from all
      </Directory>

      ServerName other-site
      ServerName http://other-site
      ServerName http://localhost/other-site

      ServerAdmin webmaster@localhost

</VirtualHost>

I have also added these entries to /etc/hosts so that localhost gets redirected to each site:
127.0.0.1       localhost
127.0.0.1       localhost/jekyll
127.0.0.1       localhost/other-site
127.0.0.1       jekyll
127.0.0.1       other-site
127.0.1.1       felipe-Inspiron-7559

A: The ServerName attribute in your Apache configuration files needn't be repeated, as each subsequent line will replace the previous ones.
Instead, you can use ServerName with ServerAlias like this:
ServerName jekyll
ServerAlias jekyll.local *.jekyll *.jekyll.local

Note that this is illogical:
127.0.0.1       localhost/jekyll
127.0.0.1       localhost/other-site

These are not domains (or subdomains), but paths under localhost. As a result, only localhost will be observed. This is why I did not include it in the Apache config as noted above.
So, with this in mind, you can have three Apache configuration files:
⇢ 000-jekyll.conf
<VirtualHost *:80>
      ServerAdmin webmaster@localhost
      ServerName jekyll
      ServerAlias jekyll.local *.jekyll *.jekyll.local

      DirectoryIndex index.html
      DocumentRoot /var/www/jekyll/_site
      LimitRequestFieldSize 48000

      <Directory /var/www/jekyll/_site>
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          Allow from all
      </Directory>

      ErrorLog ${APACHE_LOG_DIR}/jekyll-error.log
      CustomLog ${APACHE_LOG_DIR}/jekyll-access.log combined
</VirtualHost>

⇢ 001-other.conf
<VirtualHost *:80>
      ServerAdmin webmaster@localhost
      ServerName other-site
      ServerAlias other-site.local *.other-site *.other-site.local

      DirectoryIndex index.html
      DocumentRoot /var/www/other-site/_site
      LimitRequestFieldSize 48000

      <Directory /var/www/other-site/_site>
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          Allow from all
      </Directory>

      ErrorLog ${APACHE_LOG_DIR}/other-error.log
      CustomLog ${APACHE_LOG_DIR}/other-access.log combined
</VirtualHost>

⇢ 999-default.conf
<VirtualHost *:80>
      ServerAdmin webmaster@localhost
      ServerName localhost
      ServerAlias *.localhost * *.*

      DirectoryIndex index.html
      DocumentRoot /var/www
      LimitRequestFieldSize 48000

      <Directory /var/www>
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          Allow from all
      </Directory>

      ErrorLog ${APACHE_LOG_DIR}/local-error.log
      CustomLog ${APACHE_LOG_DIR}/local-access.log combined
</VirtualHost>

Apache processes traffic based on the order of the configuration files. So any domain matching the ones specified in 000-jekyll.conf will be handled by that file. If no matches are found, then 001-other.conf will be checked. If no matches are found, then 999-default.conf will be used. Note the ServerAlias in the 999-default.conf file and how it's relying on wide-open wildcards. This means that it will be treated as a catch-all for the traffic that does not match defined config files.
Note: The Apache configuration files were streamlined to eliminate irrelevant Directory blocks and to have each host use their own error logs.


text:
Q: Swap strings without reference counting In QuickSort, a lot of time is spent on the swap temp:=var[i]; var[i]:=var[j]; var[j]:=temp. When the vars are integer I time 140 msec for a large random array. When the vars are string, the time is 750 msec. It appears to me that much of the difference is caused by the need to update the reference counts in all three assignments.
But is this necessary? After all, the reference counts for var[i] and var[j] will be the same before and after these three assignments. Would the following code corrupt things? (not that it solves a speed problem, but out of interest):
    // P : Pstring;
    move(values[i],P,sizeOf(Pstring));
    move(values[j],values[i],sizeOf(Pstring));
    move(P,values[i],sizeOf(Pstring));

There is no temp variable. Only the two pointers to the strings are interchanged. And if this is oké, is there a Delphi function to swap 2 pointers?

A: What you are proposing is a well known and valid optimisation. Rather than calling the Move function it is better to perform direct assignments using casts to avoid reference counting code being generated.
var
  temp: Pointer;
....
temp := Pointer(var[i]);
Pointer(var[i]) := Pointer(var[j]);
Pointer(var[j]) := temp;

In order for this to work you need to be confident that no exceptions will be raised during the swap process. Simple assignments of valid memory will not lead to exceptions, so this concern can be readily dismissed.


text:
Q: View doesn't change after clicking on routerLink to child route angular 2 Hey I'm having this problem and I cant seem to figure out what is wrong, basically I have a routerLink that goes to a child route, the url changes to the route I want but the view doesn't update to the component that is linked to the child route that is currently active
app.component.ts
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

html

Component Elite

Web portal and promotions

Lorem Ipsum

        View More

app.module.ts
import { OurWorkComponent } from './our-work/our-work.component';
import { ComponentComponent } from './our-work-content/component/component.component'

export const ROUTES: Routes = [
  { path: 'our-work', component: OurWorkComponent,
      children: [
         { path: 'component', component: ComponentComponent }
      ]
  }
];

@ngModule({
  declarations: [
     OurWorkComponent,
     ComponentComponent
  ],
  imports: [
     BrowserModule,
     RouterModule.forRoot(ROUTES)
  ],
  providers: [],
  bootstrap: [AppComponent]
})

A: Reason it's not changing is because of children of OurWorkComponent
children: [
    { path: 'component', component: ComponentComponent }
]

This means there should be <router-outlet> in OurWorkComponent, but I can't see it, just add that in OurWorkComponent's html and you are good to go.

For more details please do read : https://angular.io/guide/router#nesting-routes


text:
Q: How to replace the source of a script tag when a select changes value I am new to javascript and I need some help.
I have two javascript files that run when the page is loaded:
    <script id="gvkbjs01" src="GVKB03_files/en_a.js" type="text/javascript" ></script>
    <script id="gvkbjs02" src="GVKB03_files/en_b.js" type="text/javascript" ></script>

I have a select drop down:
            <select lang="en" onchange="loadGVKBJS(this.value)" >
                <option value="" label=" Select a language" selected="selected" />
                <option value="af" label="Afrikaans / Afrikaans" />
                <option value="sq" label="Albanian / shqipe" />
                <option value="am" label="Amharic / አማርኛ" />
                <option value="ar" label="Arabic / العربية" />
                ..........

How do I change the javascript source of my two javascript files from the select drop down list that will then call the different js files?

A: Give an id to the dropdown, for Instance 'lang', after create a function that will read the value of the dropdown when it changes, then concatenate the value to generate the source of the file, finally find and replace the source of your old scripts. (I suppose your script tag is in the head).
function generateSrc(){

 var lang = document.getElementById('lang').value;
 var src1 = 'GVKB03_files/'+lang+'_a.js';
 var src2 = 'GVKB03_files/'+lang+'_b.js';

 //Replace src from old scripts in head
 var headElms = document.getElementsByTagName("head")[0].children;
 var found = 0
 for(var i = 0; i < headElms.length; i++) {
    if(headElms[i].tagName == 'SCRIPT') {
           src_name = headElms[i].src;
           if(src_name.search("GVKB03_files") > 0 && found == 0){
             found++;
             headElms[i].src = src;
           }else if(src_name.search("GVKB03_files") > 0 && found == 1){
             headElms[i].src = src2;
           }
     }
  }

}

on Html:
<select id="lang" lang="en" onchange="generateSrc()" >


text:
Q: Finding href in "https://www.baseball-reference.com/" webpage using a Python webscraper I would like to webscrape all of the "boxscore" hyperlinks found in the webpage highlighted in "requests.get" below and have it printed onto an excel spreadsheet. However, the program below prints all the text found under the class "game" from the webpage. What needs to be changed so that it prints only the href-boxscore found within "em" elements under the class "game"?
import requests
from bs4 import BeautifulSoup
import pandas as pd
from openpyxl import load_workbook

wb = load_workbook("tennis_input3.xlsx")
ws = wb.active

response = requests.get('https://www.baseball-reference.com/leagues/majors/2010-schedule.shtml')
webpage = response.content
soup = BeautifulSoup(response.text, "html.parser")

col1 = soup.find_all("p", class_="game")

print(pd.DataFrame({"MatchLink":col1}))
df = pd.DataFrame({"MatchLink":col1})

df.to_excel("tennis_3.xlsx", sheet_name="welcome")

A: Select your elements more specific and as described by your self:
soup.select('p.game em a')

or
soup.select('p.game a[href*=boxes]')

Example
import requests
from bs4 import BeautifulSoup
import pandas as pd

response = requests.get('https://www.baseball-reference.com/leagues/majors/2010-schedule.shtml')
soup = BeautifulSoup(response.text)

pd.DataFrame(
    ['https://www.baseball-reference.com'+e.get('href') for e in soup.select('p.game em a')],
    columns = ['url']
)#.to_excel(...)

Output

url

0
https://www.baseball-reference.com/boxes/BOS/BOS201004040.shtml

1
https://www.baseball-reference.com/boxes/ANA/ANA201004050.shtml

2
https://www.baseball-reference.com/boxes/ARI/ARI201004050.shtml

3
https://www.baseball-reference.com/boxes/ATL/ATL201004050.shtml

4
https://www.baseball-reference.com/boxes/CHA/CHA201004050.shtml

...

2457
https://www.baseball-reference.com/boxes/SFN/SFN201010270.shtml

2458
https://www.baseball-reference.com/boxes/SFN/SFN201010280.shtml

2459
https://www.baseball-reference.com/boxes/TEX/TEX201010300.shtml

2460
https://www.baseball-reference.com/boxes/TEX/TEX201010310.shtml

2461
https://www.baseball-reference.com/boxes/TEX/TEX201011010.shtml


text:
Q: PHP Includes not working after moving pages into subfolders The problem is as follows:
Originally, all of the individual pages on my website were in the root folder of the site.
I have now moved the majority of the pages into various sub-folders.
For example: The main page for our Apache Totem Freestanding Light Box used to be in the root folder, but is now in subfolders: /lightboxes/apache-totem-freestanding-lightbox/index.php
The problem is that various elements of the page have "PHP Modules" included for common elements such as the header, the breadcrumbs, the footer, the css file etc.
For example, for the header we have  as a link on each page.
The files that these "PHP includes" point to are situated in their own folder on the site root, called 'modules'.
The trouble with this, is that the 'PHP Includes' can't seem to find the modules because I guess they are expecting to see them in a folder called 'modules' that is situated in the same subfolder as the current page.
I've partially got around this by changing the link to the module to have ../../ in front to tell it that it has to look two folders up from the current folder, but the page is still having difficulties displaying all of the information.
To give you an idea of this, I have uploaded the Apache Totem Index Page in its subfolder /lightboxes/apache-totem-freestanding-lightbox/
https://www.w-co.co.uk/lightboxes/apache-totem-freestanding-lightbox/
As you can see, the main content of the page is displayed ok and the css file is doing its job with styling etc.
But there are various other problems, for example:
1.  There is an image missing from the header
2.  The quote button in the header and the content  is pointing to the wrong place (quote.php is on the root folder but the button is trying to link to the current subfolder)
3.  All of the items on the breadcrumb trail link to the current page
4.  All of the links in the footer are also trying to point to the subfolder lightboxes
Is there anything you can think of to fix these issues?
Thanks,
Tony

A: The URL for the images should be something like this https://www.w-co.co.uk/images/worldpay/visa.gif
You have to use base URL https://www.w-co.co.uk and then image path. You can define("BASE_URL", "https://www.w-co.co.uk") and use it like in the following.

<?php
define("BASE_URL", "https://www.w-co.co.uk/")
?>
<img src="<?php echo BASE_URL;?>images/worldpay/visa.gif"


text:
Q: Split marker and line in Legend - Matplotlib I want to make a legend where I specify the value for the markers and the value for the lines but not the combination of both.
This example should help to illustrate my goal:
import matplotlib.pyplot as plt
import numpy as np

pi=3.14
xx=np.linspace(0,2*pi,100)

fig = plt.figure()
ax  = fig.add_subplot(111)

phases=[0,pi/4,pi/2]
markers=['s','o','^']

for phase,mk in zip(phases,markers):
    labeltext='Sine' + '*' + str(phase)
    F=[np.sin(x+phase) for x in xx]
    ax.plot(xx,F,color='b',marker=mk,label=labeltext)

    labeltext='Cosine' + '*' + str(phase)
    F=[np.cos(x+phase) for x in xx]
    ax.plot(xx,F,color='g',marker=mk,label=labeltext)

hand, labl = ax.get_legend_handles_labels()
#hand, labl = function_to_split(hand,labl,'*')
ax.legend(hand,labl)
plt.savefig('Figure.png')

The resulting figure is the following

What I wanted is a function_to_split to automatically end up with a legend like this:
[blue line] Sine
[green line] Cosine
[black square] 0
[black circle] 0.785
[black triangle] 1.57

A: I figured it out by automatically creating fictitious handles.
import matplotlib.pyplot as plt
import numpy as np

def function_to_split(hand,labl,dividor):

    Hand_L=[]
    Hand_M=[]
    Labl_L=[]
    Labl_M=[]

    for h,l in zip(hand,labl):
        co=h.get_color()
        ls=h.get_linestyle()
        lw=h.get_linewidth()
        mk=h.get_marker()
        mew=h.get_markeredgewidth()
        ms=h.get_markersize()

        LABS=l.split(dividor)

        if len(LABS) != 2:
            print 'Split Legends Error: Only exactly 1 Dividor is accepted.'
            print '                     Currently ' + str(len(LABS)-1) + ' dividors were given'
            return hand,labl

        #Line and Color
        LICO = plt.Line2D((0,1),(0,0), color=co, marker='', linestyle=ls,linewidth=lw)
        #Marker
        MARK = plt.Line2D((0,1),(0,0), color='k', marker=mk, markeredgewidth=mew, markersize=ms, linestyle='')

        if LABS[0] not in Labl_L:
            Hand_L.append(LICO)
            Labl_L.append(LABS[0])

        if LABS[1] not in Labl_M:
            Hand_M.append(MARK)
            Labl_M.append(LABS[1])

    return Hand_L+Hand_M,Labl_L+Labl_M

pi=3.14
xx=np.linspace(0,2*pi,100)

fig = plt.figure()
ax  = fig.add_subplot(111)

phases=[0,pi/4,pi/2]
markers=['s','o','^']

for phase,mk in zip(phases,markers):
    labeltext='Sine' + '*' + str(phase)
    F=[np.sin(x+phase) for x in xx]
    ax.plot(xx,F,color='b',marker=mk,label=labeltext)

    labeltext='Cosine' + '*' + str(phase)
    F=[np.cos(x+phase) for x in xx]
    ax.plot(xx,F,color='g',marker=mk,label=labeltext)

hand, labl = ax.get_legend_handles_labels()
hand, labl = function_to_split(hand,labl,'*')
ax.legend(hand,labl)
plt.savefig('Figure.png')


text:
Q: Infinitely many zeros of a nonconstant continuous function? Let $f:[0,1]\to\mathbb{R}$ be a nonconstant continuous function. Is $S=\{x: f(x)=0\}$ finite?
I have thought of a function with countably many $0$'s like lots of triangular bumps at each point $\{1/n\}$, I mean lots of $W/M$ shapes on $[0,1]$. Is it okay?

A: Your suggestion will work well. If you want an explicit formula, look at $f(x)=x\sin(1/x)$ when $x\ne 0$, and $f(0)=0$.

A: $f(x)=\max\{0,2x-1\}$ is a nonconstant continuous function with uncountably many zeros.


text:
Q: Storing and retrieving users shopping cart from database - Cart class - CodeIgniter I haven't started the coding yet and really just want to get feedback on my ideas.
I would like to know how to store a users shopping cart contents in order to be able to retrieve them once they have returned to the website.
I'm confused with the idea of allowing users to create accounts, as I've read on this website that forcing people to create an account with you in order to put items in their shopping basket is bad practice. However, if I do give the ability to have an account, then I can create a table holding the accounts information, along with having a column for storing that users shopping cart content via the CI Cart class' function $this->cart->contents; (which I would then have to serialize before putting it in the table, right?).
I also wanted to know if it is possible to store the contents of a users shopping basket into a column as stated above, and then retrieve it back to display as the users shopping basket contents once they log back in.
Having an account would benefit in terms of having your shopping cart items available in different browsers, as they would be associated with the account and not your session.
But if I don't want to implement customers having accounts, do I just have to implement the Cart class, with no interaction with the database (and just setting the session variables in the config file to not expire, or expire in a year etc)? I don't understand why I would need the ci_sessions table in this case (any arguments for using it?)
Really confused because I've pondered over this for a long time, getting more confused as time goes by :(. Could someone please shed some light for me. Thanks

A: I think its always a good idea to get customers to create accounts because

*

*Its a good way to stop span.  Only allowing registered and logged in users to access the checkout stages is a lot better than just letting anyone get to it

*Its also a good way to gather information about your customers that can be used for marketing

In regards to the cart you can save sessions to a database by making sure sess_use_database is set to true in the config files
$config['sess_use_database'] = TRUE;

That way you can add the customer previous items into the cart when they log back in.
But I agree with @dispake you've asked quite a lot of questions so its hard to give you a definitive answer


text:
Q: JSON from python json.dumps to javascript JSON.parse() with escaped \" I have been fighting with this problem for a few weeks now and still cannot understand what's wrong here.
I created a dictionary in python dic. Then I am using dumps to convert it to a valid json.
json_js = json.dumps(dic) # works fine, a valid json from the python's viewpoint
# the reverse operation works fine also
dic = json.loads(json_js)

print(json_js)
==============
{"p0": {"pf": {"id": "pf1", "class": ["pf", "w0", "h0"], "data-page-no": "1"}, "pc": {"class": ["pc", "pc1", "w0", "h0"]}, "img": ["<img alt=\"\" clas

This json_js I use later on to add it to a js script that applies JSON.parse() on it. And this is the error that I get.
SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 143 of the JSON data

That 143 character is the first \". But why can't js figure it as a valid JSON I cannot comprehend.
Would you have any suggestions what might have gone wrong here?
EDIT.
No idea why people close my question. The desired behaviour is that JSON.parse doesn't throw any errors. The way how I added it to a script is irrelevant for the question. Please, have a look at the part of the source code inside html .
const str = `{"p0": {"pf": {"id": "pf1f", "class": ["pf", "w2", "h2"], "data-page-no": "1f"}, "pc": {"class": ["pc", "pc1f", "w2", "h2"]}, "img": ["<img alt=\"\" class=\"bi x0 y0 w1 h1\"` // this string is several megabytes so I only put the first 150 or so characters here.
var dic = JSON.parse(str);

EDIT 2.
The full transformation.
# in python using BeautifulSoup for scripts and new_html
new_html = bs()
dom = bs()
scripts = [dom.new_tag('script')]
scripts[0].string = html_script(json_js) # html_script is a "string... %s" %json_js
new_html.body.append(scripts[0])
with open('stuff.html','w',encoding='utf-8') as f:
        f.write(str(new_html))

A: In order to put a string of JSON into JavaScript source code, you used backticks to make it a template string. That's not enough, though, since many sequences have special meaning inside backticks:

*

*${…} interpolation

*backslash escape sequences (the current problem, which converted the \" in the JSON to ")

*backticks

Embedding literals in JavaScript in HTML <script>s isn't really trivial, but you can do it by JSON-encoding the JSON, which results in a string that's almost ready to embed except for:

*

*exiting the script element with </script>i

*changing the parsing mode with <!--

*creating a poorly-formed JavaScript string literal (for now) with U+2028 or U+2029

which can be avoided by escaping all <s, U+2028, and U+2029.
In all:
def script_embeddable_json(value):
    return (
        json.dumps(json.dumps(value))
        .replace("<", "\\u003c")
        .replace("\u2028", "\\u2028")
        .replace("\u2029", "\\u2029"))

json_js = script_embeddable_json(dic)

Then the template should look like const str = %s.


text:
Q: How do you populate database in Play framework? What is your way of populating database in Play framework?
We tried to write custom evolution script to do that, but it ended up not being very good solution.
Do you have some java code running on application startup that does that for you, for example by using ORM (like Ebean)?
Thank you very much.


text:
Q: Worth adding a webserver? I'm conducting a small project using the arduino uno. I will be connecting a wifi module and a gps module to the arduino and transferring the latitude and longitude over to a web server in which it will store the records to a database. Initially, I was planning on using Spring Web as the web server (for the url routing, request path etc) and mongodb as the database storage but upon further research, it looks like the arduino can act as a web server (pretty much send a HTTP POST method to the database). So I'm confused whether or not I should include Spring Web. I will also build an android app which will communicate and query the database.
In terms of efficiency and ease, which tech stack would be advisable?

A: Yes you can spring web as new feature of spring supporting the android development please refer this http://projects.spring.io/spring-android/ for further assistance.


text:
Q: How to import module installed using pip from virtualenv I installed virtual env, activated it, installed packages I want but when it came to import those packages in jupyter notebook I am wrecking my brain for a good while now.
(cntk) C:\Users\sushant>pip list
Package    Version
---------- -------
cntk       2.6
numpy      1.15.4
pip        18.1
scipy      1.1.0
setuptools 40.6.3
wheel      0.32.3

how do I import cntk from virtaul env (cntk) to jupyter notebook.
I tried
from C:\Users\sushant\cntk\Lib\site-packages\cntk import cntk

but apparently is not the way to do it  its giving me invalid syntex
Update
I have learnt that Virtual environments are not cross-importable which is what I was trying to do.

A: use
from.your_packagename.sub_package import class_name

by this you can access class and sub packages of that package


text:
Q: ¿Como puedo sumar el value de varias opciones, cuando sean seleecionadas? Estoy tratando de montar como un formulario, con varias opciones select, donde se seleccione un rango de edad, dependiendo del rango seleccionado, otorgará un value el cual sería el monto por el rango de edad.
Después vendrían dos opciones, de si y no, de las cuales si escoge si, el value es 24 si es no entonces es 0.
Para el primero logro crear el select y sus opciones, les doy su value, pero cuando quiero proceder con la suma, no sé como escribirlo.
En el caso de las opciones si/no, pensé en usar booleanos, pero como indiqué soy nuevo, entiendo la teoría pero me falta práctica, agradezco su ayuda. Esto es sólo un proyecto personal para agilizar una parte en mi trabajo.

Seleccione el Rango de Edad:

    <select id="diezk" onchange="select()">
        <option value="180">4-18</option>
        <option value="230">19-22</option>
        <option value="360">23-29</option>
        <option value="420">30-37</option>
    </select>

Desea usar

    <select id="asit" onchange="select()">
        <option value="24">Si</option>
        <option value="0">No</option>
    </select>

Desea usar

    <select id="fun" onchange="select()">
        <option value="24">Si</option>
        <option value="0">No</option>
    </select>

A: Una opción que te propongo es que a todos los select les pongas la misma clase y en jQuery podrías obtener los value seleccionados dentro de un ciclo each, se obtiene la suma y se pasa el resultado a donde lo necesites. En mi caso en un input.
Otra cosa a tener en cuenta es agregar un option con value 0 y con el atributo hidden para que se oculte una vez seleccionada otra opción. Esto es para evitar errores en el cálculo del total.

function calcular(){
  //Inicializar la suma en cero
  let suma = 0;
  //Recorrer todos los select con clase lista
  $('.lista').each(function( i ) {
    //Obtener el value seleccionado en cada select
    let valorSeleccionado = $(this).find(":selected").val();
    //Incrementar o decrementar el valor de suma
    suma = parseInt(suma) + parseInt(valorSeleccionado);
  });
  //Asignar la suma al campo donde se muestran los resultados
  $('#total').val(suma);
};

Seleccione el Rango de Edad:

    <select class="lista" onchange="calcular()">
        <option value="0" hidden>Seleccione</option>
        <option value="180">4-18</option>
        <option value="230">19-22</option>
        <option value="360">23-29</option>
        <option value="420">30-37</option>
    </select>

Desea usar

    <select class="lista" onchange="calcular()">
        <option value="0" hidden>Seleccione</option>
        <option value="24">Si</option>
        <option value="0">No</option>
    </select>

Desea usar

    <select class="lista" onchange="calcular()">
        <option value="0" hidden>Seleccione</option>
        <option value="24">Si</option>
        <option value="0">No</option>
    </select>

Total

    <input id="total" value="0"/>


text:
Q: Regex constants using $@ adding extra characters? I'm constructing a regex string from a list of words using the following code snippet:
foreach (String w in ar)
        {
            c= $@"\b{w}\b|";  //**
            result = result + c;

        }

The first word in the array ar is "can".  When I inspect the value of c in the debugger after execution of the asterisked line, the debugger shows the following value.
"\\bcan\\b\b|"

I guess I sort of understand why the backslashes are doubled, but I don't understand why  the it contains an extra "\b" at the end before the vertical bar.

OK, I've tried the experiment suggested in the comments.
Putting in this code in the routine
            foreach (String w in ar)
        {
            System.Diagnostics.Debug.WriteLine("w='" +w + "'");
            c= $@"\b{w}\b|";
            System.Diagnostics.Debug.WriteLine("c='" + c + "'");
            result = result + c;

        }

I get this result in the console:
w='can'
c='\bcan\b|'

However the debugger is still showing the unusual string value in the watch expression.  Can somebody explain what that is?


text:
Q: Transferring to another ViewController I am currently loading another viewcontroller on this code
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

NewViewController *controller = [[NewController alloc]init];
controller.licensed =@"NO";
controller.delegate = self;
self.window.rootViewController = controller;
self.window.backgroundColor = [UIColor clearColor];
[self.window makeKeyAndVisible];

But the problem is when the NewViewController loads. The subviews of the previous view controller is in the background of the NewViewController
[self.rectHolder performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
[self.btnSignup performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
[self.view removeFromSuperview];

I tried to use this, but the subviews is still in the background of the new view controller
Edit:
I also tried to use this
NewViewController* viewController = [[NewViewController alloc] init];
viewController.licensed = @"NO";
[self presentViewController:viewController animated:YES completion:nil];

But the subViews of my previous viewcontroller is still in the background


text:
Q: Perl SQL file write delayed Here is the simple perl script fetching data from SQL.
Read data and write on a file OUTFILE, and print the data on screen for every 10000th line.
One thing I am curious is that the printing the data on screen terminates very quickly(in 30 seconds), however, data fetching and writing on a file ends very slowly(30 minutes later).
The amount of data is not large. The output files size is less than 100Mbyte.
while ( my ($a,$b) = $curSqlEid->fetchrow_array() )
{
    printf OUTFILE ("%s,%d\n", $a,$b);
    $counter ++;
    if($counter % 10000 == 0){
        printf ("%s,%d\n", $a,$b);
    }
}
$curSqlEid->finish();
$dbh->disconnect();
close(OUTFILE);

A: You are suffering from buffering.
Handles other than STDERR are buffered by default, and most handles use a block buffering. That means Perl will wait until there is 8KB* of data to write before sending anything to the system.
STDOUT is special. When is attached to a terminal (and only then), it uses a different kind of buffering: line buffering. When using line buffering, the data is flushed every time a newline is encountered in the data to write.
You can see this by running
$ perl -e'print "abc"; print "def"; sleep 5; print "\n"; sleep 5;'
[ 5 seconds pass ]
abcdef
[ 5 seconds pass ]

$ perl -e'print "abc"; print "def"; sleep 5; print "\n"; sleep 5;' | cat
[ 10 seconds pass ]
abcdef

The solution is to turn off buffering.
use IO::Handle qw( );  # Not needed on Perl 5.14 or later
OUTFILE->autoflush(1);

* — 8KB is the default. It can be configured when Perl is compiled. It used to be a non-configurable 4KB until 5.14.

A: I think you are seeing the output file size as 0 while the script is running and displaying on the console. Do not go by that. The file size will show up only once the script has finished. This is due to output buffering.
Anyways, the delay cannot be as large as 30 min. Once the script is done, you should see the output file data.

A: I tried various things, but the final conclusion is that python and perl has basically different handling data flow from DB. It looks like in perl, it is possible to handle data line by line while the data is transferred from DB. However, in Python it needs to wait until the entire data download from the server to process it.


text:
Q: c# wpf datagrid merge cells I'm trying to make DataGrid look like:
    --------------------------------------
    Point name  | Distance between points|
    --------------------------------------
        pt1     |------------------------|
    ------------|            10.45       |
        pt2     |------------------------|
    ------------|            8.55        |
        pt4     |------------------------|
    ------------|            4.89        |
        pt5     |------------------------|
    ------------|                        |

The grid is going to be binded to BindingList.
    BindingList<PointClass> points;
    class PointClass
    {
         public string Name { get; set;}
         public double DistToNextPoint { get; set;}
    }

Is it even possible with datagrid? Or should I make a custom control?

A: The DataGrid is an ItemsControl adapted to represent cells in a row aligned in columns. But the basis is the same - the representation of the source elements (ItemsSource). In the case of the DataGrid, the representation is only row-by-row. Since you need an interline representation, the DataGrid is not suitable for this.
You need either very deep intervention in the DatGrid template, or creating your own CustomControl (possibly derived from ItemsControl).


text:
Q: How to determine if a file has been copied to a target When I add files to my Xcode project, I am asked if I want to "Copy items into destination groups's folders" and given a checkbox for each target I want the files added to.
First, how can I, after the fact of adding files (weeks or months later), determine if I copied the files into the destination?
Second, how can I, after the fact, determine which targets the files were added to?

A:
First, how can I, after the fact of adding files (weeks or months
  later), determine if I copied the files into the destination?

Find the files in your desired destination location. If It's available, then you have copied the files into the destination successfully:)

Second, how can I, after the fact, determine which targets the files
  were added to?

Select the file using Xcode and look at the Target Membership Section.


text:
Q: Difference between cocky and confident? What is the difference between cocky and confidence. Saying the words, "I am going to win" can come off as both cocky and confidence to any person.
In my perspective, if you win, you were "confident" and if you lose after saying that, you would be considered "cocky." Are there or can there be more objective differentiating factors other than winning?
According to dictionary.com, confidence is strong belief in one-self. When using dictionary.com for cocky, it is simply arrogant. Using google and looking up arrogant, it is defined as "having or revealing an exaggerated sense of one's own importance or abilities." So if by winning, would it not be considered over-exaggerating your abilities and therefore be considered confidence as he believed in himself?

A: All cocky people are confident, but not all confident people are cocky. Cocky adds to confident an aura of arrogant superiority.
If I say, "I'm quite sure this answer is correct," then I'm being confident.
If I add, "No one is going to be able to write a better answer than this one," then I'm being cocky.
I think your example (which discusses winners and losers) is a bit contrived. Just because a player is confident she can win doesn't make her cocky if she doesn't. Cocky is tied more to the attitude than to the result.

A: I don't agree with your reasoning at all. The tone of voice and the actions of the person saying them decide what adjectives are appropriate. Simply by adding that context we can change the meaning, e.g.
In order to give himself confidence before the race he looked in the mirror and - just as his coach had suggested - said three times, "I am going to win".
That version doesn't show cockiness and he is doing it because he lacks confidence. Compare
He strutted around thrusting his face into those of the other competitors and saying with a grin, "I am going to win."
That version, I suggest shows someone being cocky.
Here is a definition of 'cocky' that explains the difference.

cocky
ˈkɒki adjective
conceited or confident in a bold or cheeky way.
Google Search

A: cocky in a way is a more arrogant expression than being confident


text:
Q: How to Write Automated System Tests with C#? We have an old asp.net application that has no unit tests, integration tests, component tests or UI/functional tests - surprise!
Now, we'd like to introduce some automated system testing that tests the functionality so that when something breaks in the app we immediately get notified!
For example, the user registration form where user can enter username and email address and register in the system.
It's too late/expensive to introduce unit tests (as the current design is not unit testable) so the most important thing now is writing Automated System Tests.
For example, we'd like to write a test in C# which opens the browser, enters the data to the text boxes, clicks on the Register button then our test checks whether the data is inserted into the database and whether a verification email is sent and at the end whether a proper message is shown to the user (of course this is only the main scenarios and there would be numerous special cases). Basically not testing isolated units but testing whether the whole process works!
So, what tool could I use to help me write such test and automating it?
What approach would you recommend to use?
I had a look at Selenium and Fitnesse but they don't seem to allow me write C# code to test database, etc. I looked at the SoapUI/LoadUI same issue. WatiN could possibly be used, not sure. any thoughts/recommendations are very much appreciated.
Hope the question is clear.
Many thanks,

A: Selenium absolutely does allow you to write C# code for system testing. First you would have a method to interact with the website, a second method to verify the database is correct. All within a single test app/class.
For the web interaction, you would use a WebDriver (taken from the Selenium API doc). Here's some example code of IWebDriver's interface. It interacts with google, but you can modify this to interact with your website.
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;

class GoogleSuggest
{
    static void Main(string[] args)
    {
        IWebDriver driver = new FirefoxDriver();
        driver.Navigate().GoToUrl("http://www.google.com/");
        IWebElement query = driver.FindElement(By.Name("q"));
        query.SendKeys("Cheese");
        System.Console.WriteLine("Page title is: " + driver.Title);
        driver.Quit();
    }
}

Then you would just implement another method that verifies the database entries are correct, using something like LinqToSql or other C# database API.

A: If you have Visual Studio Ultimate, perhaps a Coded UI Test is what you're looking for?  http://msdn.microsoft.com/en-us/library/dd286681.aspx

A: Use CodedUI or Selenium Web driver

A: You could also look to Telerik's Test Studio as a solution for your testing needs. (Disclosure: I work for Telerik as their Test Studio Evangelist.)
Test Studio lets you easily create extremely maintainable functional and performance tests.
You can also easily add steps or tests in C# (or VB.NET) to handle things like test fixture setup/teardown, or to deal with test oracle situations like you mention. (Checking the database to ensure a record is properly saved, tying in something like nDumbster for e-mail validation, etc.)

A: Selenium Webdriver can be added as package to C# project in Visual studio express IDE and then  adding nUnit package one can write test cases. Below are the few links that can help you get kickstarted with selenium webdriver Automated test cases
On how to setup the IDE (VS express), nUnit and selenium refer
How to setup C#,nUnit and selenium client drivers on VSExpress for Automated tests
On Creating simple script that launches a browser does few steps refer
Creating Basic Selenium web driver test case using Nunit and C#
On how to Load the same webpage on a number of different browsers I suggest referring
How to invoke locally different types of browser driver using selenium and c#
On Loading the same webpage on a number of virtual machines for this, you need to use Remote webdriver instead of normal webdriver. Also with remote webdriver, you can launch different types of browser. Refer this webpage
How to invoke/run different type of web driver browser using remote webdriver in C#
To take snapshot on different browser you can refer the link
Capturing screen shots using remote/local webdriver in C#/Selenium webdriver


text:
Q: I want to take two integer numbers in one row and calculate their sum in python3 I want to take two numbers in one row by space and get their sum.
so I think I have to use a split()
This is the code I wrote
    num1,num2 = map(int,input.split())
    result = num1+num2
    print(str(result))

'''It keep says that this code have a runtime error but I can't find out why'''

A: Your error is due to the fact that you're calling ".split()" on "input" which is a function. If you want to apply the "split()" to the RESULT of the "input" function, you should write it as "input().split()".
Plus, if you want to allow only one or more than 2 numbers, you should consider using the sum() function of python.
Finally the str(result) is not needed as print() will already try to format it's parameter as a string.
Here is your version fixed (by adding the missing "()"):
num1, num2 = map(int, input().split())
result = num1 + num2
print(result)

And here is a version using the function "sum()":
values = map(int, input().split())
my_sum = sum(values)
print(my_sum)


text:
Q: Connect rails app to android one I have recently finished a rails app and Its is currently hosted in heroku, It has a database setuped and every thing. In the app you can upload users edit them, etc. .Now, I want to create an android aplication that can do the same things.
I have been reading about using rest but I am not shure that is the way. Any other options, thanks!

A: You have just two option:

*

*Create your own API in your rails app:

Manually:
http://railscasts.com/episodes/350-rest-api-versioning
Using some gem:
http://railscasts.com/episodes/348-the-rails-api-gem
or

*create android app with Webview object for working with you app by internet like browser
https://developer.chrome.com/multidevice/webview/gettingstarted
very similar question:
From ruby on rails website/webapp to Phonegap Android app?


text:
Q: Replicating Django apps from reusable packages I am trying to leverage off the available Django Package, andablog. I have installed the necessary packages from PyPI. However, I noted that even after including the following code within settings.py, the command python manage.py migrate does not create the necessary app folders within the project folder. Am I missing some other steps?
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_markdown',
    'service_reviews',
    'andablog',
    'taggit',
    'markitup',
)

A: python manage.py migrate is not supposed to create any directory, its goal is to generate the database tables required for your installed apps to work properly (read the doc for more info).
The third party apps that you installed live somewhere in your Python path and Django knows how to access them, you don't need them to be in your project's folder.

A: You are not missing any steps, but you shouldn't expect andablog to be a local Django app -- that's not what adding third-party apps to INSTALLED_APPS should do. INSTALLED_APPS informs Django of what packages it needs to load upon bootstrapping. Migrating the app will put migrations in a different directory altogether. The exact location of these migration files will vary depending on how you installed the package.


text:
Q: Highstocks not showing stock tools I am trying to plot a time-series but I am not getting the stock tools as in the left-side of this chart. Example from the highstocks website: enter link description here

The code with options:
import React from 'react';
import Highcharts from 'highcharts/highstock'
import HighchartsReact from 'highcharts-react-official'

class Graph extends React.Component {
    getOptions = (dataSets) => {
        return {
            yAxis: [{
                labels: {
                    align: 'left'
                },
                height: '80%',
                resize: {
                    enabled: true
                }
            }, {
                labels: {
                    align: 'left'
                },
                top: '80%',
                height: '20%',
                offset: 0
            }],

            title: {
                text: 'Summary'
            },

            series: [{
                name: 'INFY',
                data: dataSets.data
            }]
        };
    };

    render() {
        const {dataSets} = this.props;
        const options = this.getOptions(dataSets);

        return (

                <HighchartsReact
                    highcharts={Highcharts}
                    constructorType={'stockChart'}
                    options={options}
                />

        )
    }
}

export default Graph;

Here is what is rendered:

What is going wrong?
EDIT:
After applying the suggestions by @ppotaczek. I get this:

Updated code:
import React from 'react';
import Highcharts from "highcharts/highstock";
import indicatorsAll from "highcharts/indicators/indicators-all";
import annotationsAdvanced from "highcharts/modules/annotations-advanced";
import priceIndicator from "highcharts/modules/price-indicator";
import fullScreen from "highcharts/modules/full-screen";
import stockTools from "highcharts/modules/stock-tools";
import HighchartsReact from "highcharts-react-official";

indicatorsAll(Highcharts);
annotationsAdvanced(Highcharts);
priceIndicator(Highcharts);
fullScreen(Highcharts);
stockTools(Highcharts);

class Graph extends React.Component {
    getOptions = (dataSets) => {
        return {
            yAxis: [{
                labels: {
                    align: 'left'
                },
                height: '80%',
                resize: {
                    enabled: true
                }
            }, {
                labels: {
                    align: 'left'
                },
                top: '80%',
                height: '20%',
                offset: 0
            }],

            title: {
                text: 'Summary'
            },

            series: [{
                name: 'INFY',
                data: dataSets.data
            }]
        };
    };

    render() {
        const {dataSets} = this.props;
        const options = this.getOptions(dataSets);

        return (

                <HighchartsReact
                    highcharts={Highcharts}
                    constructorType={'stockChart'}
                    options={options}
                />

        )
    }
}

export default Graph;

A: You need load CSS styles and import and initialize all of the required modules:
import indicatorsAll from "highcharts/indicators/indicators-all";
import annotationsAdvanced from "highcharts/modules/annotations-advanced";
import priceIndicator from "highcharts/modules/price-indicator";
import fullScreen from "highcharts/modules/full-screen";
import stockTools from "highcharts/modules/stock-tools";

indicatorsAll(Highcharts);
annotationsAdvanced(Highcharts);
priceIndicator(Highcharts);
fullScreen(Highcharts);
stockTools(Highcharts);

Live demo: https://codesandbox.io/s/highcharts-react-demo-3s8v7
Docs: https://www.highcharts.com/docs/stock/stock-tools


text:
Q: What is the first reference to 'video calls' in sci-fi? I was thinking earlier today about video-calls, which reminded me of the video calls in Back To The Future 2.  Then I remembered that a similar technology existed in Gerry Anderson's (RIP) Thunderbirds.  It got me wondering about what was the first reference to this idea of a 'video-call' i.e. where you can 'call' someone like a phone call, but actually see them as well as talk to them?

A: The earliest literary reference I can find in an overtly science fictional context is from the 1889 story "In the year 2889" by Jules Verne where we learn that in the future, people will converse by telephote:

Would not our contemporaries prize the telephone and the telephote
  more highly if they had not forgotten the telegraph?
  ...
  The first thing that Mr. Smith does is to connect his phonotelephote,
  the wires of which communicate with his Paris mansion. The telephote!
  Here is another of the great triumphs of science in our time. The
  transmission of speech is an old story; the transmission of images by
  means of sensitive mirrors connected by wires is a thing but of
  yesterday.

There's an even earlier reference in an 1879 cartoon in Punch by George du Maurier captioned "Edison's Telephonoscope (transmits light as well as sound)"

Ironically, this may be one instance where science-fact overtook science-fiction. Edison and Bell were both working on telephones that could also transmit pictures as early as 1875 (some three years before any fictional account), albeit with only limited success.
Louis Figuier wrote a letter to the New York Sun in 1877 extolling the virtues of an Electroscopic device, a whole year before it appeared anywhere in fiction. Since he was describing something that didn't yet exist (presumably based on concept patents issues to Bell), this is arguably the earliest reference of any sort in print. Since he thought it was a real invention it's probably not fair to characterise it as fiction.

As far as films/TV are concerned, the "videophone" seen in Fritz Lang's Metropolis (1927) has to be one of the earliest seen on screen:

A: Hugo Gernsback predicted the "telephot" (a video telephone device) in dramatic use in his novel Ralph 124C 41+ which he ran for 12 months from April 1911 in Modern Electrics.

Stepping to the Telephot on the side of the wall he pressed a group of
  buttons and in a few minutes the faceplate of the Telephot became
  luminous, revealing the face of a clean shaven man about thirty, a
  pleasant but serious face.
As soon as he recognized the face of Ralph in his own Telephot he
  smiled and said, "Hello Ralph."

You can see an artist's impression above (from Electric Experiments Magazine) and read the full story here.


text:
Q: Stop evalulate operator<< I am trying to do a simple logging library only for my own. I know there exists several once, but I have not found any header-only, small and very "c++" like logging library which fits into my application.
Currently I have the following syntax:
logger << debug << "A debug message" << end; //debug and end is my custom manipulators

I have implemented all necessary operator<< and it works great, specially when it have backward compatibility with std::ostream. But I wonder, just for efficiency if it is a why to stop evaluate anything if some message should not be logged (after debug in the example)? Making everything after the severity manipulator "disappear"?
Just now do I have the following code in short:
template <typename Type>
Logger & Logger::operator<<(const Type & message)
{
    if(this->get_message_level() <= this->get_severity())
    {
        BOOST_FOREACH(std::ostream* stream, this->_sinks)
        {
            *stream << message;
        }
    }
    return *this;
}

Logger & Logger::operator<< (Logger & (*pf)(Logger&))
{
    return pf(*this);
}

Logger & debug(Logger& logger)
{
    logger.lock();
    logger.set_severity(7);
    //...
    return logger;
}

Logger & end(Logger& logger)
{
    logger << std::endl;
    logger.unlock();
    return logger;
}

Thanks in advance.

A: You could do something as simple as
extern "C" bool want_log;
#define LOG(Arg) do { if (want_log) \
   cout << __FILE__ << ":" << __LINE__ ": " << Arg << endl; } while(0)

and use it as LOG("x=" << x)

A: It can be a bit tricky, depending on what compromizes you're willing to
accept in the syntax.  If you really want to support everything that
outputting to an ostream does, then the best you can do (as far as I
know) is a wrapper class, along the lines of:
class Logger
{
    std::ostream* myDest;
public:
    //  Appropriate constructors...
    template<typename T>
    Logger& operator<<( T const& obj )
    {
        if ( myDest != NULL )
            (*myDest) << obj;
        return *this;
    }
};

If logging is turned off (Logger::myDest == NULL), none of the
conversion code will execute, but you'll still evaluate each of the
arguments.  In my experience, this is not usually an issue, since most
of the arguments are either string literals or a simple variable, but
it's not a total 0 cost.  It also has the potential disadvantage that
the propagated type is not std::ostream& (although I've never found
this to be a problem in practice).
A somewhat tricker solution would be to use a macro along the lines of:
#define logger loggerInstance != NULL && (*loggerInstance)

This will still allow most of the actual uses with the same syntax
(because the && operator has very low precedence), but could fail in
cases where someone has tried to be too clever, and embedded the logging
output in a more complicated expression.  In addition to not doing the
conversions, the arguments are not even evaluated if logging is turned
off.
Finally, if you accept a different syntax, you can write something like:
#ifndef NDEBUG
#define LOG(argList) logger << argList
#else
#define LOG(argList)
#endif

This requires the user to write LOG("x = " << x), instead of log <<
"x = " << x, and requires recompiling if you want to turn logging on,
but it is the only solution I know which has absolute 0 cost if logging
is turned off.
In my experience, most applications can support the first solution; in a
very few cases, you might want to use the second; and I've never seen an
application where performance required the third.
Note that even with the first, you'll probably want to use a macro to
get the logger instance, in order to automatically insert __FILE__ and
__LINE__, and that in the second, you'll probably still want to use a
wrapper class, in order to ensure a flush in the destructor; if the
application is multithreaded, you'll want the wrapper in all cases, in
order to make the entire sequence of output atomic.

A: You could check for the severity in the Logger & Logger::operator<< (Logger & (*pf)(Logger&)) operator and just return an "empty" logger that doesn't print anything in that case:
class EmptyLogger : public Logger {
  template <typename Type>
  Logger & Logger::operator<<(const Type & message)  { return *this; }
};

EmptyLogger empty;  // Can be global/static, it won't cause any race conditions as it does nothing

Logger & Logger::operator<< (Logger & (*pf)(Logger&))
{
    if (logger.get_severity() < 5)  // Replace with a proper condition
      return empty;
    return pf(*this);  // What does pf() do? Aren't you returning reference to a temporary object?
}

A: Take a look at this article in dr dobbs about logging in c++:
http://drdobbs.com/cpp/201804215?pgno=2
This page addresses your particular concern but I'd recommend reading the whole article.
I implemented a logging system based on this article and was really pleased with it.


text:
Q: Show .ico Files in Windows Phone 8 App I'm building an app for Windows Phone 8 that will be able to show the favicon of a website, but the problem is that, when the image is an icon, I get an exception telling me that the image type isn't supported.
I've tried to convert the image to png in the WCF service that my app uses, but it seems that both Azure and my other hosting service don't support the System.Drawing.Image namespace.
Now I'm looking for a way to convert ico to png in the app, even if it means having a native lib, but I cannot find any lib that would do it.
Does anyone have a solution for this? I don't care if I have to do it in the app or in the service...
If I could make it work with Windows Phone 7 either would be better, but just Phone 8 would solve the issue...
Thank you all in advance!


text:
Q: List Find() StackOverflow Error I am getting a StackOverflow Error in this code:
EDIT
[XmlAttribute("ID")]
public string ID { get; set; }

EDIT2
 public ParameterEntity this[string szID]
    {
        get
        {
            //Finds the parameter entity with the ID passed in.
            return rParameters.Find(
                  delegate(ParameterEntity oParameterEntity)
                  {
                      return oParameterEntity.ID.Equals(szID, StringComparison.OrdinalIgnoreCase);
                  });
        }
    }

Can you guys please advise?
I might just have to use a simple manual looping.
Thanks
-Oliver

A: It's likely your ID property is trying to return itself, or set itself
Something like
private int _ID;

public int ID{
   get{return ID;}
   set{ID=value;}
}

Obviously it's probably not something that simple, but along those lines
(many edits ;P)

A: Problem was elsewhere.


text:
Q: Django authentication when database is changed I have created a Django application with authentication using django.contrib.auth. I was using a database with user admin and password xyz everything works fine. Then I changed the database which has user admin with password abc.
The issue is my application is running fine after refresh (logged in as admin) even though I didn't know the password abc. which shouldn't be possible.
After I logged out, everything is working fine as expected.


text:
Q: sql aggregate data this is not a specific dbms question, but a generic sql problem.
i have this dataset
userid | objecteid| count
--------------------------
1      | 1        | 12
1      | 2        | 15
1      | 3        | 6
2      | 4        | 30
2      | 1        | 1
2      | 5        | 9

with one query i need to find: for each user, the object with the maximum count
looking for a result like this:
userid | objecteid| count
--------------------------
1      | 2        | 15
2      | 4        | 30

because the object 2 has the max count for user 1 and the object 4 has the max count for user 2

A: This can easily be solved using window functions.
The following is standard ANSI SQL:
select userid, objecteid, "count"
from (
  select userid, objecteid, "count",
         max("count") over (partition by userid) as max_cnt
  from the_table
) t
where "count" = max_cnt;

If there are two objects with the same count, both will be returned.
Alternatively this can also be done using row_number() instead:
select userid, objecteid, "count"
from (
  select userid, objecteid, "count",
         row_number() over (partition by userid order by "count" desc) as rn
  from the_table
) t
where rn = 1;

Unlike the first query, this will only pick one row if a user has more than one object with the same count. If you want those duplicates returned, use dense_rank() instead of row_number()
SQLFiddle: http://sqlfiddle.com/#!15/f02a9/1

A: try this
Select * from tableName
         where count in (
            Select Max(count)
            from tableName
            group by userid
         )


text:
Q: Javascripted HTML table addition not displaying when printed I've coded a table in HTML. However, there are some variables that could be within the table that need me to append an extra entry at the end if the variable is included.
I have the code HTML which is linked to a JavaScript block of code:

var sku = "".concat("[%ITEM_SKU1%]", "[%ITEM_SKU2%]", "[%ITEM_SKU3%]", "[%ITEM_SKU4%]");
var mini_sku = "-01969-|-01970-|-01971-|-01972-|";
var personRegExp = new RegExp(mini_sku);
if (personRegExp.test(sku)) {
  document.getElementById("Additional").innerHTML = ' \
            +          	\
           \
            Additional Item          	\
           \
            Additional Item(s) (Title)           	\
           \

 \
              n/a
          	\

 n/a
	';
}

The code basically searches the variable "sku" for the numbers listed in "mini_sku". If they're there, the extra entry to the table is added.
This code works fine when I open the .html file in a browser. When I try to print the file directly, however, the code doesn't work and the extra entry isn't added. Is there a way to make it work correctly when I go to print the file?

A: I have read your comment. Try to explain a bit more your problem since the question is to wide or a bit vague.
Remember Javascript is a interpreted programming language. Javascripts need to be interpreted by a browser to do work. If you send it to print without opening the file first in the browser the javascript part of your code will never work. That's why when you print you can't see the extra column on your table.
What you can do? Well... I suppose you have this table inside a div tag (let's name it "yourdiv") so... You can put a button on the file you want to print:

<input type="button" name="Print" value="Print" onclick="toprint();">

The javascript function:
function toprint() {

     var content= document.getElementById(tablediv);
      var contentprint = window.open(' ', 'Table');
      contentprint.document.write(content.innerHTML );
      contentprint.document.close();
      contentprint.print( );
      contentprint.close();

}


text:
Q: How avoid module duplication by separated files on typeScript compilation? According to this example the compiled ES5 code looks like :
/// <reference path="Validation.ts" />
var Validation;
(function (Validation) {

    ...

})(Validation || (Validation = {}));
/// <reference path="Validation.ts" />
var Validation;
(function (Validation) {

    ...

})(Validation || (Validation = {}));

...

How avoid the duplication of Validation module to achieve :
var Validation;
(function (Validation) {

    ...

    ...

})(Validation || (Validation = {}));

It becomes really heavy with multipes files and it stays on minification... The __extends method for super constructor stays duplicated too.
Thank you

A: You can't avoid this at the moment because the compiler combines files by simply appending them in the order you have specified (in reference comments).
Although there is visual duplication, there is still only a single object created in the global scope, so the duplication does not result in a noticeable performance problem and causes no memory issues.
If you have a large program and this is a problem for you, you should probably be considering external modules rather than internal modules as external modules are designed for bigger programs.


text:
Q: Improving Mysql updating query performance We are trying to change some data from our Mysql database (v5.7.17) from being evaluated on-the-fly to a field in the database. The concrete field is the detectable_status and it will be calculated each night for the equipment (which inherits from detectable) in order to evaluate it. That's the query updating the field for a concrete client in our application:
UPDATE tdetectable det
JOIN tdetectable_equipment equipment ON det.id = equipment.id_detectable
JOIN torganization org ON det.id_organization = org.id
SET det.detectable_status = (CASE
    WHEN (equipment.setting_up_date IS NOT NULL
        AND equipment.expiration_periodicity_type IS NOT NULL AND
        fdate_periodicity(equipment.setting_up_date,
        equipment.expiration_periodicity_type, equipment.expiration_periodicity_value,1)
        < NOW()) = 1
        THEN 'EXPIRED'
    WHEN (EXISTS(
        SELECT *
        FROM trevision_cycle incorrect_cycle
        WHERE equipment.id_detectable = incorrect_cycle.id_detectable
        AND incorrect_cycle.status = 'NO_OK'
        AND incorrect_cycle.active <> 0 AND incorrect_cycle.id IS NOT NULL))
        THEN 'INCORRECT'
    WHEN (EXISTS(
        SELECT *
        FROM trevision_cycle need_revision_cycle
        WHERE equipment.id_detectable = need_revision_cycle.id_detectable
        AND need_revision_cycle.next_revision_date IS NOT NULL
        AND need_revision_cycle.next_revision_date < NOW() = 1
        AND equipment.id_detectable = det.id
        AND need_revision_cycle.active <> 0))
        THEN 'NEEDS_REVISION'
    WHEN (equipment.setting_up_date IS NULL
        AND (equipment.expiration_periodicity_type IS NOT NULL OR EXISTS(
        SELECT *
        FROM trevision_cycle last_revision_cycle
        WHERE last_revision_cycle.id_detectable = equipment.id_detectable
        AND last_revision_cycle.last_revision_date IS NULL
        AND last_revision_cycle.active <> 0)))
        THEN 'INDETERMINATE'
    ELSE    'CORRECT'
    END)
WHERE det.active and org.id_client = ?

The status is set for every equipment in the client based in different factors (expiration dates, revision dates...). The problem is the query is quite slow. Here it is my benchmark:
Affected rows: 131, Duration: 0,375 sec.

Affected rows: 4.208, Duration: 44,585 sec.

Affected rows: 2.036, Duration: 13,712 sec.

Affected rows: 13.288, Duration: 00:10:04

Also I want to clarify the content of the fdate_periodicity function, which takes a date and adds a periodicity to it (example: 2017-09-10 + 1 YEAR = 2018-09-10):
BEGIN
IF add_to THEN
    RETURN
        CAST((CASE periodicity_type
        WHEN 'DAY' THEN (input_date + INTERVAL periodicity_value DAY)
        WHEN 'WEEK' THEN (input_date + INTERVAL periodicity_value WEEK)
        WHEN 'MONTH' THEN (input_date + INTERVAL periodicity_value MONTH)
        WHEN 'YEAR' THEN (input_date + INTERVAL periodicity_value YEAR)
        ELSE NULL
        END
        ) AS DATETIME
        );
ELSE
    RETURN  CAST((CASE periodicity_type
        WHEN 'DAY' THEN (input_date - INTERVAL periodicity_value DAY)
        WHEN 'WEEK' THEN (input_date - INTERVAL periodicity_value WEEK)
        WHEN 'MONTH' THEN (input_date - INTERVAL periodicity_value MONTH)
        WHEN 'YEAR' THEN (input_date - INTERVAL periodicity_value YEAR)
        ELSE NULL
        END
        ) AS DATETIME
        );
end if;
END

I understand MySql is doing quite a heavy work here, but are this execution times normal for a core-8 + 14Gb RAM machine? What could I do to improve it? Here it is the execution plan (explain):

Thanks in advanced!

A: Turn it into 4 UPDATES, one per status (EXPIRED, INCORRECT, ...).  Run the updates in the correct order so that if two cases apply, you end up with the desired status.
Each UPDATE would match one of your cases.  For example, for INCORRECT:
UPDATE tdetectable det
JOIN  tdetectable_equipment e  ON det.id = e.id_detectable
JOIN  torganization org  ON det.id_organization = org.id
SET det.detectable_status = 'INCORRECT'
WHERE ( EXISTS(
        SELECT *
        FROM trevision_cycle
        WHERE id_detectable = e.id_detectable
          AND status = 'NO_OK'
          AND active <> 0
          AND id IS NOT NULL -- If `id` is the PK, this test unnecessary
      ) )
      AND det.active
      AND org.id_client = ?

Indexes:
torganization: INDEX(id_client, id)
det:  INDEX(id, active) -- unless you have PRIMARY KEY(id)
trevision_cycle: INDEX(id_detectable, status, id, active)

innodb_buffer_pool_size should be about 10G for that sized machine.
More specifics:
ALTER TABLE trevision_cycle ADD INDEX(id_detectable, status, id, active);

KEY and INDEX are synonyms.  Most datatypes (INT, ENUM, etc, but not TEXT or BLOB) can be indexed.  Since it has more than 1 column, this index is called "composite" or "compound".  The order of columns in an index definition is important; I provided one useful order.


text:
Q: What is default hystrix timeout? I know that this is sounds strange, but I can't find the answer!
What timeout will be set for hystrix call by default if there is no any settings provided?
All questions about this are just that something doesn't work, etc.

A: If you ask about timeout settings for HystrixCommand then please check the source code, there are bunch of other interesting defaults there. Default execution timeout is 1sec:
private static final Integer default_executionTimeoutInMilliseconds = 1000; // default => executionTimeoutInMilliseconds: 1000 = 1 second

A: Hystrix has built in the following defaults:
Timeout for every request to an external system (default: 1000 ms)
Reference :
https://ahus1.github.io/hystrix-examples/manual.html

A: The hystrix default timeout is 1second you can change that with :
#change default timeout to 10 seconds
ribbon.ReadTimeout=10000