text:
Q: android - Settings.Global#AIRPLANE_MODE_ON - Field requires API level 17 (current min is 16) I am getting the following warning :
Field requires API level 17 (current min is 16): android.provider.Settings.Global#AIRPLANE_MODE_ON  TrainingListActivity.java   /Swimmer/src/com/swimtechtest/swimmer   line 89 Android Lint Problem
which is right , as I have in my manifest.xml
   <uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="19" />

I am testing on both Android 4.1.2 (JellyBean)  and Android 4.4.2 (KitKat) ...
AIRPLANE_MODE_ON  is well tested on 4.4.2 but not on the 4.1.2...
how should I modifiy my current test code to be used with both versions ?
            ContentResolver contentResolver = this.getContentResolver();
        Boolean airplaneMode =  Settings.System.getInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
        if (!airplaneMode) {
            SwimmerApp.displayAlertDialog("You are not connected to internet", TrainingListActivity.this);
        } else {
            SwimmerApp.displayAlertDialog("Please set airplane mode to OFF", TrainingListActivity.this);
        }

thanks for advice

A: Settings.Global.AIRPLANE_MODE_ON was only introduced in API level 17, while your app is configured to run on API level 16 or newer.
Edit your AndroidManifest.xml and set the minSdkVersion to 17.


text:
Q: How can I extract all rows of groups? Here is my table:
// notifications
+----+--------+-----------+---------+--------------------+
| id | money  | post_id   | user_id | belongs_to_user_id |
+----+--------+-----------+---------+--------------------+
| 1  | 5      | 1         | 123     | 101                |
| 2  | 10     | 2         | 123     | 101                |
| 3  | -2     | 4         | 456     | 101                |
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 7  | 5      | 4         | 789     | 101                |
| 8  | 10     | 4         | 789     | 101                |
+----+--------+-----------+---------+--------------------+

And I select a set of grouped rows using this query: (the last three groups)*
SELECT * FROM notifications
WHERE belongs_to_user_id = 101
GROUP BY post_id, user_id
ORDER BY id DESC
LIMIT 3

Here is the current result:
+----+--------+-----------+---------+--------------------+
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 7  | 5      | 4         | 789     | 101                | -- the eighth row is grouped with this
+----+--------+-----------+---------+--------------------+

While the expected result is a set of extracted groups like this:
+----+--------+-----------+---------+--------------------+
| 5  | -2     | 2         | 456     | 101                |
| 6  | -2     | 3         | 123     | 101                |
| 7  | 5      | 4         | 789     | 101                |
| 8  | 10     | 4         | 789     | 101                |
+----+--------+-----------+---------+--------------------+

How can I do that?

A: I believe you want this:
SELECT n.*
FROM notifications n JOIN
     (SELECT n2.post_id, n2.user_id
      FROM notifications n2
      WHERE n2.belongs_to_user_id = 101
      ORDER BY n2.id DESC
      LIMIT 3
     ) nn
     ON nn.post_id = n.post_id AND nn.user_id = n.user_id
ORDER BY id DESC;

Nothing in your problem suggests GROUP BY.  You seem confused by the terminology of SQL.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confidence interval for the difference of two means using boot package in R I have two samples, one of size 52, and one of size 31, that are obtained at different times. I'd like to get a 95% bootstrap confidence interval for the difference between the means of the populations that these samples represent. I've been trying to use the "boot" package in R, and I'm getting an error that I can't figure out. I was hoping someone here could help me out.
This is how my data look like (in a dataframe named "totalData"):
      X              samplingTime
1  -0.29              initial
2   0.3               initial
           ....
52  -1.2              initial
53   0.7              final
54  -1.2              final
           ....
83   1.52             final

This is what I did to get my bootstrap CI:
meanDiff = function(dataFrame, indexVector) {
    m1 = mean(subset(dataFrame[, 1], dataFrame$samplingTime == "initial"))
    m2 = mean(subset(dataFrame[, 1], dataFrame$samplingTime == "final"))
    m = m1 - m2
    return(m)
}

totalBoot = boot(totalData, meanDiff, R = 10000, strata = totalData[,2])
totalBootCI = boot.ci(totalBoot)

and in the last line I get the error:
Error in bca.ci(boot.out, conf, index[1L], L = L, t = t.o, t0 = t.o, : estimated
adjustment 'w' is infinite.

I'd very much appreciate any comments.
Thanks!

A: If you look at your totalBoot$t you will see that all the returned values are identical.  The secret is that you have not defined your statistic function (meanDiff) to actual resample the data.  The help page for boot says

When sim = "parametric", the first argument to statistic must be the
  data. ... In all other cases statistic must take at least two
  arguments. The first argument passed will always be the original data.
  The second will be a vector of indices, frequencies or weights which
  define the bootstrap sample.

If you redefine your meanDiff as
meanDiff = function(dataFrame, indexVector) {
    m1 = mean(subset(dataFrame[indexVector, 1], dataFrame[indexVector, 2] == "initial"))
    m2 = mean(subset(dataFrame[indexVector, 1], dataFrame[indexVector, 2] == "final"))
    m = m1 - m2
    return(m)
}

It should work.  Or (not that it matters) I prefer:
meanDiff =function(x, w){
    y <- tapply(x[w,1], x[w,2], mean)
    y[1]-y[2]}


text:
Q: OnClick button replacing fragment many times with FragmentTransaction, ignoring Tag I am trying to make a quick simple app to learn lifecycle of both activities and fragments.
This is my onCreate:
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toast.makeText(this, "Activity is created", Toast.LENGTH_SHORT).show();
    Log.i("onCreate():","Activity is created");

    fm = getSupportFragmentManager();

    Button button = (Button) findViewById(R.id.toMainFragment);
    button.setOnClickListener(new View.OnClickListener() {
        Fragment fragment = fm.findFragmentByTag(MAIN);
        @Override
        public void onClick(View view) {
            if(fragment == null) {
                FragmentTransaction transaction = fm.beginTransaction();
                transaction.replace(R.id.content, new MainFragment(), MAIN).addToBackStack(null).commit();
            }else{
                Toast.makeText(getApplicationContext(), "Fragment already created", Toast.LENGTH_SHORT).show();
                Log.i("onCreate():","Fragment Already created");
            }
        }
    });

    if (savedInstanceState != null){
        Toast.makeText(this, "Activity restored data", Toast.LENGTH_SHORT).show();
        Log.i("onCreate():","Activity restored data");
    }
}

However, every time I hit the button a new fragment gets created, even though I set the tag.
I thought the fragment would stay alive but is rather getting replaced. Why is this the case?

A: This line of code is misplaced:
Fragment fragment = fm.findFragmentByTag(MAIN);

You have it outside of the onClick() method, which means that the value of fragment is determined once (when you create/assign the OnClickListener) and then reused every time the button is clicked.
Just move that line inside the onClick() method:
    @Override
    public void onClick(View view) {
        Fragment fragment = fm.findFragmentByTag(MAIN);
        if(fragment == null) {
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.replace(R.id.content, new MainFragment(), MAIN).addToBackStack(null).commit();
        }else{
            Toast.makeText(getApplicationContext(), "Fragment already created", Toast.LENGTH_SHORT).show();
            Log.i("onCreate():","Fragment Already created");
        }
    }


text:
Q: Does std::thread constructor completion actually synchronize with the beginning of the thread of execution? The C++11 standard (N337, 30.3.1.2) states about the synchronization of the std::thread constructor:

Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

Reading it, I thought the constructor completes before the start of the new thread. But according to the question (std::thread construction and execution) and the current implementation in libc++/libstdc++, there seems no synchronization mechanism and the new thread of execution can possibly begin before the end of the std::thread constructor.
If that is correct, what does the standard try to say? Is this the gap between standard and implementation? Or do I understand the term "synchronize with" incorrectly? Even if constructor and new thread are running simultaneously, can the constructor completion be considered synchronizing with the beginning of new thread?

A:
Reading it, I thought the constructor completes before the start of the new thread

"synchronizes with" is a term of art. When the standard mandates that two operations synchronize with each other, that carries with it certain requirements for evaluations before and after the two operations. For example,  accessing a variable in the original thread before the std::thread constructor, and accessing it in the new thread do not cause a data race.
Intuitively, you can think of "synchronizes with" as meaning that the new thread can see all prior evaluations, modifications, and side effects from the initial thread.
There is no need to make sure the thread begins by the end of the constructor. That is not what this says.
The way standard libraries enforce this requirement is by relying on underlying libraries like pthreads that essentially also enforce this requirement.

A: Once the constructor completes there is nothing you can do to prevent the thread from executing, if it already starts or not actual execution immediately is irrelevant and depends on scheduler/cpu/load.
You are guaranteed however that all the code in the constructor has been executed when the code of the thread starts executing.
In other words it may be that the thread executes a million instructions before the next instruction after the constructor is executed (e.g. the main thread is suspended right after creating the new thread) or it may be a million instructions after the constructor are executed before the first instruction in the thread is executed (i.e. the new thread is immediately suspended).
May be the hardware is single core and indeed there is simply no way two instructions are executed "at the same time" and all operations on native types are atomic (this was the main issue when programs started being executed on first real parallel hardware... a lot of old multithread code was working without explicit synchronization because the hardware was always implicitly synchronizing but started failing in random ways when true parallelism arrived).
Anyway I wouldn't try to read too much into the formal specification: from a purely formal point of view, I think it would be hard to say that an implementation in which a thread is never actually started is not conforming (proving black-box it's not conforming would require waiting till the end of time). The same could be said of an implementation in which a+b takes 10 billion years...

A: No it does not synchronize (scheduling etc...)
I usually use a condition variable construct to be really sure the asynchronous thread has really started. Like this :
#include <condition_variable>
#include <mutex>
#include <thread>

/// <summary>
/// wrapper for a condition variable, takes into account
/// https://www.modernescpp.com/index.php/c-core-guidelines-be-aware-of-the-traps-of-condition-variables
/// </summary>
class sync_signal final
{
public:
    sync_signal() = delete;
    ~sync_signal() = default;
    sync_signal(const sync_signal&) = delete;
    sync_signal& operator=(const sync_signal&) = delete;
    sync_signal(sync_signal&&) = delete;

    explicit sync_signal(bool value) :
        m_value{ value }
    {
    }

    void set() noexcept
    {
        {
            std::unique_lock<std::mutex> lock(m_value_mutex);
            m_value = true;
        }
        m_value_changed.notify_all();
    }

    void wait()
    {
        std::unique_lock<std::mutex> lock(m_value_mutex);
        auto pred = [this] { return m_value; };

        // check pred first we might have missed a notify
        if (pred())
        {
            return;
        }

        m_value_changed.wait(lock, pred);
    }

    std::mutex m_value_mutex;
    std::condition_variable m_value_changed;
    bool m_value;
};

int main()
{
    sync_signal signal{ false };

    std::thread t([&signal]()
    {
        signal.set(); // signal that thread has really scheduled/started
        // do your async stuff here
    });

    // wait on main thread for async thread to have really started
    signal.wait();

    // wait for thread to finish to avoid race conditions at shut-down
    t.join();
}

