text:
Q: Confusion with false discovery rate and multiple testing (on Colquhoun 2014) I have read this great paper by David Colquhoun: An investigation of the false discovery rate and the misinterpretation of p-values (2014). In essence, he explains why false discovery rate (FDR) can be as high as $30\%$ even though we control for type I error with $\alpha=0.05$.
However I am still confused as to what happens if I apply FDR control in the case of multiple testing.
Say, I have performed a test for each of many variables, and calculated the $q$-values using Benjamini-Hochberg procedure. I got one variable that is significant with $q=0.049$. I am asking what is the FDR for this finding?
Can I safely assume that in the long run, if I do such analysis on a regular basis, the FDR is not $30\%$, but below $5\%$, because I used Benjamini-Hochberg? That feels wrong, I would say that the $q$-value corresponds to the $p$-value in Colquhoun's paper and his reasoning applies here as well, so that by using a $q$-threshold of $0.05$ I risk to "make fool of myself" (as Colquhoun puts it) in $30\%$ of the cases. However, I tried to explain it more formally and I failed.

A: A big part of the confusion is that, despite his comments here to the contrary, Colquhoun does NOT define FDR the same way that Benjamini-Hochberg do. It is unfortunate that Colquhoun has attempted to coin a term without first checking to make sure that the term did not already have a well-established, different definition. To make matters worse, Colquhoun defined FDR in precisely the way that the conventional FDR has often been misinterpreted.
In his answer here, Colquhoun defines FDR as "the fraction of positive tests that are false." That is similar to what Benjamini-Hochberg define as the FDP (false discovery proportion, not to be confused with the false discovery rate). Benjamini-Hochberg define FDR as the EXPECTED VALUE of the FDP, with a special stipulation that the FDP is considered as 0 when there are no positive tests (a stipulation that happens to make the FDR equal to the FWER when all nulls are true, and avoids undefinable values due to division by zero).
To avoid confusion, I suggest not worrying about the details in the Colquhoun paper, and instead just taking to heart the big-picture point (which countless others have also made) that the alpha level does not directly correspond to the proportion of significant tests that are Type I errors (whether we're talking about the significant tests in a single study or in several studies combined). That proportion depends not only on alpha, but also on power and on the proportion of tested null hypotheses that are true.

A: It so happens that by coincidence I read this same paper just a couple of weeks ago. Colquhoun mentions multiple comparisons (including Benjamini-Hochberg) in section 4 when posing the problem, but I find that he does not make the issue clear enough -- so I am not surprised to see your confusion.
The important point to realize is that Colquhoun is talking about the situation without any multiple comparison adjustments. One can understand Colquhoun's paper as adopting a reader's perspective: he essentially asks what false discovery rate (FDR) can he expect when he reads scientific literature, and this means what is the expected FDR when no multiple comparison adjustments were done.
Multiple comparisons can be taken into account when running multiple statistical tests in one study, e.g. in one paper. But nobody ever adjusts for multiple comparisons across papers.
If you actually control FDR, e.g. by following Benjamini-Hochberg (BH) procedure, then it will be controlled. The problem is that running BH procedure separately in each study, does not guarantee overall FDR control.

Can I safely assume that in the long run, if I do such analysis on a regular basis, the FDR is not $30\%$, but below $5\%$, because I used Benjamini-Hochberg?

No. If you use BH procedure in every paper, but independently in each of your papers, then you can essentially interpret your BH-adjusted $p$-values as normal $p$-values, and what Colquhoun says still applies.

General remarks
The answer to Colquhoun's question about the expected FDR is difficult to give because it depends on various assumptions. If e.g. all the null hypotheses are true, then FDR will be $100\%$ (i.e. all "significant" findings would be statistical flukes). And if all nulls are in reality false, then FDR will be zero. So the FDR depends on the proportion of true nulls, and this is something that has be externally estimated or guessed, in order to estimate the FDR. Colquhoun gives some arguments in favor of the $30\%$ number, but this estimate is highly sensitive to the assumptions.
I think the paper is mostly reasonable, but I dislike that it makes some claims sound way too bold. E.g. the first sentence of the abstract is:

If you use $p=0.05$ to suggest that you have made a discovery, you will be wrong at least $30\%$ of the time.

This is formulated too strongly and can actually be misleading.

A: Benjamini & Hochberg define false discovery rate in the same way that I do, as the fraction of positive tests that are false positives.  So if you use their procedure for multiple comparisons you control FDR properly.  It's worth noting, though, that there are quite a lot of variants on the B-H method.  Benjamini's seminars at Berkeley are on Youtube, and well worth watching:

*

*Part I: https://www.youtube.com/watch?v=oONHlua2gBY

*Part II: https://www.youtube.com/watch?v=inUr5I5WKAM
I'm not sure why @amoeba says "This is formulated too strongly and can actually be misleading".  I'd be interested to know why he/she thinks that.  The most persuasive argument comes from the simulated t tests (section 6).  That mimics what almost everyone does in practice and it shows that if you observe P close to 0.047, and claim to have made a discovery, you'll be wrong at least 26% of the time.  What can go wrong?
Of course, I should not describe this as a minimum.  It's what you get if you assume that there's a 50% chance of the there being a real effect.  Of course if you assume that most of your hypotheses are correct in advance, then you can get a lower FDR than 26%, but can you imagine the hilarity that would greet a claim that you'd made a discovery on the basis of the assumption that you were 90% sure in advance that your conclusion would be true.  26% is the minimum FDR given that it isn't a reasonable basis for inference to assume any prior probability greater than 0.5.
Given that hunches frequently don't stand up when tested, it could well be that there is only a 10% chance of any particular hypothesis being true, and in that case the FDR would be a disastrous 76%.
It's true that all this is contingent on the null hypothesis being that there is zero difference (the so called point null).  Other choices can give different results.  But the point null is what almost everyone uses in real life (though the may not be aware of it).  Furthermore the point null seems to me to be entirely appropriate thing to use.  It's sometimes objected that true differences are never exactly zero.  I disagree.  We want to tell whether are not our results are distinguishable from the case where both groups are given identical treatments, so the true difference is exactly zero.  If we decide that out data are not compatible with that view, we go on to estimate the effect size. and at that point we make the separate judgment about whether the effect, though real, is big enough to be important in practice.  There is some vigorous discussion of these topics on Deborah Mayo's blog.

@amoeba Thanks for you response.
What the discussion on Mayo's blog shows is mostly that Mayo doesn't agree with me, though she hasn't made clear why, to me at least). Stephen Senn points out correctly that you can get a different answer if you postulate a different prior distribution. That seems to me to be interesting only to subjective Bayesians.
It's certainly irrelevant to everyday practice which always assumes a point null. And as I explained, that seems to me to be a perfectly sensible thing to do.
Many professional statisticians have come to conclusions much the same as mine. Try Sellke & Berger, and Valen Johnson (refs in my paper). There is nothing very controversial (or very original) about my claims.
Your other point, about assuming a 0.5 prior, doesn't seem to me to be an assumption at all. As I explained above, anything above 0.5 woold be unacceptable in practice. And anything below 0.5 makes the false discovery rate even higher (eg 76% if prior is 0.1). Therefore it's perfectly reasonable to say that 26% is the minimum false discovery rate that you can expect if you observe P = 0.047 in a single experiment.

I've been thinking more about this question. My definition of FDR is the same as Benjamini's -the fraction of positive tests that are false. But it is applied to a quite different problem, the interpretation of a single test. With hindsight it might have been better if I'd picked a different term.
In the case of a single test, B&H leaves the P value unchanged, so it does not say anything about the false discovery rate in the sense that I use the term.

es of course you are right. Benjamini & Hochberg, and other people who work on multiple comparisons, aim only to correct the type 1 error rate. So they end up with a "correct" P value. It's subject to the same problems as any other P value.
In my latest paper, I changed the name from FDR to False Positive Risk (FPR) in an attempt to avoid this misunderstanding.
We've also written a web app to do some of the calculations (after noticing that few people download the R scripts that we provide). It's at https://davidcolquhoun.shinyapps.io/3-calcs-final/ All opinions about itare welcome (please read the Notes tab first).
PS The web calculator now has a new (permanent, I hope) at http://fpr-calc.ucl.ac.uk/
Shiny.io is easy to use, but very expensive if anyone actually uses the app :-(

I've returned to this discussion, now that my second paper on the topic is about to appear in Royal Society Open Science. It is at https://www.biorxiv.org/content/early/2017/08/07/144337
I realise that the biggest mistake that I made in the first paper was to use the term "false discovery rate (FDR)". In the new paper I make it more explicit that I am saying nothing about the multiple comparisons problem. I deal only with the question of how to interpret the P value that's observed in a single unbiased test.
In the latest version, I refer to the probability that the result as the false positive risk (FPR) rather than FDR, in the hope of reducing confusion. I also advocate the reverse Bayesian approach -specify the prior probability that would be needed to ensure an FPR of, say, 5%. If you observe P = 0.05, that comes to 0.87. In other words you'd have to be almost (87%) sure that there was a real effect before doing the experiment to achieve an FPR of 5% (which is what most people still believe, mistakenly, p=0.05 means).


text:
Q: How to know a 2d list contains another list in flutter I have a 2d list like indexList = [[1, A], [2, B], [3, C]...]. I need to check that this 2d list contains another list like item = [2, B] or not. I tried contains, listEquals, indexWhere but none of them works. In below, some examples of my code. How can I solve this?
indexWhere example
                         AppButton.buildAppButton(
                            context,
                            AppButtonType.BETSELECTION,
                            matchList[index][6],
                            kCategoryButtonDimensions,
                            color: tappedRowButtonIndex.indexWhere((test) =>
                                        test.contains([
                                          tappedRowIndex,
                                          tappedButtonIndex
                                        ])) !=
                                    null
                                ? Colors.yellow
                                : Colors.white,

listEquals example
                    AppButton.buildAppButton(
                            context,
                            AppButtonType.BETSELECTION,
                            matchList[index][6],
                            kCategoryButtonDimensions,
                            color: listEquals(tappedRowButtonIndex, [tappedRowIndex, tappedRowButtonIndex])
                                ? Colors.yellow
                                : Colors.white,
                            onPressed: () {
                              tappedRowIndex = index;
                              tappedButtonIndex = 3;

contains example
                      AppButton.buildAppButton(
                            context,
                            AppButtonType.BETSELECTION,
                            matchList[index][5],
                            kCategoryButtonDimensions,
                            color: tappedRowButtonIndex.contains(
                                    [tappedRowIndex, tappedButtonIndex])
                                ? Colors.yellow
                                : Colors.white,
                            onPressed: () {
                              tappedRowIndex = index;
                              tappedButtonIndex = 2;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using functions and while loops together in PHP Ok, so I understand that a function can only be created once, but I need to use the output of a value from an array to run through the function 3 times on the same page. I've got it set up as i thought it should work, but php just produces a blank page. Here's the original function prior to me using it:
function time_ago($date,$granularity=2) {
    $date = strtotime($date);
    $difference = time() - $date;
    $periods = array('decade' => 315360000,
        'year' => 31536000,
        'month' => 2628000,
        'week' => 604800,
        'day' => 86400,
        'hour' => 3600,
        'minute' => 60,
        'second' => 1);
    if ($difference < 5) { // less than 5 seconds ago, let's say "just now"
        $retval = "posted just now";
        return $retval;
    } else {
        foreach ($periods as $key => $value) {
            if ($difference >= $value) {
                $time = floor($difference/$value);
                $difference %= $value;
                $retval .= ($retval ? ' ' : '').$time.' ';
                $retval .= (($time > 1) ? $key.'s' : $key);
                $granularity--;
            }
            if ($granularity == '0') { break; }
        }
        return ' posted '.$retval.' ago';
    }
}

then here's my basic loop, designed to pull tweets from a database and to convert the timestamp to unix time:
$sql = $db->select("SELECT * FROM `Twitter_tweets` ORDER BY `id` DESC LIMIT 0, 3");

while($res = $db->get_row($sql))
        {
            $p .= '

                    '.display_clean($res['tweet']).'

                    ';

            $timeSince = ceil(abs(display_clean($res['created_at']) - time()) / 86400);

            $p .= ''.$timeSince.'

            ';
        }

The idea of the following section of code is to take the date in the database, convert to unixtime, find the difference between the two and then output it as 'posted x minutes ago', a la facebook/twitter etc:
//loop section converting date to 'posted x time ago'

$sql = $db->select("SELECT * FROM `Twitter_tweets` ORDER BY `id` DESC LIMIT 0, 3");

function time_ago($date,$granularity=2) {
    $date = strtotime($date);
    $difference = time() - $date;
    $periods = array('decade' => 315360000,
        'year' => 31536000,
        'month' => 2628000,
        'week' => 604800,
        'day' => 86400,
        'hour' => 3600,
        'minute' => 60,
        'second' => 1);
}

    while($res = $db->get_row($sql))
        {
            $p .= '

                    '.display_clean($res['tweet']).'

                    ';

            $date = display_clean($res['created_at']);

            if ($difference < 5) { // less than 5 seconds ago, let's say "just now"
                $retval = "posted just now";
                return $retval;
            } else {
                foreach ($periods as $key => $value) {
                    if ($difference >= $value) {
                        $time = floor($difference/$value);
                        $difference %= $value;
                        $retval .= ($retval ? ' ' : '').$time.' ';
                        $retval .= (($time > 1) ? $key.'s' : $key);
                        $granularity--;
                    }
                if ($granularity == '0') { break; }
                }
                return ' posted '.$retval.' ago';
            }

            $p .= '

            ';
        }

//end loop

can anyone point out where i'm going wrong? I'm ok with using php, but i'm no expert by any means. I just can't see where i'm going wrong and causing a blank file to be output.

A: Why not just call the original function and print out the result?
$sql = $db->select("SELECT * FROM `Twitter_tweets` ORDER BY `id` DESC LIMIT 0, 3");

while($res = $db->get_row($sql))
        {
            $p .= '

                    '.display_clean($res['tweet']).'

                    ';

            $p .= ''.time_ago($res['created_at']).'

            ';
        }

A: I dont really understand your code, but I think there is a major syntax error in this.
If it's meant to be a function, maybe you wanted this way:
function time_ago($date,$granularity=2) {
    $sql = $db->select("SELECT * FROM `Twitter_tweets` ORDER BY `id` DESC LIMIT 0, 3");
    $date = strtotime($date);
    $difference = time() - $date;
    $periods = array('decade' => 315360000,
        'year' => 31536000,
        'month' => 2628000,
        'week' => 604800,
        'day' => 86400,
        'hour' => 3600,
        'minute' => 60,
        'second' => 1);
    while($res = $db->get_row($sql))
        {
            $p .= '

                    '.display_clean($res['tweet']).'

                    ';

            $date = display_clean($res['created_at']);

            if ($difference < 5) { // less than 5 seconds ago, let's say "just now"
                $retval = "posted just now";
                return $retval;
            } else {
                foreach ($periods as $key => $value) {
                    if ($difference >= $value) {
                        $time = floor($difference/$value);
                        $difference %= $value;
                        $retval .= ($retval ? ' ' : '').$time.' ';
                        $retval .= (($time > 1) ? $key.'s' : $key);
                        $granularity--;
                    }
                if ($granularity == '0') { break; }
                }
                return ' posted '.$retval.' ago';
            }
            $p .= '

            ';
        }
}

I didn't tested it, even if I wanted to I couldn't. Maybe it will help.


text:
Q: Проблема RewriteRule в .htaccess Добрый день имеется ссылка gallery.php?gallery=test
Хочу изменить на gallery/test но не получается а вот например на gallery=test изменяется
RewriteRule ^gallery=(.*)$ gallery.php?gallery=$1 [L]

Делаю так
RewriteRule ^gallery/(.*)$ gallery.php?gallery=$1 [L]

не получается страница открывается без никаких css и js файлов и ссылки на странице не правильные экранировал слеш тоже не получается только вот не знаю правильно ли я это делаю
RewriteRule ^gallery\/(.*)$ gallery.php?gallery=$1 [L]

A: Итак. Ваш второй вариант правильный
RewriteRule ^gallery/(.*)$ gallery.php?gallery=$1 [L]

А левые JS и CSS у вас потому, что вы им задали относительные пути. То есть:
<script type="text/javascript" src="js/script.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css" />

Это неправильно
<script type="text/javascript" src="/js/script.js"></script>
<link rel="stylesheet" type="text/css" href="/css/style.css" />

Это правильно.
Ищите различие и исправляйте все относительные пути на абсолютные. Тогда все будет работать. Не будет - дайте ссыль, ткну вас туда, где не исправили.
A: Так:
RewriteRule ^gallery/([a-zA-Z0-9]+)$ /gallery.php?gallery=$1 [L]

А стили и скрипты указывать относительно корня сайта, например:
    < link href="/css/style.css"...
A: RewriteEngine On
RewriteRule ^gallery/([a-zA-Z0-9]+)$ gallery.php?gallery=$1 [L]

A:  RewriteRule ^galery\/([a-zA-Z0-9]+)\/?$ /galery.php?galery=$1 [L]

А так?


text:
Q: React - get React component from a child DOM element? I'd like to be able to figure out what React component is associated with a certain DOM element.
For example, say I have a div, and I'm rendering my entire application using React. The div has to be rendered by a React component - but which one?
I know that React supplies the method "getDOMNode" to get the DOM node associated with a React component, but I'd like to do the opposite.
Is this possible?

A: If your situtation demands getting react element from DOM node, here is an approach, "Communicate via event and call back"
You shall fire a custom event on DOM element and have event listener for that custom event in React component. This will map DOM element back to react component.

A: No.
A central concept in React is that you don't actually have a control in the DOM.  Instead, your control is that factory function.  What's in the DOM is the current render of the control.
If you actually need this, you can keep an object as a global variable, whose keys are the string representations of the names of factory functions, and whose values are the factory functions, then on your renderable div, keep an attribute containing the name of the factory function.
But chances are this is a question of the XY problem (needing X, seeing a way with Y, then asking how to do Y.)  Probably if you'd explain your goal there's a better way that better fits React's top-down conceptual model.
Generally speaking, asking to get access to the control from its render is like asking to get access to an SVG from its cached PNG render.  It's possible, but it's usually a red flag that something else is conceptually wrong.

A: Here's what I use, with React 15.3.0:
window.FindReact = function(dom) {
    for (var key in dom) {
        if (key.startsWith("__reactInternalInstance$")) {
            var compInternals = dom[key]._currentElement;
            var compWrapper = compInternals._owner;
            var comp = compWrapper._instance;
            return comp;
        }
    }
    return null;
};

And then to use it:
var someElement = document.getElementById("someElement");
FindReact(someElement).setState({test1: test2});


text:
Q: SQL Server - Return TOP X items based on aggregate function Hello I have a SQL query that I have been running, but I'm getting way too much data than what I need.
For context, we carry about 3000 items, across 30 product categories, and 50 sub-categories (parent-child relationship). We sell them in thousands of stores, and our database captures the weekly sales per store per product.  We store for multiple years worth of data.
Currently my query returns all records, while I would like to limit it to the top10 selling items, based on the sum of their unit sales for the latest 52 weeks (my where clause specifies the 52 weeks, but I need the weekly details in my pull).
SELECT
store.store_id,
store.sales_rep,
store.sales_rep_manager,
prod.category,
prod.sub_category,
prod.item,
sales.week_id,
sum(sales.units) as "UNITS SOLD",
sum(sale.dollars) as "DOLLARS SOLD"
...
GROUP BY
store.store_id,
store.sales_rep,
store.sales_rep_manager,
prod.category,
prod.sub_category,
prod.item,
sales.week_id,
ORDER BY
7 desc

I think I should be using a TOP statement, but all I've succeeded in doing was limit the entire pull to top 10 records overall.
What I would like to see is the top 10 items based on unit velocity for the date range selected, but for each store & sub-category
Store1
Category1
Sub-Category1
TOP SELLING Item #1
TOP SELLING Item #2
TOP SELLING Item #3
...
TOP SELLING Item #10
Right now I've connected my query in Excel, and I ask my pivot table to filter only top10 items.
My issue with this solution is I'm bringing a TON more data than what I need, making the file irresponsive, too big, and also takes a lot of time to complete Query.

A: You can limit the results to the total sales in the result set pretty easily:
with q as (<your query here>)
select q.*
from (select q.*, dense_rank() over (order by TotalUs) as rnk
      from (select q.*,
                  sum("Units Sold") over (partition by prod.item) as TotalUS
            from q
           ) q
      ) q
where rnk <= 10;

Getting it for the last year is a little trickier:
with q as (<your query here>)
select q.*
from (select q.*, dense_rank() over (order by TotalUs) as rnk
      from (select q.*,
                  sum(last_52weeks) over (partition by prod.item) as TotalUS
            from (select q.*,
                         (case when dense_rank() over (partition by item_id order by week_id desc) <= 52
                               then "Units Sold" else 0
                          end) as last_52weeks
                  from q
                 ) q
           ) q
      ) q
where rnk <= 10;

A: I usually try to approach these types of problems using cascading CTEs. I've noticed that this format can solve fairly complex problems, while still being somewhat more readable. The data kind of flows from one CTE to the next, then comes out with the SELECT statement at the end.
Here's an example that I put together for this case. The data itself is somewhat questionable, as store_id 5 is really the only one with more than 10 items sold, but it's really just a demonstration so hopefully you can still get the big picture. Obviously your data structure is quite different, but you should be able to make adjustments as needed to make it work with your real setup:
--===================================================================
-- Create and populate a table for demonstration purposes only:
--===================================================================

IF OBJECT_ID('tempdb..#Sales') IS NOT NULL DROP TABLE #Sales;
CREATE TABLE #Sales (
    item_id INT,
    category VARCHAR(10),
    sub_category VARCHAR(10),
    store_id INT,
    week_id INT,
    units INT,
    dollars MONEY
);

INSERT INTO #Sales
VALUES  (1, 'A', 'A1', 1, 1, 10, 50),
        (1, 'A', 'A1', 2, 1, 10, 50),
        (1, 'A', 'A1', 3, 1, 10, 50),
        (1, 'A', 'A1', 4, 1, 10, 50),
        (1, 'A', 'A1', 5, 1, 20, 50),
        (2, 'B', 'B1', 1, 1, 20, 50),
        (2, 'B', 'B1', 2, 1, 20, 50),
        (2, 'B', 'B1', 3, 1, 20, 50),
        (2, 'B', 'B1', 4, 1, 20, 50),
        (2, 'B', 'B1', 5, 1, 20, 50),
        (3, 'A', 'A1', 5, 1, 40, 50),
        (4, 'A', 'A1', 5, 1, 10, 50),
        (5, 'A', 'A1', 5, 1, 5, 50),
        (6, 'A', 'A1', 5, 1, 100, 50),
        (7, 'A', 'A1', 5, 1, 95, 50),
        (8, 'A', 'A1', 5, 1, 35, 50),
        (9, 'A', 'A1', 5, 1, 15, 50),
        (10, 'A', 'A1', 5, 1, 11, 50),
        (11, 'A', 'A1', 5, 1, 12, 50),
        (12, 'A', 'A1', 5, 1, 49, 50),
        (12, 'A', 'A1', 5, 1, 150, 50);

--===================================================================
-- The actual query starts here:
-- (note that the following is a single statement)
--===================================================================

WITH AggregatedSales AS (
    -- This CTE will give you the totals for each store, for each item and category / sub-category:
    SELECT
        s.store_id,
        s.category,
        s.sub_category,
        s.item_id,
        --s.week_id, -- If you want to see the combined data for the entire date range, don't include week here
        SUM(s.units) [total_units_sold],
        SUM(s.dollars) [total_dollars_sold]
    FROM #Sales s
    WHERE s.week_id BETWEEN 1 AND 52 -- Adjust these to match your actual range
    GROUP BY
        s.store_id,
        s.category,
        s.sub_category,
        s.item_id
        --s.week_id
),
RankedSales AS (
    -- This will assign a ranking to each of the records from the previous CTE.
    -- The ranking is reset for each store, and ranks higher number of units sold toward the top.
    SELECT
        a.*,
        DENSE_RANK() OVER (
            PARTITION BY a.store_id
            ORDER BY a.total_units_sold DESC
        ) [ranking]
    FROM AggregatedSales a
)
-- Now we just select all of the "TOP 10" ranked items here:
-- (the WHERE clause is doing all the work in this case, so we don't need an actual TOP)
SELECT
    rs.*
FROM RankedSales rs
WHERE rs.ranking <= 10
ORDER BY
    rs.store_id,
    rs.ranking;


text:
Q: How to pass the value of a command for a key (xticklabels and yticklabels of an axis environment for pgfplots) I have a square matrix plot with identical x and y ticks and tick labels, for which I hope to use a pre-defined command to avoid repeating xticklabels and yticklabels with the same value "{A, B, C}" (my actual case has a much longer list; I am just using a simplified example here).
\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}

\def\ticklabels{A, B, C}

\begin{tikzpicture}
\begin{axis}[
enlargelimits=false,
xtick=data,
ytick=data,
xticklabels=\ticklabels,
yticklabels=\ticklabels]
\addplot [
matrix plot,
mesh/cols=3,
point meta=explicit]
table [meta=C] {
x y C
0 0 0
1 0 1
2 0 2
0 1 3
1 1 4
2 1 5
0 2 6
1 2 7
2 2 8
};
\end{axis}
\end{tikzpicture}

\end{document}

I hope to use a simple command to do this as below, but xticklabels and yticklabels values are clearly not passed properly so that only "A, B, C" as a whole is assigned to the first tick, and other ticks become empty.

I guess it is because the command is not expanded before being interpreted. I read this post and tried to use the solution provided there, but could not find how to get it work. Can anyone help?

A: New (smart?) answer
The below old answer implements something that is already implemented in pgfkeys (and I just forgot about it).
In pgfkeys there are handlers to do expansion of the given values, those are .expand once, .expand twice and .expanded (the last one fully expands in \edef). You can use those to expand your macro:
\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}

\def\ticklabels{A, B, C}

\begin{tikzpicture}
\begin{axis}[
enlargelimits=false,
xtick=data,
ytick=data,
xticklabels/.expand once=\ticklabels,
yticklabels/.expand once=\ticklabels]
\addplot [
matrix plot,
mesh/cols=3,
point meta=explicit]
table [meta=C] {
x y C
0 0 0
1 0 1
2 0 2
0 1 3
1 1 4
2 1 5
0 2 6
1 2 7
2 2 8
};
\end{axis}
\end{tikzpicture}

\end{document}

Output like in the old answer.

Old (stupid) answer
The following defines the keys xticklabels-exp and yticklabels-exp that'll expand the argument of those keys once and forward the result to xticklabels and yticklabels. This way you can use macros:
\documentclass{standalone}

\usepackage{pgfplots}

\pgfplotsset
  {%
     xticklabels-exp/.code=%
      {%
        \expanded
          {\noexpand\pgfkeysalso{xticklabels={\unexpanded\expandafter{#1}}}}%
      }
    ,yticklabels-exp/.code=%
      {%
        \expanded
          {\noexpand\pgfkeysalso{yticklabels={\unexpanded\expandafter{#1}}}}%
      }
  }

\begin{document}

\def\ticklabels{A, B, C}

\begin{tikzpicture}
\begin{axis}[
enlargelimits=false,
xtick=data,
ytick=data,
xticklabels-exp=\ticklabels,
yticklabels-exp=\ticklabels]
\addplot [
matrix plot,
mesh/cols=3,
point meta=explicit]
table [meta=C] {
x y C
0 0 0
1 0 1
2 0 2
0 1 3
1 1 4
2 1 5
0 2 6
1 2 7
2 2 8
};
\end{axis}
\end{tikzpicture}

\end{document}

Explanation of this answer:
\pgfkeysalso{<key=val-list>} is the same as if you used that list in the outer \pgfkeys-call but you can use this in the code of your keys.
\expanded fully expands its argument (similar but not exactly like \edef would, namely macro parameters need no special handling unlike in \edef).
\noexpand protects the following token from expanding in an expansion context (so in an \expanded or \edef).
\unexpanded is similar to \noexpand but takes an argument and protects the entire argument (with removing the one set of braces).
\expandafter steps over the following token and first expands the next one. Since \unexpanded expands everything until it finds an opening brace (weird given its name...) and so expands the \expandafter, which steps over the opening brace and expands the first token in the argument of \unexpanded once.

A: I would probably define a new style that sets both xticklabels and yticklabels at the same time. In the example below they're set to the same thing, and the list of labels is set as a default value for the key. If you want different lists, replace the two #1 with your lists, and remove the line with .default.

\documentclass[border=5mm]{standalone}

\usepackage{pgfplots}
\pgfplotsset{
  xyticklabels/.style={
    xticklabels={#1},
    yticklabels={#1}
  },
  xyticklabels/.default={A,B,C} % set the default value for #1
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
enlargelimits=false,
xtick=data,
ytick=data,
xyticklabels  % <--  no value passed to the key, so the default A,B,C is used
]
\addplot [
matrix plot,
mesh/cols=3,
point meta=explicit]
table [meta=C] {
x y C
0 0 0
1 0 1
2 0 2
0 1 3
1 1 4
2 1 5
0 2 6
1 2 7
2 2 8
};
\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
\begin{axis}[
enlargelimits=false,
xtick=data,
ytick=data,
xyticklabels={D,E,F}  % <-- a value passed to the key, so D,E,F is used instead
]
\addplot [
matrix plot,
mesh/cols=3,
point meta=explicit]
table [meta=C] {
x y C
0 0 0
1 0 1
2 0 2
0 1 3
1 1 4
2 1 5
0 2 6
1 2 7
2 2 8
};
\end{axis}
\end{tikzpicture}
\end{document}

A: The above answers can be combined to have a simpler solution with just one new style.
\documentclass{standalone}

\usepackage{pgfplots}
\pgfplotsset{
     xyticklabels/.code={
        \expanded{
              \noexpand\pgfkeysalso{
                xticklabels={\unexpanded\expandafter{#1}},
                yticklabels={\unexpanded\expandafter{#1}}
              }
        }
    }
}

\begin{document}

\def\ticklabels{A, B, C}

\begin{tikzpicture}
\begin{axis}[
enlargelimits=false,
xtick=data,
ytick=data,
xyticklabels={\ticklabels}]
\addplot [
matrix plot,
mesh/cols=3,
point meta=explicit]
table [meta=C] {
x y C
0 0 0
1 0 1
2 0 2
0 1 3
1 1 4
2 1 5
0 2 6
1 2 7
2 2 8
};
\end{axis}
\end{tikzpicture}

\end{document}

A: You can use xticklabels from table to use a table or a file.
\documentclass[border=1cm]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\pgfplotstableread{
ticks
A
B
C
}\loadedtable
\begin{axis}[
enlargelimits=false,
xtick=data,
ytick=data,
xticklabels from table={\loadedtable}{ticks},
yticklabels from table={\loadedtable}{ticks},
]
\addplot [
matrix plot,
mesh/cols=3,
point meta=explicit]
table [meta=C] {
x y C
0 0 0
1 0 1
2 0 2
0 1 3
1 1 4
2 1 5
0 2 6
1 2 7
2 2 8
};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: problem with UnboundLocalError: local variable referenced before assignment So I'm testing my knowledge on webscraping by writing this little script (I know some things are redundant, it's just me playing around with things):
def programstart():
    import re
    from selenium import webdriver
    from bs4 import BeautifulSoup

    ff=webdriver.Firefox()
    ff.get('https://www.ozbargain.com.au/deals')

    linkpattern = r'https://www.ozbargain.com.au/node/.*'

    donotpassthislink = 'https://www.ozbargain.com.au/node/415763'

    #list of found lnks
    titlelist = []

    #loop to find links
    while True:
        soup = BeautifulSoup(ff.page_source)
        raw_links = soup.find_all(name='a', href=re.compile(linkpattern))
        for links in raw_links:
            titles = ff.find_element_by_xpath("//h2[@class='title']").text
            extract = links
            if donotpassthislink == extract:
                break
            else:
                pass
            titlelist.append(titles)
        # Load next page
        if donotpassthislink == extract:     # stop loop at first movie link from last time.
            break
        else:
            ff.get(ff.find_element_by_xpath("//a[@class='pager-next active']").get_attribute('href'))

programstart()

I get this error:
Traceback (most recent call last):
  File "F:/Dropbox/Funfile/ben.py", line 35, in <module>
    programstart()
  File "F:/Dropbox/Funfile/ben.py", line 29, in programstart
    if donotpassthislink == extract:     # stop loop at first movie link from last time.
UnboundLocalError: local variable 'extract' referenced before assignment

I find this weird since this loop was used in another script that works perfectly.
So I write a simplified script:
test = 'lets break this sentence up'

list = []

def func():
    while True:
        for i in test:
            extract = i
            print(extract)
            if extract == 'u':
                break
            else:
                pass
            list.append(extract)
        if extract == 'u':
            print('done')
            break

func()

And it executes without any issues.
What's going on?


text:
Q: How to run "hipster" pure Java program in Android Studio, specifically? I am going to develop indoor navigation app using Android studio using this "Hipster" library.Hipster provide several Algorithms for searching and shortest path calculations.in my case it is Dijkstra's shortest path algorithm.
in Hipster, They have mention, "This is pure Java library".
I use this library in Eclipse and it's working fine.
my question is,
I am newbie to Android and Android Studio i tried to implement this code in Android Studio as well but it seems not working. I used provided sample by the library authors.
and I used this Gradle dependency:
 implementation 'es.usc.citius.hipster:hipster-core:1.0.1'

Official Web - http://www.hipster4j.org/
Github       - https://github.com/citiususc/hipster
I used this example:
https://github.com/citiususc/hipster/blob/1.0.X/hipster-examples/src/main/java/es/usc/citius/hipster/examples/UndirectedGraphSearchExample.java
I put this line to show result on my android app instead to System.out.print.
  Toast.makeText(getApplicationContext(), Hipster.createDijkstra(p).search('L'),Toast.LENGTH_LONG).show();

but this line is highlighted and when i hover mouse pointer, Android Studio says
 Cannot resolve method 'makeText(android.content.Context, es.usc.citius.hipster.algorithm.Algorithm.SearchResult, int)

Here this is my MainActivity.java
 package com.example.ireshan.indoor_navigation;

 import android.content.Context;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.TextView;
 import android.widget.Toast;

 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;

 import es.usc.citius.hipster.algorithm.Hipster;
 import es.usc.citius.hipster.algorithm.Algorithm;
 import es.usc.citius.hipster.graph.GraphBuilder;
 import es.usc.citius.hipster.graph.GraphSearchProblem;
 import es.usc.citius.hipster.graph.HipsterDirectedGraph;
 import es.usc.citius.hipster.graph.HipsterGraph;
 import es.usc.citius.hipster.model.problem.SearchProblem;

 public class Find_Shortst_Path extends AppCompatActivity {
      Context context = getApplicationContext();
      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_find__shortst__path);
            TextView helloTextView = (TextView)findViewById(R.id.myTextView);

    HipsterGraph<String,Double> graph =
            GraphBuilder.<String,Double>create()
                    .connect("A").to("B").withEdge(2d)
                    .connect("A").to("C").withEdge(2d)
                    .connect("A").to("D").withEdge(2d)
                    .connect("B").to("E").withEdge(5d)
                    .connect("B").to("F").withEdge(10d)
                    .connect("B").to("G").withEdge(5d)
                    .connect("B").to("H").withEdge(10d)
                    .connect("C").to("I").withEdge(5d)
                    .connect("C").to("J").withEdge(10d)
                    .connect("C").to("K").withEdge(5d)
                    .connect("K").to("L").withEdge(5d)

                    .createUndirectedGraph();

    SearchProblem p = GraphSearchProblem
            .startingFrom("A")
            .in(graph)
            .takeCostsFromEdges()
            .build();

    //Toast.makeText(context, Hipster.createDijkstra(p).search('L').toString(),Toast.LENGTH_LONG).show();
    helloTextView.setText(String.valueOf(Hipster.createDijkstra(p).search('L')));

}
}

How can I solve this problem? I am going to find shortest path for shopping mall activities such as find some item and reach to it by using shortest path. If you know any other alternative way, it will help me.

A: I determined,
  Hipster.createDijkstra(p).search("L").getOptimalPaths();

output is a list when i use
 .getOptimalPaths();. // Dijkstra's algorithms out put as shortest path

My objective was get only optimal path not the whole output genarated by the
  Hipster.createDijkstra(p).search("L")

then i inserted that output to "List"
  List ab= Hipster.createDijkstra(p).search("L").getOptimalPaths();
  helloTextView.setText(ab.get(0).toString());

And i send the output to the TextViwe. It's working fine on Andoid
use this dependency
implementation 'es.usc.citius.hipster:hipster-core:1.0.1'


text:
Q: Dynamically choose a theme NET, I recently buy a book to start by myself and try to follow the exercises.
I was aware that you can apply a theme in the  tag of a web config file by just adding "theme" property, however the following exercise was to choose a theme from a dropdownlist which I couldn't  understand very well and is simply not working for me.
Here is the master page cs code (Book's code)
namespace WebApplication7
{
    public partial class SiteMaster : MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string selectedTheme = Page.Theme;
                HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
                if (preferredTheme != null)
                {
                    selectedTheme = preferredTheme.Value;
                }
                if (!string.IsNullOrEmpty(selectedTheme))
                {
                    ListItem item = ThemeList.Items.FindByValue(selectedTheme);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }

        }

        protected void Theme_SelectedIndexChanged(object sender, EventArgs e)
        {
            HttpCookie preferredTheme = new HttpCookie("PreferredTheme");
            preferredTheme.Expires = DateTime.Now.AddMonths(3);
            preferredTheme.Value = ThemeList.SelectedValue;
            Response.Cookies.Add(preferredTheme);
            Response.Redirect(Request.Url.ToString());
        }
    }
}

Here is the dropdownlist
<asp:DropDownList ID="ThemeList" runat="server" OnSelectedIndexChanged="Theme_SelectedIndexChanged" AutoPostBack="True">
                        <asp:ListItem Value="monochrome" >Monochrome</asp:ListItem>
                        <asp:ListItem Value="colors">Colors</asp:ListItem>
                    </asp:DropDownList>

This is an example of the book "Beginning ASP.NET 4.5.1: in C# and VB"
The book doesn't mention any missing step and to be honest I don't understand how the drop down list "indexchanged" is linked to the themes I created in the App_Themes folder. I am just assuming this is related to "Page.Theme".
Thanks in advance.

A: The book includes this code:

to set the theme.
I suspect you should read the entire chapter, you need to do all of it to make it work. You can also read the entire source code (to compare with yours).

A: Yes I had to create a new Asp.net folder, then App_Code folder, create a BasePage.cs folder, right click and set that file to compile, Copy and Paste the code missing in BasePage.cs.
After apply all the inheritance from Page to BasePage in all my aspx pages and done.
Thank you for your answer.


text:
Q: How to define basePath in Swagger 3.0 inside Wildfly I integrated Swagger-ui in my wildfly application.
The project is configured through maven with the following (relevant) dependencies:
    <dependency>
      <groupId>io.swagger.core.v3</groupId>
      <artifactId>swagger-jaxrs2</artifactId>
      <version>2.0.0</version>
    </dependency>
    <dependency>
      <groupId>io.swagger.core.v3</groupId>
      <artifactId>swagger-jaxrs2-servlet-initializer</artifactId>
      <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>swagger-ui</artifactId>
        <version>3.23.2</version>
    </dependency>

I also extracted the swagger-ui.html page from the webjar and customized the javascript to connect to my server as follow (see the url):
window.onload = function() {
  // Begin Swagger UI call region
  const ui = SwaggerUIBundle({
    url: "doc/openapi.json",
    dom_id: "#swagger-ui",
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })
  // End Swagger UI call region

  window.ui = ui
}

The swagger-ui is working well, it displays the list of my endpoints. But when I try to connect to my endpoints, it fails because the url used to connect does not contain the context path of my application (myApp here), it tries to connect with:
curl -X GET "http://localhost:8080/aop/hello/version" -H "accept: */*"

But it should be:
curl -X GET "http://localhost:8080/myApp/aop/hello/version" -H "accept: */*"

I found that the missing part is named the basePath but I did not find any solution to add it in my Wildfly application.
Update:
Following the documentation, it seems that the basePath comes from Swagger, the OpenApi uses a server.
Then I tried:
@ApplicationPath("/api")
public class ApplicationConfig extends Application
{
    public ApplicationConfig(@Context ServletConfig servletConfig) {
        // Swagger Configuration
        super();
        OpenAPI oas = new OpenAPI()
                .servers(Collections.singletonList(new Server().url("http://localhost:8080/my_app")));
        Info info = new Info()
                .title("Swagger");

        oas.info(info);
        SwaggerConfiguration oasConfig = new SwaggerConfiguration()
                .openAPI(oas)
                .prettyPrint(true);

        try {
            new JaxrsOpenApiContextBuilder<>()
                    .servletConfig(servletConfig)
                    .application(this)
                    .openApiConfiguration(oasConfig)
                    .buildContext(true);
        } catch (OpenApiConfigurationException e) {
            throw new ConfigurationException(e.getMessage(), e);
        }
    }
}

But it is still not taken into account.
Any lead?
Thanks :-)

A: Finally, I got it working, but not with the Java configuration which is not taken into account (seen in debug) but using a configuration file openapi.yaml in the classpath of the application.
The file looks like:
prettyPrint: true
cacheTTL: 0
openAPI:
  servers:
    - url: /my_app
  info:
    version: '1.0'
    title: Swagger application

With the server url now correctly handled.
But I am still curious to know what should be the right solution for a Java configuration.

A: Provided at Global Level it is working fine in java
@OpenAPIDefinition(servers = @Server(url="/my_app"))
@ApplicationPath("api")
public class ApplicationConfig extends Application {
}

A: I have faced the same problem and for some reason your solution with openapi.yaml did not work for me either.
Then I found that you can use the Server annotation with your service/resource class:
@Path("/myservice")
@Server(url="/my_app")
public interface MyService {
...
}


text:
Q: Re-deploy AWS CloudWatch Logs with serverless framework I deployed an AWS service using the serverless framework, which created and deployed all the resources automatically.
But later on I accidentally deleted the log group for this service, and no logs are beeing created anymore.
Is there a way to recreate / redeploy just the log-group resource, because serverless --remove & serverless --deploy would delete all existing resources and create new ones which would be bad in my case.
Any ideas?

A: Comment out the function in serverless.yml, deploy, uncomment the function and deploy again. As far as I can tell, serverless tries to remove the log group when you "remove" the function and then create it when you "add" the function.
Also, afaict, you have to actually deploy. You can't just save, you have to do the full stack update for serverless to notice.

A: sls deploy -f <function name>

Or you can manually just create the log groups for now


text:
Q: Listing the object inside the listed array of json I'm trying to list my JSON array from a file using jquery $.getJSON
Here is what I have for now:
(document).ready(function() {
    var theAPI = "test.js";

    $("button").click(function() {
        $.getJSON(theAPI, function(result) {
            $.each(result, function(i, field) {
                $("div").append(i + " - - - " + field + "
");
            });
        });
    });
});

and my output is:
kind - - - mykind
nextPageToken - - - CAUQAA
pageInfo - - - [object Object]
How do I append this [object Object]?
here is the test.js:
{
 "kind": "mykind",
 "nextPageToken": "CAUQAA",

 "pageInfo": {

  "totalResults": 1691,
  "resultsPerPage": 5
 }

}

UPDATE
JSON.stringify() is not an answer, I want to list every json object.

A: If there is only one level of nesting you can do
$("button").click(function(){
  $.getJSON(theAPI, function(result){
    $.each(result, function(key, value){
      if (key=="pageInfo") { // or typeof value=="object"
        $.each(value, function(pKey, pValue){
          $("div").append(pKey+ " - - - " +pValue + "
");
        });
      }
      else {
          $("div").append(key+ " - - - " +value + "
");
      }
    });

  });
});

otherwise you will need to recourse
Example:

var result = {

  "kind": "mykind",

  "lineInfo": {
    "totalLineResults": 691,
    "resultsPerLine": 9
  },

  "nextPageToken": "CAUQAA",

  "pageInfo": {
    "totalResults": 1691,
    "resultsPerPage": 5
  }
}

$.each(result, function(key, value) {
  if (typeof value=="object") {
    $("div").append(key + "
");
    $.each(value, function(pKey, pValue) {
      $("div").append("
"+pKey + " - - - " + pValue + "
");
    });
    $("div").append("
");
  } else {
    $("div").append(key + " - - - " + value + "
");
  }
});
ul { display:inline }

A: I believe a generic solution to this would be great because sometime in the future your JSON structure might change and become more complex.
Hence, I have attempted to come up with a generic solution here
var result = {
    "key-1": "value-1",
    "key-2": "value-2",
    "key-3": {
        "key-31": "value-31",
        "key-32": "value-32",
        "key-33": ["value-331", "value-332", "value-333"],
        "key-34": {
            "key-341": 341,
            "key-342": 342,
            "key-343": [3431],
            "key-344": true,
            "key-345": false,
            "key-346": {
                "key-3461": [3461, "value-3462", true, false]
            }
        }
    },
    "key-4": "value-4",
    "key-5": ["value-51", "value-52"],
    "key-6": {
        "key-61": "value-61",
        "key-62": ["value-621", "value-622"],
        "key-63": {
            "key-631": "value-631",
            "key-632": true,
            "key-633": false
        }
    },
    "key-7": function() {
        console.log("I am a function...");
    }
};

var tabCount = 0,
    typeMap = {
        "STRING": "[object String]",
        "NUMBER": "[object Number]",
        "BOOLEAN": "[object Boolean]",
        "ARRAY": "[object Array]",
        "OBJECT": "[object Object]",
        "FUNCTION": "[object Function]"
    },
    getTypeOfObject = function(o) {
        return Object.prototype.toString.call(o);
    },
    getTabSpacing = function(numberOfTabs) {
        var tab = "    ",
            result = "";
        for(var index = 0; index < numberOfTabs; index++) {
            result += tab;
        }
        return result;
    },
    iterator = function(obj, tab) {
        $.each(obj, function(key, value) {
            if(getTypeOfObject(value) === typeMap.OBJECT) {
                $("div").append(getTabSpacing(tab) + key + ":
");
                iterator(value, ++tabCount);
                --tabCount;
            }
            else {
                $("div").append(getTabSpacing(tab) + key + ": " + value + "
");
            }
        });
    };

iterator(result, tabCount);

I am not sure if this is what you were looking for.

A: You can stringify it like this (here is the jsfiddle):
$(document).ready(function(){
var theAPI = "test.js";
$("button").click(function(){
    $.getJSON(theAPI, function(result){
        $.each(result, function(i, field){
            $("div").append(i+ " - - - " +JSON.stringify(field)+ "
");
        });
    });
});
});

A: User JSON.stringify()
$("button").click(function(){
    $.getJSON(theAPI, function(result){
        $.each(result, function(i, field){
            $("div").append(i+ " - - - " +JSON.stringify(field) + "
");
        });
    });
});


text:
Q: program get EXC_BAD_ACCESS compilation is ok, but the program is stopped in this function. I have version for win and it function fine, but when i make version for Mac, it get this exception :(

 int Reconstruct(int rez)
{ //here is program stopped!!!!

static SDL_Surface *projekce;
 static SDL_Surface *sc;
 static SDL_Surface *rek;

projekce = SDL_CreateRGBSurface(SDL_SWSURFACE,240,240, 32,0,0,0,0);
 sc = SDL_CreateRGBSurface(SDL_SWSURFACE, 400, 400, 32, 0, 0, 0, 0);
 // Create two arrays of unsigned bytes (chars). 4 bytes per pixel (RGBA)
 unsigned char *pixels[400 * 400 * 4];
 unsigned char *pixelsbuf[400 * 400 * 4];

glGenTextures(1, &gl_texture);// generate one texture
 glBindTexture(GL_TEXTURE_2D, gl_texture);// Set the texture

// Set the texture filters
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

int angle = 0;
 int snimek = 0;
 int i, j, k, l;// promene pro cykly

for(i=0;i<88;i++)
 {

char nazev[25] = "OUT/snimek";
  itoa(snimek, CisloSnimku);
  strcat(nazev,CisloSnimku);
  strcat(nazev,".bmp");
  rek = IMG_Load(nazev);
  snimek++;

SDL_LockSurface(rek);
  SDL_LockSurface(projekce);

//zkopiruj radek do snimku = vytvor snimek pro rotaci

for(j=0;j<240;j++)
  {
   if(j == 0) PixV1 = 0;
   else
   {
    PixV1 = getpixel(rek,j-1,rez);
   }
   if(j == 239) PixV3 = 0;
   else
   {
    PixV3 = getpixel(rek,j+1,rez);
   }
   PixV2 = getpixel(rek,j,rez);

SDL_GetRGB(PixV1,rek->format, &R, &G, &B);
   //Gs1 = ((R * 21) + (G * 61) + (B * 174)) / 256;  //preved do grayscale pro blue
   Gs1 = ((R * 11) + (G * 174) + (B * 71)) / 256;  //preved do grayscale pro green
   Gs1 = 255 - Gs1;                        //invert
   if (Gs1 < 50) Gs1 = 1;
   SDL_GetRGB(PixV2,rek->format, &R, &G, &B);
   //Gs2 = ((R * 21) + (G * 61) + (B * 174)) / 256;  //preved do grayscale pro blue
   Gs2 = ((R * 11) + (G * 174) + (B * 71)) / 256;  //preved do grayscale pro green
   Gs2 = 255 - Gs2;                                //invert
   if (Gs2 < 50) Gs2 = 1;
   SDL_GetRGB(PixV3,rek->format, &R, &G, &B);
   //Gs3 = ((R * 21) + (G * 61) + (B * 174)) / 256;  //preved do grayscale pro blue
   Gs3 = ((R * 11) + (G * 174) + (B * 71)) / 256;  //preved do grayscale pro green
   Gs3 = 255 - Gs3;                                //invert
   if (Gs3 < 50) Gs3 = 1;
   //Gs = (Gs1*(1)) + (Gs2*(-4)) + (Gs3*(1)); //convolution GOOD
   //Gs = (Gs1*(-1)) + (Gs2*(3)) + (Gs3*(-1)); //convolution

for(k=0;k<240;k++)
   {
    DrawPixel(projekce, j, k, Gs2, Gs2, Gs2);
   }
  }

SDL_UnlockSurface(rek);
  SDL_UnlockSurface(projekce);

gluBuild2DMipmaps(GL_TEXTURE_2D, 3, projekce->w, projekce->h, GL_RGBA, GL_UNSIGNED_BYTE, projekce->pixels);
  angle += 360/88;
  Atlantis_Display(angle);

////////////////////////////////////////////////////////////////////////////

glReadPixels(0, 0, 400, 400, GL_RGBA, GL_UNSIGNED_BYTE, pixelsbuf);

////////////////////////////////////////////////////////////////////////////

SDL_LockSurface(sc);
  SDL_LockSurface(final);

G1 = 0;
  G = 0;
  R = 0;
  B = 0;

for(l=0;l<400;l++)
  {
   memcpy(pixels+(400-l-1)*400*4, pixelsbuf+l*400*4, 400*4);
   sc->pixels = pixels;

for(j=0;j<400;j++)
   {

            PixelValue = getpixel(sc, j, l);
            SDL_GetRGB(PixelValue, sc->format, &R, &G, &B);
            PixelValue = getpixel(final, j, l);
            SDL_GetRGB(PixelValue, final->format, &R1, &G1, &B1);

            //pom = ((R/2)+(B/2)+(G*2));

            G1 += (G/90);

            DrawPixel(final, j, l, G1, G1, G1);

}
  }
SDL_UnlockSurface(sc);
}
char fin[25] = "FIN/final";
 itoa(rez, CisloSnimku);
 strcat(fin,CisloSnimku);
 strcat(fin,".bmp");
 SDL_SaveBMP(final, fin);
 SDL_UnlockSurface(final);
SDL_FreeSurface(final);
 SDL_FreeSurface(sc);
 SDL_FreeSurface(projekce);
 SDL_FreeSurface(rek);
 SDL_Quit();
 return 0;
}

A: The following code is highly suspect:
 unsigned char *pixels[400 * 400 * 4];
 unsigned char *pixelsbuf[400 * 400 * 4];

For one thing, those should probably be char and not char * but the bigger issue is that you are allocating enormous data structures on the stack (2.5 MB for each array, as written).  I am guessing that you are exceeding your available stack.  They should instead be dynamically allocated (and sized correctly).


text:
Q: Selecting specific 5 row in a list of XML I have a list of 10 items as shown in the XML below.
<books_standing bestsellers="My Book" total="10">
  <book book_id="4" book_name="Book 4" copy_sold="41" position="1"/>
  <book book_id="14" book_name="Book 14" copy_sold="38" position="2"/>
  <book book_id="23" book_name="Book 23" copy_sold="33" position="3"/>
  <book book_id="1" book_name="Book 1" copy_sold="30" position="4"/>
  <book book_id="4" book_name="Book 4" copy_sold="28" position="5"/>
  <book book_id="25" book_name="Book 25" copy_sold="27" position="6"/>
  <book book_id="13" book_name="Book 13" copy_sold="24" position="7"/>
  <book book_id="7" book_name="My Book" copy_sold="20" position="8"/>
  <book book_id="8" book_name="Book 8" copy_sold="19" position="9"/>
  <book book_id="2" book_name="Book 2" copy_sold="18" position="10"/>
</book_standing>

What I want to do is to select a specific row, and then show 2 rows on top and 2 rows below.  I want to show the the book name title "My Book" which is currently in 8 position.  What I want to show "My Book" in between of 2 data above and below.  My out example is Position, Book Title & Copy sold.
6  Book 25 27
7  Book 13 24
**8  My Book 20**
9  Book 8 19
10 Book 2 18

I'm able to pull the data, but not sure how to focus on that particular book that I need.
class BookStanding
  {
    public int BookId { get; set; }
    public string BookName { get; set; }
    public string Position { get; set; }
    public string CopySold { get; set; }
  }

System.Xml.Linq.XDocument _xdoc = System.Xml.Linq.XDocument.Parse(responseAsString);
var bookData = from books in _xdoc.Descendants("book")
            select new
               {
                  book_id = books.Attribute("book_id").Value,
                  book_name = books.Attribute("book_name").Value,
                  position = books.Attribute("position").Value,
                  copy_sold = books.Attribute("copy_sold").Value
                };

            ObservableCollection<BookStanding> MyBookStanding = new ObservableCollection<BookStanding>();

            int bookIdx = 0;
            foreach (var books in bookData.Take(10))
            {
                BookStanding mBookStanding = new BookStanding();

                mBookStanding.BookId = Convert.ToInt32(books.book_id);
                mBookStanding.BookName = books.book_name;
                mBookStanding.Position = Convert.ToInt32(books.position);
                mBookStanding.CopySold = Convert.ToInt32(books.won);

                MyBookStanding.Add(mBookStanding);

                bookIdx++;
            }
            BooksListBox.DataContext = MyBookStanding;

            BooksGrid.Visibility = System.Windows.Visibility.Visible;

Thanks!
Credits to @Nir Smadar for helping me out on this one.  The solution given by him was after the loop put these codes in.
var BookPosition = MyBookStanding.Single(b => b.Book_Name == "My Book").Position;
var selectedBooks = MyBookStanding.Where(b => b.Position <= BookPosition + 2 && b.Position >= BookPosition - 2);

BooksListBox.ItemsSource = MyBookStanding;
BooksGrid.Visibility = System.Windows.Visibility.Visible;

A: After loading the items you end up with a collection of books 'MyBookStanding'.
Now you need to find the position of the selected book:
var bookPosition = MyBookStanding.Single(b => b. book_name == whateverBookName).position;
And finally the 5 books:
var selectedBooks = MyBookStanding.Where(b => b.position <= bookPosition + 2 || b.position >= bookposition - 2);
Sorry for not formatting my answer- I'm typing from my cell..


text:
Q: Desktop application loopback connections - reliable and safe? I am writing a Desktop application for professional users using C++.  My current design relies on a third-party C++ component whose API is based on TCP/IP.  To integrate this component might involve modifying it to replace the networking code with a conventional C++ API.
It would be a lot easier if I could leave the component unmodified and communicate with it in the way it expects - over the network.  To do so I would need to run the component as a server listening on some high port for loopback connections.
I have two concerns with this loopback approach.  Can anyone allay or confirm my fears?
Reliability and performance
The loopback connection might fail, be blocked or intercepted by antivirus software.  Something like this: Loopback connections working in user's context but not working from Local System account
Security
I am not too concerned about someone sniffing my loopback packets but I don't want my server to become a security risk itself.  Is it risky to have a process listening on some high port?
Do many desktop applications operate like this?
I am initially developing on Windows but may move to Mac and Linux in future so this question applies to all the common desktop OSs.

A: Reliability: if component itself is reliable then there's no problem with listening to loopback interface. If component is not reliable then it's better to talk with it via loopback interface instead of calling it's functions directly. You can easily handle disconnects and restart component to continue working, but if you would link to the component and component will fail - your app will fail too.
Performance: There's some performance penalty. Not really big with current CPU power. It should be acceptable for most applications.
Security: component should bind to localhost address to avoid security issues. But local 3-d party software (virus) software with sufficient access level can intercept or even modify communication streams. Same for any other method of communication.
Loopback connections are widly used (java uses it for intercommunication, named used it for master service control, etc.)


text:
Q: Mathematica Newmark Optimization Here is my Mathematica code which implements the Newmark method to solve an equation of motion. The variable ag contains the acceleration values from an earthquake record. Is it possible to optimize this piece of code? It takes a long time to calculate a spectral response, which runs this code about 500 times, taking around 20 minutes.
The "Data.txt" can be found here or here.
Parallelize[Axel = Import["https://pastebin.com/raw/t7itJ7Q3"]];
Data = Array[{Axel[[#]][[1]], Axel[[#]][[2]]} &, Length[Axel] - 1, 2];
ag = 10 Data[[All, 2]];

M[y_] := N[
  Parallelize[
   u = fs =
     kt = kthat = rhat = phat = v = a = ConstantArray[1., Length[ag]];
   k = 1.;
   m = 1.;
   p = -m ag;
   c = 0.1;
   fy = y;
   gamma = 1/2.; beta = 1/6.;
   v[[1]] = 0.;
   fs[[1]] = 0.;
   u[[1]] = 0.;
   a[[1]] = (p[[1]] - c v[[1]] - fs[[1]])/m;
   dt = 0.01;
   a1 = 1./(beta dt^2) m + gamma/(beta dt) c;
   a2 = 1./(beta dt) m + (gamma/beta - 1) c;
   a3 = (1/(2 beta) - 1.) m + dt (gamma/(2 beta) - 1) c;

   For[i = 1, i < Length[ag], i++,
    u[[i + 1]] = u[[i]];
    fs[[i + 1]] = fs[[i]];
    phat[[i + 1]] = p[[i + 1]] + a1 u[[i]] + a2 v[[i]] + a3 a[[i]];
    While[
     Abs[rhat[[i + 1]] =
        phat[[i + 1]] - fs[[i + 1]] - a1 u[[i + 1]]] > 0.000001,
     u[[i + 1]] = u[[i + 1]] + rhat[[i + 1]]/(k + a1);
     If[
      (fz = fs[[i]] + k (u[[i + 1]] - u[[i]])) >= 0,
      fs[[i + 1]] = Min[fz, fy];,
      fs[[i + 1]] = Max[fz, -fy];
      ];
     ];
    v[[i + 1]] =
     gamma/(beta dt) (u[[i + 1]] - u[[i]]) + (1. - gamma/
         beta) v[[i]] + dt (1 - gamma/(2 beta)) a[[i]];
    a[[i + 1]] =
     1/(beta dt^2) (u[[i + 1]] - u[[i]]) -
      1/(beta dt) v[[i]] - (1/(2 beta) - 1.) a[[i]];

    ];
   uy = fy/k;
   um = Max[Abs[u]];
   miu = Max[um/uy, 1]
   ]]

Here's a single run which takes quarter of a second, but implementing the function into a solver algorithm runs this around thousand times.
In[778]:= M[0.04343505938959662`] // AbsoluteTiming

Out[778]= {0.259419, 5.97369}

single solver run:
In[734]:= y = 6;
x = 1/y;
While[Abs[az = y - M[x]] > 0.05,
   x = (1 - 0.1 Sign[az]) x]; // AbsoluteTiming
M[x]

Out[736]= {7.78515, Null}

Out[737]= 5.97369

A: I have tried compiling my code in C, as well as storing the Length function into a variable. It has increased the speed by a factor of 100.
cf = Compile[{{x, _Real}}, Block[{u, fs, kt, kthat, rhat, phat, v, a,
    dt, k, c, m, gamma, beta, fy, a1, a2, a3, p, um, uy, i, fz, l},
   l = Length[ag];
   u = fs = kt = kthat = rhat = phat = v = a = ConstantArray[0., l];
   k = 1.;
   m = 1.;
   p = -m ag;
   c = 0.1;
   fy = x;
   gamma = 1/2.; beta = 1/6.;
   v[[1]] = 0.;
   fs[[1]] = 0.;
   u[[1]] = 0.;
   a[[1]] = (p[[1]] - c v[[1]] - fs[[1]])/m;
   dt = 0.01;
   a1 = 1./(beta dt^2) m + gamma/(beta dt) c;
   a2 = 1./(beta dt) m + (gamma/beta - 1) c;
   a3 = (1/(2 beta) - 1.) m + dt (gamma/(2 beta) - 1) c;

   For[i = 1, i < l, i++,
    u[[i + 1]] = u[[i]];
    fs[[i + 1]] = fs[[i]];
    phat[[i + 1]] = p[[i + 1]] + a1 u[[i]] + a2 v[[i]] + a3 a[[i]];
    While[
     Abs[rhat[[i + 1]] =
        phat[[i + 1]] - fs[[i + 1]] - a1 u[[i + 1]]] > 0.000001,
     u[[i + 1]] = u[[i + 1]] + rhat[[i + 1]]/(k + a1);
     If[
      (fz = fs[[i]] + k (u[[i + 1]] - u[[i]])) >= 0,
      fs[[i + 1]] = Min[fz, fy];,
      fs[[i + 1]] = Max[fz, -fy];
      ];
     ];
    v[[i + 1]] =
     gamma/(beta dt) (u[[i + 1]] - u[[i]]) + (1. - gamma/
         beta) v[[i]] + dt (1 - gamma/(2 beta)) a[[i]];
    a[[i + 1]] =
     1/(beta dt^2) (u[[i + 1]] - u[[i]]) -
      1/(beta dt) v[[i]] - (1/(2 beta) - 1.) a[[i]];

    ];
   uy = fy/k;
   um = Max[Abs[u]];
   miu = Max[um/uy, 1]
   ], CompilationTarget -> "C", Parallelization -> True]

Running times for the C-compiled version:
In[870]:= cf[0.0434] // AbsoluteTiming

Out[870]= {0.00213977, 5.9806}

In[887]:= y = 6;
x = 1/y;
While[Abs[az = y - cf[x]] > 0.05,x = (1 - 0.1 Sign[az]) x]; // AbsoluteTiming
cf[x]

Out[889]= {0.0474829, Null}

Out[890]= 5.97369

I'd appreciate it if you could point out any other possible optimizations ;)


text:
Q: Python - Bounding Box/Circle Library Python - Bounding Box/circle and string issues
I have a couple of issues I am trying to resolve in regards to some Python V2.7.x scripts I run under some Debian based units...
1) GIS - Bounding Box and Circles
I am trying to find a library that can do this
Given lat/long pair, point A determine if point A is WITHIN the bounding box of a lat/long set Point 1, Point 2, Point 3, Point 4.
Given lat/long pair, point A, lat/long point B and radius from point b in miles, determine if point A is WITHIN the bounding circle of Point B
Is there some library that does this?
The GeoPy lib I have to do the geocoding doesn't offer these choices. Some of the other libs seem to be related to ArcGIS shape files etc... which I am not using, and don't have any future need for them either.. certainly there is something that has some of this without the kitchen sink as well.
I've seen several things that take a Point A and give a bounding box...like:
https://github.com/jfein/PyGeoTools/blob/master/geolocation.py
Not what I am after... I want to pass Point a, with the box cords (P1-4) and it tells me if Point A is in that box.
Same for the circle. Point A, Point B and radius in MILES from Point B, and the function returns if Point A is WITHIN that bounding cirlce.
Anything that can do these???

A: You may be better of asking your question at http://gis.stackexchange.com.
Anyway: checking whether a point is within a bounding box is dead easy: just check that both coordinates fall within the range of the bounding box. No need to use a library here. (check whether
lat_min < lat_oint <lat_max and lat_min<lat_point <lat_max).
For checking the radius, you can use the vincenty function of geopy: just calculate the distance in miles between both points and check if the distance is smaller than your radius.
>>> from geopy.distance import vincenty
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(vincenty(newport_ri, cleveland_oh).miles)
538.3904451566326


text:
Q: How to pass array into anonymous function? I am currently using anonymous functions in Powershell and I noticed there is a weird casting problem when going from System.ValueType to System.Object.
Take the following example:
$f = {
    param($InputArray)
    Write-Host "`$Arr Type During Call:" ($InputArray.GetType().FullName)
    Write-Host "`$Arr Contents During Call:" $InputArray
}

[object[]]$Arr = [object[]]@($true, $false)

Write-Host "`$Arr Type Before Call:" ($Arr.GetType().FullName)
Write-Host "`$Arr Contents Before Call:" $Arr "`n"

$f.Invoke($Arr)

The following example will output the following:

$Arr Type Before Call: System.Object[]
    $Arr Contents Before Call: True False
$Arr Type During Call: System.Boolean
    $Arr Contents During Call: True

It looks like Powershell casted my variable $Arr into the type System.Boolean. If I force the parameter to be of type object[], a new problem is introduced:
$f = {
    param([object[]]$InputArray)
    Write-Host "`$Arr Type During Call:" ($InputArray.GetType().FullName)
    Write-Host "`$Arr Contents During Call:" $InputArray
}

[object[]]$Arr = [object[]]@($true, $false)

Write-Host "`$Arr Type Before Call:" ($Arr.GetType().FullName)
Write-Host "`$Arr Contents Before Call:" $Arr "`n"

$f.Invoke($Arr)

The new change produces the following output:

$Arr Type Before Call: System.Object[]
    $Arr Contents Before Call: True False
$Arr Type During Call: System.Object[]
    $Arr Contents During Call: True

Powershell is only providing the anonymous function one element of my array. What is going on here?

*

*Why is Powershell casting to a boolean when I clearly am giving it an object array?

*Even when I force the input parameter's type of the anonymous function, why does Powershell not provide the entire array?

A: Use:
$f.Invoke((, $Arr))

or, more PowerShell-idiomatically:
& $f $Arr

As for what you tried:

$f.Invoke($Arr)

passes the elements of array $Arr as individual arguments.
Since your script block $f defines only one parameter, only the first element of $Arr is bound to that parameter, $InputArray.
(, ($Arr)) works around that problem by wrapping the array in an auxiliary single-element array, which $f.Invoke() then unwraps and therefore passes $Arr as a single argument.
That said, using object methods in PowerShell is generally an awkward experience, given that the invocation syntax causes confusion with PowerShell's command syntax.
Often, it's possible to stay in the realm of PowerShell's commands and operators.
Specifically, the PowerShell-idiomatic way to invoke script blocks ({ ... }) is to use &, the call operator (to execute the script block in a child scope; alternatively ., the dot-sourcing operator, (typically) executes directly in the caller's scope).
& (and .) use command syntax (argument parsing mode), where arguments are passed without parentheses and separated with whitespace rather than , - see this answer for more information.
Therefore, & $f $Arr interprets $Arr as the 1st and only argument to be passed as a whole to the script block.


text:
Q: Inject Environment variables into a Jenkins build process with a shell script The starting situation
I have a Jenkins build Project where I'm doing almost everything by calling my build script (./jenkins.sh). I'm building a Cordova Project, which is dependent on certain versions of Node and Xcode. I'm running the builds on Macs with the latest MacOS Sierra.
So far I'm setting the environment variables in the Jenkins Build with the EnvInject Plugin(https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin):

The Goal
I want to have the environment variables also set by the build script instead of in the Jenkins Build. This way the environment variables are also in version control and I don't have to touch the Jenkins Build itself.
Basically I need to rebuild the logic of the EnvInject Plugin with bash.
What I've tried #1
Within my jenkins.sh build script I've set the environment variables with export
jenkins.sh:
#!/bin/bash -ve

nodeVersion=7.7.8
xcodeVersion=8.3.1
androidSDKVersion=21.1.2

export DEVELOPER_DIR=/Applications/Xcode_${xcodeVersion}.app/Contents/Developer
export ANDROID_HOME=/Applications/adt/sdk
export PATH=/usr/local/Cellar/node/${nodeVersion}/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/local/bin:/usr/local/bin:/Applications/adt/sdk/tools:/usr/local/bin/:/Applications/adt/sdk/build-tools/${androidSDKVersion}:$PATH

# print info
echo ""
echo "Building with environment Variables"
echo ""
echo "  DEVELOPER_DIR:  $DEVELOPER_DIR"
echo "  ANDROID_HOME:   $ANDROID_HOME"
echo "  PATH:           $PATH"
echo "  node:           $(node -v)"
echo ""

This yields:
Building with environment Variables

  DEVELOPER_DIR:  /Applications/Xcode_8.3.1.app/Contents/Developer
  ANDROID_HOME:   /Applications/adt/sdk
  PATH:           /usr/local/Cellar/node/7.7.8/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/local/bin:/usr/local/bin:/Applications/adt/sdk/tools:/usr/local/bin/:/Applications/adt/sdk/build-tools/21.1.2:/Users/mles/.fastlane/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin
node -v
  node:           v0.10.48

PATH, DEVELOPER_DIR, ANDROID_HOME seems to be set correctly, however it is still using the system version of node v0.10.48 instead of v7.7.8 as set in PATH.
What I've tried #2
I've sourced the variables:
jenkins.sh:
#!/bin/bash -ve

source config.sh

# print info
echo ""
echo "Building with environment Variables"
echo ""
echo "  DEVELOPER_DIR:  $DEVELOPER_DIR"
echo "  ANDROID_HOME:   $ANDROID_HOME"
echo "  PATH:           $PATH"
echo "  node:           $(node -v)"
echo ""

config.sh
#!/bin/bash -ve
# environment variables
nodeVersion=7.7.8
xcodeVersion=8.3.1
androidSDKVersion=21.1.2

export DEVELOPER_DIR=/Applications/Xcode_${xcodeVersion}.app/Contents/Developer
export ANDROID_HOME=/Applications/adt/sdk
export PATH=/usr/local/Cellar/node/${nodeVersion}/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/local/bin:/usr/local/bin:/Applications/adt/sdk/tools:/usr/local/bin/:/Applications/adt/sdk/build-tools/${androidSDKVersion}:$PATH

The result was the same as in What I've tried #1: Still using system node v0.10.48 instead of node v7.7.8
The question
How can I set the PATH, DEVELOPER_DIR, ANDROID_HOME environment variables properly to be used only within the build script?
@tripleee
Above I'm determining node by calling node: $(node -v). In the build script I'm running gulp which triggers Ionic / Apache Cordova. Do the brackets around node -v start a subshell which has it's own environment variables?
@Jacob
We have used nvm before, but we want to have less dependencies. Using nvm requires to install nvm on all build machines. We have a standard of installing node with brew. That's why I'm using /usr/local/Cellar/node/${nodeVersion} as path to node.
@Christopher Stobie
env:
jenkins@jenkins:~$ env
MANPATH=/Users/jenkins/.nvm/versions/node/v6.4.0/share/man:/usr/local/share/man:/usr/share/man:/Users/jenkins/.rvm/man:/Applications/Xcode_7.2.app/Contents/Developer/usr/share/man:/Applications/Xcode_7.2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/share/man
rvm_bin_path=/Users/jenkins/.rvm/bin
NVM_CD_FLAGS=
TERM=xterm-256color
SHELL=/bin/bash
TMPDIR=/var/folders/t0/h77w7t2s1fx5mdnsp8b5s6y00000gn/T/
SSH_CLIENT=**.**.*.** ***** **
NVM_PATH=/Users/jenkins/.nvm/versions/node/v6.4.0/lib/node
SSH_TTY=/dev/ttys000
LC_ALL=en_US.UTF-8
NVM_DIR=/Users/jenkins/.nvm
rvm_stored_umask=0022
USER=jenkins
_system_type=Darwin
rvm_path=/Users/jenkins/.rvm
rvm_prefix=/Users/jenkins
MAIL=/var/mail/jenkins
PATH=/Users/jenkins/.nvm/versions/node/v6.4.0/bin:/Users/jenkins/.fastlane/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/jenkins/.rvm/bin:/Users/jenkins/tools/oclint/bin:/Applications/adt/sdk/tools:/Applications/adt/sdk/platform-tools:/Applications/adt/sdk/build-tools/android-4.4:/Users/jenkins/.rvm/bin
NVM_NODEJS_ORG_MIRROR=https://nodejs.org/dist
rvm_loaded_flag=1
PWD=/Users/jenkins
LANG=en_US.UTF-8
_system_arch=x86_64
_system_version=10.12
rvm_version=1.26.10 (latest)
SHLVL=1
HOME=/Users/jenkins
LS_OPTIONS=--human --color=always
LOGNAME=jenkins
SSH_CONNECTION=**.**.*.** ***** **.**.*.** **
NVM_BIN=/Users/jenkins/.nvm/versions/node/v6.4.0/bin
NVM_IOJS_ORG_MIRROR=https://iojs.org/dist
rvm_user_install_flag=1
_system_name=OSX
_=/usr/bin/env

alias:
jenkins@jenkins:~$ alias
alias l='ls -lAh'
alias rvm-restart='rvm_reload_flag=1 source '\''/Users/jenkins/.rvm/scripts/rvm'\'''

A: This doesnt look like an environment variable issue. It looks like a permissions issue. The user executing the script is either:

*

*not able to read the /usr/local/Cellar/node/7.7.8/bin directory, or

*not able to read the node executable from that directory, or

*not able to execute the node executable from that directory

In order to test, become that user on the machine and execute the node command against the full path:
/usr/local/Cellar/node/7.7.8/bin/node -v

or, if you need to, change the script to avoid using PATH lookups (Im suggesting this for diagnosis only, not as a solution):
echo "  node:           $(/usr/local/Cellar/node/7.7.8/bin/node -v)"

If you are still at a loss, try this line:
echo "  node:           $(sh -c 'echo $PATH'; which node)"


text:
Q: Can type classes at the type level be simulated with higher-rank types? I have a pluggable runtime type checker that supports parametric but no ad-hoc polymorphism, because there is no compiling step and type information are erased as soon as the type checker is deactivated.
Now I recently came up with the idea to reify type classes with an explicit type, so that I gain some of their advantages without having to fully incorporate the underlying mechanism into the type checker:
data Functor f = Functor {fmap :: forall a b. (a -> b) -> f a -> f b}

mapList = Functor map
fmap (mapList) (+1) [1,2,3]

It seems as if type classes can be simulated with rank-2 types, at least at the type level, since, of course, there is still no static dispatching.
Is my assumption right and since I am a Haskell rookie, does my explicit functor type involves any advantages over just using map directly?

A: The idea of representing a class by a data type is basically a dictionary, which is in fact pretty much how GHC implements type classes anyway: a constrained-polymorphic function/value
f :: Functor f => Y

is at runtime represented by a function
_f_ :: FunctorDict f -> Y

where FunctorDict is essentially your Functor Rank2-ADT (or GADT).
The main thing that's special about actual type classes is that these dictionaries have the singleton property: for every type constructor F, there can only ever be exactly one instance Functor F, whereas you can in principle have multiple different FunctorDict F values. That can at times actually be an an advantage, but often it's just a burden because you need to explicitly carry those dictionaries around (GHC can just pick them automatically, because the choice is unambiguous), and it's harder to state laws.


text:
Q: RegExp to Parse and replace specific Words
*

*My Input: Fwd: [ProQuest Alert] test fwd:TestFwd: test2fwd: fwd:test3 Fwd: fwd:

*My output needs to be:  test fwd:TestFwd: test2fwd: fwd:test3

*My wrong (Parse) output: test TestFwd: test2fwd: test3
I want to delete the words Fwd: and [ProQuest Alert] (the string that's  between square brackets) and not the Fwd: that's Part of the string text
Explanation:
\[(.*?)\] ->  to extract text between square brackets (regex globally)
The \b denotes a word boundary, which is the (zero-width) spot between a character in the range of "word characters" ([A-Za-z0-9_]) and any other character
This my Regexp:
 ?\b(Fwd:)|\[(.*?)\] ?

Demo: https://regex101.com/r/qlTpWb/7

    var str = "Fwd: [ProQuest Alert] test fwd:TestFwd: test2fwd: fwd:test3 Fwd:";
    str = str.replace(/ ?\b(Fwd:)|\[(.*?)\] ?/gi, ' ');
    console.log(str)

A: One solution would be to match what you don't want and to capture what you do want to be removed:
keep_me1|keep_me2|(delete_me)

See a demo on regex101.com.

As lookbehinds and (*SKIP)(*FAIL) are not supported, you need some programming functionality:

let data = 'Fwd: [ProQuest Alert] test fwd:TestFwd: test2fwd: fwd:test3 Fwd: fwd:';
let regex = /\w+:\w+|(\[[^\[\]]+\]|\bFwd:)/gi

data = data.replace(regex, function(match, group1) {
    if (typeof(group1) == "undefined") {
        return match;
    } else {
        return '';
    }
});
console.log(data);

A: And this regular expression?
var str = "Fwd: [ProQuest Alert] test fwd:TestFwd: test2fwd: fwd:test3 Fwd:";
str = str.replace(/\b(Fwd:)(\s|$)|\[(.*?)\]/gi, ' ');
console.log(str)

I only tried it in regex101.com.


text:
Q: How can I find the value of the first element in an associative array in PHP? I have an array like this:
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
);

Is there a function that'll grab 'apple' (the first key) from that array? Or do I have no choice but to do this?
function firstkey($array)
{
    for($array as $first)
    {
        return $first;
    }
}

A: $firstValue = reset($array);
http://www.php.net/manual/en/function.reset.php


text:
Q: Hibernate not retrieving data with JBOSS I am trying to get the following configured.
Spring, Hibernate, Jboss 5.1, Mysql 5.14
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"    xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-   mvc-3.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring- tx-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

<context:annotation-config />
<context:component-scan base-package="au.com.kiche" />
<tx:annotation-driven transaction-manager="transactionManager" />

<bean
    class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

<!-- Most controllers will use the ControllerClassNameHandlerMapping above,
    but for the index controller we are using ParameterizableViewController,
    so we must define an explicit mapping for it. -->

<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

<!-- the following bean description should be moved to applicationContext. I'm leaving this  decision to Chief. -->
<jee:jndi-lookup id="dataSource" jndi-name="java:/MyDS"/>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
    <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
    </property>
</bean>
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

hibernate.cfg.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
                                     "http://hibernate.sourceforge.net/hibernate-configuration-  3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.datasource">java:/MyDS</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="hibernate.show_sql">true</property>

    <mapping class="au.com.kiche.model.User"/>
  </session-factory>
</hibernate-configuration>

The data source file "kiche-ds.xml" is:
<datasources>
<local-tx-datasource>
    <jndi-name>MyDS</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/kiche</connection-url>

    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password>root5</password>

    <min-pool-size>5</min-pool-size>
    <max-pool-size>100</max-pool-size>

    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>

    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml -->
    <metadata>
        <type-mapping>mySQL</type-mapping>
    </metadata>
</local-tx-datasource>
</datasources>

The followis is my class that is try to get all users from the DB:
@Repository
public class UserDAOImpl implements UserDAO{

    @Autowired
    SessionFactory sessionFactory;

    @Override
    public List<User> getUserByLogin() {
            Criteria criteria=sessionFactory.getCurrentSession().createCriteria(User.class);
        List<User> users=criteria.list();
        System.out.println("**** The size of the user is: "+users.size());
            return users;
    }
   .
   .
   .
}

The strange part is that I am able to get the data form the DB when I use Tomcat(not the one with JBOSS). But when I try to run this application in JBOSS, NO data is retrived, there are no errors or exceptions.
Any help will be highly appraciated.
Regards
Adofo

A: You should use the Java EE convention of resource mapping. For your case:
application context:
<jee:jndi-lookup id="dataSource"
                 jndi-name="MyDS"
                 lookup-on-startup="false"
                 proxy-interface="javax.sql.DataSource"
                 resource-ref="true"
        />

WEB-INF/web.xml:
<resource-ref>
    <res-ref-name>MyDS</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

WEB-INF/jboss-web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web PUBLIC
        "-//JBoss//DTD Web Application 4.2//EN"
        "http://www.jboss.org/j2ee/dtd/jboss-web_4_2.dtd">
<jboss-web>
    <resource-ref>
        <res-ref-name>MyDS</res-ref-name>
        <jndi-name>java:MyDS</jndi-name>
    </resource-ref>
</jboss-web>

This will work for both JBoss and pure Tomcat.


text:
Q: How do I make a property dynamic (unknown until the code is executed)? This is the format of the data I work with:
ChecksCollection = new Mongo.Collection(null);
ChecksCollection.insert({
  oddsChecked: ['', ''],
  oddsAverages: ['', ''],
  oddsCompeting: ['', ''],
  ...

dynamicProperty could be 'oddsChecked', 'oddsAverages', 'oddsCompeting' and so on. It depends on execution time. How do I make the code from below work?
var odds = ChecksCollection.findOne().dynamicProperty[index];

A: You could use the transform option to create a getter with Object.defineProperty:
ChecksCollection.findOne({}, {
  transform: doc => Object.defineProperty(doc, 'dynamicProperty', {
    get: function getDynamicProperty() {
      // Your logic here
      // This should return a value (unless you want some obscure
      // side-effecting getter, which no you don't)

      if (this.something) {
        return 42;
      }
      else {
        return 53;
      }
    }
  })
);

You can access the object on which the getter is with this as long as you don't use an arrow function (which locks this).

A: Try it with template string
var t = ['oddsChecked', 'oddsAverages', 'oddsCompeting'];
var s = t[i]; // the `i` determined at the running time.
var odds = ChecksCollection.findOne({`${s}`: value})...;


text:
Q: Route forwarded traffic through eth0 but local traffic through tun0 I have a Ubuntu 12.04/Zentyal 2.3 server configured with WAN NATed on eth0, local interfaces eth1 and wlan0 bridged on br1 on which DHCP runs, and an OpenVPN connection on tun0.  I only need the VPN for some things running on the gateway itself and I need to make sure that everything running on the gateway goes through the VPNs tun0.
root:~# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         gw...           0.0.0.0         UG    100    0        0 eth0
link-local      *               255.255.0.0     U     1000   0        0 br1
192.168.1.0     *               255.255.255.0   U     0      0        0 br1
A.B.C.0         *               255.255.255.0   U     0      0        0 eth0

root:~# ip route
169.254.0.0/16 dev br1  scope link  metric 1000
192.168.1.0/24 dev br1  proto kernel  scope link  src 192.168.1.1
A.B.C.0/24 dev eth0  proto kernel  scope link  src A.B.C.186

root:~# ip route show table main
169.254.0.0/16 dev br1  scope link  metric 1000
192.168.1.0/24 dev br1  proto kernel  scope link  src 192.168.1.1
A.B.C.0/24 dev eth0  proto kernel  scope link  src A.B.C.D

root:~# ip route show table default
default via A.B.C.1 dev eth0

How can I configure routing (or otherwise) such that all forwarded traffic for other hosts on the LAN goes through eth0 but all traffic for the gateway itself goes through the VPN on tun0?  Also, since the OpenVPN client changes routing on startup/shutdown, how can I make sure that everything running on the gateway itself loses all network access if the VPN goes down and never goes out eth0.

A: You need to use some form of policy routing, because you want to route the traffic based on something other than the destination address. I would first try source policy routing, which uses the source address of the packet to select the route. I haven't used it in this kind of situation before, so I'm not if the source address will have already been selected when the rules are checked for new outgoing connections.
First label a new routing table for the VPN connection. This only needs to be done once.
echo 10 vpn >> /etc/iproute2/rt_tables

Populate the new routing table with the rules to send traffic over the VPN (assuming that 1.0.0.10/24 is the eth0 address, and the VPN gateway is at 10.8.0.1).
ip route add 169.254.0.0/16 dev br1 table vpn
ip route add 192.168.1.0/24 dev br1 table vpn
ip route add 1.0.0.0/24 dev eth0 table vpn
ip route add default via 18.8.0.1 table vpn

Then add a rule to use this new table for traffic from the host itself.
ip rule add from 1.0.0.10/32 lookup vpn

If this doesn't work then you're going to have to use firewall marking to select the correct packets instead.

A: I was able to accomplish this using iif lo as follows.
Move the default route to a separate table so the local rule can
override it:
default_route=$(ip route list | grep -m 1 "default via")
ip route add $default_route table default
ip route delete $default_route

Move the priority of the main rule so that the local role can be
placed between it and the default rule.
main=$(ip rule list | grep -m 1 "lookup main $")
main_rule=$(echo $main | cut -d ":" -f 2)
main_priority=$(echo $main | cut -d ":" -f 1)
ip rule add $main_rule priority 16384
ip rule delete $main_rule priority $main_priority

Add the VPN default gateway route to a separate table and add
the rule.
echo "10 vpn" >> /etc/iproute2/rt_tables
ip rule add priority 24576 iif lo lookup vpn

Tell the OpenVPN client to put the default route in the vpn table by
adding the following to the /etc/openvpn/* config file:
script-security 2
route-up "/bin/sh -x -c 'route_net_gateway=$(ip route ls table default | cut -d \" \" -f 3) && ip route add $trusted_ip via $route_net_gateway table vpn && /sbin/ip route add default via $ifconfig_remote table vpn' route-up"


text:
Q: How to get visibility to inserted records where DbContext is not saved yet I am implementing a service layer where I need to make sure that certain number of operations across multiple tables happen in a transaction. Here is the work flow.

*

*I get an instance of HistoricalData object that need to be stored in HistoricalData table. This is accomplished in AddHistoricalData method.

*I need to retrieve all records from HistoricalData table that include what's inserted in #1 but can have more records. This is done in ProcessAllData method.

*After processing all those records, the results are stored in two other tables, ProcessStatus and ProcessResults. If anything goes wrong, I need to rollback transaction include what's inserted in operation #1.

This is how its implemented.
public class HistoricalDataService : IHistoricalDataService
    {
        private MyDbContext dbContext;
        public HistoricalDataService(MyDbContext context)
        {
            this.dbContext = context;
        }

        void AddHistoricalData(HistoricalData hData)
        {
            // insert into HistoricalData table
        }

        void ProcessAllData()
        {
            // Here we process all records from HistoricalData table insert porcessing results into two other tables
        }

        void SaveData()
        {
            this.dbContext.SaveChanges();
        }
    }

Here is how this class methods are been called.
HistoricalDataService service = new HistoricalDataService (dbcontext);
service.AddHistoricalData(HistoricalData instance);
service.ProcessAllData();
service.SaveData();

Problem with this approach is that whatever is inserted in HistoricalData table during call to AddHistoricalData method is not visible in the ProcessAllData call, because dbContext.SaveChanges is called only at the end. I am thinking that I need to somehow bring transaction scope in here but not sure how to expose a function where that transaction scope should be started?

A: There are different ways you can do this. Try this (untested, but POC)
public class HistoricalDataService : IHistoricalDataService
{
    private DbContext dbContext;
    private DbContextTransaction dbContextTransaction;

    public HistoricalDataService(DbContext context)
    {
        this.dbContext = context;
    }

    void AddHistoricalData(HistoricalData hData)
    {
        if (dbContext.Database.CurrentTransaction == null)
        {
            dbContextTransaction = dbContext.Database.BeginTransaction();
        }

        // insert into HistoricalData table
        dbContext.SaveChanges();
    }

    void ProcessAllData()
    {
        // Here we process all records from HistoricalData table insert porcessing results into two other tables
    }

    void Rollback()
    {
        if (dbContextTransaction != null)
        {
            this.dbContextTransaction.Rollback();
        }
    }

    void SaveData()
    {
        this.dbContextTransaction.Commit();
        this.dbContextTransaction.Dispose();
    }
}

Use as such:
HistoricalDataService service = new HistoricalDataService (dbcontext);

try
{
     service.AddHistoricalData(HistoricalData instance);
     service.ProcessAllData();
     service.SaveData();
}
catch (Exception ex)
{
     service.Rollback();
}

A: I would recommend refactoring the code so that the service has a single method (at a higher level of abstraction) and a single responsibility: handling the use case.
then, the client class would have
private readonly IHistoricalDataService _historicalDataService;

_historicalDataService.RearrangeSeatingArrangement(); //High level abstraction

the purpose of doing the above is to ensure your service class has all the operations occur within a single method, wrapped with either a transaction scope if using raw ADO.NET or context object if using EF. Dont have the client class call three methods when it could just call ONE. This is the purpose of the service class in the first place: Handle use cases and return response to client class ( perhaps controller in your case).
Now, when it comes to ensuring that some part of your code is aware of data that has been persisted, it brings up some additional questions: The commands that occur during ProcessAllData() above, why does it split the data exactly? Can that data that is split be split in memory ( in another domain class), added to the context, and saved in the SaveChanges() method? This would ensure you only make one call to the database ( which is the purpose of Entity Framework Unit Of Work. That is: accumulate changes in the context, adds, delete, udpates, then in one operation, talk with database).