text:
Q: If the Earth left the solar system for interstellar space. How long would it take for atmosphere to freeze? If the Earth left the solar system for some reason. Assuming its moving at the same velocity it's currently exhibiting. How long would it take for the atmosphere to freeze. Would we get methane clouds like Titan. Would there be an atmosphere or would it all be frozen on the ground?

A: If you could suddenly drop a big screen between the Earth and Sun, the initial rate of energy loss would equal the total solar energy input:
$$\frac{dE}{dt} = \alpha F A_e .$$
Where $\alpha$ is the mean albedo, which Wolfram puts at $0.37$, the flux is $F = 1400\frac{\text{W}}{\text{m}^2}$, and the radius of the Earth is $R_e = 6.4 \times 10^6\text{ m}$, I get $7 \times 10^{16} W$.
Now, the atmosphere masses roughly $5 \times 10^{18}\text{ kg}$ (Wolfram again), and the heat capacity of Nitrogen gas is $c_p = 30 \frac{\text{J}}{\text{mol K}} = 1070 \frac{\text{J}}{\text{kg K}}$. So the initial cooling will be around $1.3 \times 10^{-5}\text{ K/s}$, or about one Kelvin per day. That rate will drop by the fourth power of the temperature (use absolute units!).
Things left unconsidered:

*

*I've neglected the oceans, and geothermal heat. Both effects will slow things down, the ocean considerable, geothermal, not so much. There is also a great deal of heat in the rock itself, but rock is a much better insulator than water, so it will have a smaller effect in the short term. Still, head into a deep mine or cave to stay warm, and watch out for the mineshaft gap!

*The heat of vaporization of water vapor and the heats of fusion of liquid water and carbon dioxide will slow things down while the phase transitions happen. There will be other phase transitions later on, but they won't matter to the frozen corpses...

*I've used a blackbody approximation which is surely not exact, but it should do for our purposes.

As Omega says in the comments all these factors are mitigating, and the real rate of temperature loss could be a factor of several (maybe even ten) lower than the above calculation. There are a lot of details that really matter, and things will change as the atmosphere changes (more clouds, then less, possible carbon dioxide clouds...) and the oceans freeze over.
However, the fact that the day/night temperature cycle is much larger than the daily change derived above suggests that the temperature near the Earth's surface is only loosely coupled to the mean atmospheric temperature (I guess that's not a big surprise as the surface is probably the warmest part of the atmosphere), so you can expect surface temperatures to drop much more rapidly than than the mean at first. How much faster? Well, like the day-to-night change initially, though I'd guess this will slow pretty quickly.

A: the Earth is emitting thermal radiation corresponding to its temperature, and losing the energy (and decreasing temperature) in this way. Normally, this is cancelled - every day or every year - by the energy coming from the Sun. The second term would be absent in your thought experiment.
So those 342 Watts per meter squared in average coming from the Sun (more precisely, only 250 or so because a part is reflected without any transformation of the energy form anyway, so it's like if it is not coming at all) would disappear from the budget. One needs to estimate the heat capacity of the atmosphere - and the relevant layers of the ocean that are capable to heat the atmosphere above it for a while. But you don't need to be that sophisticated. It's enough to look at the reality of weather - numbers that everyone knows.
In the continental climate, going from day to night lowers the temperature of the atmosphere by 1 Celsius degree in average (cloudiness makes the day-time difference smaller; sunny skies make it larger). Because what you say is just a permanent night, this rate of cooling would simply continue and continue. So the initial rate would be cooling by 1 degree per day or so; it would be slower above the ocean.
As the temperature of the Earth would be going down, the radiation would be dropping as the fourth power of the absolute temperature (in Kelvin degrees). The atmosphere would be getting cooler, partly condensed (if not frozen), and much thinner. So once the absolute temperature decreased by 20 percent (note that $1.2^4$ equals 2 or so) or about 50 Celsius degrees, the rate of cooling would drop to 1/2 of the original one. At any rate, you need a few months to get to minus 50 degrees or something like that. The ocean would still be oscillating for a long time and it would try to unmelt the thinner atmosphere right above it - just like the circulation of water beneath the ice in a pond. Note that deep ocean circulation takes 1,500 years or so.
So of course, the ocean wouldn't freeze over for a very long time. But that's already a different question. Needless to say, heat almost doesn't get beneath the solid ground - kilometers below the rocks, they wouldn't notice that the Sun is gone for thousands of years or much longer.
Best wishes
Lubos

A: Velocity relative to where? Not that crucial though =)
It would take a matter of hours(maybe a few days) if you instantly take it to an empty space. It would take a few weeks if you gradually move away from the Sun. Let me note that as Noldorin said the only way of heat transfer is via radiation, but since Earth is a relatively good radiator, it would not take very long.
There would almost always be an atmosphere because there simply is enough gravity to attract gas, no matter what kind of gas it is. It will surely be dimmer&less dense though. There is not nearly enough methane on Earth to form a methane cycle similar to that of Titan. Titan possesses maybe hundreds of times more methane than Earth.


text:
Q: Toggle classes with radio button in jQuery I have a set of radio buttons where when I click a radio button, I want the label to change color or whatever. But when I click another radio button, the color goes away. Therefore I have something like this:
jQuery('label').mouseup(function(){
   jQuery(this).prev().attr('checked', 'checked');
   jQuery('input').next().removeClass('selected');
   jQuery('input:checked').next().addClass('selected');

});

if you need to see some html:
<input type="radio" id="radio1" name="myRadio" value="option-1" />
Label 1

<input type="radio" id="radio2" name="myRadio" value="option-2" />
Label 2

This first removes 'selected' class from all the labels and then re-applies to only the checked labels.
It works and is simple, but I was thinking this might not be the most efficient way of doing this. I imagine that javascript is iterating through each input element and using more resources than necessary.
I'm curious if anyone knows of a common way of doing this more efficiently. I seem to be doing this type of thing quite often in my jQuery code. I've just been using jQuery for the past 3 months or so btw.

A: There are a few things I think are worth mentioning.
Clicking on a  will automatically change the value of the <input>.  You don't need to set the checked attr manually, and therefore could bind to the change event on the radios instead.  This will also allow keyboard events to select/deselect the radios, and will work anytime the radio values change, not just when someone raises their mouse over a label.
Also, you can save the whole collection of radio inputs in its own variable to make referencing them later not have to search through the DOM again.
Suggested code (w/ jsfiddle preview)
var $radios = jQuery('input[type=radio]');
$radios.change(function() {
   $radios.next().removeClass('selected');
   $radios.filter(':checked').next().addClass('selected');
});

A: Besides the use of mouseup who seems a little bit unusual in this case (at least, to me), your code is fine.
I'd use click or change.

A: It actually looks like it works when clicking the label.  I wouldn't worry too much about the number of DOM elements searched as long as the performance is ok.  Optimize when it becomes a problem and not before.  Clarity/readability is probably more important.  You might be able to improve it, though, by using some information from the label or its related input to narrow down the selectors.  Using end and filter would also allow you to reuse the second query.
$('label').click(function(){
   var radio = $(this).prev();
   radio.attr('checked', 'checked');
   var name = radio.attr('name');
   $('input[name=' + name ']').next()
                              .removeClass('selected')
                              .end()
                              .filter(':checked')
                              .next()
                              .addClass('selected');

});

Note that using change on the actual radios, as some others suggest might be better.  You could use the same techniques with that.
$('input[type=radio]').change( function() {
     $('input[type=radio]').next()
                           .removeClass('selected')
                           .end()
                           .filter(':checked')
                           .next()
                           .addClass('selected');
});

Use live handlers if you are adding radios dynamically to the page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: R: testing whether a coefficient is equal across the different equations in a multivariate regression (using linearhypothesis())? I have a question about how to compare coefficients in a multivariate regression in R.
I conducted a survey in which I measured three different attitudes (scale variables). My goal is to estimate whether some characteristics of the respondents (age, gender, education and ideological position) can explain their (positve/negative) attitudes.
I was advised to conduct a multivariate multiple regression instead of three univariate multiple regression. The code of my multivariate model is:
MMR <- lm(cbind(Attitude_1, Attitude_2, Attitude_3) ~
             Age + Gender + Education + Ideological_position,
           data = survey)
summary(MMR)