For short duration functions I prefer using std::async though.
Instead of creating a whole new thread (and taking up resources) it will get a thread from a threadpool
#include <future>

auto ft = std::async(std::launch::async, [&signal]()
{
    signal.set(); // signal that thread has really started
    // do your async stuff here
});

ft.get();


text:
Q: How could I define the type of a variable that will be later assigned to an initialized class? I'm trying to do something like this:
let cached: TYPETOBENAMED | undefined;

export default async function getPackage() {
  if (cached) {
    return cached;
  }

  return import("@package/package_name").then(({ default: AClass }) => {
    cached = new AClass({
      key: apiKey
    });
    return cached;
  });
}

I wanted to define cached as unknown | undefined however that's throwing a ts error TS2571: Object is of type 'unknown'.
How could I define the type of a variable that will be assigned to an initialized class?

A: I solved it by doing this:
let cached: import("@package/package_name").default | undefined;


text:
Q: Horizontal scrolling with sticky div that stays on the left border I have two rows of data (green) and a header (red), which should be visible at all times:
Check out the example I already have:
http://jsfiddle.net/j9C8R/33/
Now the red header scrolls away together with the content, but it should stick to where it is now, but scroll vertically with the content (MS Excel style).
How can this be achieved (preferably with only CSS).
UPDATE: It is important that the red headers scroll vertically along with the corresponding content but stick to the left edge when scrolling horizontally.

.main {
  background-color: blue;
  overflow: scroll;
  height: 200px;
  width: 400px;
}

.row {
  height: 50px;
  overflow: scroll;
  clear: both;
  width: 1000px;
  background-color: yellow;
}

.sticky,
.content {
  float: left;
  width: 150px;
  border: 1px solid black;
}

.sticky {
  background-color: red;
}

.content {
  background-color: green;
}

Sticky header A

ContentA

ContentA

ContentA

ContentA

Sticky header B

ContentB

ContentB

ContentB

ContentB

Sticky header C

ContentC

ContentC

ContentC

ContentC

Sticky header D

ContentD

ContentD

ContentD

ContentD

Sticky header E

ContentE

ContentE

ContentE

ContentE

A: UPDATE
please note the below is now a little out of date as we have css position sticky
Original Post
I do not think it is possible to achieve your goal through pure css as items that are sticky usually use position:fixed which unfortunately fixes them relative to the viewport.
with the use of javascript (in this case the jquery library) and absolute positioning, you should be able to achieve what you are after:

$('.main').scroll(function() {
    $(this).find('.sticky').css('left', $(this).scrollLeft());
});
.main {
    background-color:blue;
    overflow:scroll;
    height:200px;
    width:400px;
}
.row {
    height:50px;
    overflow:scroll;
    clear:both;
    width:1000px;
    position:relative;
    background-color:yellow;
    padding-left:150px;
    box-sizing:border-box;
}
.sticky, .content {
    float:left;
    width:150px;
    border:1px solid black;
}
.sticky {
    background-color:red;
    position:absolute; left:0; top:0;
}
.content {
    background-color:green;
}

I should stick to the left border

Content

Content

Content

Content

I should stick to the left border

Content

Content

Content

Content

I should stick to the left border

Content

Content

Content

Content

I should stick to the left border

Content

Content

Content

Content

I should stick to the left border

Content

Content

Content

Content

A: Ok I've scrapped your thing and have made a complete new one, I've just not wrapped up things inside a position relative container but you can manage to do it atleast
The things are easy for vertical scroll but if you expect horizontal scroll and move headers along, (CSS Wont Just Do It)
Demo
CSS
.head {
    background-color: #f00;
    width: 300px;
    position: absolute;
    left: 100px;
}

.head table {
    width: 100%;
}

.body {
    position: relative;
    left: 100px;
    top: 20px;
    width: 300px;
    height: 50px;
    overflow-y: auto;
}

.body table {
    width: 100%;
}

.body td {
    width: 100px;
}

.head table td {
    width: 100px;
}

.left {
    position: absolute;
    background-color: #0f0;
    width: 90px;
    top: 40px;
}


text:
Q: Can "cross-validation" be used to choose a prior? To be clear, I doubt I am using the term "cross-validation" correctly here; what I am suggesting also seems similar to "boot-strapping" and "hyperparameter tuning". Terminology is not my strength.
Let's say we have a data set with $20$ observations, $D_1, \dots, D_{20}$. We don't know what prior to use for the data set, so we decide to use the maximum entropy prior given the population mean and variance, i.e. a normal prior. (This of course assumes the population distribution has finite second moment. I am not convinced that this assumption is innocuous, but it is common.)
But of course we don't know the population mean and population variance, so we estimate them. We can't use all of the data to estimate them, because then there wouldn't be any data left to do our inference on. So let's say we use observations $D_1, \dots, D_{15}$ to get an estimate $\hat{\mu}$ for the population mean $\mu$ and an estimate $\hat{\sigma}^2$ for the population variance $\sigma^2$. Then we choose $\mathscr{N}(\hat{\mu}, \hat{\sigma}^2)$ as our prior and then use the remaining $5$ observations $D_{16}, \dots, D_{20}$ to do inference with our prior.
No one would like this situation because we are no longer using all of our data for inference. So:

Question: In this situation would it make sense to:

*

*Calculate priors $\mathscr{N}(\hat{\mu}_1, \hat{\sigma}^2_1)$, $\mathscr{N}(\hat{\mu}_2, \hat{\sigma}_2^2)$, $\mathscr{N}(\hat{\mu}_3, \hat{\sigma}_3^2)$, $\mathscr{N}(\hat{\mu}_4, \hat{\sigma}_4^2)$, the first using the exact same procedure above, the second using an analogous procedure with $D_{11}, \dots, D_{15}$ as the "holdout set", the third using an analogous procedure with $D_{6}, \dots, D_{10}$ as the "holdout set", and the fourth using an analogous procedure with $D_1, \dots, D_5$ as the "holdout set",

*Choose as our prior either (a) the convex combination of these above four priors, which would be a Gaussian mixture model I guess, or (b) take as our prior $\mathscr{N}(\tilde{\mu}, \tilde{\sigma}^2)$, where $$\tilde{\mu} := \frac{1}{4}(\hat{\mu}_1 + \hat{\mu}_2 +  \hat{\mu}_3 + \hat{\mu}_4 ) \,, \quad \tilde{\sigma}^2 := \frac{1}{4}(\hat{\sigma}^2_1 + \hat{\sigma}_2^2 + \hat{\sigma}_3^2 + \hat{\sigma}_4^2) \,?$$

The above example generalizes readily, of course (for example I didn't even specify a particular method to get our estimates $\hat{\mu}$ and $\hat{\sigma}^2$), but I thought I would use this concrete example because I don't think I could explain myself clearly in full generality.
(Actually I even doubt that the above concrete example is explained clearly.)

Additional questions: Does something similar to the above procedure already have an established name? And is there any literature either showing its lack of optimality properties or otherwise analyzing it theoretically?

I think this question is different from this related question because that question has both an internal and external source of data. In this example, our parameter estimation and inference are both "competing" for the same data, so we use "cross-validation" or repeated sub-sampling ("bootstrapping") to accomplish the required "hyperparameter tuning" for the prior.
It is also different from the method suggested here which Andrew Gelman argued (probably convincingly, I don't understand the argument to be honest) does not work well. But that method is suggesting use of an "M-estimation" approach with cross-validation to get the prior, i.e. to select the "best-performing" prior from $\mathscr{N}(\hat{\mu}_1, \hat{\sigma}^2_1)$, $\mathscr{N}(\hat{\mu}_2, \hat{\sigma}_2^2)$, $\mathscr{N}(\hat{\mu}_3, \hat{\sigma}_3^2)$, $\mathscr{N}(\hat{\mu}_4, \hat{\sigma}_4^2)$, whereas I am suggesting using some combination of them. This makes more sense to me than the other method, in order to both (a) avoid "overfitting"  and (b) to use more of the data to inform the choice of prior.

A: In this paper Andrew Gelman used cross validation on a corpus of datasets to propose a weakly informative prior, intended for routine use. That seems a sensible approach!
Gelman, Andrew, et al. "A weakly informative default prior distribution for logistic and other regression models." The annals of applied statistics 2.4 (2008): 1360-1383.

A: Since prior etymologically signifies before:

prior
adjective
existing or coming before in time, order, or importance.
"he has a prior engagement this evening"
synonyms:   earlier, previous, preceding, foregoing, antecedent, advance, preparatory, preliminary, initial.

using the data to build the prior is not correct within a Bayesian perspective. It is found however in the "empirical Bayes" methodology, initiated by Robbins (1955) and defended by Efron, which uses first the data to estimate the parameters in a prior, like your Normal example, and a second time to run a pseudo-Bayesian analysis as if the prior was a true prior. Some versions of this approach enjoy convergence properties, for instance in semi- and non-parametric settings.
The question however seems to shy away from this solution by making a single use of the data and separating it into learning and inference parts. This is connected with the construction of intrinsic Bayes factors in the 1990's, by Jim Berger and co-authors, where a fraction of the data is used to make a flat (or otherwise improper) prior into a proper posterior, and use the remaining fraction to compute a Bayes factor (and run a test decision). In order to avoid the choice of the partition impacting the final result, all possible permutations are considered and one form of average (among arithmetic, geometric, harmonic, median) is computed. A much more elegant alternative is O'Hagan's (1995) fractional Bayes factor where the likelihood $L(\theta)$ is replaced with a fractional power $L^\alpha(\theta)$, which is used to create a posterior and this posterior is then used as a prior for the remainder of the likelihood $L^{1-\alpha}(\theta)$. The difficulty with these approaches is in determining the "right" amount of partitioning, e.g., the value of $\alpha$.

A: Firstly, I completely understand the temptation to do this. You want your model assumptions to be defensible and your model to be valid out-of-sample.
The issue is: this is not Bayesian inference. This is regularization using Bayes theorem. That isn't "good" or "bad." The answer to your titular question is yes absolutely. The only thing I would say is that there are probably better regularization methods that would be easier and equally valid under cross-validation.
Bayesian priors are not validated, they are solicited. A prior reflects your preexisting beliefs. If you have to validate it, you didn't believe it in the first place and therefore it is not a genuine prior in the true sense of the term.
The related technique of using secondary data sources to generate a prior that has been brought up is what is refereed to as "empirical" Bayes method, using a second separate date set to generate a prior. This works well for hierarchical models and for situations in which you have empirical prior knowledge you can call on.
I don't see how this makes sense if you are taking one data set and splitting it into two specifically for that purpose. It begs the question why not perform inference on the whole data set with a subjective prior? If you're going to infer your prior from a subset of the data using Bayesian inference, that requires a non-empirical prior which you could just use on the entire data set (in other words, you're just splitting Bayesian inference into two unnecessary steps). If you are not using Bayesian inference to generate a prior, then you don't really believe in using Bayesian inference to solve your given problem in the first place. In that case, just use the method you really believe in on the entire data set.
TLDR: if you don't have a prior belief you feel comfortable using, don't use Bayesian inference; just skip to the method you would use to generate the prior and use it across the board.


text:
Q: Backbone, correct way of saving data into a model? I have two ways of saving data (into a rest API), it works Ok in both ways but I was wondering which one is the way to go.
1st way:
// here serializeObject just converts form inputs into a serialized object
var inputs_data = this.ui.form.serializeObject();
// here in 3rd param from extend is the same as this.model.unset('logged');
var data = _.extend(this.model.toJSON(), inputs_data ,{logged: undefined});
// here I save and the data goes Ok!
this.model.save(data);

2nd way:
// here i serialize the object the same as above
var inputs_data = this.ui.form.serializeObject();
// here i exclude 3rd parameter
var data = _.extend(this.model.toJSON(), inputs_data);
// set data with model.set instead of model.save
this.model.set(data);
// remove unwanted attributes
this.model.unset('logged',{silent:true});
// finnaly just save
this.model.save(data);

So far I am using the 1st way, so I do not know if the app goes bigger it will bring any problems because of this.

A: If I were you I would use either Backbone.StickIt to synchronise an existing model with the form or use Backbone.Syphon to do something similar to what you are doing above.

A: I would go this way. You don't have to pass all attributes to model's save method, only the attributes that need to be changed (http://backbonejs.org/#Model-save)
var inputs_data = this.ui.form.serializeObject();
// remove unwanted attributes
delete inputs_data.logged;
// finally just save
this.model.save(inputs_data);


text:
Q: Syntax error in API JSON File I'm sending a json request to this url https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=213471&format=json
In Chrome's developer console I'm get this error from the JSON file I'm accessing:
Uncaught SyntaxError: Unexpected token :
Am I doing something wrong or is the json code wrong?
How can I bypass this?
function go () {
  send("https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?      stopid=213471&format=json&callback=processData");

  }

 function send(url) {
  var script = document.createElement('script');
  script.setAttribute('src', url );

  var head = document.getElementsByTagName('head')[0];
  head.appendChild(script);
}

 function processData (data) {
  var dueTimes = document.getElementsByTagName('results')[0];
  var result = document.getElementsByTagName('result');
  var time = document.getElementsByTagName('duetime');

  var one = dueTimes.result[0].time;
  var two = dueTimes.result[1].time;

  document.getElementById("times").innerHTML = "Due: " + one + "Second: " + two;
}

window.onload = go;


text:
Q: Generated code does not respect correct protocol (eg. HTTPS) Browsing StackOverflow, I've found out, that not all resources are loaded over HTTPS (if using that protocol)
Looking into code, I've found out, it's related to Imgur addresses:

view-source:https://stackoverflow.com/

0

votes

0

answers

7

views

OnUpgrade Android SQLite Database from Assets Folder

       android database sqlite assets

            55m ago
            LukeG224 10

Also related links, are not using the same protocol:
eg. Hot Network Questions

            Hot Network Questions

                    Is it better to have light come from the left side?

or main noscript

Stack Overflow works best with JavaScript enabled


text:
Q: Javascript listener on load - not loading I have a JS listener to check file type on file upload (input type file).
I placed it in the head of the document. It should work on load but it's not working.
 <script type="text/javascript">
 document.getElementById('confirm').addEventListener('change', checkFile, false);
 approveletter.addEventListener('change', checkFile, false);

function checkFile(e) {

var file_list = e.target.files;

for (var i = 0, file; file = file_list[i]; i++) {
    var sFileName = file.name;
    var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
    var iFileSize = file.size;
    var iConvert = (file.size / 10485760).toFixed(2);

    if (!(sFileExtension === "pdf" || sFileExtension === "doc" || sFileExtension === "docx" || sFileExtension === "png") || iFileSize > 10485760) {
         txt = "File type : " + sFileExtension + "\n\n";
        txt += "Size: " + iConvert + " MB \n\n";
             txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
        alert(txt);
     }
 }
}
 </script>

My HTML
 <input type="file" name="file" id="confirm">

I can make this work in the fiddle but not in my document - http://jsfiddle.net/4JHgk/

A: Make sure your script tag appears after your html declaration of the input and/or wrapt your function, like this:
window.onload=function(){
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);

function checkFile(e) {

    var file_list = e.target.files;

    for (var i = 0, file; file = file_list[i]; i++) {
        var sFileName = file.name;
        var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
        var iFileSize = file.size;
        var iConvert = (file.size / 10485760).toFixed(2);

        if (!(sFileExtension === "pdf" || sFileExtension === "doc" || sFileExtension === "docx" || sFileExtension === "png") || iFileSize > 10485760) {
            txt = "File type : " + sFileExtension + "\n\n";
            txt += "Size: " + iConvert + " MB \n\n";
            txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
            alert(txt);
        }
    }
}
}


text:
Q: Hide Page Layouts and Import SpreadSheet I would like to hide the standard Page and Web Part Page layouts in the create page and only use Publishing Page. I tried the SetAvailablePageLayouts but that doesn't work. I'm also trying to hide the Import Spreadsheet option but can't find a corresponding feature for that option. Have anybody here succeded with that?
Best regards,
Niclas

A: I'm not sure witch SharePoint version your asking about. So this is for SharePoint 2010.
go to Site Settings > Page Layout and Site Template Settings.
Select "Pages in this site can only use the following layouts:" and select the publishing pages (Article Page) you would like. Also you can select the default page layout in the section below that.

A: What I ended up doing was to hide "More Options" in site actions and make an own "Create Page" site action that redirected the user to CreatePage.aspx where only our page layouts where shown.


text:
Q: How to download PDF file url from google drive with latest IOS SDK? To work with google Drive, google developer portals says that
https://developers.google.com/drive/ios/devguide/files#reading_files
1
NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media",file.identifier];

This is my url for normal document/text file and
2
NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@/export?alt=media&mimeType=application/pdf", file.identifier];

This is my url for pdf files.. however none of url works for me
I come to now for #1 that if I replace my url with kClientID as
NSString *url = [NSStringstringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?key=%@", file.identifier,kClientID];

Its working  fine for normal text/document files…. But not sure how to access PDF file url.

A: If you are using google drive sdk api you can download files something like,
 GTMHTTPFetcher *fetcher =
[self.driveService.fetcherService fetcherWithURLString:downloadUrl];
//async call to download the file data
 [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
    NSLog(@"\nfile %@ downloaded successfully from google drive", self.selectedFileName);

    //saving the downloaded data into temporary location
    [data writeToFile:<path> atomically:YES];
} else {
    NSLog(@"An error occurred: %@", error);
}
}];

You will get files as data. You can store it in document directory. Or you can load it on webview to show. If file is pdf then you can load it on webview.
You can refer this stackoverflow link  for more details. refer it's answer all step mentioned.
Hope this will help :)


text:
Q: javascript not adding/removing divs in set order I'm working with JavaScript and am having issues with a couple of for loops at a specific value.
When the slider value is incremented, the amount of pics increase by one and vice versa for when its lowered. However, for a reason I'm unsure of, it will remove one of the pics when the slider is incremented from 9 to 10, and will add one when it's lowered from 10 to 9. This problem doesn't occur anywhere else in the slider, so I'm not sure whats going on.
Here's the code. The picture used isn't attached but the missing image favicon does the same job.

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2

var numberofdivs = 0;
output.innerHTML = slider.value;

slider.oninput = function() {
  prevnum = num;
  output.innerHTML = this.value;
  num = this.value;
  var newnum = num;
  var newprevnum = prevnum;
  console.log(prevnum, num);
  if (prevnum > num) {

    for (newnum; newprevnum > newnum; newnum++) {

      var element = document.getElementById("id");
      element.parentNode.removeChild(element);

    }

  } else if (num > prevnum) {

    for (newprevnum; newnum > newprevnum; newprevnum++) {

      var picpol = document.createElement("img");
      picpol.src = "polee.png";
      picpol.setAttribute("id", "id");
      picpol.setAttribute("class", "polio");
      document.getElementById("basecontainer").appendChild(picpol);
      console.log(picpol);

    }

  } else {

    console.log("no change");

  }
}
body {
  text-align: center;
}

#basecustom {
  text-align: center;
}

.polio {
  margin: none;
  padding: none;
}
Base Customization

  Select your amount of pics
  <input type="range" min="2" max="25" value="2" id="myRange">

Value:

A: You were missing casting value to int. By default it is string.
num = parseInt(this.value);
Above casting will fix your problem.

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2

var numberofdivs = 0;
output.innerHTML = slider.value;

slider.oninput = function() {
  prevnum = num;
  output.innerHTML = this.value;
  num = parseInt(this.value);
  var newnum = num;
  var newprevnum = prevnum;
  console.log(prevnum, num);
  if (prevnum > num) {

    for (newnum; newprevnum > newnum; newnum++) {

      var element = document.getElementById("id");
      element.parentNode.removeChild(element);

    }

  } else if (num > prevnum) {

    for (newprevnum; newnum > newprevnum; newprevnum++) {

      var picpol = document.createElement("img");
      picpol.src = "https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif";
      picpol.setAttribute("id", "id");
      picpol.setAttribute("class", "polio");
      document.getElementById("basecontainer").appendChild(picpol);
      console.log(picpol);

    }

  } else {

    console.log("no change");

  }
}
body {
  text-align: center;
}

#basecustom {
  text-align: center;
}

.polio {
  margin: none;
  padding: none;
}
Base Customization

  Select your amount of pics
  <input type="range" min="2" max="25" value="2" id="myRange">

Value:

A: change num = this.value; to num = parseInt(this.value,10); in your original code, num will be a string. so when it increments to 10, you will get a string '10'. And prevnum is '9'. And if (prevnum > num) { will be true.


text:
Q: Loop through data multiple times with tf.train.shuffle_batch I'm using tensorflow to practice on mnist dataset which has 55,000 training images (5,000 images from the original 60,000 images from mnist was reserved for validation).
Currently I'm using tf.TFRecordReader to read in training tf.record, and subsequently using tf.train.shuffle_batch for training input. This process may be found in inputs function in mnist.py in https://bitbucket.org/jackywang529/tesorflow-sandbox/src.
However, I keep on getting the below error after step 2720.
tensorflow.python.framework.errors.OutOfRangeError: RandomShuffleQueue '_1_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

Thus I have 2 questions:

*

*Why is it after step 2720? given that each step takes in a batch of 100, and I have 55,000 training images? If it were to go out of range, shouldn't it have done so at around step 550?

*How can I keep looping over the dataset forever using tf.train.shuffle_batch? I'm not sure if it's a limitation set by the shuffle_batch implementation or something else.
Thank you!

A: Have you checked that your tf.train.string_input_producer has the argument num_epochs=None so that it cycles indefinitely?


text:
Q: Fascinating induction problem with numerous interpretations Problem: Suppose you begin with a pile of $n$ stones and split this pile into $n$ piles of one stone each by successively splitting a pile of stones into two smaller piles. Each time you split a pile, multiply the number of stones in each of the two smaller piles you form, so that if these piles have $r$ and $s$ stones in them, respectively, you compute $rs$. Once you have finished splitting the piles, calculate the sum of the products computed at each step. Does the order of how you split the piles effect the final summation?

Simple strong induction proof: It looks as if the sum will always be $n(n-1)/2$. Briefly, the pile of $n$ stones is split into piles of $r$ and $s=n-r$ stones, where $r$ is a positive integer less than $n$. The key inductive step for the strong induction proof is
$$
rs+\frac{r(r-1)}{2}+\frac{s(s-1)}{2}=\frac{(r+s)(r+s-1)}{2}=\frac{n(n-1)}{2}.
$$

My question: Are there any neat ways to interpret this problem and its solution?

This problem appears in several sources where the result is often included and you are asked to prove it using induction. I noticed that there are a number of ways to view this problem and its concomitant analogues (but I am lacking a good, intuitive geometric interpretation or analysis):

*

*Combinatorics: Instead of summing the products for all of the pile splittings for $n$ stones, label the stones $1$ through $n$ and let them be elements of a set $M$. For every split, pair all of the stones in the first set with all of the stones in the second set. Every pair produced in this way appears exactly once during the activity. The terms in the sum are the number of new pairs generated after every split. Consider the power set $\mathcal{P}(M)$. By making such pairings, we have generated all distinct 2-element subsets of $\mathcal{P}(M)$.

*Graph theory: Instead of summing the products for all of the pile splittings for $n$ stones, scatter the stones on a flat surface. Mathematically speaking, let $P_1,P_2,\ldots,P_n$ be $n$ points in a plane where no three points are collinear. Each point represents a stone or vertex. With this understanding, the situation may be modeled by a simple graph $G=(V,E)$. If we were to connect every pair of vertices with an edge for a graph $G$, that is, construct the complete graph $G=K_n$, then the number of edges for $K_n$ would be the same as the sum of the products in the original activity.

*Combinatorics and graph theory: We can actually give a sort of restatement of the key inductive step that was used to prove the result of the activity by considering an exercise that appears in D.B. West's Introduction to Graph Theory:
$\underline{\text{Exercise:}}$ Use complete graphs and counting arguments to prove that
$$
\binom{n}{2} = \binom{k}{2} + k(n-k) +\binom{n-k}{2}\quad|\quad 0\leq k\leq n.
$$
Proof. Consider the complete graph $K_n$ which has $\binom{n}{2}$ edges. If we partition the vertices of $K_n$ into a set with $k$ elements and a set with $n-k$ elements, then we can count the edges as those within one block of the partition and those choosing a vertex from each. Consequently, the number of edges is given by $k(n-k)+\binom{k}{2}+\binom{n-k}{2}$.

I think these are some pretty cool ways to look at the original problem/activity. A geometric interpretation (or other) that added some intuition as to why the result of the activity is true would be quite nice.

A: Think of it as an energy calculation with stack of chips (or coins) instead of piles of stones.  A chip whose bottom side is at height $h$ has "potential energy" $h$; when it moves down to height $k$, it "releases" (as "heat" or whatever) the amount of energy $h-k$.  A stack of $n$ chips starts with potential energy $0+1+2+\cdots+(n-1)=n(n-1)/2$, all of which is released by the time things are down to $n$ stacks of $1$ chips each.
When you split a pile of $r+s$ chips into two piles by taking, say $r$ chips from the top to make a new pile, each of those chips moves down by $s$ positions.  This releases energy $rs$.  So no matter how you go about the disassembly of the initial stack, the sum of those $rs$'s must be $n(n-1)/2$.
(I have to give credit here to Richard Guy, who told me about the problem a few years ago and gave me the hint "potential energy.")

A: regard the pile $A$ of $n$ stones as the nodes of a graph which initially has no edges. if $A$ is partitioned into two non-empty sets $B$ and $C$ add all the edges of the bipartite graph, which is a total of $|B| \cdot |C|$ edges. each of the piles $B$ and $C$ is again a graph with no edges.
suppose at some stage of the process a given pebble $p$ lies in a pile $D$. then $p$ is connected by an edge to all the pebbles in the complement of $D$, but to none of the pebbles in $D$.
at the completion of the process each stone is in a pile on its own. it is now connected to all the other nodes, a total of $n-1$ edges. since there are $n$ nodes, and each edge is associated with two nodes, the total number of edges is $\frac12 n (n-1)$.

A: Here is something I cobbled together that others may wish to see:
Any better (i.e., intuitive, etc) ways of doing it though?

A: Along the lines of an interpretation, and following the combinatorics interpretation given by OP in the original statement:
You want to conduct a round-robin tournament among $n$ players.  One way to do this is to split the players into two sets of size $k$ and $n-k$ and have each player in one set play each player in the other set, for a total of $k(n-k)$ games.  Then split any remaining set of size at least $2$ into two smaller sets, and have each player in each of the two smaller sets play each other.  The number of games from any one splitting will be the product of the sizes of the two resulting sets.  Continue in this manner.
Eventually all sets will be of size $1$, and everyone will have played everyone else; and so the total number of games will be $n\choose 2$, but it will also be the sum of products $rs$ where $r$ and $s$ are the sizes of the two sets coming from the splitting of one larger set.
You could do a similar interpretation with handshakes.

A: Here's a slick geometric proof (I'll clean this diagram up later when I can draw it properly):
$$
\begin{array}{lllllll}
\circ \\
\circ & \circ\\
\circ & \circ & \circ\\
\bullet& \bullet& \bullet& \bullet\\
\bullet& \bullet& \bullet& \bullet& \circ\\
\bullet& \bullet& \bullet& \bullet& \circ & \circ \\
\end{array}
$$
Here $n=7$, $r=4$, $s=3$.  We start with an $(n-1)\times(n-1)$ right triangle (of area $\frac{n(n-1)}2$); then splitting $n$ and adding a term of form $r\times s$ corresponds to taking the rectangular chunk above out of the triangle, and the two piles of size $r$ and $s$ correspond to the two right triangles (of edge lengths $r-1$ and $s-1$) left over.  Each further step of the process just corresponds to taking another rectangle (with its top right corner on the diagonal) out of what's left of the original right triangle and leaving two more right triangles (possibly empty) behind.

A: The splitting process induces the fundamental recurrence
$$\color{green}{S_{r+s}=rs+S_r+S_s}.$$
This relation is sufficient to prove order invariance as $r$ and $s$ are chosen freely.


text:
Q: sin_port in sockaddr_in Which port should I use if I need to get the hostname of an IP ? From where does getnameinfo() get the hostname ?
struct sockaddr_in sa;
sa.sin_family    = AF_INET;
sa.sin_port    = htons(?); // which port ?
inet_pton(AF_INET, "x.x.x.x", &(sa.sin_addr));

char host[NI_MAXHOST];
getnameinfo((struct sockaddr *)&sa, sizeof(sa), host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);

puts(host);

A: If you don't use serv and servlen arguments, port number is irrelevant. Otherwise it's used to look up the service by the port number, something like "ssh" for port 22, "smtp" for port 25, etc. (see /etc/services for more).
getnameinfo() can get the hostname from a number of places (with nsswitch.conf, miscellaneous libnss modules can be enabled for different kinds of name resolution). On a typical desktop linux distro, I'd expect it to look at /etc/hosts first, then query DNS servers according to /etc/resolv.conf.

A: From http://www.kernel.org/doc/man-pages/online/pages/man3/getnameinfo.3.html:

The sa argument is a pointer to a generic socket address structure (of type
  sockaddr_in or sockaddr_in6) of size salen that holds the input IP address and
  port number.  The arguments host and serv are pointers to caller-allocated
  buffers (of size hostlen and servlen respectively) into which getnameinfo()
  places null-terminated strings containing the host and service names
  respectively.
The caller can specify that no hostname (or no service name) is required by
  providing a NULL host (or serv) argument or a zero hostlen (or servlen)
  argument.  However, at least one of hostname or service name must be
  requested.

So, if you're only interested in the hostname, don't provide a buffer for the service name.
I'll defer to others on the topic of where this comes from, but the code is in glibc if you're curious.


text:
Q: Can't do linear regression in scikit-Learn due to "reshaping" issue I have a simple CSV with two columns:

*

*ErrorWeek (a number for the week number in the year)

*ErrorCount (for the number of errors in a given week)

I read the CSV data into a pandas dataframe, like this:
df = pd.read_csv("Errors.csv", sep=",")

df.head() shows:
   ErrorWeek  ErrorCount
0          1          80
1          2         118
2          3         249
3          4         397
4          5         159

So far so good.
Then, I create a test/train split, like this:
X_train, X_test, y_train, y_test = train_test_split(
    df['ErrorWeek'], df['ErrorCount'], random_state=0)

No errors so far.
But, I then create a linear regression object and try to fit the data.
# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(X_train, y_train)

Here I do get an error: "Reshape your data either using array.reshape(-1, 1)"
--
Looking at the shape of X_Test and y_Test, I get what looks like two one dimensional "arrays":
X_train shape: (36,)
y_train shape: (36,)

--
I have spent many hours trying to figure this out, but I'm new to Pandas, Python, and to scikit-learn.
I'm reading in two dimensional data, but Pandas isn't seeing that way.
What do I need to do, specifically?
Thanks,

A: Doing:
X_train, X_test, y_train, y_test = train_test_split(
         df['ErrorWeek'], df['ErrorCount'], random_state=0)

will make all output arrays of one dimension because you are choosing a single column value for X and y.
Now, when you pass a one dimensional array of [n,], Scikit-learn is not able to decide that what you have passed is one row of data with multiple columns, or multiple samples of data with single column. i.e. sklearn may not infer whether its n_samples=n and n_features=1 or other way around (n_samples=1 and n_features=n) based on X data alone.
Hence it asks you reshape the 1-D data you provided to a 2-d data of shape [n_samples, n_features]
Now there are multiple ways of doing this.

*

*You can do what the scikit-learn says:
X_train = X_train.reshape(-1,1)
X_test = X_test.reshape(-1,1)
The 1 in the second place of reshape tells that there is a single column only and -1 is to detect the number of rows automatically for this single column.

*

*Do as suggested in other answers by @MaxU and @Wen

A: change your fit part
regr.fit(X_train[:,None], y_train)

A: Try this:
X_train, X_test, y_train, y_test = train_test_split(
    df[['ErrorWeek']], df['ErrorCount'], random_state=0)

PS pay attention at additional square brackets: df[['ErrorWeek']]

A: Apparently sklearn wants x to be a pandas.core.frame.DataFrame because it cannot distinguish between a single feature with n samples or n features with one sample.
Instead y can be one single column, that is a pandas.core.series.Series.
Therefore, in your example, you should transform x to a pandas.core.frame.DataFrame.
As already pointed out by @MaxU:
x=df[['ErrorWeek']]   # double brakets
y=df['ErrorCount']    # single brakets
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

A: X_train.reshape(-1,1) won't work as it's a series, you'll need to use X_train = X_train.values.reshape(-1,1)