What I am trying to do next is to estimate whether the coefficients of let's say 'Gender' are statistically significant across the three individual models.
I found a very clear instruction how to do this in Stata (https://stats.idre.ucla.edu/stata/dae/multivariate-regression-analysis/), but I don't have a license, so I have to find an alternative in R. I know a similar question has been asked here before (R - Testing equivalence of coefficients in multivariate multiple regression), but the answer was that there does not exist a package (or function) in R which can be used for this purpose. Because this answer was provided a few years back, I was wondering whether in the meantime some new packages or functions are implemented.
More precisely, I was wondering whether I can use the linearHypothesis() function (https://www.rdocumentation.org/packages/car/versions/3.0-11/topics/linearHypothesis)? I already know that this function allows me to test, for instance, whether the coefficient of Gender equals to coefficient of Education:
linearhypothesis(MMR, c("GenderFemale", "EducationHigh-educated")

Can I also use this function to test whether the coefficient of Gender in the equation modelling Attitude_1 equals the coefficient of Gender in the equation modelling Attitude_2 or Attitude_3?
Any help would be greatly appreciated!

A: Since the model presented in the question is not reproducible (the input is missing) let us use this model instead.
fm0 <- lm(cbind(cyl, mpg) ~ wt + hp, mtcars)

We will discuss two approaches using as our linear hypothesis that the intercepts of the cyl and mpg groups are the same, that the wt slopes are the same and the hp slopes are the same.
1) Mean/Variance
In this approach we base the entire comparison only on the coefficients and their variance covariance matrix.
library(car)

v <- vcov(fm0)
co <- setNames(c(coef(fm0)), rownames(v))
h1 <- c("cyl:(Intercept) = mpg:(Intercept)", "cyl:wt = mpg:wt", "cyl:hp = mpg:hp")

linearHypothesis(NULL, h1, coef. = co, vcov. = v)

giving:
Linear hypothesis test

Hypothesis:
cyl:((Intercept) - mpg:(Intercept) = 0
cyl:wt - mpg:wt = 0
cyl:hp - mpg:hp = 0

Model 1: restricted model
Model 2: structure(list(), class = "formula", .Environment = <environment>)

Note: Coefficient covariance matrix supplied.

  Df  Chisq Pr(>Chisq)
1
2  3 878.53  < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

To explain what linearHypothesis is doing note that In this case the hypothesis matrix is L <- t(c(1, -1)) %x% diag(3) and given v then as a large sample approximation we have that L %*% co is distributed as N(0, L %*% v %*% t(L)) under the null hypothesis hence t(L %*% co) %*% solve(L %*% v %*% t(L)) %*% L %*% co is distributed as chi squared with nrow(L) degrees of freedom.
L <- t(c(1, -1)) %>% diag(3)
nrow(L) # degrees of freedom
SSH <- t(L %*% co) %*% solve(L %*% v %*% t(L)) %*% L %*% co # chisq
p <- pchisq(SSH, nrow(L), lower.tail = FALSE) # p value

2) Long form model
With this approach (which is not equivalent to the first one shown above) convert mtcars from wide to long form, mt2.  We show how to do that using reshape or pivot_longer at the end but for now we will just form it explicitly.  Define lhs as the 32x2 matrix on the left hand side of the fm0 formula, i.e. cbind(cyl, mpg).  Note that its column names are c("cyl", "mpg").  Stringing out lhs column by column into a 64 long vector of the cyl column followed by the mpg column gives us our new dependent variable y.  We also form a grouping variable g. the same length as y which indicates which column in lhs the corresponding element of y is from.
With mt2 defined we can form fm1. In forming fm1 We will use a weight vector w based on the fm0 sigma values to reflect the fact that the two groups, cyl and mpg, have different values of sigma given by the vector sigma(fm0).
We show below that the fm0 and fm1 models have the same coefficients and then run linearHypothesis.
library(car)

lhs <- fm0$model[[1]]
g. <- colnames(lhs)[col(lhs)]
y <- c(lhs)
mt2 <- with(mtcars, data.frame(wt, hp, g., y))

w <- 1 / sigma(fm0)[g.]^2
fm1 <- lm(y ~ g./(wt + hp) + 0, mt2, weights = w)

# note coefficient names
variable.names(fm1)
## [1] "g.cyl" "g.mpg" "g.cyl:wt" "g.mpg:wt" "g.cyl:hp" "g.mpg:hp"

# check that fm0 and fm1 have same coefs
all.equal(c(t(coef(fm0))), coef(fm1), check.attributes = FALSE)
## [1] TRUE

h2 <- c("g.mpg = g.cyl", "g.mpg:wt = g.cyl:wt", "g.mpg:hp = g.cyl:hp")
linearHypothesis(fm1, h2)

giving:
Linear hypothesis test

Hypothesis:
- g.cyl  + g.mpg = 0
- g.cyl:wt  + g.mpg:wt = 0
- g.cyl:hp  + g.mpg:hp = 0

Model 1: restricted model
Model 2: y ~ g./(wt + hp) + 0

  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     61 1095.8
2     58   58.0  3    1037.8 345.95 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

If L is the hypothesis matrix which is the same as L in (1) except the columns are reordered, q is its number of rows, n is the number of rows of mt2 then SSH/q is distributed F(q, n-q-1) so we have:
n <- nrow(mt2)
L <- diag(3) %x% t(c(1, -1))  # note difference from (1)
q <- nrow(L)
SSH <- t(L %*% coef(fm1)) %*% solve(L %*% vcov(fm1) %*% t(L)) %*% L %*% coef(fm1)
SSH/q # F value
pf(SSH/q, q, n-q-1, lower.tail = FALSE) # p value

anova
An alternative to linearHypothesis is to define the reduced model and then compare the two models using anova. mt2 and w are from above.  No packages are used.
fm2 <- lm(y ~ hp + wt, mt2, weights = w)
anova(fm2, fm1)

giving:
Analysis of Variance Table

Model 1: y ~ hp + wt
Model 2: y ~ g./(wt + hp) + 0
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)
1     61 1095.8
2     58   58.0  3    1037.8 345.95 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Alternate wide to long calculation
An alternate way to form mt2 is by reshaping mtcars from wide form to long form using reshape.
mt2a <- mtcars |>
  reshape(dir = "long", varying = list(colnames(lhs)), v.names = "y",
    timevar = "g.", times = colnames(lhs)) |>
  subset(select = c("wt", "hp", "g.", "y"))

or using tidyverse (which has rows in a different order but that should not matter as long as mat2b is used consistently in forming fm1 and w.
library(dplyr)
library(tidyr)

mt2b <- mtcars %>%
  select(mpg, cyl, wt, hp) %>%
  pivot_longer(all_of(colnames(lhs)), names_to = "g.", values_to = "y")


text:
Q: How do I connect to Google Cloud SQL from Google Compute Engine in production? I have a web application running on Google Compute Engine. I am currently running MySQL on a regular instance, and I want to migrate to Cloud SQL for scalability and reliability.
The GCE docs describe how to connect by Internet IP address or the Cloud SQL Proxy to run the MySQL client to configure a database. They do not describe how to connect to Cloud SQL for a "production" environment that needs to reliably handle a large volume of queries. The Cloud SQL Proxy seems like an elegant solution, because I prefer not to assign external IP addresses to the web servers (they are behind a load balancer), or send database traffic over the Internet.

*

*Which method(s) are considered "production-ready" for connecting a web server to a Cloud SQL instance?

*Is Cloud SQL Proxy suitable for a production application?

*Is traffic encrypted between the Cloud SQL Proxy and Cloud SQL?

A: 1) Either direct connection by IP or via Cloud SQL Proxy.
2) Yes, the Cloud SQL Proxy is production ready.
3) Yes, the connection between the Cloud SQL Proxy and the Cloud SQL instance happens over SSL.


text:
Q: Oracle SQL Missing Years Calculate Last Value and Compound Interest I have the following table in Oracle:

F1
F2
YEAR
AMT

DC1
123
2021
1000

DC1
123
2022
1100

DC1
123
2023

DC1
123
2024

DC2
456
2021
5000

DC2
456
2022
6000

DC2
456
2023

DC2
456
2024

I want to calculate the missing years (YEAR 2023 and 2024) per grouping of F1 and F2 based on the AMT of the last available date (YEAR 2022) and multiply AMT by 2.1% compounding each year.
I've used the LAST_VALUE function
`(LAST VALUE(AMT IGNORE NULLS) OVER (PARTITION BY F1, F2 ORDER BY F1 F2 YEAR ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS NEXT_AMT`

to get the last values per grouping (1100 and 6000), but when I multiply by 2.1%, I don't get the compounding interest effect.
Desired Output:

F1
F2
YEAR
AMT
NEXT_AMT
NEW_AMT

DC1
123
2021
1000

1000

DC1
123
2022
1100

1100

DC1
123
2023

1100
1123.1

DC1
123
2024

1100
1146.68

DC2
456
2021
5000

5000

DC2
456
2022
6000

6000

DC2
456
2023

6000
6126

DC2
456
2024

6000
6254.65

A: Calculate the ratio and then use arithmetic to do the multiplication:
with t as (
      select t.*,
             max(case when year = 2022 then amt end) over (partition by f1, f2) as year_2022,
             (max(case when year = 2022 then amt end) over (partition by f1, f2) /
              max(case when year = 2021 then amt end) over (partition by f1, f2)
             ) as ratio
      from mytable t
     )
select t.*,
       coalesce(amt,
                year_2022 * power(ratio, year - 2022)
               ) as new_amt
from t;

EDIT:
Oops, I misread the question.  You actually have a fixed ratio for incrementing the amount.  That is even easier:
with t as (
      select t.*,
             max(case when year = 2022 then amt end) over (partition by f1, f2) as year_2022
      from mytable t
     )
select t.*,
       coalesce(amt,
                year_2022 * power(1.021, year - 2022)
               ) as new_amt
from t;

I also realize that you might not want to hardcode 2022.  So:
with t as (
      select t.*,
             last_value(case when amt is not null then year end ignore nulls) over (partition by f1, f2 order by year) as last_year,
             last_value(amt ignore nulls) over (partition by f1, f2 order by amt) as last_year_amt
      from mytable t
     )
select t.*,
       coalesce(amt,
                last_year_amt * power(1.021, year - last_year)
               ) as new_amt
from t;

Here is a db<>fiddle.


text:
Q: Where to store images the user has selected from their gallery? So one of the functionalities of the prototype app I'm making allows the user to create a recipe and add a thumbnail and video to it. Once a user has selected an image from their gallery for the thumbnail and a video, how and where should I store it so that it can be retrieved whenever the recipe is viewed again?

A: Here is the code to store an image in the DCIM/ directory

    @Throws(IOException::class)
    private fun saveImage(bitmap: Bitmap, name: String) {
        val saved: Boolean
        val fos: OutputStream?
        fos = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val resolver: ContentResolver = requireActivity().contentResolver
            val contentValues = ContentValues()
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/$IMAGE_DIRECTORY")
            val imageUri =
                resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
            resolver.openOutputStream(imageUri!!)
        } else {
            val imagesDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM
            ).toString() + File.separator + IMAGE_DIRECTORY
            val file = File(imagesDir)
            if (!file.exists()) {
                file.mkdir()
            }
            val image = File(imagesDir, "$name.png")
            FileOutputStream(image)
        }
        saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
        fos!!.flush()
        fos.close()
    }

Then get all the images as a list of URI like so
private fun getAllImages(): List<Uri>
    {
        val allImages = mutableListOf<Uri>()

        val imageProjection = arrayOf(
            MediaStore.Images.Media._ID
        )

        val imageSortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC"

        val cursor = activity?.contentResolver?.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            imageProjection,
            null,
            null,
            imageSortOrder
        )

        cursor.use {

            if (cursor != null)
            {
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                while (cursor.moveToNext())
                {
                    allImages.add(
                        ContentUris.withAppendedId(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            cursor.getLong(idColumn)
                        )
                    )
                }
            }
            else
            {
                Log.d("AddViewModel", "Cursor is null!")
            }
        }
        return allImages
    }

Then query it to find the required image


text:
Q: Separate linux terminal input based on new line using Java I'm trying to separate the terminal input into a Java code based on new lines.
Here is the current code I have.
Scanner sc = new Scanner(System.in);
String initial_input = sc.nextLine();

String[] lines = initial_input.split("\\r?\\n");

for (String line : lines) {
    System.out.println(line);
}

Here is my input:
INSERT KEY adam key\nTURN KEY adam\nENTER HOUSE adam\nINSERT KEY pat foobar\nTURN KEY pat\nENTER HOUSE pat\nWHO'S INSIDE?

It doesn't print lines separately.. instead it print all in one line.
Please provide your suggestions.

A: As split takes a regular expression argument carriage return characters need to be escaped to match characters literally
String[] lines = initial_input.split("(\\\\r)?\\\\n");

A: It should be with  \\\\n
Scanner sc = new Scanner(System.in);
String initial_input = sc.nextLine();

String[] lines = initial_input.split("\\\\n");

for (String line : lines) {
      System.out.println(line);
}

A: You seem to have some misconceptions about regular expressions and text.
As Reimeus said before, you have to escape the pattern once more with two backslashes (\\\\n). That's because what you're typing on the keyboard is just one line of text.
Right here
INSERT KEY adam key\nTURN KEY adam\nENTER HOUSE adam\nINSERT KEY pat foobar\nTURN KEY pat\nENTER HOUSE pat\nWHO'S INSIDE?