text:
Q: C++ "system(command)" not working on NetBeans / Windows I am working on a C++ project using CodeBlocks on Windows but then decided to switch to NetBeans IDE 8.2.
Within my project, I am calling another executable file with some passed parameters (I run the other .exe with suitable parameters then I take the output of it to use in my main project), and it used to work on CodeBlocks but not on NetBeans.
The code is the following:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#include "My_Constants.h"
#include "Data.h"
#include "Parameters.h"
#include "Pattern.h"
#include "Squish.h"
#include "Deserializer.h"
#include "Automatic_Run.h"

using namespace std;

int main()
{

    Parameters parameters;
    parameters.mode = SQUISH;
    Automatic_Run runner;
    string inputname;

    //--------------------------------User Input-------------------------------------
    cout << "enter input file name \n";
    getline(cin, inputname);
    parameters.inputFileName.assign(inputname);
    cout<<"=============================================================================\n";

    //--------------------------------Running SQUISH/first call--------------------------
    cout<<"Running SQUISH - first call\n";
    char command[1000]="";
    string passedParameters = " -i "+parameters.inputFileName +" -f "+ "t";
    strcat(command,"C:\\Users\\Administrator\\Documents\\CodeBlocksProjects\\TestSQUISH\\bin\\Debug\\TestSQUISH.exe ");
    strcat(command,passedParameters.c_str());
    int result = system(command);

 // the rest of the code(not relevant to the problem)

    return 0;
}

On CodeBlocks, it used to work perfectly and give me the output as a file in the path of my main project (the one I am calling TestSQUISH from). However, now on NetBeans, I am getting the following error:

sh: C:UsersAdministratorDocumentsCodeBlocksProjectsTestSQUISHbinDebugTestSQUISH.exe: command not found

I checked the terminal of NetBeans to get an idea of what is happening (assuming it might be related) and I noticed that I have to change the path first, then run the executable using:

./ TestSQUISH.exe (+parameters)

However, that also didn't work for my project.
Can anyone please suggest a solution or tell me how I can make NetBeans run the command on a Windows terminal as CodeBlocks used to do?

A: Go to the project settings and set the project path for execution to be the folder where the other application is.
OR
Set the system path to include that folder.

A: Thanks to the comment of @Yksisarvinen, I was able to solve the problem.
Noticing that NetBeans uses the shell and not the Windows-style commands and after using the NetBeans own terminal to really get a clear idea of how it translates paths, I was able to run the code successfully using the following:
char command[1000]="";
string passedParameters = " -i "+parameters.inputFileName +" -f "+ "t";
strcat(command, "/cygdrive/c/Users/Administrator/Documents/CodeBlocksProjects/TestSQUISH/bin/Debug/TestSQUISH.exe ");
strcat(command,passedParameters.c_str());
int result = system(command);

Netbeans terminal adds cygdrive to the beginning of the path, and uses c instead of C:.
And in case the executable is in the same directory as your own project then this would be enough:
char command[1000]="";
string passedParameters = " -i "+parameters.inputFileName +" -f "+ "t";
strcat(command ,"./TestSQUISH.exe ");
strcat(command,passedParameters.c_str());
int result = system(command);


text:
Q: How can install mod_evasive or mod_security with httpd24 I'm trying to install mod_evasive and mod_security vainly, with httpd24 under Cenots 6.10.
I have tried this solution : https://github.com/shivaas/mod_evasive, downloaded : mod_evasive24.c $APACHE_ROOT/bin/apxs -i -a -c mod_evasive24.c
i got that message :

/usr/lib64/apr-1/build/libtool --silent --mode=compile gcc -prefer-pic
  -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -Wformat-security -fno-strict-aliasing -DLINUX=2 -D_REENTRANT -D_GNU_SOURCE -pthread -I/usr/include/httpd -I/usr/include/apr-1 -I/usr/include/apr-1 -c -o mod_evasive24.lo mod_evasive24.c && touch mod_evasive24.slo mod_evasive24.c: In function âcreate_hit_listâ:
  mod_evasive24.c:122: warning: no return statement in function
  returning non-void mod_evasive24.c: In function âaccess_checkerâ:
  mod_evasive24.c:146: error: ârequest_recâ has no member named
  âuseragent_ipâ mod_evasive24.c:150: error: ârequest_recâ has no member
  named âuseragent_ipâ mod_evasive24.c:162: error: ârequest_recâ has no
  member named âuseragent_ipâ mod_evasive24.c:169: error: ârequest_recâ
  has no member named âuseragent_ipâ mod_evasive24.c:184: error:
  ârequest_recâ has no member named âuseragent_ipâ mod_evasive24.c:191:
  error: ârequest_recâ has no member named âuseragent_ipâ
  mod_evasive24.c:212: error: ârequest_recâ has no member named
  âuseragent_ipâ mod_evasive24.c:219: error: ârequest_recâ has no member
  named âuseragent_ipâ mod_evasive24.c:225: error: ârequest_recâ has no
  member named âuseragent_ipâ mod_evasive24.c:226: error: ârequest_recâ
  has no member named âuseragent_ipâ mod_evasive24.c:232: error:
  ârequest_recâ has no member named âuseragent_ipâ mod_evasive24.c:233:
  warning: ignoring return value of âsystemâ, declared with attribute
  warn_unused_result mod_evasive24.c: In function âdestroy_hit_listâ:
  mod_evasive24.c:305: warning: no return statement in function
  returning non-void apxs:Error: Command failed with rc=65536

A: Since CentOS 6 is a bit on the old side, in my opinion, the best course of action is upgrading it to CentOS 7. You seem to be suffering of using Apache 2.2 tools with Apache 2.4.
Addressing several concerns on your question:

*

*If you are using CentOS 6, I would advise upgrading it to 7;

*As for mod_evasive, there are packages for that;

*About mod_security, the difficult part is not installing it, but configuring it properly, without it interfering with your current site/solution.

For installing mod_evasive and mod_security in CentOS 7, you need to enable the EPEL repositories first:
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo rpm -Uvh epel-release-7*.rpm

and then do:
sudo yum --enablerepo=epel install mod_evasive  mod_security mod_security_crs

For configuring mod_evasive, see: Using a load balancer instead of Apache to throttle transactions from specific IP's
About mod_security, by default it only logs events. For making it active, after installing it, you have to edit /etc/httpd/conf.d/mod_security.conf and change SecRuleEngine to On and restart Apache.
However, I advise against enabling SecRuleEngine to On, if you are not prepared to:

*

*debug mod_security on your own;

*understand why some parts of your web site might stop working;

*correcting / tracking down the corresponding rules to disable, on the default mod_security config.


text:
Q: Coding exercise to check for pangrams Running through the Functions and Methods homework for Jose Portillos python course and I wrote this for the last problem:
import string

def ispangram(str1):
    alphabet=string.ascii_lowercase
    x=0
    for y in set(str1):
        if y.lower() in alphabet:
            x+=1
    return x

I was just going to check that x returned 26 and then change the code to return x==26 to check for pangrams. But for some reason with the string "The quick brown fox jumps over the lazy dog" it's returning 27 instead of 26.
Can anyone explain why that might be so? I can figure out a fix easily enough, but I have no idea why I'm getting this result.

A: You are converting the string to lower after converting it to a set, in which case T and t are treated as different characters, as they should be.
P.S.: Issues are like these are excellent cases for learning how to use a debugger. (Not being snarky, genuine tip.)

A: If you observe carefully your sentence 'The quick brown fox jumps over the lazy dog' it contains T two times and T as capital caused due to lower function. While your function does not have capability to count it once. Although you can solve this problem by

*

*write y only instead of y.lower()
if y in alphabet:
x+=1

*Or either count for repeated alphabet which it will count as once only

A: I think you just have to iterate over a string here, you do not need to convert the string to a set.

def ispangram(str1):
    alphabet=string.ascii_lowercase
    x=0
    for y in str1:
        if y.lower() in alphabet:
            x+=1
    return x

Hope this helps :)


text:
Q: Images repeated in GridView I have a list of 6 distinct images. To display these images in GridView, I have a custom adapter. Now the problem is, only the 1st image is repeatedly showing in GridView instead of all distinct images.
Here is my getView()
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;

    if (convertView == null) {
        // if it's not recycled, initialize some attributes
        WindowManager wm = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.model_grid, null, false);
        convertView.setLayoutParams(new GridView.LayoutParams((int) (width / 2.05), (int) (height /4.6)));
        convertView.setPadding(1,1,1,2);
        ImageView thumb = convertView.findViewById(R.id.thumbs);
        Log.i(TAG, "getView: "+mthumbs.size()+mthumbs.get(0)+mthumbs+getItem(5));
        Picasso.with(mActivity).load(mthumbs.get(position)).into(thumb);
    } else {
        convertView = convertView;
    }

    return convertView;
}

A: I think you missing below method in your adapter.
Please add this below method to your adapter.
public int getItemViewType(int position) {
        return position;
}

A: public View getView(int position, View convertView, ViewGroup parent) will be called on your adapter zero to many times per position, and the convertView it supplies may be a reusable instance.
Since you're only ever setting the content when the supplied convertView child is null, you're effectively removing the adapter's functionality and only setting an image for the last element to be called when the convertView was still null.
Move the following code outside of that if/else check:
ImageView thumb = convertView.findViewById(R.id.thumbs);
Log.i(TAG, "getView: "+mthumbs.size()+mthumbs.get(0)+mthumbs+getItem(5));
Picasso.with(mActivity).load(mthumbs.get(position)).into(thumb);

You're also going to want to look into the ViewHolder pattern to make it work more efficiently (you were almost there with the attempt to reuse the convertView).

A: Please check the use of getItem(int) , getCount() & getItemId(int) .
"getCount()" - Should return size of Adapter.
getItem(int) - Normally, should return the actual object at the specified position in the adapter.
"getItemId(int)" - Should return the row id of the item.


text:
Q: icons not appearing in the BottomNavigationBar from drawable This links contains the screenshot. It shows the dark places inplace of the icons. The shape of those places is just like that of the icons but icons are not appearing.
MainActivity.java
    [private BottomNavigationView.OnNavigationItemSelectedListener
    mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case R.id.navigation_buy:
                fragment = new Buy();
                break;
            case R.id.navigation_orders:
                fragment = new Orders();
                break;
            case R.id.navigation_navigation:
                fragment = new Navigation();
                break;
            case R.id.navigation_chat:
                fragment = new Chat();
                break;
            case R.id.navigation_invite:
                fragment = new Invite();
                break;

        }
        final FragmentTransaction transaction =
fragmentManager.beginTransaction();
        transaction.replace(R.id.content, fragment).commit();
        return true;

    }

};]

menu.xml
[<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/navigation_buy"
    android:icon="@drawable/buy_ic"
    android:title="@string/title_buy"
    app:showAsAction="ifRoom"/>

<item
    android:id="@+id/navigation_orders"
    android:icon="@drawable/orders_ic"
    android:title="@string/title_orders"
    app:showAsAction="ifRoom"/>

<item
    android:id="@+id/navigation_navigation"
    android:icon="@drawable/navigation_ic"
    android:title="@string/title_navigation"
    app:showAsAction="ifRoom"/>
<item
    android:id="@+id/navigation_chat"
    android:icon="@drawable/chat_ic"
    android:title="@string/title_chat"
    app:showAsAction="ifRoom"/>
<item
    android:id="@+id/navigation_invite"
    android:icon="@drawable/invite_ic"
    android:title="@string/title_invite"
    app:showAsAction="ifRoom"/>

</menu>]

activity_main.xml
<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/colorPrimary"
    app:itemTextColor="@color/white"
    app:menu="@menu/navigation" />

A: Use itemIconTint instead of app:itemBackground="@color/colorPrimary"
app:itemIconTint="@color/colorPrimary"


text:
Q: Impact of trim when used on mean in R I am executing below two statements in R
x <- c(33,16,18,21,10,30,28)
mean(x, trim = 0.2)
The Output 22.6
My understanding is that trim should have removed length(x) * 0.2 elements from the vector x before computing mean. That is it should removed 7*.2 = 1.4 elements.
Removing 1 element from both sides of the vector, I get 16,18,21,10,30 and hence I expect the mean to be 19 from (16+18+21+10+30)/5. Instead the O/P is 22.6

A: The issue is when trim goes to work it removes the highest and lowest values from the data, not the first and last values. So in your case it removes 10 and 33 and gets 22.6 as the mean of the remaining values.


text:
Q: Problems when upload files 2MB or More using php
when Try to upload files less 2mb everything goes fine  when it be more 2Mb I  get "cant not upload a file"

<!DOCTYPE html>
 <title> My website  </title>

 <?php $directory = "userfiles/";
 $File_name = $_FILES["userfile"]["name"];
 $Type = $_FILES["userfile"]["type"] ;
 $Size = ($_FILES["userfile"]["size"] / 1024);
 $File_temp_name = $_FILES["userfile"]["tmp_name"];
 if($Size<= 0){ die('cant not upload a file '); }
 if (file_exists($directory . " / " . $_FILES["userfile"]["name"])) { die($_FILES["userfile"]["name"] . " already exists. "); }
 if(is_uploaded_file($_FILES["userfile"]["tmp_name"])){ if(!move_uploaded_file($File_temp_name,$directory."/".$File_name))
 { die('cant not file'.$File_name); } } else { die('attack on file'); } echo $File_name . " is sucessfully uploaded " . "
 " ;
echo "file size : " .$Size. "
 ";
echo"type :".$Type."
 "; ?>

when upload file 2mb or more I get "cant not upload a file"

A: This is basically a problem with the default configuration set in php.ini file

By default, PHP file upload size is set to maximum 2MB file in php.ini file

To increase file upload size in PHP, update the upload_max_filesize and post_max_size in your php.ini file
upload_max_filesize = 64M
post_max_size = 32M

You can set the value based on your requirements.
In addition, you can also set the maximum number of files allowed to be uploaded in a single request using the max_file_uploads.
max_file_uploads = 30

After modifying php.ini file, make sure you restart your server.
For confirmation, whether your changes are done or not. You can create a test file inside your project folder.
Create test.php and write following code:
<?php
   phpinfo();
?>

Save the file and open in browser. It will look something like this:

Search for upload_max_filesize and post_max_size in this, it should reflect the new values.

A: Most probably you reached upload_max_filesize within your PHP config, change the value for higher in your php.ini file, and don't forget to restart the Apache server.
TIP: you can check current vaalues and location of the path of used php.ini using this PHP script:
<?php
   phpinfo();

phpinfo() docs


text:
Q: Creating a WHERE IN clause using SQL JQUERY C# JavaScript I am writing a large SQL statement, which has a large WHERE clause:
SELECT ID FROM TABLE
WHERE ID IN
(
'C1',
'C2',
'C3',
'C4',
)

Is there a way I can wrap my list of values or a way to create the WHERE ID IN clause programatically?
My list of values are as follows:
C1
C2
C3
C4
C5
C6
C7
C8
C9
C10
C11

A: If you want your list of values to be declared as ('alpha','beta','gamma') in your IN clause dynamic sql use something like.
function retCol(arr) {
     return (arr.length ? "'" + arr.join("','") + "'" : "");
}.
and then store the values in a variable

var myArray = new Array("alpha","beta","gamma");
var sortedVal = retCol(myArray);.

var sqlString = "SELECT ID FROM TABLE WHERE ID IN ("+sortedVal+").
Hope this helps.

A: You will require Dynamic SQL
DECLARE @query varchar(1000)
DECLARE @colList varchar(500)

SELECT @colList=COALESCE(@colList+',','') + columnName
FROM yourTable

SET @query = 'SELECT id FROM otherTable WHERE id IN ('+ @colList +')'

EXEC(@query)

A: We usually pass all the Ids as a concatenated varchar, like this:
declare @ids varchar(max) = 'C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11'

We then have a function to split the varchar into a table, and query is written like:
SELECT ID FROM TABLE
WHERE ID IN (select item from [dbo].[func_Split](@ids, ','))

We usually pass @ids as a parameter from code, so you can just create the string there. Or you create it in SQL.
See the function func_Split here.

Can also be used as in mhasan's example, to avoid Dynamic SQL:
DECLARE @colList varchar(max)

SELECT @colList=COALESCE(@colList+',','') + columnName
FROM yourTable

SELECT ID FROM TABLE
WHERE ID IN (select item from [dbo].[func_Split](@colList, ','))


text:
Q: How to push JSON Objects and create a nested one in AngularJs I end up with a frontend task on my desk yesterday and since our frontend dev is on annual leave I need some help.
I have this piece of AngularJs script which is part of my angular controller. I am trying to post some data to the server which I fetch from a multi-step wizard form. On the server side I have already the implementation (I am a backend dev) so nothing scary there but I need to tweak somehow the JSON object before I try to POST so I can bind that nicely with my Spring boot rest controller.
That's the piece of code.
//These are my guys which I am trying to push
$scope.department = {};
$scope.user1 = {};
$scope.user2 = {};

//Some POST method
$scope.save = function () {

    var data = [{}];
    //here I do the push but it looks like I've no idea what I am doing
    data.push($scope.department);
    data.push($scope.user1);
    data.push($scope.user2);

    var config = {
            headers : {
                'Content-Type': 'application/json'
            }
        }

        console.log(JSON.stringify(data));

        $http.post('http://localhost:8080/api/', data, config)
        .success(function (data, status, headers, config) {
            $scope.PostDataResponse = data;
        })
        .error(function (data, status, header, config) {
            console.log(data);
        });
    };

This is the JSON output of what I have achieved with the above script
[
    {
        "department": "foo",
        "code": 1234
    },
    {
        "firstName": "Megan",
        "lastName": "Fox"
    },
    {
        "firstName": "Margot",
        "lastName": "Robbie"
    }
]

This is the JSON output I am looking for
{
    "department": "foo",
    "code": 1234,

    "user1": {
        "firstName": "Megan",
        "lastName": "Fox"
    },

    "user2": {
        "firstName": "Margot",
        "lastName": "Robbie"
    }
}

Thank you!!!

A: I was able to replicate your JSON, can you please verify its correct?

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope, $http) {
  //These are my guys which I am trying to push
  $scope.department = {
    "department": "foo",
    "code": 1234
  };
  $scope.user1 = {
    "firstName": "Megan",
    "lastName": "Fox"
  };
  $scope.user2 = {
    "firstName": "Margot",
    "lastName": "Robbie"
  };

  //Some POST method
  $scope.save = function() {
    var data = Object.assign({}, $scope.department);
    //here I do the push but it looks like I've no idea what I am doing
    data["user1"] = $scope.user1;
    data["user2"] = $scope.user2;

    var config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }

    console.log(JSON.stringify(data));

    $http.post('http://localhost:8080/api/', data, config)
      .success(function(data, status, headers, config) {
        $scope.PostDataResponse = data;
      })
      .error(function(data, status, header, config) {
        //console.log(data);
      });
  };
  $scope.save();
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">

</div>

A: Please note that, you are looking output in the form of object, however, you created data variable as array. I like the answer given by "Naren Murali" but you can make it more developer friendly and easy to read:
var data = $scope.department;
    data.user1=$scope.user1;
    data.user2=$scope.user2;


text:
Q: LNK1169 Error I can't find LNK1169: one or more multiply defined symbols found.
My project is a parallelized random number generator, using MPI and the parallel prefix algorithm.  I have looked up many solutions to LNK1169 errors.  To try to prevent it I made many variables static, I looked for multiply defined variables, and cannot find any.  I have no header files where variables could have been multiply defined.  If anyone could help me find the error I would greatly appreciate it.  I am fairly sure the error occurs in functions.cpp somewhere, as everything was building correctly before I attempted to implement the parallel_prefix function.
Also here is the output from LNK2005:
LNK2005 "class std::vector >,class std::allocator > > > __cdecl parallel_prefix(class std::vector >,class std::allocator > > >,class std::allocator >,class std::allocator > > > > >,int,int)" (?parallel_prefix@@YA?AV?$vector@V?$vector@HV?$allocator@H@std@@@std@@V?$allocator@V?$vector@HV?$allocator@H@std@@@std@@@2@@std@@V?$vector@V?$vector@V?$vector@HV?$allocator@H@std@@@std@@V?$allocator@V?$vector@HV?$allocator@H@std@@@std@@@2@@std@@V?$allocator@V?$vector@V?$vector@HV?$allocator@H@std@@@std@@V?$allocator@V?$vector@HV?$allocator@H@std@@@std@@@2@@std@@@2@@2@HH@Z) already defined in functions.obj RandomNumberGenerator
Here is my code.
RandomNumberGenerator.cpp
#include "functions.cpp"

int main(int argc, char *argv[])
{
    // Establishes what rank it is, and how many processes are running.
    static int rank, p, n, per_Process;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    static vector<int> Broadcast_data;
    n = 100;
    per_Process = n / p;

// The first and second arguments are constants for number generation, the third is a large prime to mod by, and the fourth is a random seed. x1 is calculated based off x0.
// All provided by the user except x1.
// Rank 0 broadcasts the data to all processes.
if (rank == 0)
{
    for (static int i = 1; i < 5; i++)
    {
        Broadcast_data.push_back(std::atoi(argv[i]));
    }
    Broadcast_data.push_back(std::atoi(argv[1]) *std::atoi(argv[4]) % std::atoi(argv[3]));

    // NOTE: THIS PUSH BACK IS HOW MANY RANDOM NUMBERS WILL BE GENERATED
    Broadcast_data.push_back(n);
    cout << "Rank " << rank << " Broadcast Data: ";
    for (static int i = 0; i < 6; i++)
    {
        cout << Broadcast_data[i] << " ";
    }
    cout << endl;
}
else
{
    Broadcast_data.resize(6);
}
MPI_Bcast(Broadcast_data.data(), 6, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);

// Initialize an array of n/p values at every process.  Each of the n/p values is the matrix M.
// M is this 2 dimmensional array:
// [ a 1 ]
// [ b 0 ]
static vector<vector<int>> M;
M.resize(2);
M[0].resize(2);
M[1].resize(2);
M[0][0] = Broadcast_data[0];
M[0][1] = Broadcast_data[1];
M[1][0] = 1;
M[1][1] = 0;

// Now we must initialize the array of these M values.  Notation might get complex here
// as we are dealing with 3D arrays.
static vector<vector<vector<int>>> M_values;
M_values.resize(per_Process);
for (static int i = 0; i < per_Process; i++)
{
    M_values.push_back(M);
}

// Now we are ready for the parallel prefix operation.  Note that the operator here
// is matrix multiplication.
static vector<vector<int>> prefix;
prefix = parallel_prefix(M_values, rank, p);

MPI_Finalize();

return 0;
}