This input is just one line. Those \n are not newline characters. They are just two separate characters. One of them containing the backslash character (code 0x5C) and the other containing the n character (code 0x6E).
The actual newline character is just one single character (code 0x0A), represented as \n in source code because the real character is not visible (it's just a mark of a new line).
On the other hand, Scanner.nextLine() reads just one line, until it finds the newline character, that you entered when pressed the ENTER key on the keyboard.
Your code does actually split a text into several lines, but your input is just one line long.
You can either read from a file with several lines in it, or split one line in some strings, taking the backslash and n character as separators.


text:
Q: A confusion on Composition Series. I have just started studying composition series of groups from Dummit and Foote's Abstract Algebra. So, in a group $G$ if we find a finite number of subgroups $N_0, N_1, N_2,...., N_{k-1}, N_k$ such that $${e_G}=N_0\triangleleft N_1\triangleleft N_2\triangleleft ......\triangleleft N_{k-1}\triangleleft N_k=G.....(A)$$, where each $N_{i+1}/N_i$ is simple then $(A)$ is called a Composition Series. Now I have two confusion regarding this and I have clash in two concepts.So, please help me to get the right concept.
(Concept 1) $N_{i+1}/N_i$ is a simple group.So, $N_{i+1}/N_i$ may  contain a nontrivial proper subgroup but may not contain a non-trivial proper normal subgroup,i.e. $N_{i+1}$ may contain proper subgroup $H$ which properly contains $N_i$ but this $H$ can't be normal in $N_{i+1}$,So, we can say that $N_i$ is a maximal normal subgroup of $N_{i+1}$.And (I) $N_i$ is a maximal normal subgroup of $N_{i+1}$, (II) $N_i$ is a normal subgroup of $N_{i+1}$ which is also maximal in $N_{i+1}$,....(I) and (II) are different.Moreover (I) implies(II) but (II)
doesn't imply(I)
(Concept 2) following the wolfram mathworld definition of composition series $N_i$ have to be a normal subgroup of $N_{i+1}$ which is also maximal subgroup of $N_{i+1}$.In this case the simplicity of $N_{i+1}/N_i$ need not to be mentioned as simplicity of $N_{i+1}/N_i$ follows from this maximal subgroup condition.

A: It would seem to me Concept 2 is simply an inaccurate statement in Wolfram Mathworld. For example, if you take a finite simple group of order $60$, it has a trivial composition series, but the maximal subgroups play no role.
The first statement is right: saying that the quotient is simple is the same thing as saying the subgroup is maximal normal.


text:
Q: Listview onTouch within a ListFragment single click not working I a using a Fragment which extends a ListFragment, this then uses an ArrayAdapter in order to create a dynamic list of custom rows (this is all working perfectly).
What I am now trying to do is implement an onTouch event where when the user swipes each row left of right then do something. This logic is all working the only issue is I am having to do the onTouch event as the ACTION_UP does not seem to get called first time.
@Override
public void onListItemClick(ListView l, View v, final int position, long id) {
    super.onListItemClick(l, v, position, id);

    v.setOnTouchListener(new View.OnTouchListener() {
        int initialX = 0;
        final float slop = ViewConfiguration.get(getActivity()).getScaledTouchSlop() * 1.5f;

        @Override
        public boolean onTouch(final View v, MotionEvent event) {
            switch(event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    initialX = (int) event.getX();

                    return true;
                case MotionEvent.ACTION_UP:
                    // Do something here

                    return false;
            }

            return false;
        }
    });
}

I am returning true from the ACTION_DOWN so from my understanding this should indicate to the onTouch event to continue processing touch events and in my above code this will be the ACTION_UP when the user lifts his finger from the screen, not sure what I am missing here.
Further to this if at all possible I would also like to bind an onClick event onto the same view (not essential as already have workaround if I can get above working).

A: You must have used OnTouchListener listener for swiping each rows of listView, make sure that you are returning false on ACTION_UP event.
Parent view receives a call back only when child views have not consumed it. So if each rows of list view is having a onTouchListener, you have to propagate event to parent by returning false.
Hope it will help.


text:
Q: Is it possible to use java ServerSocket to accept HTTPs requests I have the following code, works fine for sending HTTP requests but how do I convert it so that it support HTTPs requests?
    public test() throws Exception {
        ServerSocket ss = new ServerSocket(32567);

        Socket client = null;
        while ((client = ss.accept()) != null) {
           System.out.println("-- Sending --");
           BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
           String s = "<?xml version=\"1.0\" ?><root><message>test</message><status>OK</status></root>";
           String output = "HTTP/1.1 200 OK\nContent-Type: text/xml; charset=UTF-8\nCache-Control: no-cache\nConnection: closed\nAccess-Control-Allow-Origin: *\n\n" + s;
           System.out.println("--- RESPONSE ---\n" +  output);
           out.write(output);
           out.flush();
           out.close();
           in.close();
           client.close();
        }
    }

A: You use javax.net.ssl.SSLServerSocket, but be warned that there is nothing simple about an HTTP server. You need a good knowledge of RFC 2616 and successors.
You also need to know that the line terminator in HTTP is \r\n, not \n.

A: I used this code and works well
  HttpsURLConnection.setDefaultHostnameVerifier(
        new HostnameVerifier() {
           public boolean verify(String hostname, SSLSession sslSession) {
              return true;
           }
        }
  );

  TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
           public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[0];
           }

           public void checkClientTrusted(X509Certificate[] certs, String authType) {}

           public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        }
  };

  SSLContext sc = SSLContext.getInstance("SSL");
  sc.init(null, trustAllCerts, new java.security.SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      char[] keyPassword =  "MY_PASSWORD".toCharArray();
      KeyStore keystore = KeyStore.getInstance("PKCS12");;
      keystore.load(this.getClass().getClassLoader().getResourceAsStream("MY_CERT.p12"), keyPassword);

      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(keystore, keyPassword);
      KeyManager keyManagers[] = keyManagerFactory.getKeyManagers();

      Enumeration aliases = keystore.aliases();
      String keyAlias = "";
      while (aliases.hasMoreElements()) {
          keyAlias = (String) aliases.nextElement();
          System.out.println("KEY FOUND: " + keyAlias);
      }

      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(keyManagers, null, null);

      SSLServerSocketFactory sslContextFactory = (SSLServerSocketFactory) sc.getServerSocketFactory();
      SSLServerSocket ssl = (SSLServerSocket) sslContextFactory.createServerSocket(32567);
      ssl.setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2", "SSLv3"});
      ssl.setEnabledCipherSuites(sslContextFactory.getSupportedCipherSuites());

And the cert is stored in the jar files. The above reads the cert from the jar file instead of passing in from command line -Djavax.net.ssl.keyStore=MY_CERT.p12 -Djavax.net.ssl.keyStorePassword=MY_PASSWORD
Generate your cert by
openssl req -new -newkey rsa:4096 -nodes -out MY_CERT.csr
openssl rsa -in privkey.pem -out MY_CERT.key -passin pass:MY_PASSWORD
openssl x509 -in MY_CERT.csr -out MY_CERT.crt -req -signkey MY_CERT.key -days 3650
openssl pkcs12 -export -inkey MY_CERT.key -in MY_CERT.crt -name localhost -out MY_CERT.p12 -passout pass:MY_PASSWORD -caname root

It is the MY_CERT.p12 only that is need in the jar files (in the root directory of the jar file)


text:
Q: Does $\int_a^b \text{Im}(f(t))e^{int}dt=0$ implies $f=0$ on $[a,b]$ Let $f$ be a complex valued function of a real variable for which
$$
\int_a^b \text{Im}(f(t))e^{int}dt=0 \text{, for all } n.
$$
Is $\text{Im}(f(t))$ identicaly zero on $[a,b]$?
I think the answer is yes, but I don't know why.

A: It is about the $L_2[a,b]$ function space: http://en.wikipedia.org/wiki/L2_space
Probably it is important that $a$ and $b$ are multiples of $\pi$.
The key is that the $\varphi_n:=t\mapsto e^{int}$ functions generate the $L_2$ space: form an orthogonal base in the sence that every $f\in L_2$ can be uniquely written in the (potentially infinite) sum:
$\sum_n \alpha_n\cdot\varphi_n$ for some $\alpha_n\in\mathbb C$.
Then, using the "scalar product" $\langle \varphi,\psi\rangle := \int_a^b \overline\varphi\cdot\psi$, we basically arrive that your $f$ is   orthogonal  to all base vector $\varphi_n$.


text:
Q: f(2x + 1) transformation I was working on a problem that asked:

If there is a vertical asymptote at $x = 5$ for $f(x)$, where is the vertical asymptote for $f(2x + 1)$?

The correct answer is at $x = 2$, but this confused me because the transformation would seem to suggest that the asymptote was at $5/2 - 1$, or $1.5$. Only when the $+ 1$ part of the transformation is done first does the correct answer of $x = 2$ result, but this seems to violate the order of operations. Can someone explain?

A: Let $y=2x+1$. Then $f(y)$ has an asymptote at $y=5$ (given). So the asymptote of $f(y)$ is at
$$ 2x+1=y=5. $$
Solving, we find $x=2$.

A: You can think of a vertical asymptote being a value of $x$ for which the function has a problem. Think of $\tan (90^{\circ})$ or $\frac 10$ - old calculators would say "Math error."
Your function has a problem when the input value $x$ is equal to $5$.
Your transformed function will have a problem when $2x+1=5$, which gives $x=2$. So the asymptote is now at $x=2$.

A: To make the function $f(2x+1)$ more analytical we  need to express it as follows
$$f(2(x+\frac{1}{2}))$$
This suggests that we perform the transformation by compressing horizontally by a factor of 2, and then shifting to the left by $\frac{1}{2}$. Compressing $5$ by a factor of $2$, we get $5/2$, and then shifting to the left by $1/2$ we get $2$.
This is easily seen by looking at a one-to-one portion of the function $f(2x+1)$, and turning it inside out (algebraically).
$$\begin{array}{lll}
g(x)&=&f(2x+1)\\
f^{-1}(g(x))&=&2x+1\\
f^{-1}(g(x))-1&=&2x\\
\frac{1}{2}(f^{-1}(g(x))-1)&=&x\\
x&=&\frac{1}{2}f^{-1}(g(x)) - \frac{1}{2}\\
\end{array}$$
Now it is a bit easier to see why "$x$" becomes compressed and (in this form) shifted downwards (because we are now looking at $x$ on the vertical axis). That downward shift becomes a leftward shift when we place $x$ again on the horizontal axis.
Now lets go back the other way, this time, expressing $f$ in a more analytical form.
$$\begin{array}{lll}
x&=&\frac{1}{2}f^{-1}(g(x)) - \frac{1}{2}\\
x+\frac{1}{2}&=&\frac{1}{2}f^{-1}(g(x))\\
2(x+\frac{1}{2})&=&f^{-1}(g(x))\\
f(2(x+\frac{1}{2}))&=&g(x)\\
g(x) &=& f(2(x+\frac{1}{2}))\\
\end{array}$$

A: Note that it isn't the same $x$. Therefore, if for $x_0$ there is an asymptote for $f(x),f(x_0)$, then this same $f(x)$ at point $x_1=2 x_0 + 2$, there is also the asymptote. So $x_0 = 5$ and $x_1=2x_0+1$, then $x_1 = 2$.

A: The problem just boils down to figuring out where $2x + 1 = 5$. You're just setting
\begin{align*}\text{input of } f &= \text{location of old asympote}\\
2x + 1 &= 5
\end{align*}
since you know $f$ has an asymptote at $x = 5$.
Remember that you can solve an equation in any order you'd like; the order of operations only tells you how to do arithmetic.
You could solve using the sequence of steps
\begin{align*}
2x + 1 &= 5 \\
x + 1/2 &= 5/2 \tag{divide by 2}\\
x &= 5/2 - 1/2 = 2, \tag{subtract 1/2}
\end{align*}
or by doing the usual thing and subtracting $1$ first, then dividing by $2$.

A: You could also make up an example for a function that gives you an x asymptote of 5 to begin with. The most simple function would be
f(x) = 1/(x-5)
You now apply the transformation f(2x+1) into the original function.
You get f(2x+1) = 1/(2x+1-5)
f(2x+1) = 1/(2x-4)
Then solve for denominator = 0 since we can never divide by 0 to get your asymptote.
2x - 4 = 0
x = 2
Voila


text:
Q: How to query @JoinTable in Spring Data Jpa? I used the Type filter in BookRepository, but it's not work.
Book.java
@Entity
public class Book {
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinTable(
            name = "book_type",
            joinColumns = @JoinColumn(name = "book_id"),
            inverseJoinColumns = @JoinColumn(name = "type_id")
    )
    private Type type;

    // getter and setter
}

Type.java
@Entity
public class Type {
    private Long id;
    private String name;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "book_type",
            joinColumns = @JoinColumn(name = "type_id"),
            inverseJoinColumns = @JoinColumn(name = "book_id")
    )
    private Collection<Book> books;

    // getter and setter
}