functions.cpp
#include <mpi.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <time.h>

using namespace std;

// This is parallel prefix with the operator being matrix multiplication
vector<vector<int>> parallel_prefix(vector<vector<vector<int>>> Matrices, int rank, int p)
{
    // The first step is a local multiplication of all M values.
    // In a matrix represented by:
    // [ a b ]
    // [ c d ]
    // The new matrix will be this:
    // [ a^2+bc ab+bd ]
    // [ ca+dc cb+d^2 ]
    // So the first step will be to complete this operation once for every matrix M in M_values

static vector<vector<int>> local_sum;
local_sum = Matrices[0];
for (static int i = 1; i < Matrices.size(); i++)
{
    vector<vector<int>> temp_vector;
    temp_vector = local_sum;
    temp_vector[0][0] = local_sum[0][0] * Matrices[i][0][0] + local_sum[1][0] * Matrices[i][0][1];
    temp_vector[0][1] = local_sum[0][1] * Matrices[i][0][0] + local_sum[1][1] * Matrices[i][0][1];
    temp_vector[1][0] = local_sum[0][0] * Matrices[i][1][0] + local_sum[0][1] * Matrices[i][1][1];
    temp_vector[1][1] = local_sum[0][1] * Matrices[i][1][0] + local_sum[1][1] * Matrices[i][1][1];

    local_sum = temp_vector;
}
// Now that all the local sums have been computed we can start step 2: communication.

// Determine how many steps it will take
int steps = 0;
while (int j = 1 < p)
{
    j *= 2;
    steps++;
}
while (int k = 0 < steps)
{
    // First determine the rank's mate.
    static int mate;
    mate = rank | (1u << steps);

    // Now we send the local sum to mate, and receive our mate's local sum.
    // First modify the local sum vector to a vector that can be sent.
    // Send vector syntax is [ a c b d ]
    static vector<int> send_vector, recv_vector;
    send_vector.resize(4);
    recv_vector.resize(4);
    send_vector[0] = local_sum[0][0];
    send_vector[1] = local_sum[0][1];
    send_vector[2] = local_sum[1][0];
    send_vector[3] = local_sum[1][1];

    // Send the vector to your mate, and recieve a vector from your mate.
    static MPI_Status status;
    MPI_Send(send_vector.data(), 4, MPI_INT, mate, 0, MPI_COMM_WORLD);
    MPI_Recv(recv_vector.data(), 4, MPI_INT, mate, 1, MPI_COMM_WORLD, &status);

    // Update the local sum if your mate rank is lower than your rank.
    if (mate < rank)
    {
        static vector<vector<int>> temp_vector;
        temp_vector = local_sum;
        temp_vector[0][0] = local_sum[0][0] * recv_vector[0] + local_sum[1][0] * recv_vector[1];
        temp_vector[0][1] = local_sum[0][1] * recv_vector[0] + local_sum[1][1] * recv_vector[1];
        temp_vector[1][0] = local_sum[0][0] * recv_vector[2] + local_sum[0][1] * recv_vector[3];
        temp_vector[1][1] = local_sum[0][1] * recv_vector[2] + local_sum[1][1] * recv_vector[3];

        local_sum = temp_vector;
    }
    MPI_Barrier(MPI_COMM_WORLD);
    k++;
    // After completion of this loop the local sum is the parallel prefix output for each process.
}

return local_sum;
}

A: You're including functions.cpp in main.cpp, and probably also including it in your project.  This compiles the things in functions.cpp twice.
Don't include functions.cpp in main.  Use functions.h to declare the functions from within it.


text:
Q: How to make elements blink in Vue.js I have a custom function in jQuery which makes an element blink when it is clicked. What is the proper way to do this in Vue?
I assume it is done with a directive? Is there a way to make it so I can add "blinkable" to any element to make it blink when clicked?

button 1

button 2

button 3

button 4

A: I'd just go with pure CSS animation

div.button {
  background:purple;
  color:white;
  margin-bottom:2px;
  padding:5px;
}

div.button:active {
  animation: blink 0.02s 20 alternate;
}

@keyframes blink {
  from { background-color: purple; }
  to { background-color: red; }
}

button 1

button 2

button 3

button 4

A: You could also do it with a method and some vanilla JS: https://codepen.io/aprouja1/pen/QgJZEP
methods: {
    blink(event) {

  event.target.style.background = 'red'
  setTimeout(()=>{
    event.target.style.background = 'purple'
  },500)

    }


text:
Q: What library and what version of XSLT does Solr 7.6 install for use with the response writer? I've written an XSL to transform my XML response from Solr 7.6.  The XSL is version 2.  It works fine if I apply it to the pure XML response using Oxygen, but when I reference it in the query string using wt=xslt&rt=my.xsl, it errors out.  The example.xsl shipped with Solr works, so my configuration is correct.

A: Checking the version of XSLT dynamically is easy via system-property('xsl:version').
system-property('xsl:vendor') will return the XSLT processor being used.


text:
Q: How do I get the horizontal and vertical scroll bar position of TWinControl such as TSynEdit? In Delphi, in many TWinControl descendants, such as in my exact case, the TSynEdit control, how would I read the horizontal and vertical scroll bar position?
I have been searching around in the source code for my particular control, and in the base class documentation for TWinControl, and can't figure it out.
Is there a general VCL specific way to do this, or should I do this via Win32 API calls?

A: The GetScrollBarInfo function is the way to get the scrollbars position of any TWinControl. You must pass the handle of the control, an OBJID_VSCROLL or OBJID_HSCROLL value and a  SCROLLBARINFO structure to return the data.
Check this sample
var
 LBarInfo: TScrollBarInfo;
begin
 LBarInfo.cbSize := SizeOf(LBarInfo);
 if GetScrollBarInfo(SynEdit1.Handle, Integer(OBJID_VSCROLL), LBarInfo) then
  ShowMessage(Format('Left %d Top %d Height %d Width %d', [LBarInfo.rcScrollBar.Left, LBarInfo.rcScrollBar.Top, LBarInfo.rcScrollBar.Height, LBarInfo.rcScrollBar.Width]));
end;


text:
Q: Como pegar os 5 primeiros registros do xml? <?php
                        $xml = simplexml_load_file('http://g1.globo.com/dynamo/economia/rss2.xml') or die("erro carregar arquivo");

                        foreach ($xml->channel->item as $noticia) {
                            $noticia->pubDate = date('d/m/Y');

                            echo "

 $noticia->pubDate

                                          link\" target=\"_blank\">$noticia->title

                            ";
                        }
                    ?>

A: <?php
    $limite = 5;
    $xml = simplexml_load_file('http://g1.globo.com/dynamo/economia/rss2.xml') or die("erro carregar arquivo");
    $noticias = $xml->xpath(sprintf('/rss/channel/item[position() <= %d]', $limite));

    foreach ($noticias as $noticia) {
        $noticia->pubDate = date('d/m/Y');

        echo "

 $noticia->pubDate

                        link\" target=\"_blank\">$noticia->title

        ";
    }
?>


text:
Q: Plot multiple fitdist objects in same the plot with different colors? I have a list of fitdist objects, which I have stored using this piece of code.
norm_dist_res <- list()
for(i in 1:10)
{
  x <- 1+(8000*(i-1))
  y <- 8000*i
  print (x)
  print(y)
  norm_dist_res[[i]] = norm_dist_res[[i]] <- fitdist(data=as.vector(g_all_p$data[x:y,]), distr="norm")

}

Is there a way to plot all the normal distributions extracted from fittest with a different color to show how the data is distributed?
Or in general how to visualize multiple normal distributions?

A: You are estimating the parameters of a normal distribution, so just plot the densities.
## Don't no what g_all_p is, so simplifying the data
library(fitdistrplus)
norm_dist_res <- list()
for(i in 1:10)
{
  norm_dist_res[[i]] = norm_dist_res[[i]] <- fitdist(data=rnorm(10), distr="norm")

}

Then just plot using lines and changing the colour
x = seq(-5, 5, length.out=100)
plot(x, type="n", ylim=c(0, 1), xlim=range(x))
for(i in 1:10) {
  est = norm_dist_res[[i]]$estimate
  lines(x, dnorm(x, est[1], est[2]), col="grey90")
}

To get


text:
Q: If P is a transition matrix from basis A to B, Q is a transition matrix from B to C, then PQ is a transition matrix from A to C. Problem:
Let $B = (w_1,...,w_n)$ and $C = (u_1,...,u_n)$ be bases in linear space V.
$P$ is a transition matrix from basis $A$ to $B$.
$Q$ is a transition matrix from basis $B$ to $C$.
Prove that $PQ$ is a transition matrix from $A$ to $C$.
My attempt:
$P[\alpha_1,...,\alpha_n]_A = [\beta_1,...,\beta_n]_B$
$Q[\beta_1,...,\beta_n]_B = [\gamma_1,...,\gamma_n]_C$
Where $\alpha_i,\beta_i,\gamma_i$ are scalars denoting position of a vector $[v]$ in given basis. Then:
$[v]_C=[\gamma_1,...,\gamma_n]_C = Q[\beta_1,...,\beta_n]_B = Q(P[\alpha_1,...,\alpha_n]_A) = QP[v]_A$ WRONG
Attempt 2:
Let $P = ([w_1]_A,..,[w_n]_A)^{-1}$ be a transition matrix from basis A to B, where each column is filled with corresponding vector $w_i\in B$ in base A. The same with Q: $Q = ([u_1]_B,..,[u_n]_B)^{-1}$
The transition matrix we're looking for is $M = ([u_1]_A,..,[u_n]_A)^{-1} =_{(1)} (P^{-1} * Q^{-1})^{-1} = QP$
wrong again??
In transition (1) I used the fact that $P^{-1}$ is a transition from basis $B$ to $A$, and that $Q^{-1}$ is the set of base vectors of $C$.
I will be grateful for any help as I'm very frustrated with this problem.

A: Given a vector $[x_1, \ldots, x_n]^T$ expressed in basis $A$ (which is to say, our vector is equal to $x_1a_1+\cdots+x_na_n$), then $P^{-1}[x_1, \ldots, x_n]^T$ is going to be the same vector expressed in basis $B$.
Similarly, given a vector $[y_1,\ldots, y_n]^T$ expressed in basis $B$, $Q^{-1}[y_1, \ldots, y_n]^T$ is the same vector expressed in basis $C$.
Now note that this means $Q^{-1}P^{-1}[x_1, \ldots, x_n]^T$ is the first vector expressed in basis $C$. So to translate from $A$ to $C$ we multiply by $Q^{-1}P^{-1}=(PQ)^{-1}$, which makes $PQ$ the transition matrix from $A$ to $C$.
Which is to say, your attempt 1 was very close to the real solution. It's just that we multiply by the inverse of the transition matrix when transitioning between bases. At least according to some conventions for transition matrices.


text:
Q: Weirdness of results in array-style Search function When I put a set of formulas in excel 2013 like this:
A1 = abc
A2 = ac
A3 = bc

B1 = OR(TRUE) = TRUE
B2 = OR(FALSE) = FALSE

B3 = ISNUMBER(SEARCH({"a", "b"}, A1)) = TRUE
B4 = ISNUMBER(SEARCH({"a", "b"}, A2)) = TRUE
B5 = ISNUMBER(SEARCH({"a", "b"}, A3)) = FALSE

Yet if I add an OR function in the formulas :
C1 = OR(ISNUMBER(SEARCH({"a", "b"}, A1))) = TRUE
C2 = OR(ISNUMBER(SEARCH({"a", "b"}, A2))) = TRUE
C3 = OR(ISNUMBER(SEARCH({"a", "b"}, A3))) = TRUE

Logically the input reveived by the OR function in cell C3  is supposed to be FALSE (see B5 and compare it with B2) yet it resulted in TRUE when it supposed to result in FALSE. I want to know why is this happening? Is there an explanation for this?  And does this happen in all version of excel after 2007?
Another interesting fact is that if I take the result in B5 as the direct input of an OR function like so:
C4 = OR(B5) = FALSE

It resulted in FALSE yet it is basically the same formula as C3. Why does this inconsistency happens? Is it a bug?
Updated question
According to the answers below, the OR function is an "array-friendly" function. What does that exactly mean? And how would a beginner like me know which function in excel are "array friendly" and which are not? Is there a list as such?
Also does this mean that the SEARCH and ISNUMBER function aren't "array friendly"? Yet it accepts "array" as an argument. I'm confused.

A: OR can take multiple arguments, or evaluate all items from an array...
ISNUMBER(SEARCH({"a","b"}, A3)) returns a single value in context of displaying formula result in a single cell, but it returns an array in array-friendly context such as inside OR (I don't know the exact name of this feature though.)
OR({FALSE, TRUE}) is TRUE, similar to OR(ISNUMBER(SEARCH("a", A3)), ISNUMBER(SEARCH("b", A3))).

Update after changing the question:
All of the intermediate functions must be array-friendly for this to work (I believe most functions are, but I am not aware of any list - you have to do some research yourself, this is not paid support).
The single cell output is NOT array friendly. When a result is an array, e.g. {TRUE, FALSE} and it's displayed in a single cell, only the first value will be visible in the cell.
More on array formulas where 1 formula can be inserted into multiple cells: https://support.office.com/en-us/article/create-an-array-formula-e43e12e0-afc6-4a12-bc7f-48361075954d


text:
Q: python: get objects imported from __all__ variable Contents of module.py:
__all__ = ["A", "B"]

class A(object):
    ATTRIBUTE = 'a'

class B(object):
    ATTRIBUTE = 'b'

My goal is to import this module and create the following dict: {'a': A, 'b': B}, mapping the ATTRIBUTE of each class to the class itself. The catch is that I don't know the names of the classes, so I cannot simply do: from module import A, B. However, I do know that all the classes I want should be stored in the __all__ variable.
I tried the following code, which works, but it looks ugly, I wonder if there is a more pythonic way to get my expected output?
Contents of main.py:
import module
from module import __all__ as module_all

if __name__ == '__main__':
    data = {}
    for obj_str in module_all:
        obj = eval("module.{}".format(obj_str))
        data[obj.ATTRIBUTE] = obj
    print(data)

Output:
{'a': <class 'module.A'>, 'b': <class 'module.B'>}


text:
Q: Why I am not been able to close any question?
Possible Duplicate:
What is a "closed" question?

Once I got close link in questions after getting enough rep on Stack Overflow but once I voted a question to close it and the link is gone forever. Now I never seen close link below any question Why?
Edit
Its my mistake I have seen some times the link below some questions during my question may be and i try to click on it and vote for close so I post question here

A: At your reputation level, you can only see the vote-to-close dialog on your own questions. You don't get the privilege for all questions until you reach 3,000.


text:
Q: Hibernate & Spring Roo: org.hibernate.PersistentObjectException: detached entity passed to persist I'm using Spring Roo to generate an entity based on a table(created on the MS SQL Server). The following is my sql script:
CREATE TABLE [dbo].[JMSMessage](
     [MessageID] [nvarchar](100) NOT NULL,
     [Destination] [varchar](50) NOT
     [Status] [varchar](15) NULL,
CONSTRAINT [PK_JMSMessage] PRIMARY KEY CLUSTERED
(
    [MessageID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Java entity generated by Spring Roo is
@Entity
@Table(schema = "dbo",name = "JMSMessage")
@Configurable
public class Jmsmessage {

    @Column(name = "Destination", length = 50)
    @NotNull
    private String destination;

    @Column(name = "Status", length = 15)
    private String status;

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "MessageID", length = 100)
    private String messageId;

    public String getMessageId() {
        return this.messageId;
    }

    public void setMessageId(String id) {
        this.messageId = id;
    }

    @PersistenceContext
    transient EntityManager entityManager;

    public static final EntityManager entityManager() {
        EntityManager em = new Jmsmessage().entityManager;
        if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
        return em;
    }

    public static Jmsmessage findJmsmessage(String messageId) {
        if (messageId == null || messageId.length() == 0) return null;
        return entityManager().find(Jmsmessage.class, messageId);
    }

    @Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

    @Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Jmsmessage attached = Jmsmessage.findJmsmessage(this.messageId);
            this.entityManager.remove(attached);
        }
    }

    @Transactional
    public void flush() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.flush();
    }

    @Transactional
    public void clear() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.clear();
    }

    @Transactional
    public Jmsmessage merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        Jmsmessage merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}

Then when i run the following code to create an entity instance and try to persistent it, the program throws an PersistentObjectException saying "detached entity passed to persist".
Jmsmessage message = new Jmsmessage();
message.setMessageId("m1");
message.setDestination("queue1");
message.setStatus("status1");
message.persist(); // If i use message.merge(), it will throws another Sql exception saying "Cannot insert the value NULL into column 'MessageID'"

How can i make the persistent work, any suggestions? Thanks in advance!

A: You should not set a value for messageId, because you have the strategy to @GeneratedValue(strategy = GenerationType.AUTO)
On another note, I notice that you have used the active record pattern that roo provides. I suggest that you change this to the DAO pattern since code like this in very uncommon in the Java/Spring/Hibernate world :)

A: You have ID generation strategy auto but you have assigned some id value in your entity. Meaning ORM engine will consider your fresh entity as detached entity since it got id and it will throw exception like trying to save detached entity.. if you try to merge the entity to overcome the problem , ORM engine will check the id you provided to the entity and it will not able to match any row against your entity since there is no such row with that primary key..
Bottom line of the error is, you are confusing the ORM engine with Id generation.
Hope This is helpful!


text:
Q: Problem with displaying array length correctly In an Angular project, I want to loop through filterLifePolicies array because I want to pass via URI the LobDsc property.
The problem is that I also want to output as a number the length of the array but because I loop through each element if the array contains e.g.
3 objects, 3 cards are displayed...I only want one card with the number 3 (array length).
HTML:

Ζωή & Υγεία

{{countLife}}

Part of Typescript:
getCustomerPolicies () {

    this.http.get<any>('http://localhost:8080/o/mye/pol').subscribe({
    next: res => {

    this.filterLifePolicies = res.Life.Policies;
    console.debug(this.filterLifePolicies);
    this.countLife = this.filterLifePolicies.length;

A: You can do the following, considering countLife variable is assigned the required value.

  <ng-container *ngFor="let policy of filterLifePolicies; index as i">
    <a *ngIf="i < 1" [routerLink]="['/contracts', policy.LobDsc]" routerLinkActive="active" class="noLinksDecoration">

Ζωή & Υγεία

  </ng-container>

{{countLife}}

In the above code snippet, ng-container is being used to iterate through filterLifePolicies in order to access LobDsc value. Since the iteration should not create duplicate HTML div elements with CSS class card-body, an additional check via ngIf is being used to check the index value, such that it should be always lesser than 1.
Although if the LobDsc value is the same for all the values of filterLifePolicies, the recommended approach would be to fetch its value via the dot notation and store it in a variable that can be later binded directly to your template during runtime.


text:
Q: Facebook Graph API: Get user city (location) I have currently implemented facebook login and taking access of user's location. Like this:
    user.profile.city = auth.info.location

I need only city of user, but location gives city and state. As per permission docs, location is user's city. But it is giving state too.
How to get only city? Is there any way?

A: https://developers.facebook.com/tools/explorer/
Try with Graph API Explorer : /me
gives the location and home town only with city and state, NOT the zipcode, country, etc.,
FB.api('/me', function (json) {
    var fid = json.id;
    var sCity = '';
        var sState = '';
    if (json.location !== undefined && json.location.name !== undefined) {
            var sLoc = json.location.name;
        var aLoc = sLoc.split(',');
        if (aLoc.length > 0) {
            sCity = aLoc[0];
        }
        if (aLoc.length > 1) {
            sState = aLoc[1];
        }
    }
});

A: I assume that you are using some gem like omniauth, omniauth-facebook
Try this:
 user.profile.city = auth.info.location.split(",")[0]

since for example
`auth.info.location` value = location: Olongapo City, Philippines

using the provided code it will return Olongapo City

A: Do this:
SELECT current_location FROM user WHERE uid=USER_ID

Example: https://developers.facebook.com/tools/explorer?fql=SELECT%20current_location%20FROM%20user%20WHERE%20uid%3D4


text:
Q: How to get wordpress post with flutter How can i get the post information on my mobile app, which was added from my website using flutter and show in listview?
vist http://heratexchangeunion.com/wp-json/wp/v2/exchanger

A: here are two plugins you can use :
https://pub.dev/packages/flutter_wordpress
https://pub.dev/packages/wordpress_api
CODE EXAMPLE
import 'package:flutter_wordpress/flutter_wordpress.dart' as wp;

wp.WordPress wordPress;

wordPress = wp.WordPress(
  baseUrl: 'http://localhost',
  authenticator: wp.WordPressAuthenticator.JWT,
  adminName: '',
  adminKey: '',
);

Future<wp.User> response = wordPress.authenticateUser(
  username: 'ChiefEditor',
  password: 'chiefeditor@123',
);

Future<List<wp.Post>> posts = wordPress.fetchPosts(
  params: wp.ParamsPostList(
    context: wp.WordPressContext.view,
    pageNum: 1,
    perPage: 20,
    order: wp.Order.desc,
    orderBy: wp.PostsOrderBy.date,
  ),
  fetchAuthor: true,
  fetchFeaturedMedia: true,
  fetchComments: true,
);