BookRepository.java
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
    Page<Book> findBookListByType(Type type, Pageable pageable);
}

Is not Spring Data Jpa does not support this feature.

A: Try this
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

    @Query(value="Select b from Book b where b.type = :type")
    Page<Book> findAllByType(@Param("type") Type type, Pageable pageable);

}

A: Since you only have one @OneToMany associations, you can change the FetchType to EAGER.


text:
Q: If a request is changed to POST, then SoapUI changing all other requests into POST method A testcase contains 2 requests and 1 groovy script.
Now 1st request is using POST method and 2nd request is using GET method.
Now I am facing an issue that If I am changing the 2nd request as GET, my 1st request also gets turned into GET request while I need 1ST Request to remain as POST.
How to handle this situation?
I am new in Soap UI. any suggestion will be helpful.

A: You can create multiple methods under the same endpoint - this is what REST is designed to do!
Under your "Api" resource, right-click, and select "New Method". Select this new one to be of type GET. This is going to be your "CheckingResponse". So the final hierarchy for your endpoint will look like:
REST Project 1
+-[REST] http://endpoint.URL/...
  +-Api [] <--- THIS IS A RESOURCE
    +-[POST] Api <--- THIS IS YOUR CURRENT METHOD
    | +-3LevelProducts
    +-[GET] Api <--- THIS IS A NEW METHOD
      +-CheckingResponse

A: Refer my answer here:-
http://stackoverflow.com/questions/34786729/if-a-request-is-changed-to-post-then-soapui-changing-all-other-requests-into-po/34831359#34831359

there I have described a full example to achieve the issue


text:
Q: Display GridView with many columns as two sets of columns I apologize for the odd title. I've been trying to figure out how to do this and can't quite put it into words. Basically, I need to try to display a GridView with a whole bunch of columns (37 in one case) in two "rows" of columns. More or less.
So instead of this:
Column1 Column2 Column3 Column4 Column5 Column6
Data    Data    Data    Data    Data    Data
Data    Data    Data    Data    Data    Data
Data    Data    Data    Data    Data    Data

I'd like something like this:
Column1 Column2 Column3
Data    Data    Data
Data    Data    Data
Data    Data    Data

Column4 Column5 Column6
Data    Data    Data
Data    Data    Data
Data    Data    Data

As in the example there can be multiple rows returned which all need to be displayed. I'm trying to stop a very large horizontal scroll bar being required. I've been searching as much as I can but haven't found anything that fits what I'm looking for. Any help would be appreciated.

A: I'd use 2 gridviews. I'd fetch the data in the code behind and cache it in a datatable. I'd then make 2 dataviews - the 1st one taking the 1st 3 columns; the 2nd one showing the last 3 columns. And then pass dataview1 to gridview1 and dataview2 to gridview2 and databind.
alternatively,
If you are simply worried that the page might overflow with horizontal scrolling, put the gridview in a div tag with style overflow scroll
<div style="overflow:scroll; width:95%">
<!-- gridview goes here -->
</div>


text:
Q: Bash script in cron job - email when a file has been modified I looked at this topic to write a bash script that checks if a file has been modified every 60 min and sends me an email using ssmtp if that is the case. Here is its content (monitoring.sh):
#!/bin/bash

[[ -z `find /home/myuser/sites/mysite/logs/nginx/error.log -mmin -60` ]]

if [ $? -eq 0 ]
then
    echo -e "nothing has changed"
else
    echo -e "Something went wrong!" | ssmtp -vvv myemail@gmail.com
fi

I then added this script to an hourly cronjob:
 01 * * * * /home/myuser/sites/mysite/logs/nginx/monitoring.sh

This does not work at all. Looking at my emails (the sender account that ssmtp uses), the script runs every hour and echoes nothing has changed even if the error.log file has been modified.
Maybe using inotifywait would be more appropriate? Any ideas?
Thanks in advance.
EDIT: If I run this script manually after modifying the error.log file, it works and I receive the email.

A: The -mmin option as you used it matches an exact number of minutes, not a "within this range" number of minutes. See this example:
$ touch foo
$ find . -mmin 1
.
./foo
$ find . -mmin 10
$

What you want is to use a value of -10 instead of 10:
$ touch foo
$ find . -mmin -10
.
./foo

And you'll probably want to give it the -type flag as well to only match files, not directories:
$ find . -type f -mmin -10
./foo


text:
Q: issue with invalid literal for int() with base 10 I was asked to write a program that accepts from the user 10 and only int and positive numbers (bigger than 0), and prints the maximum.
I wrote a lot of programs that gave me the maximum number from those 10 the user inserts, but when i entered negative numbers it also gave me the max of them, something that is wrong, and when i put float numbers, it comes with an error
invalid literal for int()with base 10

Any suggestions to write a correct program?

A: The "invalid literal" error is int()'s way of saying "I don't understand what you typed".
the int() function only understands numbers (in different bases/counting systems by the way, see the python int() doc).
If you want to 'protect' agains users typing in comma-numbers, wrap it like so:
int(float(userinput))

This will first make the user-input into a fractional-number, then into an int.
Beware that float() is picky about "," vs. "."
float("3.4") # gives 3.4
float("3,4") # throws "ValueError: invalid literal for float(): 3,4"

The test if the number is negative can come afterwards by checking the parsedNumber >= 0
It is mathematically perfectly valid to ask for 'the highest number of -1, -2 and -3', so the python built-ins won't do that for you. You have to add that criterium by hand (see also @AlexChumley's answer.)
max(-1, -2, -3)

returns -1, the 'highest' number, where 'highest' means 'closest to positive infinity'

A: Here's some code that does what you're asking. However, you are a bit unclear on what you want to code to do in the case of negative or non-integer input. I just threw an Exception:
def find_max(my_list):
 for x in my_list:
   if x<0 or type(x) != int:
     raise Exception("You must input positive integers!")
 print max(my_list)


text:
Q: Refresh tab from another tab I have an Activity that contains a ViewPager with four tabs .
each tab has a fragment.
When I click something in tab 4, I want tab 3 to refresh(or access a non-static method in tab 3 ) ..I've searched but all I found had this in it:
FragmentB fragment = (FragmentB)getFragmentManager().findFragmentByTag("FragmentB");

and I can't use it since I never set a tag on the fragment.
I also could call a function from fragment in another fragment but it has to be static , and I don't want that since everything inside it must be static too and that would mess things up for me..
is there a solution to this ?

A: First of all i think it's not a good practice to update a view which user cannot see on screen at the moment. It's much better to update your data when user navigates to screen. By the way it not our first concern now.
I'm not sure this is still a valid way to find Fragments in a ViewPager byTag but you can find them like below:
This method generates default Tag for a Fragment in ViewPager.
@NonNull
public static String generateViewPagerFragmentTag(int viewPagerId, int position) {
    final StringBuilder tagBuilder = new StringBuilder();
    tagBuilder.append("android:switcher:");
    tagBuilder.append(viewPagerId);
    tagBuilder.append(":");
    tagBuilder.append(position);
    return tagBuilder.toString();
}

Than you can use this tag to find your Fragment with findFragmentByTag method.
Also as mentioned in comments you can use an EventBus library to achieve what you want to do but be careful of Fragment Lifecycle states in ViewPager because the Fragment you want to communicate can be in onPause state an your changes canned be received. This depends on in which lifecycle method you subscribe and unsubscribe to bus. (If you are using OttoBus you can get no subscribers found for this event exception.) You can do same pattern with interfaces. You can create an interface and implement in your Fragments.
For an other solution, you can directly access our fragments in your ViewPager. Here's my answer for another question it.
Finally, as i mentioned at the beginning i think you should implement a solution which updates your data when user switched to specific tab of ViewPager. You can keep your data changes in a mem-cache and listen tab changes and update your view when user exactly navigated to that screen and ready to see data changes. You can check Repository pattern for a more complex solution.


text:
Q: Grouping with geojson in mongodb I have an mongodb collection that contains document in form of
{ "name":"test","city":"c1","geom":{"type": "Point","coordinates":[66,33]} }
{ "name":"test","city":"c1","geom":{"type": "Point","coordinates":[77,22]} }

now i want to group geometries by city name and create a POLYGON feature i cant figure out how can i achieve this and weather mongodb support this or not. If i try to craete an aggregate on geom it throws "The field 'geom' must be an accumulator object

A: You need to use accumulator operators.
Restrictions:

*

*Closed LineStrings have at least four coordinate pairs and specify the same position as the first and last coordinates.

*For Polygons with a single ring, the ring cannot self-intersect.

db.collection.aggregate([
  {
    $group: {
      _id: {
        city: "$city",
        name: "$name"
      },
      coordinates: {
        $push: "$geom.coordinates"
      }
    }
  },
  {
    $project: {
      _id: 0,
      city: "$_id.city",
      name: "$_id.name",
      type: "Polygon",
      coordinates: [
        "$coordinates"
      ]
    }
  }
])

MongoPlayground | Valid Polygon


text:
Q: How to pass css styles to plugins in Vue? I use Vue-Editor.
<vue-editor id="editor" ref="editor" v-model="content" :use-custom-image-handler="true" @image-added ="added" @image-removed ="deleted" :key="componentKey"/>

On mobile devices, the icons are to small. I like to increase the icons size on mobile devices, but on medium devices, I like to keep the default size.
If I do it in this way, the size changes for all pages not only for the current page:
<style>
.p {
    color: black
}

.ql-snow.ql-toolbar button {
    height: 35px !important;
    width: 35px !important;
}

.quillWrapper .ql-snow.ql-toolbar button svg {
    width: 35px !important;
    height: 35px !important;
}
</style>

If I do it with <style scoped> it doesn't pass the css to the plugin component.
How I can change the css for the plugin only in one Vue component without having a global effect?

A: You can keep scoped but then, you need to make a deep selector like >>> .ql-snow.ql-toolbar button to select the 3rd party library.
If using SASS, use ::v-deep, more details here.


text:
Q: Block TripAdvisor pop-ups in Chrome tripadvisor.com has very annoying pop-ups that appear after certain clicks. How can I block them? I use Chrome and already have the AdBlock Plus extension installed, subscribing to Fanboy's Adblock list - that doesn't block it. I've even added personal filters for the following URLs:
www.tripadvisor.*/CommercePopunderEnhanced*
www.tripadvisor.*/ExitWindowEnhanced*

but the pop-ups still come up. Surely there is some extension that will let me specify: never show any pop-up for this domain?


text:
Q: Is there a max number of devices that adb can detect I was wondering if there is a maximum number of devices that android adb tools can detect? I didn't find any answer on Google. I already connected 13 devices successfully but I don't know if it still working for more devices.
Thanks.

A: It seems that there is no adb limit but there is an usb controller limit depending of your controller (~10 devices/controller).


text:
Q: How can i distribute an iOS product application through Appstore or using any other medium to multiple clients? We are having a product application and need to distribute it to multiple clients with different themes n colours. Currently we are uploading these multiple targets to our own apple itunes accounts and releasing on Appstore. These apps are publicly available and only the users purchasing the product can login to the application. Recently  submitted applications were rejected from appstore review due to the reason "During our review, we still found that this app was designed for a specific business or organization and not for general distribution on the App Store. Business apps available on the App Store are meant for use by a wide variety of external customers around the world. " .
How can i overcome this situation?.
Can we solve this issue by using a Single enterprise account?


text:
Q: Indexing instances in AWS cloudformation auto scaling group I am trying to setup a AutoScalingGroup and somehow index instances in it. I need unique hostnames for:

*

*DNS

*Configuration management

This is easy with OpenStack HEAT - ResourceGroup (just use %index%) but I am struggling in AWS world with similar functionality...
So basically what I need is for example:
hostname-0, hostname-1, hostname-2... etc

A: You should be able to execute a script in the user-data of each instance that sets the instance's hostname [1] based on some logic. Instead of changing the hostname you could set the instance's "Name" tag value [2]. You could then use the AWS CLI or API to get the hostname from the "Name" tag. This may be simpler if your use-case permits it.
[1] http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-hostname.html
[2] http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html

A: This might be a new feature since the OP happened, but you can access this via meta-data after launch:
curl -s http://169.254.169.254/latest/meta-data/ami-launch-index
Docs:
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html


text: Q: OSX NSVisualEffectView Decrease Blur Radius I have an NSVisualEffect with as the background for my mac app. I want the visual effect view to blur whatever it is over, but the vibrant dark is just looks like a black view. How do I decrease the blur radius so that I can see the background more clearly. If this is not possible is NSVisualEffect, then how do I do it? Thanks.


text:
Q: With rails, how do I find objects NOT in a Has Many Through collection? Let's say an article has many tags through taggings.
Article
   has_many :taggings
   has_many :tags, :though :taggings
end

@article.tags #gives all the tags for that article
How do I find all the tags that this article does NOT have?
Thanks

A: The only way I can think of to do this using Rails finders would be to do two queries and subtract:
class Article
  def unused_tags
    Tag.all - self.tags
  end
end

Alternately, you could do this through SQL (which would be more efficient since you'd be only getting rows that you want):
query = <<-eos
SELECT *
FROM tags AS t
WHERE NOT EXISTS (
  SELECT 1
  FROM taggings
  WHERE article_id = ?
    AND tag_id = t.id
)
eos
Tag.find_by_sql [query, article.id]

A: Here's what I came up with:
 class Article
    def missing_tags
       Tag.find(:all, :conditions => ['id NOT IN (SELECT taggings.tag_id FROM taggings WHERE (taggings.article_id = ?))', self.id])
    end
 end

@article.missing_tags


text:
Q: What version of Jacoco should I be using with gradle / sonarqube? So I have:
plugins {
...
    id "org.sonarqube" version "2.0"
    id "jacoco"
}

and also...
jacoco {
    toolVersion = "0.7.1.201405082137"
}

and I'm getting...
Caused by: java.io.IOException: Incompatible version 1007.

Does this mean I have the wrong toolVersion and if so, what is the correct setting?
The server version I am targeting is 5.3.

A: We also had a hard time to find a version of JaCoCo compatible with all the toolchain. We found that version 0.7.5.201505241946 is working fine.


text:
Q: Google Sheet: IMPORTXML from Yahoo Finance I'm trying to import current stock price from yahoo finance. I used a formula from some website and it partially work. I only know how to tell it to look for a specific query and it worked fine for some other data point I need but the price change query changes from
"Fw(500) Pstart(10px) Fz(24px) C($dataRed)"

to
"Fw(500) Pstart(10px) Fz(24px) C($dataGreen)"

depending if the price is up or down for the day.
How do I modify the formula I'm using below to use the "or" operator in this case? so that it will pull the price down whether the stock is up or down for the day. Thanks!
Formula I'm using:
=IMPORTXML("https://finance.yahoo.com/quote/IBM","//span[@class='Fw(500) Pstart(10px) Fz(24px) C($dataRed)']")

A: I noticed the other answers did not work for me (they may have worked in the past), so I decided to post this solution. Just put the ticker in cell A1 and one or both of the below formulas somewhere else.
Price:
=IFNA(VALUE(IMPORTXML("https://finance.yahoo.com/quote/" & A1, "//*[@class=""D(ib) Mend(20px)""]/span[1]")))

Change:
=IFNA(VALUE(REGEXEXTRACT(IMPORTXML("https://finance.yahoo.com/quote/" & A1,"//*[@class=""D(ib) Mend(20px)""]/span[2]"), "^.*?\s")))

A: Currently using googlefinance but find it does not update often enough even when updates set to every minute so currently testing if below will allow updates at least with an F5 press within the sheet
This brings in the price and other information (dated 2022/09/27)
=IMPORTXML("https://finance.yahoo.com/quote/SAVA/", "//*[@id=""quote-header-info""]/div[3]/div[1]/div[1]")

A: If you just want the price: =IFNA(VALUE(IMPORTXML("https://finance.yahoo.com/quote/" & $A1, "//*[@class=""D(ib) Mend(20px)""]/span[1]")))

A: You could use a more dynamic/generic xpath that doesnt require such specific paths such as this:
This one pulls in both the price and the change:
=ARRAY_CONSTRAIN(transpose(IMPORTXML("https://finance.yahoo.com/quote/IBM:,"//*[@class='Mt(6px)']//span")),1,2)

If you just want the price:
=trim(IMPORTXML("https://finance.yahoo.com/quote/IBM","//*[@class='Mt(6px)']//span"))

If you just want the change:
=IMPORTXML("https://finance.yahoo.com/quote/IBM","//*[@class='Mt(6px)']//span[2]")

A: Sadly Yahoo Finance changes the XML/HTML structure of its website quite often. The one that works for now is:
=IMPORTXML("https://finance.yahoo.com/quote/IBM/", "//*[@id=""quote-header-info""]/div[3]/div[1]/div/span[1]")

You may always open the HTML structure and use the developer tools to find and copy the X-path.
P.S.1. Though there seem to be a bug and the function can't retrieve data from URLs where there is a dot/point/period "." in the name.
P.S.2. The IMPORTHTML() function can't also fetch the latest price from Yahoo Finance because the information is neither in a table nor a list. You can try the scripts from this page and this page to list all the tables and lists.


text:
Q: Delete text contained by bookmarks that are hidden I created a template in which, based on the values of the specific checkboxes (content controls), paragraphs that are selected with bookmarks having the same name as the checkboxes are hidden using the following formula
Dim bookmark As String
Dim ctl As ContentControl
For Each ctl In ActiveDocument.ContentControls
    If ctl.Type = wdContentControlCheckBox Then
        If ctl.Checked = False Then
            bookmark = ctl.Tag
            Bookmarks(bookmark).Range.Font.Hidden = True
        Else
            bookmark = "hide_" & ctl.Tag
            Bookmarks(bookmark).Range.Font.Hidden = True
        End If
    End If
Next

I am trying to strip the document of the paragraphs that are using the above mentioned formula (delete them).
I am trying to strip the document of the hidden paragraphs because I want to number the paragraphs and, without deleting them, the numbering refers to the hidden ones.
Using find and replace with hidden font doesn't help because it's a different type of hidden content. I think the bookmarks are saved in xml code.

A: Try:
Dim CCtrl As ContentControl
For Each CCtrl In ActiveDocument.ContentControls
  With CCtrl
    If .Type = wdContentControlCheckBox Then
      If .Checked = False Then
        ActiveDocument.Bookmarks(.Tag).Range.Delete
      End If
    End If
  End With
Next


text:
Q: Why install gcc again in chapter 6 linux from scratch I am trying to follow the LFS book, and couldn't get my mind around this question: we built the GCC compiler in chapter 5 in the target partition, why do we do that again after entering the chroot mode? what's the point, why not use the previous build. Same thing for the GlibC.

A: I believe that the build in the chroot would check to see that all of the ancillary files and programs to build GCC and GlibC are present, and independent of the "build system". Compiling a compiler isn't simple at all, usually. I believe that GCC will require bison and flex and all kinds of header files, config files and who knows what else. The chroot build is just an intermediate step between the build system (which is not LFS) and the final LFS installation, which is supposed to be self-hosting.
Because the run-time environment of GCC is complicated (PATH, LD_LIBRARY_PATH and other configuration items) it's also possible that some side effects will leak through from the initial GCC compiler. I cannot find the paper, but I recall that it can take as many as 5 generations of compiling a compiler with the previously-compiled generation to get all the weird bugs and dependencies to surface.

A: As you are entering a chroot, it means you have an empty system with nothing installed nor working for that matter, so you need tools to compile things which you do in chapter 5. It's also the reason why in chroot you are giving /tools/bin/env with a PATH pointing to the tools directory.
Chapter 6 is doing nothing more then populating chroot by downloading the packages and installing them including gcc and that's where you compile them using the tools from chapter 5.


text:
Q: How does key-based caching work? I recently read an article on the 37Signals blog and I'm left wondering how it is that they get the cache key.
It's all well and good having a cache key that includes the object's timestamp (this means that when you update the object the cache will be invalidated); but how do you then use the cache key in a template without causing a DB hit for the very object that you are trying to fetch from the cache.
Specifically, how does this affect One to Many relations where you are rendering a Post's Comments for example.
Example in Django:
{% for comment in post.comments.all %}
   {% cache comment.pk comment.modified %}

{{ post.body }}

   {% endcache %}
{% endfor %}

Is caching in Rails different to just requests to memcached for example (I know that they convert your cache key to something different). Do they also cache the cache key?

A: For caching a straight dump of a single already-loaded object, yes, you gain nothing or next-to-nothing.  That's not what those examples are describing - they're describing a hierarchy, where any change to something lower should also trigger an update to everything higher up in the hierarchy.
The first example, from the 37signals blog, uses Project -> Todolist -> Todo as the hierarchy.  A populated example might look like this:
Project: Foo (last_modified: 2014-05-10)
   Todolist:  Bar1 (last_modified: 2014-05-10)
       Todo:  Bang1 (last_modified: 2014-05-09)
       Todo:  Bang2 (last_modified: 2014-05-09)

   Todolist:  Bar2 (last_modified: 2014-04-01)
       Todo:  Bang3 (last_modified: 2014-04-01)
       Todo:  Bang4 (last_modified: 2014-04-01)

So, let's say Bang3 was updated.  All its parents also get updated:
Project: Foo (last_modified: 2014-05-16)
   Todolist:  Bar2 (last_modified: 2014-05-16)
       Todo:  Bang3 (last_modified: 2014-05-16)

Then when it comes time to render, loading Project from the database is basically inevitable.  You need a point to start at.  However, because its last_modified is an indicator of all its children, that's what you use as the cache key before attempting to load the children.

While the blog posts use separate templates, I'm going to lump them together into one.  Hopefully seeing the complete interaction in one place will make it a little clearer.
So, the Django template might look something like this:
{% cache 9999 project project.cache_key %}

{{ project.name }}

   {% for list in project.todolist.all %}
   {% cache 9999 todolist list.cache_key %}

         {% for todo in list.todos.all %}

{{ todo.body }}

         {% endfor %}

   {% endcache %}
   {% endfor %}

{% endcache %}

Say we pass in a Project whose cache_key still exists in the cache.  Because we propagate changes to all related objects to the parent, the fact that that particular key still exists means the entire rendered contents can be pulled from the cache.
If that particular Project had just been updated - for example, as with Foo above - then it will have to render its children, and only then will it run the query for all Todolists for that Project.  Likewise for a specific Todolist - if that list's cache_key exists, then the todos inside it have not changed, and the whole thing can be pulled from the cache.
Also notice how I'm not using todo.cache_key in this template.  It's not worth it, since as you say in the question, body has already been pulled from the database.  However, database hits aren't the only reason you might cache something.  For example, taking raw markup text (such as what we type into question/answer boxes on StackExchange) and converting it to HTML may well take sufficient time that caching the result would be more efficient.
If that were so, the inner loop in the template might look more like this:
         {% for todo in list.todos.all %}
            {% cache 9999 todo todo.cache_key %}

{{ todo.body|expensive_markup_parser }}

            {% endcache %}
         {% endfor %}

So to pull everything together, let's go back to my original data at the top of this answer.  If we assume:

*

*All the objects had been cached in their original state

*Bang3 was just updated

*We're rendering the modified template (including expensive_markup_parser)

Then this is how everything would be loaded:

*

*Foo is retrieved from the database

*Foo.cache_key (2014-05-16) does not exist in the cache

*Foo.todolists.all() is queried:  Bar1 and Bar2 are retrieved from the database

*Bar1.cache_key (2014-05-10) already exists in the cache; retrieve and output it

*Bar2.cache_key (2014-05-16) does not exist in the cache

*Bar2.todos.all() is queried:  Bang3 and Bang4 are retrieved from the database

*Bang3.cache_key (2014-05-16) does not exist in the cache

*{{ Bang3.body|expensive_markup_parser }} is rendered

*Bang4.cache_key (2014-04-01) already exists in the cache; retrieve and output it

Savings from the cache in this tiny example are:

*

*Database hit avoided: Bar1.todos.all()

*expensive_markup_parser avoided 3 times: Bang1, Bang2, and Bang4
And of course, next time it's viewed, Foo.cache_key would be found, so the only cost to rendering is retrieving Foo alone from the database and querying the cache.

A: Your example is good if it needs some data retrieval or processing for each comment. If you just take body and display it - cache will be useless. But you can cache all comments tree (including {% for %}). It this case you need to invalidate it with every added comment, so you can put last comment timestamp or comments count somewhere into Post and build comments cache key with it. If you prefer more normalized data, and use comments on only one page, you can just clear a cache key on comment save.
For me, saving comments count in Post looks good enough (if you don't allow to delete and edit comments) - you have a value to show anywhere with the Post and a key for caching.


text:
Q: Remove "Hinh" in caption on Beamer I keep getting this unwanted "Hihn" before the caption starts on Beamer.

How can I remove it? Here is my code for the figure:
\begin{frame}

\frametitle{\textcolor{red}{Example Slide}}

\begin{figure}[!ht]

   \begin{center}

   \includegraphics[width=6 cm, height = 6 cm]{Plot.pdf}

   \caption {\textbf{\emph{Simulation 1}}: True activity status of the corresponding cell.}

    \end{center}

\end{figure}

\end{frame}

A: I assume Hihn is the equivalent of your language to Figure:. To remove this from the caption, you could redefine the caption template or simply not use a caption.
(replace \usepackage[french]{babel} in the example below with whatever language you are using)
Some other comments:

*

*instead of using formatting instructions in arguments of macros such as the \frametitle better change the appropriate beamer colour, e.g. \setbeamercolor{frametitle}{fg=red}

*beamer does not have a floating mechanism, giving floating specifier such as [ht!] does not make sense

*you don't need to center images inside beamer figures, they are centred by default

*don't specify both the height and width of an image, this will distort the image. If you must specify both, at least add keepaspecratio
Solution 1
\documentclass{beamer}

\usepackage[french]{babel}

\setbeamercolor{frametitle}{fg=red}
\setbeamertemplate{caption}{%
  \raggedright
  \insertcaption\par
}

\begin{document}

\begin{frame}

\frametitle{Example Slide}

\begin{figure}
   \includegraphics[width=6cm]{example-image}
   \caption{\textbf{\emph{Simulation 1}}: True activity status of the corresponding cell.}
\end{figure}

\end{frame}

\end{document}

Solution 2
\documentclass{beamer}

\usepackage[french]{babel}
\setbeamercolor{frametitle}{fg=red}

\begin{document}

\begin{frame}

\frametitle{Example Slide}

\begin{figure}
  \includegraphics[width=6cm]{example-image}

  \textbf{\emph{Simulation 1}}: True activity status of the corresponding cell.
\end{figure}

\end{frame}

\end{document}


text:
Q: Failing to successfully expose my ViewModel data to my View for XAML binding I'm building a Windows Universal app and trying to expose data from my ViewModel to my View so that I can bind it to XAML elements. I have completely commented out all of my code at this point and am just writing lines of test code to try and get it to work, that is what is in the examples below. Binding directly from the View (if I create an object there as a test) does work.
Please help me to understand where I am going wrong, I think I've read every binding tutorial on the internet and still just don't get it.
View (MainPage.xaml.cs):
public MainPage()
{
    InitializeComponent();
    DataContext = new MainViewModel();

}

ViewModel (MainViewModel.cs):
public class MainViewModel
{
    public Term newTerm = new Term
    {
        TermName = "Table",
        TermDescription = "You eat dinner on it"
    };
}

XAML (MainPage.xaml):
<StackPanel DataContext="{Binding newTerm}" x:Name="mvvmStack" Orientation="Vertical">
    <TextBlock x:Name="mvvmTermName" Text="{Binding TermName,  FallbackValue='Fallingback'}" />
    <TextBlock x:Name="mvvmDescription" Text="{Binding TermDescription, FallbackValue='Fallingback', TargetNullValue='Unknown'}" />
</StackPanel>

The error I get is:
Error: BindingExpression path error: 'newTerm' property not found on ''. BindingExpression: Path='newTerm' DataItem=''; target element is 'Windows.UI.Xaml.Controls.StackPanel' (Name='mvvmStack'); target property is 'DataContext' (type 'Object')

I have read about this type of error and although I have some idea of what it is trying to say I cannot work out how to fix it. I'm very much a complete beginner with coding, especially C# so please take that into account when answering :-)

A: Just try to change it from field to a property and it will be working correctly. You can't bind to fields.
EDIT:
private Term _term;
public Term NewTerm{
    get{return _term;}
    set
    {
       _term= value;
       OnPropertyChanged("Term");
    }
}

if you need to add notify the view of changes in the viewmodel you need to implement INotifyPropertyChanged.
check this answer it will provide an example for property changed. https://stackoverflow.com/a/27685925/1448382
If you want to bind the view to sub properties, you have two options depending on the situation:
1- Relative Binding: this scenario is used when you will not modify the properties inside the Term object from the ViewModel i.e. they will be just initialized in the viewmodel and can be modified in the view, just like the way you are doing it. Plesae note, that anything you need to bind to should be a property and not a field.
2- Binding to Viewmodel directly: this scenario is used when you will modify the properties inside the Term object from the Viewmodel after the view load. This way you will need to add properties to the viewmodel for the properties TermName and TermDescription.
public string TermName{
    get{return NewTerm.Name;}
    set{NewTerm.Name = value;
        OnPropertyChanged("TermName");
    }//The same is applied for TermDescription

But be aware that you will need to remove the binding on the Stackpanel object since you have defined the properties directly in the Viewmodel.

A: Try something like that:
<Page.Resources>
    <viewModels:MainViewModel x:Key="MainViewModel" />
</Page.Resources>

And then:
<StackPanel x:Name="mvvmStack" Orientation="Vertical">
            <TextBlock x:Name="mvvmTermName" Text="{Binding newTerm.TermName, Source={StaticResource MainViewModel}  FallbackValue='Fallingback'}" />
            <TextBlock x:Name="mvvmDescription" Text="{Binding newTerm.TermDescription, Source={StaticResource MainViewModel} FallbackValue='Fallingback', TargetNullValue='Unknown'}" /></StackPanel>

Of cource newTerm should be an property with INotifyChanged


text:
Q: How to add windows credentials to an apache camel route? I need to authenticate myself when I want to access a REST api.
I have created a simple example with apache's WinHttpClients which works and also accepts a self signed crt which is used by that site.
These are my dependencies
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5.+'
compile 'org.apache.httpcomponents:httpclient-win:4.5.+'

testCompile group: 'junit', name: 'junit', version: '4.11'
}

And this is the working code (authorization works, acceptance of crt works)
public class Application {

  public static void main(String[] args) throws IOException {

    if (WinHttpClients.isWinAuthAvailable()) {
      PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
        buildSSLSocketFactory());
      HttpClientBuilder clientBuilder = WinHttpClients.custom().useSystemProperties();
      clientBuilder.setConnectionManager(httpClientConnectionManager);
      CloseableHttpClient httpClient = clientBuilder.build();

      HttpHost httpHost = new HttpHost("server.evilcorp.com", 443, "https");
      HttpGet httpGet = new HttpGet(
        "/evilwebapi/streams/endpointalpha/data");
      httpGet.setHeader("accept", "application/json");

      CloseableHttpResponse httpResponse = httpClient.execute(httpHost, httpGet);

      String content = EntityUtils.toString(httpResponse.getEntity());
      System.out.println(content); // returns expected json result
    }
  }

  private static Registry<ConnectionSocketFactory> buildSSLSocketFactory() {
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(buildSSLContext(), NoopHostnameVerifier.INSTANCE);
    return RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory())
      .register("https", sslSocketFactory)
      .build();
  }

  private static SSLContext buildSSLContext() {
    SSLContext sslContext = null;
    try {
      sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
      System.out.println("Failed to initialize SSL handling.\n" + e);
    }
    return sslContext;
  }
}

When I try to access the same site through apache camel I get a 401 status.
I tried to configure camel's httpComponent in various ways but so far I can't make authentication work. This is the current camel setup.
These are my dependencies:
dependencies {
  compile 'org.apache.camel:camel-core:2.18.+'
  compile 'org.apache.camel:camel-sql:2.18.+'
  compile 'org.apache.camel:camel-http4:2.18.+'
  compile 'org.apache.camel:camel-jetty:2.18.+'
  compile 'org.apache.camel:camel-jackson:2.18.+'
  compile 'org.apache.camel:camel-guava-eventbus:2.18.+'
  compile 'org.apache.camel:camel-quartz2:2.18.+'
  compile 'com.fasterxml.jackson.core:jackson-core:2.7.+'
  compile 'org.apache.httpcomponents:httpclient:4.5.+'
  compile 'org.apache.httpcomponents:httpclient-win:4.5.+'
  testRuntime files('src/test/resources')
  runtime files('src/main/resources')
}

And this is the RouteBuilder which does not work (authorization doesm't works, statusCode: 401)
context = new DefaultCamelContext(registry);
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:model.properties");
context.addComponent("properties", pc);
try {

  context.addRoutes(new RouteBuilder() {
    public void configure() {
      HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
      httpComponent.setHttpClientConfigurer(new WinHttpClientConfigurer());
      httpComponent.setClientConnectionManager(new PoolingHttpClientConnectionManager(WinHttpClientConfigurer.buildSSLSocketFactory()));
      httpComponent.setHttpConfiguration(buildHttpConfiguration());
      getContext().getProperties().put("CamelJacksonEnableTypeConverter", "true");
      getContext().getProperties().put("CamelJacksonTypeConverterToPojo", "true");

      from("quartz2://pipull?cron=0+0/1+*+1/1+*+?+*")
        .setHeader(Exchange.HTTP_QUERY,
            simple("start='${header.start}'&end='${header.end}'"))
        .multicast().parallelProcessing()
        .to("direct:model");

      from("direct:model")
        .setHeader("contractRef", simple("${properties:model.name}"))
        .to("https4://server.evilcorp.com/evilwebapi/streams/endpointalpha/data")
        .to("direct:transform");

      from("direct:transform").unmarshal()
        .json(JsonLibrary.Jackson, Model.class)
        .bean(ProcessorImpl.class)
        .to("guava-eventbus:botBus");
      }

      private HttpConfiguration buildHttpConfiguration() {
        WindowsCredentialsProvider credentialsProvider = new WindowsCredentialsProvider(
          new SystemDefaultCredentialsProvider());
        Credentials credentials = credentialsProvider.getCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM));
        HttpConfiguration httpConfiguration = new HttpConfiguration();
        httpConfiguration.setAuthMethod(AuthSchemes.NTLM);
        httpConfiguration.setAuthUsername(credentials.getUserPrincipal().getName());

        return httpConfiguration;
      }

    });
    context.start();
  } catch (Exception e) {
    isRunning.set(false);
    throw new RuntimeException(e);
  }

A: I have resolved the problem through subtyping HttpComponent and adding that to the camel context.
public class WinHttpComponent extends HttpComponent {
  private static final Logger LOG = LoggerFactory.getLogger(WinHttpComponent.class);

  public WinHttpComponent() {
    this(HttpEndpoint.class);
  }

  public WinHttpComponent(Class<? extends HttpEndpoint> endpointClass) {
    super(endpointClass);
  }

  @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
      // copy-paste everything from super method
      // replace this
      // HttpClientBuilder clientBuilder = HttpClientBuilder.create();
      // with this
      HttpClientBuilder clientBuilder = WinHttpClients.custom().useSystemProperties();
      // copy-paste everything from super method
  }
}

context = new DefaultCamelContext(registry);
context.addComponent("https4", new WinHttpComponent());
try {
  context.addRoutes(new RouteBuilder() {
    public void configure() {
      HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
      // connection manager which accepts self-signed cert
      httpComponent.setClientConnectionManager(new PoolingHttpClientConnectionManager(
        NoopSslVerifierHttpClientConfigurer.buildSSLSocketFactory()));
      ...
      ...
      ...
    }
  }


text:
Q: Why doesn't 0.1+0.2-0.3 equal 0.0? Why doesn't 0.1+0.2-0.3 equal 0.0 ? according to normal equation the result should be 0 but why isn't it?
Could someone please explain me the reason?

A: All programming languages including Python use 32-bit floating point representation for numbers. With decimal fractions, this floating-point number system causes some rounding errors which results in 0.1 + 0.2 == 0.3 as false.
The Actual Answer
For Example:
1.2 is exactly equal to 1.1999999999999999555910790149937383830547332763671875
Solution:
One solution to handle this inconsistency in floating-point value is by using a native Python module called Decimal

For Detailed Answer, Read these articles:
https://gauravkk22.medium.com/why-0-1-0-2-0-3-is-false-in-js-mystery-unsolved-with-solution-4f7db2755f18
https://python.plainenglish.io/floating-point-arithmetic-precision-error-in-python-decimal-comes-for-rescue-8803d1290601https://python.plainenglish.io/floating-point-arithmetic-precision-error-in-python-decimal-comes-for-rescue-8803d1290601


text:
Q: py2exe - generate single installer file I use python2.7, py2exe, pyqt4 and want to generate a installer file just like dropbox . This is my setup.py file
# coding=utf8

from distutils.core import setup
import py2exe
import sys, os

sys.argv.append('py2exe')
py2exe_options = {
    "includes": ["sip",'encodings', 'encodings.*'],
    "dll_excludes": ["MSVCP90.dll", 'OLEAUT32.dll', 'USER32.dll', 'IMM32.dll', 'SHELL32.dll', 'ole32.dll', 'WINMM.dll', 'USER32.dll', 'EKRNEL32.dll', 'ADVAPI32.dll', 'COMDLG32.dll', 'WS2_32.dll', 'WINSPOOL.DRV', 'GDI32.dll', 'KERNEL32.dll'],
    "compressed": 1,
    "optimize": 2,
    "ascii": 0,
    "bundle_files": 1
}

setup(
    name='IP',
    version='1.0',
    zipfile = None,
    windows=["main.py"],
    options={'py2exe': py2exe_options}
)

I want to generate install by running 'python setup.py py2exe', but failed.
How do i do next to generate installer ?

A: Which do you want? a Single Executive File or a Installer?
Your code seems to pack all the code in one file.
If you want a Installer, you can pass that Single Executive File to some program like Inno setup, to generate a Installer.


text:
Q: How to remove Vertical Lines in image opencv Python I wanted to remove both horizontal and vertical lines the following code works well to remove horizontal lines but in this

Here is the output image where the horizontal line is removed

Here is the code attached please can you tell me how can I remove the vertical lines
import cv2
import matplotlib.pyplot as plt
import glob
import os
def remove_lines(image_path,outdir):
    image = cv2.imread(image_path)
    result = image.copy()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    # Remove horizontal lines
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (50,1))
    remove_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)

    cnts = cv2.findContours(remove_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    for c in cnts:
        cv2.drawContours(result, [c], -1, (255,255,255), 5)

    # Remove vertical lines
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,50))
    remove_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
    #remove_vertical =cv2.dilate(remove_vertical , vertical_kernel, iterations=2)
    cnts = cv2.findContours(remove_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    for c in cnts:
        cv2.drawContours(result, [c], -1, (255,255,255), 5)

    cv2.imwrite(os.path.join(outdir,os.path.basename(image_path)), result)
    plt.imshow(result)
for jpgfile in glob.glob(r'C:\custom\TableDetectionWork\images/*'):
    print(jpgfile)
    remove_lines(jpgfile,r'C:\custom\TableDetectionWork\output/')

A: To remove both lines:
msk = im.copy()
msk = cv2.medianBlur(msk, 11)
msk = cv2.erode(msk, np.ones((5, 5)))
msk = cv2.threshold(msk, 200, 255, cv2.THRESH_BINARY)[1]
msk = cv2.GaussianBlur(msk, (5, 0), 11)
msk = cv2.threshold(msk, 120, 255, cv2.THRESH_BINARY)[1]
msk = cv2.erode(msk, np.ones((31, 31)))
im[np.where(msk != 0)] = 255


text:
Q: How to Convert drawn shapes of HWPFDocument to XSL FO? I am trying to convert .doc file to PDF,
For this I am initially trying to convert .doc > XSL-FO > PDF.
On Converting the .doc to XSL-FO I am unable to convert the drawn objects such as checkbox,rectangle,square to XSL-FO.
It gets converted as below , which should actually be a box

The conversion code I am using is
    HWPFDocumentCore wordDocument = WordToFoUtils.loadDoc(is);
    WordToFoConverter wordToFoConverter = new WordToFoConverter(

    XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument());

    wordToFoConverter.processDocument(wordDocument);
    File foFile = new File("D:\\Testing\\testing\\" + "test.fo");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamResult streamResult = new StreamResult(out);

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                    transformer.transform(new
                                     DOMSource(wordToFoConverter.getDocument()), streamResult);
    String result =
     org.apache.commons.lang3.StringUtils.normalizeSpace(java.text.Normalizer.normalize(new
     String(out.toByteArray(), "UTF-8"), java.text.Normalizer.Form.NFD));

    result = URLEncoder.encode(result, "UTF-8");

Further Apache FOP is used to convert the .fo to pdf
The .doc file is as below

and the WordToFoConverter converted the boxes as below

A: In Plain Text like XML, check boxes usually come from basic symbol fonts.
They are seen / shown as ☐ when unchecked, or ☑ or ☒ when checked.
In any basic text stream it should be relatively easy to use or find and replace them. However beware the encoding especially UTF , thus best copied from a clean set of Zapf Dingbats or Adobe TTF Symbol font.
many have a Unicode description but do test visually that they work after copy and paste from the PDF since the font mapping may not always tally.
8999   ⌧   ⌧     \002327 0x2327  X in a rectangle box
By far the simplest way to use UniCode text is as Rich Text which you can on Windows Command Line (you don't need the lower left dialogue, its just to illustrate export settings) outPort as Port-AbleDocFile using Write.exe which can read TXT and /PrintTo PDF.

Its much simpler than XML where just one character requires:-
<w:rPr>
<w:rFonts w:ascii="Segoe UI Symbol" w:hAnsi="Segoe UI Symbol" w:cs="Segoe UI Symbol" w:eastAsia="Segoe UI Symbol"/>
<w:color w:val="auto"/>
<w:spacing w:val="0"/>
<w:position w:val="0"/>
<w:sz w:val="48"/>
<w:shd w:fill="auto" w:val="clear"/>
<w:vertAlign w:val="subscript"/>
</w:rPr>
<w:t xml:space="preserve">☑</w:t>


text:
Q: Static View Models / Presentation Models Would it be incorrect to make all my View Models / Presentation Models static classes so that if any other View Presenter wanted to change a view model other than its own it could easily aquire a reference to it?
If this is the wrong approach how would you achieve it?

A: If you want to make it static you'd be better off implementing a proper Singleton pattern. You will find it extremely difficult to test all the classes that consume your static models as you won't be able to use any Dependency Inversion techniques.
Also, be aware of concurrency if you only have 1 class - you'll need to lock pretty much everything. Not good.
Finally, you might want to consider using a Factory pattern. Easily accessible but will create a new model object for each class that wants to use it. Concurrency issue (mostly) solved.

A: Static ViewModels sounds like an awful idea (I consider static evil as a general principle). This would mean that you can't have more than one instance of a ViewModel. I can think of many examples of UI where there are several instances of the same View type, but that wouldn't be possible with static ViewModels.
If you want to enable communication across Views, Publish/Subscribe (events) are a much better option.
Remember that when we talk about ViewModels/Presentaion Models they usually expose underlying Domain Objects. If you have sevaral Views that display parts of the same Domain Object, you can have the Domain Object raise events when it changes state, and any ViewModel that display data from that Domain Object can subscribe to those events and update their controls accordingly.


text:
Q: how to grab the max of common columns with partition in sql i have this Table Chips:

im looking to find the max for each ID but
the code im using is just not correct i need the new table to be

  select *
  from
  (
     max (numchips) over (partition by Id)
     from @chips
  )

A: You can use ROW_NUMBER:
 SELECT Id, numchips
 FROM (
     SELECT Id, numchips,
            ROW_NUMBER() OVER (PARTITION BY Id
                               ORDER BY numchips DESC) as rn
     FROM @chips
  ) t
  WHERE rn = 1

rn is equal to 1 for the record having the highest numchips value within each Id partition.
Using ROW_NUMBER() makes sense only if you have some additional columns in Chips table that you also want to retrieve.

A: Why can't you just do?:
SELECT
   MAX(c.numchips),
   c.Id
FROM
   @chips as c
GROUP BY
   c.Id


text:
Q: Maven (m2e) is not executing ant task I have a POM file (to be executed by Eclipse) where I want to execute a ANT task during the generate-sources phase. Based on m2e documentation, in How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds, Maven: execute antrun task during package and Where should be placed maven-compiler-plugin declaration: in <plugins> or <pluginManagement>?, I wrote my POM file in this way:
<?xml version="1.0" encoding="UTF-8"?>
    <project>

    ...

    <build>
        <pluginManagement>
            <plugins>
                ...
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-antrun-plugin</artifactId>
                                        <versionRange>[1.8,)</versionRange>
                                        <goals>
                                            <goal>generate-sources</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute/>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>

        <plugins>

            <plugin>
                <!-- Plugin 1 -->
            </plugin>

            <plugin>
                <!-- Plugin to be executed during generate-sources phase. -->
            </plugin>

            <plugin>
                <!-- Should be in the generate-sources phase after the plugin above. -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.8</version>
                <executions>
                    <execution>
                        <id>ant-test</id>
                        <configuration>

                            <task>
                                <echo message="ANT TEST" />
                            </task>

                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

    ...

</project>

What I understood from my reading, is that I am asking telling to Maven the following: First ask to Eclipse plugin for Maven (m2e) to allow the maven-antrun-plugin (version 1.8 or above) to be executed during generate-sources. Next, in the generate-sources phase and after the execution of the first plugin, call the ant plugin to run the task which echo my message.
However, the messagem is not being showed. Neither when I execute just the generate-sources goal nor when I execute the install goal.
I if follow this sugestion here, and add the <phase> element inside <execution>, like here:
<executions>
    <execution>
        <id>ant-test</id>
        *<phase>generate-sources</phase>*
        <configuration>

            <task>
                <echo message="ANT TEST" />
            </task>

        </configuration>
        <goals>
            <goal>run</goal>
        </goals>
    </execution>
</executions>

I have a Eclipse error message: Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-antrun-plugin:1.8:run (execution: ant-test, phase: generate-sources). Here shows a example where there is no a specific <pluginManagement> for ant plugin. But also I had no success.
So What is missing here?
Thanks,
Rafael Afonso

A: Actually, I discovered that the error message Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-antrun-plugin:1.8:run (execution: ant-test, phase: generate-sources) has no effect in the Maven execution. The message is shown with no problems. To speak the truth, I had to change the task to target, but the message continues to be displayed. May be it is just a kind m2e's bug which the only effect is annoys us.

A: Actually, I did the structure below, and it worked:
<build>
        <plugins>
            <plugin>
                ....
            </plugin>
            <plugin>
                ...
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            org.apache.maven.plugins
                                        </groupId>
                                        <artifactId>
                                            maven-antrun-plugin
                                        </artifactId>
                                        <versionRange>
                                            [1.8,)
                                        </versionRange>
                                        <goals>
                                            <goal>run</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
</build>


text:
Q: How to run iOS simulator 4.3 in Xcode 4.6? I'm trying to test my iOS application on iOS 4.x.
I'm using MAC OS X Mountain Lion(10.8.2) and Xcode 4.6.
I tried to install the older iOS 4 version from the Downloads tab inside the Xcode but that simulator option is not available: http://cl.ly/image/412l3V3C1E3W
I then manually installed the the iOS 4.0 and 4.3 sdk using the packages from the "xcode_4.0.2_and_ios_sdk_4.3.dmg" file and now they are available inside the folder: "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs".
My deployment target is set to 4.0 and I'm able to select the iOS simulator from the scheme.
I even checked if the iOS 4.x SDK is correctly installed using the command line "xcodebuild -showsdks" and the system recognizes it:
$ xcodebuild -showsdks
OS X SDKs:
    Mac OS X 10.7                   -sdk macosx10.7
    OS X 10.8                       -sdk macosx10.8

iOS SDKs:
    iOS 4.3                         -sdk iphoneos4.3
    iOS 6.1                         -sdk iphoneos6.1

iOS Simulator SDKs:
    Simulator - iOS 4.0             -sdk iphonesimulator4.0
    Simulator - iOS 4.3             -sdk iphonesimulator4.3
    Simulator - iOS 5.0             -sdk iphonesimulator5.0
    Simulator - iOS 5.1             -sdk iphonesimulator5.1
    Simulator - iOS 6.1             -sdk iphonesimulator6.1

The problem I'm facing is that when I run the project I get and error from the simulator: "iOS Simulator could not find the SDK. The SDK may need to be reinstalled."
And if I try to change the version from the simulator there is no 4.3 option:
http://cl.ly/image/1y04201e2o08
Does anyone know how to force the simulator to start with iOS 4.3?


text:
Q: Adding Id attribute to multiple checkboxes ISSUE: Id attributes is applied to all elements.
Request: I am trying to add id attribute to an element that consists of 3 checkbox, but i'm not sure how to do that. I tried to add it to the main one but it applied to all.

Here is my full step.
import GTM from "/components/gtm"

 offerHelp: {
    prefix: "OFS",
    volunteer: "_VO",
    donor: "_DI",
    orgbtn: "_ORG",
  },

const Step1 = (props) => {
  const [state, updateState] = useState(STEP_1_STATE);
  const { answers, none } = state;

  const toggleAnswer = (answer) => {
    const updatedAnswers = { ...answers, [answer]: !answers[answer] };
    const checkedAnswers = getCheckedAnswers(updatedAnswers);
    updateState({ ...state, answers: updatedAnswers });
    props.update("providers", checkedAnswers);
  };

  return (
    <WizardStep>
      <WizardProgress className="text-primary">
        Question {props.currentStep}/{props.totalSteps}
      </WizardProgress>
      <StepTitle>How do you want to contribute?</StepTitle>
      <WizardFormWrapper>
        <WizardCheckboxWrapper>
          {Object.entries(answers).map(([answer, checked], i) => (
            <WizardCheckboxItem
              key={i}
              id={
                GTM.offerHelp.volunteer +
                props.currentStep +
                GTM.offerHelp.orgbtn +
                GTM.offerHelp.donor //this is the id where i need to fix. currently its not giving the three elements different ids. They are all the same
              }

              onChange={() => toggleAnswer(answer)}
              checked={!none && checked}
              text={answer}
            />
          ))}
        </WizardCheckboxWrapper>
      </WizardFormWrapper>
    </WizardStep>
  );
};

A: I suggest putting this into a function that returns a string and then use the string as the ID value.
GTM.offerHelp.volunteer +
props.currentStep +
GTM.offerHelp.orgbtn +
GTM.offerHelp.donor

I am under the impression that your ID is not unique. Please add something like an index that will make this unique

A: Will using the i counter to compose your unique id be enough?
{
  GTM.offerHelp.volunteer +
  props.currentStep +
  GTM.offerHelp.orgbtn +
  GTM.offerHelp.donor +
  i
}