text:
Q: Where are they getting this number from? Here's the question that I'm having a problem with:
After reviewing previous loan records, the credit manager of a bank determines
that the data follows a normal distribution. The debts have a mean of $20000
and the probability that the loss could be greater than $25000 or less than
$15000 is 0.418. Determine the standard deviation of the data to the nearest
hundred dollars.

After looking at the answer (shown below), I can't understand how they're able to figure out to do $\frac{0.418}{2}$. I understand that they're using inversion on $\frac{0.418}{2}$ to get $-0.81$. Can someone please explain it better and maybe include a normal distribution curve to visualize it? I can't see where $0.418$ is on the normal distribution curve...
$$A_{(Z_1)} = \frac{0.418}{2} = 0.2090$$
$$Z_1 = -0.81$$
$$-0.81 = \frac{15000 - 20000}{\sigma} $$
$$-0.81 = \frac{5000}{\sigma} $$
$$-0.81\sigma = 5000$$
$$\frac{-0.81\sigma}{-0.81} = \frac{5000}{-0.81}$$
$$\sigma = 6172.8395 \approx 6200 $$

A: The events they are concidering are the events in the tails of the distribution, i.e. less than some number at the left side and larger than some number at the right. Since the normal distribution is symmetric and they are concidering symmetric deviations around the mean, you know that, for example, the probability of a loss less than 15000 is  $0.418/2$. Then you look at the CDF of the standard normal distribution and find that -0.81 standard deviations has the probability $0.418/2$ (the deviation is negative since we are at the left of the mean). So if $X$ is the loss and $\Phi(Z)$ the CDF of the standard normal distribution, we have $$ P(X \leqslant 15000) = \Phi \left(\frac{15000 - 20000}{\sigma} \right) = \frac{0.418}{2} \Leftrightarrow \\  \frac{-5000}{\sigma} = -0.81 \\ \sigma = \frac{5000}{0.81}$$


text:
Q: Gatsby graphql resolver query not returning all fields I have this resolver query where I filter through all markdown entries to build a collection:
export const createResolvers = ({createResolvers}) => {
    const resolvers = {
        Query : {
            allPosts     : {
                type   : ["Post"],
                args   : { limit: `Int`, skip: `Int` },
                resolve: async (source, args, context, info) => {
                    const { entries } = await context.nodeModel.findAll({
                        type : "MarkdownRemark",
                        query: {
                            limit : args.limit,
                            skip  : args.skip,
                            filter: {
                                fileAbsolutePath: {
                                    regex: "//collections/posts//"
                                }
                            }
                        }
                    });

                    return entries;
                }
            },
        }
    }
}

It returns a collection of type Post:
    type Post implements Node @dontInfer {
        id: ID!
        html: String
        rawMarkdownBody: String
        fileAbsolutePath: String
        ...
    }

The MarkdownRemark entries that I select have a html field which contains the html output of the markdown file. I can see it in the Graphiql playground/console.
When I query with allPosts, the html field is empty. I get rawMarkdownBody and other fields but not html.
Any ideas why?

A: The issue here is that createResolvers runs after transformers, so other nodes of type MarkdownRemark have already had the html field added to them by the time your resolver runs.
You can instead make the change in createSchemaCustomization. For example, something like this (probably won't work verbatim, but wanted to get you the gist):
exports.createSchemaCustomization = async ({
  actions: { createTypes },
  schema,
}) => {
  createTypes([
    schema.buildObjectType({
      name: "Query"
      fields: {
        allPosts: {
          type: ["Post"],
          args: { limit: `Int`, skip: `Int` },
          resolve: async (source, args, context, info) => {
            // …
          },
        },
      },
    })
  ])
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compute the volume of a single voxel of nifti medical image? I have loaded a nifti image file using nibabel tool and I have played with some properties.
But I don't have idea how to compute the volume (in mm³) of a single voxel.

A: Here's the answer using NiBabel, as OP asked:
import nibabel as nib
nii = nib.load('t1.nii.gz')
sx, sy, sz = nii.header.get_zooms()
volume = sx * sy * sz

A: I am not a NiBabel expert, but I can instead recommend the SimpleITK package for Python. I often use it for reading NifTi image files. It has a method GetSpacing() which returns the pixel spacing in mm.
import SimpleITK as sitk

# read image
im = sitk.ReadImage("/path/to/input/image.nii")

# get voxel spacing (for 3-D image)
spacing = im.GetSpacing()
spacing_x = spacing[0]
spacing_y = spacing[1]
spacing_z = spacing[2]

# determine volume of a single voxel
voxel_volume = spacing_x * spacing_y * spacing_z


text:
Q: Why is typeof hex or binary number Uint64 while type of decimal number is Int64? julia> typeof(-0b111)
Uint64

julia> typeof(-0x7)
Uint64

julia> typeof(-7)
Int64

I find this result a bit surprising. Why does the numeric base of the number determine signed or unsgined-ness?

A: Looks like this is expected behavior:

This behavior is based on the observation that when one uses unsigned
  hex literals for integer values, one typically is using them to
  represent a fixed numeric byte sequence, rather than just an integer
  value.

http://docs.julialang.org/en/latest/manual/integers-and-floating-point-numbers/#integers
...seems like a bit of an odd choice.

A: This is a subjective call, but I think it's worked out pretty well. In my experience when you use hex or binary, you're interested in a specific pattern of bits – and you generally want it to be unsigned. When you're just interested a numeric value you use decimal because that's what we're most familiar with. In addition, when you're using hex or binary, the number of digits you use for input is typically significant, whereas in decimal, it isn't. So that's how literals work in Julia: decimal gives you a signed integer of a type that the value fits in, while hex and binary give you an unsigned value whose storage size is determined by the number of digits.


text:
Q: Do they make anti-parallel diodes in 2-lead packages? Sometimes diodes in an anti-parallel configuration are used on the inputs to high-gain instrumentation amplifiers in order to protect against large differential voltages.
Does anyone know if the industry produces 2-pin packages in this kind of configuration? If so, what is the name of this configuration?

simulate this circuit – Schematic created using CircuitLab

A: Just use a BAV99 and connect pins 1 and 2 together.

If a lower voltage is desired (and the leakiness is not an issue) you can use a common dual Schottky such as BAT54S, as @RohatKılıç suggests. The package is the same as the BAV99.
There are dual back-to-back LEDs available, which exactly meets your request, however a red one would limit at more like +/-2V than +/-700mV for the BAV99 or +/-300mV for the BAT54S. The visual indication might be useful.


text:
Q: Android screen missing elements defined in XML I am new to Android development. I have created many screens and all are working quite nicely except one.
I am not sure why screen is not coming up as per XML. Below is my code :
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dip"
    android:id="@+id/linearMain">

   <TextView
        android:id="@+id/courseTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="17sp"
        android:textColor="#2258A2"
        android:layout_marginBottom="10dp"
        />

    <TextView
        android:id="@+id/assignmentTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#000000"
         />
    <TextView
        android:id="@+id/lesson"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#000000"
        android:text="Lesson : Lecture 5"
         />
    <TextView
        android:id="@+id/dueDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#000000"
        android:text="Due Date : Nov 20, 2014"
         />
   <TextView
        android:id="@+id/marks"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#000000"
        android:text="Marks : 20"
         />

   <Button android:id="@+id/btnDownload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download"
        />
</LinearLayout>

And here is main class :
public class AssignmentDetail extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_announcement_detail);

    Intent intent = getIntent();
    //String course = intent.getStringExtra(Assignments.COURSE);
    //TextView textview = (TextView) findViewById(R.id.courseTitle);
    //textview.setText(course);

    String announcementTitle = intent.getStringExtra(Announcement.ANNOUCEMENT_TITTLE);
    TextView announcementTitleTextView = (TextView) findViewById(R.id.annoucementTitle);
    announcementTitleTextView.setText(announcementTitle);

}

And here is output :

You can see there are 4 textView and one button in my xml but i can see only onr textView in output, why it is so and how to fix it.
Thanks..
Anjum

A: Make sure following stuff is correct in ur activity :

*

*Make some changes in layout file and see it display that changed stuff

*Correct xml file layout is specified at setContentView.

It seems that you are using some other layout xml..try removing textview and run it..if it still shows that Assignment #1 then ur xml itslef is wrong

A: I think you are not inflating the right XML layout file.
You can see that the TextView that you modify at the end of your code is not present in the XLM file. Therefore the layout that you inflate cannot be the one you are showing us or you would have an error at run time.


text:
Q: How can I detect if there is no more paper in the printer with Java? How can I detect if there is no more paper in the printer, "paper out" with Java? I don't know if it is possible to do in Java, but I would like to use it if possible.
I am using Java on Windows.

A: I'm not java expert but I'd be very surprised if there was a java standard way of doing this. It's clearly depending on your specific printer and its driver.
Check if there is an SDK for your printer. In that case it is very likely to provide you an API to achive that.
It will most probably be a windows dll, you can interface with it through JNI.

A: If you use the Java Print Service API you can use the Attribute "PrinterIsAcceptingJobs" to test if the printer is ready.
http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/print/attribute/standard/PrinterIsAcceptingJobs.html
The print service api takes a while to learn but it's worth it IMHO.


text:
Q: How to get Universal time if my computer is not showing correct time with vb.net I am developing a desktop application in vb.net
I am facing a problem.
If my computer's time is not correct , then how can i get correct universal time ?

A: You could use something like this
http://www.codeproject.com/Articles/38276/An-SNTP-Client-for-C-and-VB-NET
to set the correct time on the computer.


text:
Q: The unit groups of $A = \mathbb{Z}[S,T]/(S^2-3S, T^2 - 6T, ST - 3T)$
Let $I = (S^2-3S, T^2 - 6T, ST - 3T)$, an ideal of $\mathbb{Z}[S,T]$, and $A = \mathbb{Z}[S,T]/I$.
  Decompose the unit group of $A[1/2]$ into a direct sum of cyclic groups.

I think the answer is $A[1/2]^* \cong \mathbb{Z}/2 \times \mathbb{Z}^3$.
But I can't show it.
Here is what I have tried:
First of all, $A$ is generated by $1,S,T$ as a$\mathbb{Z}$-module.
(Actually this is a basis, but I don't need it in my proof.)
Define an injection $g: A \to \mathbb{Z}^3$ by $1 \mapsto (1,1,1), S \mapsto (0,3,3), T \mapsto (0,0,6)$.
Localizing it by $2 \in A$, we have an injection $A[1/2] \to \mathbb{Z}[1/2]^3$.
So $a+bS+cT \in A[1/2]$ is unit only if $a, a+3b, a+3b+6c \in \mathbb{Z}[1/2]^*$.
And computing $(a+bS+cT)(d+eS+fT)$ directly, we have that $a+bS+cT \in A[1/2]^*$ iff $a, a+3b, a+3b+6c \in \mathbb{Z}[1/2]^*$.
So we have an injective group homomorphism $ h: A[1/2]^* \to (\mathbb{Z}[1/2]^*) ^3$.
We have $ \left< (2,2,2), (-2,1,1), (1,-2,1), (1,1,-2) \right> \subseteq \operatorname{Im}h$.
If the converse is true, then using the isomorphism $\mathbb{Z}[1/2]^* \cong \mathbb{Z}/2 \times \mathbb{Z}: a \mapsto (\operatorname{sgn}a, \log_2 |a|)$, we have $A[1/2]^* \cong \left< (0,0,0,1,1,1), (1,0,0,1,0,0), (0,1,0,0,1,0), (0,0,1,0,0,1) \right> \subseteq \mathbb{Z}/2 ^3 \times \mathbb{Z}^3$.
Finally, this group is isomorphic to $\mathbb{Z}/2 \times \mathbb{Z}^3$.
So my question is : $ \left< (2,2,2), (-2,1,1), (1,-2,1), (1,1,-2) \right> = \operatorname{Im}h$?
The previous part of the question also asks us to find all prime ideals of $A$ containing $2$.
(The answer is $(2,S,T)$ and $(2,S-3,T)$, I think.)
So I doubt that this strategy is not good to determine $A[1/2]^*$...
Thank you very much!

A: Let $G=\left< (2,2,2), (-2,1,1), (1,-2,1), (1,1,-2) \right>$; we will show any element $(a,a+3b,a+3b+6c)$ in the image of $h$ must be in $G$.  Writing $c=d/2-b/2$, we can instead write our element as $(a,a+3b,a+3d)$  Multiplying by a power of $(2,2,2)$ and possibly by $(-2,1,1)$, we may assume $a=1$.  Then $a+3b$ is either a power of $2$ or negative a power of $2$.  Multiplying by a power of $(1,-2,1)$, we can assume that $a+3b$ is either $1$ or $-1$.  But since $a=1$, we must then have $a+3b=1$, since otherwise we would need to have $b=-2/3$ which is not in $\mathbb{Z}[1/2]$.  Similarly, by multiplying by a power of $(1,1,-2)$ we may assume $a+3d=1$.  Thus by multiplying by elements of $G$, we have reduced our element of the image of $h$ down to just $(1,1,1)$, and so every element in the image of $h$ must be in $G$.


text:
Q: How to auto play this slider when i add auto play is true in javascript then slider is not working how i resolve this How to auto play this slider whan i add autoplay is true in javascript then slider is not working how i resolve this.

jQuery(document).ready(function($) {
 $('.banner_slider').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  arrows: false,
  fade: true,
  asNavFor: '.thumbnail_slider'
});

$('.thumbnail_slider').slick({
  slidesToShow: 6,
  slidesToScroll: 1,
  asNavFor: '.banner_slider',
  dots: false,
  arrows: false,
  centerMode: true,
  focusOnSelect: true,

  responsive: [
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 3,
        infinite: true,
        dots: false,
     arrows: false,
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2
      }
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    }
  ]

});

});

*{
 box-sizing: border-box;
}

img {
 max-width:100%;
}

.slider_wrap{
 position:relative;
}

.thumbnail_slider_area {
 position:absolute;
 left:0;
 bottom:0;
 width:100%;
 z-index:1;
}

.thumbnail_slider{
 border:1px solid #000;
 padding:1px;
}

.thumbnail_slider .col{
 padding:5px;
}

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>

<link rel="stylesheet" type="text/css" href="slick.css" />

[for slick css and js download link][1]

How to auto play this slider whan i add autoplay is true in javascript then slider is not working how i resolve this.

How to auto play this slider whan i add autoplay is true in javascript then slider is not working how i resolve this.

A: Working example:
<!DOCTYPE HTML>

        <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css" integrity="sha256-UK1EiopXIL+KVhfbFa8xrmAWPeBjMVdvYMYkTAEv/HI=" crossorigin="anonymous" />


text:
Q: What's the deal with 17- and 40-bit math in TI DSPs? The TMS320C55x has a 17-bit MAC unit and a 40-bit accumulator. Why the non-power-of-2-width units?

A: The 40-bit accumulator is common in a few TI DSPs. The idea is basically that you can accumulate up to 256 arbitrary 32-bit products without overflow. (vs. in C where if you take a 32-bit product, you can overflow fairly quickly unless you resort to using 64-bit integers.)
The only way you access these features is by assembly code or special compiler intrinsics. If you use regular C/C++ code, the accumulator is invisible. You can't get a pointer to it.
So there's not any real need to adhere to a power-of-2 scheme. DSP cores have been fairly optimized for power/performance tradeoffs.

A: I may be talking through my hat here, but I'd expect to see the 17-bit stuff used to avoid the need for a separate carry bit when adding/subtracting 16-bit samples.


text:
Q: gls with ML not working so I can't find the best model My question is close to this one which wasn't really answered: https://stackoverflow.com/questions/66571314/gls-with-arma-terms-not-working-for-one-combination-of-terms
I am running models to understand the trends highlighted by a Principal Component Analysis regarding variability in the morphology of some plants.
I have a set of quantitative (n=1, "PI", a percentage) and mostly qualitative (n=10, eg., Family, Genus, Species, leaf type) variables whose effect I would like to test on a quantitative variable "LMA" (a leaf thickness).
I initially used a GLM (because LMA data are neither normal nor homoskedastic) and on a reduced dataset because of a lot of lines with NAs for LMA.
In order to have a larger dataset, we supplemented LMA measurements with average values for some species (variable "Species") having n>5 LMA measurement. The variance of LMA is now highly heterogeneous and reduced for some of the species.
Thus, I switched to GLS to take into account this particularity with weights = varIdent(form=\~1|Species) and I made several models with method = REML to test the effect of the different variables (as some categorical variables were nested, I did not test them at the same time).
Today, I read several times that selecting the best fitting gls using AIC is only possible for gls made using ML (especially since not all my models have the same fixed effects).
A solution seems to be to make anova on the models updated in ML ... But ... it doesn't work for me ... (although I have no NAs in my dataset) ...
The problem is that depending on the models, the significant effects are different ... I have read that the best model is also the one that contains the most variables with a significant effect. Is this right? Should I just go back to this and choose my model based on this individual anovas?
I hope this post is quite clear and I sincerely thank you in advance!
-------
The dataset I use (all variables but "PI" are qualitative), I specified they were factors, there is no NAs.
x <- c("species_LMA", "Locality", "Family",
    "Genus", "Species", "specimen_TCT",
    "taxon_TCT", "combined_TCT", "cat_TCT",
    "PI", "Pheno", "Growth_form")
noNA4 <- subset(data2, complete.cases(data2[,
                x])) # n = 561

Here are are the different models I made:
xm1a <- gls(species_LMA ~ -1 + Family + PI +
    Locality + cat_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)
xm1b <- gls(species_LMA ~ -1 + Family + PI +
    Locality + specimen_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)
xm1c <- gls(species_LMA ~ -1 + Family + PI +
    Locality + combined_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)

xm2a <- gls(species_LMA ~ -1 + Genus + PI +
    Locality + cat_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)
xm2b <- gls(species_LMA ~ -1 + Genus + PI +
    Locality + specimen_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)
xm2c <- gls(species_LMA ~ -1 + Genus + PI +
    Locality + combined_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)

xm3a <- gls(species_LMA ~ -1 + Species + PI +
    Locality + cat_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)
#xm3b <- gls(species_LMA ~ -1 + Species + PI +
    Locality + specimen_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA3, na.action=na.omit)
# do not work for some reason ... correlation?`
xm3c <- gls(species_LMA ~ -1 + Species + PI +
    Locality + combined_TCT + Pheno ,
    weights = varIdent(form=~1|Species),
    data=noNA4, na.action=na.omit)

Line to select the best model based on AIC (package MuMIn)
model.sel(xm1a, xm1b, xm1c, xm2a, xm2b, xm2c,
          xm3a, xm3c)

    Model selection table
         cat_TCT Fml Lcl Phn     PI spc_TCT cmb_TCT Gns Spc df    logLik   AICc  delta weight
    xm3c               +   +  8.254               +       + 60 -2051.166 4237.2   0.00      1
    xm3a       +       +   +  8.604                       + 56 -2064.354 4253.6  16.37      0
    xm2b               +   + 10.380       +           +     52 -2085.641 4286.3  49.10      0
    xm2c               +   +  9.439               +   +     49 -2092.155 4292.1  54.84      0
    xm2a       +       +   + 10.510                   +     45 -2105.152 4308.5  71.26      0
    xm1b           +   +   +  2.933       +                 47 -2111.535 4326.0  88.79      0
    xm1c           +   +   +  5.425               +         44 -2115.838 4327.5  90.26      0
    xm1a       +   +   +   + 11.680                         40 -2138.920 4364.2 127.04      0
    Models ranked by AICc(x)

# best option are *3c* then 3a, 2b, 2c, 2a, 1c, 1b, 1a but AIC are highly similar
# xm3c : LMA ~ Species + PI + Locality + combined_TCT + Pheno

but since we took species-mean LMA, it is quite logical ... if we consider the relation to species is biased because we used species mean values, then the best model would be xm2b: LMA ~ Genus + PI + Locality + specimen_TCT + Pheno
What I tried to update the model (here an example for two of them) to ML to evaluate their performance using AIC (and resulting error message).
anova(update(xm3c, . ~ ., method = "ML"), update(xm2b, . ~ ., method = "ML"))`

    Error in eigen(val, only.values = TRUE) :
      infinite or missing values in 'x'

Example of anova results for 3 models. The problem is that depending on the models, the significant effects are different ...
    anova(xm1b)
    Denom. DF: 531
                 numDF   F-value p-value
    Family           9 2137401.7  <.0001
    PI               1       0.1  0.7331
    Locality         1     118.4  <.0001
    specimen_TCT    10       5.2  <.0001
    Pheno            1       0.1  0.7080

    > anova(xm2b) # nothing but Species is significant... marginal corr of PI...
    Denom. DF: 526
                 numDF   F-value p-value
    Genus           14 247220.46  <.0001
    PI               1      2.76  0.0970
    Locality         1      0.10  0.7500
    specimen_TCT    10      0.56  0.8456
    Pheno            1      0.41  0.5226

    anova(xm3c) # nothing but Species is
                # significant
    Denom. DF: 518
                 numDF   F-value p-value
    Species         25 195602.70  <.0001
    PI               1      2.12  0.1463
    Locality         1      0.18  0.6691
    combined_TCT     7      0.75  0.6304
    Pheno            1      0.17  0.6784

A:
I initially used a GLM (because LMA data are neither normal nor heteroskedastic [maybe you meant "homoskedastic"?])

That might not be necessary. The distributional issues have to do with errors around the model predictions, not the raw data.

we supplemented LMA measurements with average values for some species

That's not typically a good way to deal with missing data. See Stef van Buuren's Flexible Imputation of Missing Data for the advantages of creating multiple imputed data sets so that you have the best chance of avoiding bias while including the variance arising from filling in missing data.

Example of anova results for 3 models. The problem is that depending on the models, the significant effects are different ...

Check the documentation for how anova() works with those model objects. It's possible that it uses a sequential Type I method so the order of variables in the model might affect the apparent "significance" of the individual predictors.
It's not clear why you are doing separate models for each of cat_TCT, specimen_TCT and combined_TCT. It's generally better to start with as many predictors in a model as reasonable without overfitting, even if some predictors are somewhat correlated. (If predictors are linearly dependent or close to that, you should choose a linearly-independent set.)
I don't know why you are having troubles with ML versus REML. You can't compare AIC values among models having different fixed effects that are fit via REML. Work through one step at a time to see the source of the error, instead of combining updates with anova().


text:
Q: Smart way to use Collation from Spring Data ReactiveMongoRepository We are developing an Application on Spring 5 Reactive Stack. For persistance we use MongoDb with ReactiveMongoRepository (ReactiveCrudRepository) from Spring Data.
Currently for fetching data we are using a Query like
@Query("{ 'ownerId': ?0, filePath: {$regex: ?1}, tags: { $all : ?2}}")
Flux<Media> findAllByOwnerIdAndFilePathRegexAndTagsContainingAll(String ownerId, String pathRegex, List<Tag> tags);

Now we want to get the data by incasesensitive tags. For this I've created a index in the db with a collation like { locale: 'en', strength: 2 } as described here.
Now i want to get my data from db with using the index. The MonogoDB way would be db.media.find( { filePath: "/example/" } ).collation( { locale: 'en', strength: 2 } ).
Does someone know a smart way to use Collations from ReactiveMongoRepository?

A: With the current versions of Spring Data you need to use MongoOperations providing a Query that defines the Collation.
Please refer to the Reference Documentation for details on that.
Please make sure to also check out/comment on DATAMONGO-1854 which proposes adding collation to @Query.


text:
Q: Remove first columns of every tibble in list in R I have a list with several tibbles comprising several columns; and I want to remove the first 2 columns in each tibble (not using for loop).
 #Example data with tibble and list
 w <- c(1, 2, 3, 4, 5)
 x <- c(1, 2, 3, 4, 5)
 y <- c(1, 2, 3, 4, 5)
 z <- c(1, 2, 3, 4, 5)
 tibble <- tibble(w, x, y, z)
 list <- list(tibble, tibble, tibble, tibble)

 #Remove the first 2 columns in the tibble
 tibble1 <- subset(tibble, select=-c(1:2))
 tibble1

 #Tried this to remove the first two columns of each tibble in list
 list1 <- sapply(list, FUN = function(x) subset(x, select=-c(1:2)) )
 list1

A: You could replace sapply with lapply to get expected output as list
lapply(list, FUN = function(x) subset(x, select=-c(1:2)))

With sapply you need to add simplify = FALSE
sapply(list, FUN = function(x) subset(x, select=-c(1:2)), simplify = FALSE)

Another alternative is to use [ to subset which is shorter and concise.
lapply(list, `[`, -c(1, 2))

A: you can try:
library(purrr)
list %>% map(subset,select=-c(1:2))

A: Another base R method using Map:
Map(function(x){x[,-c(1:2)]}, df_list)

Data:
require("tidyverse")
w <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
y <- c(1, 2, 3, 4, 5)
z <- c(1, 2, 3, 4, 5)
tibble <- tibble(w, x, y, z)
df_list <- list(tibble, tibble, tibble, tibble)


text:
Q: How can I make a RelativeLayout scrollable without using a ScrollView? I've got a RelativeLayout and I need to obtain a scrollable Layout without using a ScrollView, how can I do this?

A: Use ListView or RecycleView and make your RelativeLayout as an item of ListView or RecycleView.  You can follow it - Android 5.0 - Add header/footer to a RecyclerView


text:
Q: JSON ListVIew in Fragment - doInBackground() error I'm trying to get list from JSON in the fragment on button click. Just when I thought I had all figured out I hit the wall. So if anyone can take a look and if you know whats wrong please explain it to me since I'm android beginner(php and js only).
public class ExampleFragment extends Fragment {

    ListView list;
    TextView id;
    TextView zip;
    TextView city;
    TextView state;
    TextView country;
    Button Btngetdata;

    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();

    //URL to get JSON Array
    private static String url = "http://url.com/web_services/get_cities.php";

    //JSON Node Names
    private static final String TAG_ARRAY = "cities";
    private static final String TAG_ID = "id";
    private static final String TAG_CITY = "city_text";
    private static final String TAG_ZIP = "zipcode_text";
    private static final String TAG_STATE = "state_text";
    private static final String TAG_COUNTRY = "country_text";

    JSONArray cities = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        oslist = new ArrayList<HashMap<String, String>>();
        Btngetdata = (Button)getView().findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONParse().execute();
            }
        });

    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {

        private ProgressDialog pDialog;
        JSONparser jParser = new JSONparser();
        private JSONObject json;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            city = (TextView)getView().findViewById(R.id.city);
            state = (TextView)getView().findViewById(R.id.state);
            country = (TextView)getView().findViewById(R.id.country);
            id = (TextView)getView().findViewById(R.id.id);
            zip = (TextView)getView().findViewById(R.id.zip);

            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {

            // Getting JSON from URL
            json = jParser.getJSONFromUrl(url);

            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {

            pDialog.dismiss();
            try {
                 // Getting JSON Array from URL
                 cities = json.getJSONArray(TAG_ARRAY);

                 for(int i = 0; i < cities.length(); i++){

                     JSONObject c = cities.getJSONObject(i);

                     // Storing  JSON item in a Variable
                     String id = c.getString(TAG_ID);
                     String zip = c.getString(TAG_ZIP);
                     String city = c.getString(TAG_CITY);
                     String state = c.getString(TAG_STATE);
                     String country = c.getString(TAG_COUNTRY);

                     // Adding value HashMap key => value
                     HashMap<String, String> map = new HashMap<String, String>();
                     map.put(TAG_ID, id);
                     map.put(TAG_ZIP, zip);
                     map.put(TAG_CITY, city);
                     map.put(TAG_STATE, state);
                     map.put(TAG_COUNTRY, country);

                     oslist.add(map);

                     list = (ListView)getView().findViewById(R.id.list);

                     ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
                         R.layout.list_item,
                         new String[] { TAG_CITY, TAG_STATE, TAG_COUNTRY, TAG_ID, TAG_ZIP }, new int[] {
                             R.id.city, R.id.state, R.id.country, R.id.id, R.id.zip});
                     list.setAdapter(adapter);
                     list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                         @Override
                         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                             Toast.makeText(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
                         }
                     });
                 }
            } catch (JSONException e) {
              e.printStackTrace();
            }
        }
    }
}

EDIT: Logcat posting

A: <manifest xlmns:android...>
     <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

A: Everything is clear from LogCat: you forgot to add permission to access Internet. Add it to the Manifest:
<uses-permission android:name="android.permission.INTERNET"/>

A: Your logcat clearly says Permission Denied (Missing Internet Permission), You need to add following line in your Manifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>

A: For future reference add this following code to avoid adding internet permission always for different application:
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA};

if(!hasPermissions(this,PERMISSIONS))
{
    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}

public static boolean hasPermissions(Context context, String... permissions)
    {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null)
        {
            for (String permission : permissions)
            {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
                {
                    return false;
                }
            }
        }
        return true;
    }


text:
Q: Wix : error LGHT0204 : ICE80: This 32BitComponent xxx uses 64BitDirectory yyy I want to create an installer (msi) for my application. I want to add a folder that contains lot of files.  So I use heat to create the wxs file for the folder.  The wxs file created looks like this :
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <DirectoryRef Id="INSTALLDIR">
            <Directory Id="dirD443000E4EC0AE53948090C1CD372519" Name="www">
                <Component Id="cmp258C40B6C01189153117075B9889DA7C" Guid="{23189859-29AE-46E6-A940-0B2307344910}">
                    <File Id="fil0DE52257C6EF99D33B0974915A17454E" KeyPath="yes" Source="$(var.WwwPath)\3rdpartylicenses.txt" />
                </Component>
                <Component Id="cmp85367E8DB342884A004620F1E4153AE4" Guid="{00EBB07A-6178-4072-B47C-2D9130CB96A7}">
                    <File Id="filB62696889B5411543CB3DFD6E2A1270D" KeyPath="yes" Source="$(var.WwwPath)\color.c7a33805ffda0d32bd2a.png" />
                </Component>
                ...
                ...

When I run my command light, I get a lot of error like this one (one per file):
error LGHT0204 : ICE80: This 32BitComponent cmp258C40B6C01189153117075B9889DA7C uses 64BitDirectory dirD443000E4EC0AE53948090C1CD372519

But the msi created seems to work as expected. But I would like to understand and remove that error if I could.
Any idea ?
Thanks

A: I've tried adding componnents atrributes Win64='yes' like in @Brian's comment, but it removed during build.
This answer helped me solve this issue.


text:
Q: C# - Iterate over all possible pairwise combinations of array contents If I have a C# array of objects and want to iterate over all pairwise combinations, how is this best accomplished? For:
int[] list = new int[3] {100, 200, 300};

This would look like:
100, 200
100, 300
200, 300

Obviously, I want a function that can take an array of any size, and preferably is generic so that any object type could work.

A:
Try this:
public static IList<Tuple<T,T>> GetPairs<T>(IList<T> list)
{
    IList<Tuple<T,T>> res = new List<Tuple<T,T>>();
    for (int i = 0; i < list.Count(); i++)
    {
        for (int j = i + 1; j < list.Count(); j++)
        {
            res.Add(new Tuple<T, T>(list[i], list[j]));
        }
    }
    return res;
}

A: int[] input = new int[] {100, 200, 300};

List<int[]> result = new List<int[]>();

for(int i=0; i<input.Length-1; i++)
{
    for(int j=i+1; j<input.Length; j++)
    {
        result.Add(new int[]{input[i], input[j]});
    }
}

A: int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

        for (int i = 0; i < arr.Length; i++)
        {
            for (int j= i; j< arr.Length; j++)
            {
    if(i!=j)

                    //Console.Write(arr[i] + " " + arr[j]);
Console.WriteLine(arr[i] + " " + arr[j]);

            }
        }

Instead of 'int' you can take Object type. Then you need to maintain further checking.


text:
Q: struggling to get cookie information to print in PHP For some reason, I can't get the value of "price" from a cookie.
Here's the cookie info.
[{"label":"300 HOME ","price":150},{"label":"Yes, my phone line is (1234567890)","price":40},{"label":"internet 2","price":0},{"price":-25}]

And here's the code I'm using. What am I doing wrong?
<?php
$cookie = $_COOKIE["MonthlyOptions"];
$obj = json_decode($cookie);
print $obj->{'price'};
?>

A: Thanks to both @waterloomatt and @Ravi Patel for their suggestions. In the end, what was stopping me from progressing was the need to add stripslashes.
$cookie = (stripslashes( $_COOKIE["MonthlyOptions"] ));
$obj = json_decode($cookie);
print $obj[0]->price;


text:
Q: different output when I use lambda which return lambda too in c++? # pass by value
    #include "stdafx.h"
    #include <functional>
    #include <iostream>
    #include <string>
    std::function<void(int)> Foo(int v)
    {
        auto l = [v](int i)
        {
            std::cout << v << " " << i << std::endl;
        };
        return l;
    }

    int main()
    {
        //[](int e, int f) {std::cout << e << f; }(5, 6);
        [](int a, int b)
        {
            return [=](int c, int d)
            {
                int a1 = a, a2 = b, a3 = c, a4 = d;
                std::cout << a << " " << b << std::endl << c << " " << d << std::endl;
            };
        }(2, 3)(4, 5);
    }

# pass by reference
    #include "stdafx.h"
    #include <functional>
    #include <iostream>
    #include <string>
    std::function<void(int)> Foo(int v)
    {
        auto l = [v](int i)
        {
            std::cout << v << " " << i << std::endl;
        };
        return l;
    }

    int main()
    {
        //[](int e, int f) {std::cout << e << f; }(5, 6);
        [](int a, int b)
        {
            return [&](int c, int d)
            {
                int a1 = a, a2 = b, a3 = c, a4 = d;
                std::cout << a << " " << b << std::endl << c << " " << d << std::endl;
            };
        }(2, 3)(4, 5);
    }

my question is when I pass references, why the output is not the same as passing values?
mingw also has different values with reference-passing:

4 5
4 5

when I learn the little schemer, I try convert codes in the book to c++, then come up with the question.

A: a and b are dangling references at the point of call.


text:
Q: ArcGIS spatial joining problem I have two polygon layers, Land-use and Mesh.
I had this mesh layer in specific geometric way. Anyways, I want the mesh layer to have the landuse value of the maximum area it contains. Lets say that a polygon in the mesh contains three land use types (40% urban, 30% roads, 30% green areas). I want it to assign the value of urban because it has the biggest area.
I tried Spatial Join tool, but it did not give me what I was looking for. I used the (mode) as a Field Map of Join Features which should Use the value with the highest frequency but it did not work.


text:
Q: Convert all number abbreviations to numeric values in a text file I'd like to convert all number abbreviations such as 1K, 100K, 1M, etc. in a text file into plain numeric values such as 1000, 100000, 1000000, etc.
So for example, if I have the following text file:
1.3K apples
87.9K oranges
156K mangos
541.7K carrots
1.8M potatoes

I would like to convert it to the following in bash:
1300 apples
87900 oranges
156000 mangos
541700 carrots
1800000 potatoes

The command I have used is to replace matching strings of number abbreviations with their full numeric values like so:
sed -e 's/1K/1000/g' -e 's/1M/1000000/g' text-file.txt

My problem is that I cannot find and replace ALL of the possible number abbreviations when variation occurs. I'd like to do this until at least up to one decimal abbreviations.

A: Use numfmt from GNU coreutils, don't reinvent the wheel.
$ numfmt --from=si <file
1300 apples
87900 oranges
156000 mangos
541700 carrots
1800000 potatoes

If abbreviated numbers may appear as any field, then you can use:
numfmt --from=si --field=- --invalid=ignore <file

A: In a bit more of a programming way, and based on this answer, you can create a list of all possible conversion factors and preform the multiplications when needed:
awk 'BEGIN{f["K"]=1000; f["M"]=1000000}
     match($1,/[a-zA-Z]+/){$1 *= f[substr($1,RSTART,RLENGTH)]}
     1' file

A: Another option might be using bash only and a pattern with capturing groups, where you would capture either M or K. If the pattern matches, then test for one of them and set the multiplier and use bc
while IFS= read -r line
do
  if [[ $line =~ ^([[:digit:]]+(\.[[:digit:]]+)?)([MK])( .*)$ ]];then
    echo "$(bc <<< "${BASH_REMATCH[1]} * $([ ${BASH_REMATCH[3]} == "K" ] && echo "1000" || echo "1000000") / 1")${BASH_REMATCH[4]}"
  fi
done < text-file.txt

Output
1300 apples
87900 oranges
156000 mangos
541700 carrots
1800000 potatoes

Bash demo

A: With GNU awk for gensub():
$ awk '
    BEGIN { mult[""]=1; mult["k"]=1000; mult["m"]=100000 }
    { $1 *= mult[gensub(/[^[:alpha:]]/,"","g",tolower($1))] }
1' file
1300 apples
87900 oranges
156000 mangos
541700 carrots
180000 potatoes

A: Given:
$ cat file
1.3K apples
87.9K oranges
156K mangos
541.7K carrots
1.8M potatoes

Just for giggles, pure Bash (with sed and bc):
while read -r x y
do
    new_x=$(echo "$x" | sed -E 's/^([[:digit:].]*)[kK]/\1\*1000/; s/^([[:digit:].]*)[mM]/\1\*1000000/' | bc)
    printf "%'d %s\n" "$new_x" "$y"
done <file

Prints:
1,300 apples
87,900 oranges
156,000 mangos
541,700 carrots
1,800,000 potatoes

A: This might work for you (GNU sed):
sed -E '1{x;s/^/K00M00000/;x}
        :a;G;s/([0-9])(\.([0-9]))?([KM])(.*)\n.*\4(0*).*/\1\3\6\5/i;ta
        P;d' file

Create a lookup and store it in the hold space.
Append the lookup to each line and use pattern matching to replace the keys in the lookup by its value.
Finally print the line when no further matches are found.

A: Could you please try following, written and tested with shown samples in GNU awk.
awk '
{
  if(sub(/[kK]$/,"",$1)){
    $1*=1000
  }
  if(sub(/[mM]$/,"",$1)){
    $1*=1000000
  }
}
1
' Input_file

Explanation: Adding detailed explanation for above.
awk '                     ##Starting awk program from here.
{
  if(sub(/[kK]$/,"",$1)){ ##Checking condition if 1st field ends with k/K then do following. Substituting k/K in first field with NULL here.
    $1*=1000              ##Multiplying 1000 with current 1st field value here.
  }
  if(sub(/[mM]$/,"",$1)){ ##Checking condition if 1st field ends with m/M then do following. Substituting m/M in first field with NULL here.
    $1*=1000000          ##Multiplying 1000000 with current 1st field value here.
  }
}
1                         ##1 will print current line here.
' Input_file              ##Mentioning Input_file name here.

Output will be as follows.
1300 apples
87900 oranges
156000 mangos
541700 carrots
1800000 potatoes

A: Another awk variant:
awk '{q = substr($1, length($1));
$1 *= (q == "M" ? 1000000 : (q=="K"?1000:1))} 1' file

1300 apples
87900 oranges
156000 mangos
541700 carrots
1800000 potatoes

A: This performs a global substitution (in case you have >1 string to convert per line):
perl -pe 's{\b(\d+(?:\.\d+)?)([KM])\b}{ $1*1000**(index("KM",$2)+1) }ge' file

A: here's how to convert them to both base-2 and base-10 scales from kilo all the way to the recent addition of quetta-(Q) (10^30)
-— (plus one special case of treating B(illion) as G):
echo '1.3K apples
87.9K oranges
156K mangos
541.7K carrots
1.8M potatoes
1189.135311B peaches
1189.135311G grapes
73.3231T sourgrapes' | gtee >( gcat -b >&2;) |

.
{m,g,n}awk '

 ($!NF = sprintf("%s %s %s %s", __ = toupper($++_), __, __, $++_))^!_ + \
 ($_   = __ * ((_____ = (_+=_)^_*_--) + _-_^_--)^(sub("B$","G",__)^!_ * \
                    index(____="KMGTPEZYRQ",___=substr(__,length(__)))))^!_ + \
 ($++_ = __ * _____^index(____, ___))^(_-=_)' CONVFMT='%.f' |

column -t

.
     1  1.3K apples
     2  87.9K oranges
     3  156K mangos
     4  541.7K carrots
     5  1.8M potatoes
     6  1189.135311B peaches
     7  1189.135311G grapes
     8  73.3231T sourgrapes

1.3K          1300            1331            apples
87.9K         87900           90010           oranges
156K          156000          159744          mangos
541.7K        541700          554701          carrots
1.8M          1800000         1887437         potatoes
1189.135311B  1189135311000   1276824317816   peaches
1189.135311G  1189135311000   1276824317816   grapes
73.3231T      73323100000000  80619601034582  sourgrapes


text:
Q: How to disable the iOS inset bevel effect on tableview cells Is it possible to
Disable the inset bevel effect comes by default with iOS 5, see http://www.tim-oliver.com/2011/10/22/the-new-uitableview-in-ios5/, the question is - can we disable it? How?

A: set the separator style to UITableViewCellSeparatorStyleSingleLine
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;


text:
Q: CherryPy: remove version from header and error pages To prevent version disclosure, I would like CherryPy not to reveal its version. It is revealed on the error page and in the server header. How can this be disabled?

A: Adding onto Luc's answer;
In your config you should change your 'response.headers.server' to '' or something custom to hide the version in browser headers as well.
You can edit the template code as well to remove the Powered By.  For example this will replace it with a ''.
    cherrypy.__version__ = ''
    cherrypy._cperror._HTTPErrorTemplate = cherrypy._cperror._HTTPErrorTemplate.replace('Powered by CherryPy %(version)s\n','%(version)s')

A: This does not seem to be supported by CherryPy, but we can manage ourselves!
The error page template is hardcoded in _cperror.py and removing the version number from the template would only be possible through a custom error page. However, we can override the variable from which the version number is read:
cherrypy.__version__ = ''

Looking at usage of the variable, we see that this will affect both the error pages and the HTTP header:
/usr/local/lib/python3.6/dist-packages/cherrypy$ grep cherrypy.__version__ *.py
_cperror.py:         kwargs['version'] = cherrypy.__version__
_cprequest.py:       'Server': 'CherryPy/' + cherrypy.__version__,

The HTTP Server header will still mention CherryPy. This can be overridden, as mentioned by Baxter, by setting the config variable response.headers.server:
cherrypy.config.update({
    'response.headers.server': '',
    })

Your error pages will still disclose 'Powered by CherryPy', but at least no version number will be mentioned.
Note that both code snippets have to be put before starting the server (i.e. before you call cherrypy.quickstart(...)).


text:
Q: Spring Boot JUnit5: TypeCast Mocking Consider the below code,
JAXBElement<Response> jaxb=(JAXBElement<Response>) service.getResponse("abc",2000); //getResponse return an Object.

Response resp=jaxb.getValue(); // Null Pointer Exception

Now in JUnit I am mocking the "service.getResponse(...)"
@Mock
Service service;

when(service.getResponse(anyString(),anyInt()).thenReturn(new Response("value"));

Why am I getting NullPointerException here? Is this not the way to mock the given line?

A: You have to mock the response aswell.
JAXBElement<Response> jaxb=(JAXBElement<Response>) service.getResponse("abc",2000); //getResponse return an Object.

Response resp=jaxb.getValue(); // Null Pointer Exception

Junit here,
@Mock
Service service;

JAXBElement response = mock(JAXBElement.class);
when(service.getResponse(anyString(),anyInt()).thenReturn(response);
when(response.getValue()).thenReturn(something);


text:
Q: Whats the difference between writing MethodChannel bridge versus dart:ffi bridge to run c/c++ code to get the response? Before I start my question I want to point out that it's not similar this question.
Difference between writing platform specific code vs dart:ffi code. Here the questioner is asking the actual difference whereas I am trying to know the difference for the same task that can be achieved using both methods.
What's the difference in running native c/c++ code on the platform, getting the outcome on platform side(let's say Kotlin for instance) and sending it to dart via method channel versus writing the dart:ffi interface and directly calling the native c++ code. They basically will provide the same code execution. The only difference I see is that the MethodChannel call would be an async task vs dart:ffi which will be synchronous. Apart from the async behavior, will there be any difference(performance primarily) in getting the response from either of the technique.

A: Here is a tour repo for dart:ffi: https://github.com/Sunbreak/native_interop.tour

*

*Async/Sync

*

*For MethodChannel, both Dart -> Native and Native -> Dart are asynchronous

*For dart:ffi, Dart -> Native and Native -> Dart could be synchronous (except native call from non-mutator thread of Isolate)

*Memory

*

*For MethodChannel, each interop requires serilization/deseriliazation

*For dart:ffi, you'd easily write C-like memory-efficient operation

*Performance

dart:ffi synchronous interop has a good advantage on non-frequent small data
https://www.xdea.xyz/2020/11/flutter-platform-channel-%e6%80%a7%e8%83%bd%e6%b5%8b%e8%af%95/


text:
Q: Extending JBoss Data Virt ws translator to handle paginated source What is a good way to extend org.teiid.translator.ws to read a complete set of records by iterating over all pages returned by a paginated webservice?

A: Since the pagination of results is not part of any REST API standard (unlike OData), you would have to extend the current translator and provide that custom behaviour to scroll through the pagination. Unlike JDBC kind of resultset scrolling, you would need to devise a way to execute the URL with your offsets each time the Teiid engine asks for next batch of results. If you want an example take look at OData translator for similar flow.


text:
Q: Something goes wrong with fadeIn Hello I want to fadeOut image, and then do fadeIn with a new one, so I wrote a simple code, but something goes wrong, because when .photo img fadesOut, then fadesIn this same photo, but after, a few second its changes because of new "src", but even if browser didn't load a new image, the old one shound't show, becuase src is changed, but it shows, and after a second, maybe two changes to the new one. Can somebody tell me what's wrong?
var dimage = $next.children("img").attr("rel");
$(".photo img").fadeOut("slow", function () {
    $(".photo img").attr("src", dimage);
    $(".photo img").fadeIn("slow");
});

A: This may be because the image has to load after the src is altered.
Consider putting the image in a tag, then setting the css property to display:none.  This way the image will preload in the browser before your script runs and will be available when it does.

A: you aren't giving the new image enough time to load.
function loadImage (src) {
    return $.Deferred(function(def){
        var img = new Image();
        img.onload = function(){
            def.resolve(src);
        }
        img.src = src;
    }).promise();
}
var dimage = $next.children("img").attr("rel");
var imageLoadedDef = loadImage(dimage);
$(".photo img").fadeOut("slow", function () {
    def.done(function(src){
        $(".photo img").attr("src", src);
        $(".photo img").fadeIn("slow");
    });
});

A: the problem as highlighted is about images not ready for display when you call them, so the solution is to preload them before starting the slideshow, create a function with an array of images path
function preLoad(){
  var imgs = {'test1.jpg', 'test2.jpg', 'test3.jpg'};
  var img = document.createElement('img');
  for(var i = 0; i < imgs.leght; i++){
    img.src = imgs[i]; //all images gets preloaded at this stage
  }

  startSlider(); //here you will do your code
}


text:
Q: Get Google Drive Link in Google Sheets if the folder name matches I'm trying to find a script that can retrieve the folder link (of Google Drive) in Google Sheets when the folder name matches.
Below is the code which I used but it is only showing the first 2 drive links and after that, it is showing the error "Cannot retrieve the next object: iterator has reached the end"
function onOpen() {
  var sheet = SpreadsheetApp.getActive();
  var menu = [{name: "Get Folder Links", functionName: "getFolderLinks"}];
  sheet.addMenu("Custom Menu", menu);
}

function getFolderLinks() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 3;
  var data = sheet.getRange(startRow, 7, sheet.getLastRow() - startRow + 1, 1).getValues();

  for (var i = 0; i < data.length; i++) {
    var folderName = data[i][0];
    var folder = DriveApp.getFoldersByName(folderName).next();
    var link = folder.getUrl();
    sheet.getRange(i+startRow, 15).setValue(link);
    logger.log(query);
  }
}

Folder Names are in Column G3:G and the link to the folder will be shown in O3:O.
Need advice from community experts on the above code.
P.S: Can the code work on a real-time basis (without clicking on the button which is created by the above code) and without any limitations?
Thank you in advance.

A:
Cannot retrieve the next object: iterator has reached the end

This error means the folder does not exist when you call next().
I've modified your script to check if a folder exists:
function getFolderLinks() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 3;
  var data = sheet.getRange(startRow, 7, sheet.getLastRow() - startRow + 1, 1).getValues();

  for (var i = 0; i < data.length; i++) {
    var folderName = data[i][0];
    Logger.log(folderName);
    var folderIterator = DriveApp.getFoldersByName(folderName);
    if(folderIterator.hasNext()) //check if the folder exists
    {
        var link = folderIterator.next().getUrl();
        sheet.getRange(i+startRow, 15).setValue(link);
    } else
    {
      Logger.log("Folder not exist: " + folderName);
    }
  }
}

Can the code work on a real-time basis (without clicking on the button which is created by the above code) and without any limitations

To achieve this, you can schedule a Time-Driven trigger shown in the below picture:


text:
Q: Celery logging to file from inside the Django modules I have the following in my tasks.py
from celery.utils.log import get_task_logger
logger = get_task_logger("celery.task")

I have setup logging for celery.task in my settings.py and all the log from my tasks.py file are properly logged to file.
I have Django modules. These modules can be called directly from Django or by a Celery task. What I want is, if the module is called by Django, then logs should go to Django log file. If the module is called by a task, the log should go to celery task logger.
Example:
# tasks.py

from app.foo import MyFoo

@task(name="bar")
def boo():
    MyFoo.someFoo()

# app.foo.py

log = logging.getLogger(__name__)

I want the log messages inside MyFoo to go to celery log when run by a worker task.
Any ideas?

A: You should be able to configure loggers separately for Django process and Celery process, as if by definition they run in separate processes.
Actually I am surprised that the log output does not go to a separate log files; thus maybe it would make sense to you expose what kind of logging configurations you have already in-place.
Where Python logging output goes is defined by logging handlers.
Configuring logger for Django: https://docs.djangoproject.com/en/dev/topics/logging/
For Celery, there doesn't seem to be straightforward way to override logging settings. They seem to give a celery.signals.setup_logging where you could set a breakpoint, use logging API to reconfigure logging handlers to go to a separate log file.
http://docs.celeryproject.org/en/latest/configuration.html#logging
Alternatively, you can just pull out different logger object on a task level. When you execute a task you know whether it is executed from Django (eager) or Celery.
I have never done this myself, but apparently Celery tasks expose the task running context as self.request parameter (nothing to do with Python classes).
http://docs.celeryproject.org/en/latest/userguide/tasks.html#context
So at the beginning of your task function you could switch between the loggers:
# Define web_worker_logger
# Define task_logger

@task(name='example')
def moobar():
    logger = web_worker_logger if self.request.is_eager else task_logger


text:
Q: try to upload a file from a UWP app to flask restful web api, failed I'm trying to build a UWP application using C#. And I also build a restful web api using flask on my other device(i.e. raspberry pi). But when I tried to upload an image from UWP app to raspberry pi through the api, the raspberry pi didn't receive the file while the request seemed to be successful.
so, after running the web api on raspberry pi and then running the uwp app on windows 10, I got this return: "no file".
This is the code for my UWP app
public async void Upload_FileAsync(string WebServiceURL, string
FilePathToUpload){
    IStorageFile storageFile = await
    StorageFile.GetFileFromPathAsync(FilePathToUpload);

    IRandomAccessStream stream = await
    storageFile.OpenAsync(FileAccessMode.Read);
    HttpStreamContent streamfile = new HttpStreamContent(stream);
    HttpMultipartFormDataContent httpContents = new
                      HttpMultipartFormDataContent();

    httpContents.Headers.ContentType.MediaType = "multipart/form-data";
    httpContents.Add(streamfile, "file");

    var client = new HttpClient();
    HttpResponseMessage result = await client.PostAsync(
                       new Uri(WebServiceURL), httpContents);
    string stringReadResult = await result.Content.ReadAsStringAsync();
    textBox.Text = stringReadResult;
}

This is how I call the function
Upload_FileAsync("http://192.168.0.111:5000/upload",
             "c:\\pictures\\testImage3.jpg");

This is the code for rest api
from flask import Flask
from flask_restful import Resource, Api, reqparse
import werkzeug, os

app = Flask(__name__)
api = Api(app)
UPLOAD_FOLDER = 'static/img'
parser = reqparse.RequestParser()
parser.add_argument('file',
    type=werkzeug.datastructures.FileStorage,
    location='files')

class PhotoUpload(Resource):
    def post(self):
        data = parser.parse_args()
        if data['file'] == None:
            return "no file"
        photo = data['file']

        if photo:
            filename = 'received.png'
            photo.save(os.path.join(UPLOAD_FOLDER, filename))
            return "file uploaded"

api.add_resource(PhotoUpload, '/upload')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

What I am expecting is: successfully upload an image to raspberry pi through the api and store it on raspberry pi. But the actual output is "no file".
And the printout on raspberry pi was this:
[27/Jan/2019 17:18:02] "POST /upload HTTP/1.1" 200 -

so it seems the request was fine but the file wasn't in the request.

A: I've found the problem.
I forgot to parse the file name when calling this function:
httpContents.Add(streamfile, "file");

So, the proper way to do is:
httpContents.Add(streamfile, "file", Path.GetFileName(FilePathToUpload));

and now it works!


text:
Q: Get dates where category change happened for each user in dataframe I am using pandas==1.2.1
MRE:
x = pd.DataFrame({"date":["20201211", "20201211", "20201212", "20201222", "20201222","20201223",
                          "20201211", "20201211", "20201212", "20201222", "20201222"],
                  "userid":["A", "A", "A", "A", "A", "A","B", "B", "B", "B", "B"],
                  "category":[1,1,2,2,2,1, 33, 33, 33, 34, 34]})

which looks like this:
    date    userid  category
0   20201211    A   1
1   20201211    A   1
2   20201212    A   2
3   20201222    A   2
4   20201222    A   2
5   20201223    A   1
6   20201211    B   33
7   20201211    B   33
8   20201212    B   33
9   20201222    B   34
10  20201222    B   34

What I want to do is get dates for each user when their category changed
so desired dataframe should look like this:
user         cat_changed             changed_cat
  A      [20201212, 20201223]         [2, 1]
  B          [20201222]                [34]

I've tried grouping by userid, cate, date however stuck from there...

A: You could first get the transition points using diff() on the category, then index those transitions and aggregate as list:
>>> transitions = x.groupby('userid').category.diff().fillna(0).ne(0)
>>> x[transitions].groupby('userid').agg(list)

                          date  category
userid
     A    [20201212, 20201223]    [2, 1]
     B              [20201222]      [34]

A: You can try with df.shift considering both userid and category , then create a grouper column to group:
u = x[['userid','category']]
c = u.ne(u.shift())
out = (x.groupby(['userid',c.any(1).mask(c.all(1)).replace(0,np.nan)])
       .agg(list).droplevel(1))

print(out)

                        date category
userid
A       [20201212, 20201223]   [2, 1]
B                 [20201222]     [34]


text:
Q: Javascript setTimeout timing reliability I have recently started exploring Javascript in more detail, and how it executes within the browser. Specifically, the setTimeout function.
My understanding is that calling setTimeout(foo,x)
will pass a handle to foo to be executed after x milliseconds. How reliable is this timing? Obviously if another long-running script is still executing after x milliseconds then the browser won't be able to call foo, but can I be absolutely certain that setTimeout(foo,101) will always be executed after setTimeout(foo,100)?

A: First of all, the timeout is in miliseconds, therefor 1 sec = 1000 ms. consider that.
you can always be sure that delay of 1001 will be later than 1000.
BUT You must remember that if the 2nd methods relay on changes of the first method it doesnt mean it will work good.
the first methods can take for reasonable time of 3ms (not a complicated one) and the 2nd one can start only 1 ms after the first one causing your reliability on the first method to fail.
i would suggest not to use this feature but in some rare cases.
you can tag me in this answer comment for your specific case and i can suggest the right way to work it out.

A: In nodejs we may be able to time events very precisely by setting a timeout to expire shortly before the desired moment, and then creating a tight series of event-loop ticks, and after each one checking how close to the target time we've approached:

*

*Imagine Date.now() is currently, e.g., 11000 (unrealistic; just an example!)

*Determine we want to act in EXACTLY 4000ms

*Note that means EXACTLY when Date.now() === 15000

*Use setTimeout to wait less than 4000ms, e.g., 3800ms

*Keep awaiting microticks until Date.now() >= 15000

*

*This won't block the event loop

*(But it will keep your CPU very busy)

let preciseWaitMs = async (ms, { nowFn=Date.now, stopShortMs=200, epsilonMs=0 }={}) => {

  let target = nowFn() + ms;

  await new Promise(resolve => setTimeout(resolve, ms - stopShortMs));

  // Allow `epsilonMs` to shift our wait time by a small amount
  target += epsilonMs;

  // Await a huge series of microticks
  // Note: this will eat cpu! Don't set `stopShortMs` too high!
  while (target > nowFn()) await Promise.resolve();

};

(async () => {

  let t1 = Date.now();
  let target = t1 + 2000;
  console.log(`Trying to act in EXACTLY 2000ms; at that point the time should be ${target}`);

  await preciseWaitMs(2000);

  let t2 = Date.now();
  console.log(`Done waiting; time is ${t2}; deviation from target: ${t2 - target}ms (negative means early)`);

})();

Note that preciseWaitMs(4000) will never wait less than 4000ms. This means that, if anything, it is biased towards waiting too long. I added an epsilonMs option to allow the bias to be moved back according to the user; for example preciseWaitMs(4000, { epsilonMs: -1 }) may cancel out preciseWaitMs's bias towards always being late.
Note that some js environments provide a higher-precision current-time query than Date.now - for example, nodejs has require('perf_hooks').performance.now. You can supply a function like this using the nowFn option:
{ epsilonMs: -0.01, nowFn: require('perf_hooks').performance.now };

Many browsers support window.performance.now; try supplying:
{ epsilonMs: -0.01, nowFn: window.performance.now };

These settings achieve sub-millisecond "precise" timing; off by only about 0.01ms on average
Note the -0.01 value for epsilonMs is what seemed to work best for my conditions. Note that supplying fractional epsilonMs values is only meaningful if nowFn provides hi-res timestamps (which isn't, for example, the case with Date.now).

A: Most browsers use single thread for UI and JavaScript, which is blocked by synchronous calls. So, JavaScript execution blocks the rendering.

Events are processed asynchronously with the exception of DOM events.

but setTimeout(function(),1000) trick is very useful. It allows to:

Let the browser render current changes. Evade the "script is running too long" warning.
  Change the execution flow. Opera is special in many places when it comes to timeouts and threading.

So if another function is executing it will handle it by running in parallel.
another thing to setTimeout(function(),1000) her time is in millisecond not in seconds.


text:
Q: Using notation to sample rows from a data file and run individual T-test on the in R I am trying to do three steps with my data file.

*

*Resample from the data file 100 times with replacement. My code is below

    Q3<-question.3
    Q.3<-data.frame(question.3)
    resample<-Q.3[sample(100, replace = TRUE),]'

        x1    x2
    61     9.49 10.17
    18    10.96  9.42
    30    10.12  8.08
    51    10.72 10.23
    70    10.52  9.14
    87    10.32  8.32
    42    10.21  9.77
    72     8.66 10.80
    87.1  10.32  8.32
    76     8.78 10.15
    25    11.11  9.42
    29    11.68 12.37
    87.2  10.32  8.32
    66     7.91  7.96
    51.1  10.72 10.23
    22     9.24 11.57
    90     9.99 10.19
    92    10.02  9.30
    75    10.04 10.23
    8      9.83  8.96
    41     9.60  9.86
    79     8.59  8.93
    5      9.51  9.19
    10     9.27  7.50
    36    10.15 10.85
    68    11.26  8.47
    88     9.03  8.71
    79.1   8.59  8.93
    6      9.75  9.83
    58    11.05  8.58
    6.1    9.75  9.83
    21     9.94 13.32
    34     8.56 10.21
    10.1   9.27  7.50
    67     9.10  9.90
    35     9.59  9.65
    82    10.61  9.46
    62    11.18  8.71
    58.1  11.05  8.58
    77    11.50 10.94
    4     11.01 11.77
    71    10.92  9.51
    24    10.35  9.23
    26     9.91  9.49
    29.1  11.68 12.37
    96     9.33  8.62
    76.1   8.78 10.15
    81    13.52  8.69
    66.1   7.91  7.96
    34.1   8.56 10.21
    91     9.93 11.53
    100   10.52  9.94
    76.2   8.78 10.15
    86    11.55 10.26
    30.1  10.12  8.08
    59     9.22 11.00
    44     8.76 10.40
    83     9.93 10.49
    77.1  11.50 10.94
    73     8.34  8.90
    7      8.55  7.09
    58.2  11.05  8.58
    4.1   11.01 11.77
    37    10.29 10.80
    84    10.20  9.78
    87.3  10.32  8.32
    50    10.23  9.72
    8.1    9.83  8.96
    44.1   8.76 10.40
    76.3   8.78 10.15
    74    11.55 11.30
    51.2  10.72 10.23
    28    11.25 10.13
    53    10.54  9.43
    51.3  10.72 10.23
    47     7.65  8.56
    99    10.26 11.21
    96.1   9.33  8.62
    23     7.58 11.08
    43     9.20  8.84
    40     8.68  9.94
    31    10.16 10.32
    36.1  10.15 10.85
    62.1  11.18  8.71
    55    10.40 10.14
    20     9.95  9.71
    100.1 10.52  9.94
    80    10.34  7.09
    86.1  11.55 10.26
    6.2    9.75  9.83
    56     9.01  9.77
    51.4  10.72 10.23
    45     7.86  7.09
    77.2  11.50 10.94
    9      8.43  9.79
    48    10.28  9.52
    36.2  10.15 10.85
    69    10.92 10.14
    3      8.07 11.98
    38     9.41  9.60

*Conduct an independent sample t-test for each of the re-sampled data to obtain 100 p-values.

I am stuck here. I can conduct a T-test for the 2 columns but I am stuck on how to do this for reach row?
I tried unlisting my re-sample and using notation to work within the R object resample to collect T.test but this doesn't work.
resample1<-unlist(resample)
resample1[t.test(resample1,mu = .05),] #didnt work
resample1[t.test(resample,mu = .05, alternative = "greater",)] #didnt work

*I then want to extract the 100 p-values from each T-test. I want to code p-values <0.05 as 1 and p-values >0.05 as 0.

If I had the 100 values I would use a if else statement and the $ to fun the if statement in each row. I would use a for loop and if else statement to extract the p-values and code them as 1's and 0's

*I want to compute the mean to see if it is close to 0.05.

thanks
P.S I am using CTRL-K to make the code be in the right format for asking a question but its not working for some reason

A: Youi can try a tidyverse approach
library(tidyverse) # load required packages
library(broom)
set.seed(1234) # set seeding number for reproducibiliy
df <- data.frame(x1 = runif(1000), x2=runif(1000)) # some data  with 1000 rows
# calculate the pvalues using t.test.
pvals <- map_df(1:100, ~slice_sample(df, n = 100, replace = T) %>%
                        with(., t.test(x1, x2)) %>%
                        broom::tidy() %>% select(p.value))
pvals
# A tibble: 100 x 1
p.value
<dbl>
1  0.0360
2  0.405
3  0.774
4  0.265
5  0.614
6  0.482
7  0.808
8  0.956
9  0.459
10  0.184
# ... with 90 more rows

purrr's map function serves as loop with 100 iterations.
dplyr's slice_sample gives you 100 rows by chance and replacement.
broom::tidy function is used to easily extract p.values.
# how many values below 0.05
pvals %>%
  count(p.value > 0.05)
# A tibble: 2 x 2
`p.value > 0.05`     n
<lgl>            <int>
1 FALSE              8
2 TRUE              92

# mean pvalue
pvals %>%
  summarise(mean = mean(p.value))
# A tibble: 1 x 1
mean
<dbl>
  1 0.436


text:
Q: Replace an axiom of propositional calculus formal system P. We construct a new propositional calculus formal system $P'$. Different from $P$, axiom (A3) is changed to:
$$(\neg\alpha\rightarrow\neg\beta)\rightarrow((\neg\alpha\rightarrow\beta)\rightarrow\alpha)$$
Prove that the set of internal theorems of $P'$ and $P$ are identical.
Note: Axioms of $P$
(A$1$) - $(\alpha\rightarrow(\beta\rightarrow\alpha))$
(A$2$) - $((\alpha\rightarrow(\beta\rightarrow\gamma))\rightarrow((\alpha\rightarrow\beta)\rightarrow(\alpha\rightarrow\gamma)))$
(A$3$) - $(((\neg\alpha)\rightarrow(\neg\beta))\rightarrow(\beta\rightarrow\alpha))$
I've understood that if we mark the new axiom as (A4), we just need to prove that (A3) could be derived directly from (A1), (A2) and (A4). But I've tried different combinations and failed.

A: Here's how you can show that you can derive $A3$ from $A1$, $A2$, and $A4$.
As you yourself note, given $A1$ and $A2$, we can prove the Deduction Theorem for this system. So given that, let's try to show that for any $\alpha$ and $\beta$ we can derive $\alpha$ from $\neg \alpha \to \neg \beta$ and $\beta$:
$1. \neg \alpha \to \neg \beta$
$2. \beta$
$3. \beta \to (\neg \alpha \to \beta) \ (\text{by } A1)$
$4. \neg \alpha \to \beta \ (\text{MP } 2,3)$
$5. (\neg\alpha\rightarrow\neg\beta)\rightarrow((\neg\alpha\rightarrow\beta)\rightarrow\alpha)  (A4)$
$6. (\neg\alpha\rightarrow\beta)\rightarrow\alpha \ (\text{MP } 1,5)$
$7. \alpha \ (\text{MP } 4,6)$
OK, so we have shown that $\neg \alpha \to \neg \beta,  \beta \vdash \alpha$
By the Deduction Theorem, this means that $\neg \alpha \to \neg \beta \vdash  \beta \to \alpha$
And thus by the Deduction Theorem again, we have $\vdash (\neg \alpha \to \neg \beta) \to ( \beta \to \alpha)$


text:
Q: How to Debug JUnit tests similar to a regular Java program within Eclipse In eclipse, if I run a Java program in debug mode with no breakpoints, and if the JVM hits a NullPointerException, Eclipse will kindly highlight the offending line of code, and show the local variables, etc. Execution is paused. I can evaluate code using the Display tab, and so on.
But, if I run a JUnit test in debug mode, and the jvm hits a NullPointerException, the jvm does not pause, and I don't have a chance to see the local variables.
Is it possible to run JUnit tests so that the JVM will pause automatically when I hit a NullPointerException, without using breakpoints?
Edit:
Using JUnit 4 & Juno

A: Eclipse stops when the exception that's thrown is uncaught and would bump you out of main(). However, when you run with JUnit framework, all exceptions are caught by JUnit, so Eclipse does not stop.
Two solutions come to mind:

*

*set exception breakpoint to stop when NullPointerException is thrown

*use the exception's stack trace reported by JUnit and set the breakpoint on the line that throws the exception (that's the one I prefer).

A: *

*Open the Junit test case or Junit Test Suite you want to run.

*Place your Break Point.

*Right Click on the File and click on Debug As > Junit Test.

A: *

*Double click set breakpoint

*Use Debug mode to run in Eclipse
Hover on that line of code, and then click step over or f6

A: You can see it on JUnit tab, if you double-click on the line that has a problem, you'll go to the location where the null-pointer exception happened.
java.lang.NullPointerException        <--First line of the error
at.com.myProject.MyClass.myMethod(MyClass.java:theLineOfMyCode) <-- the line that you should double-click

After you do this, you will be redirected to the line of the error.


text:
Q: How would I extract data from a video with time stamps? I recently recorded a decent chunk of data by recording the mass of a digital scale by videoing it by hand on my phone. The mass is changing over time, and I am needing to look at the relationship there. The equipment I have was relatively limited, which is why I was not able to connect this scale directly to a data logger.
I would very much prefer not to have to manually go through every second of every video to log the data as it would be a very repetitive process.
Thus, I was hoping computer vision would be a good alternative but I have no idea how to go about it. Would anyone happen to know a program or tool I could use or create that can just read these numbers from the video and then record them with their timestamps, possibly as a .csv file?
I'd be willing to learn about computer vision or AI to do so myself as well, as I am interested in this area, but simply don't have experience in it, so any advice or tools would be greatly appreciated.


text:
Q: CSS styling Trello-like board with cards I'm building a board with cards inside, just like Trello board.
The JSFiddle is here
Here is the code:

TOP MENU ITEM 1

TOP MENU ITEM 2

Test Panel 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

Test Panel 2

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

Test Panel 3

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

Test Panel 4

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

And stylesheet:
.board-container {
  padding: 0px;
  margin: 0px;
  display: flex;
  flex-direction: column;
}

.board-top-menu {
  width: 100%;
  background-color: grey;
  display: flex;
  flex-direction: row;
  padding: 5px;
}

.board-top-menu-item {
  padding: 5px;
}

.board-top-menu-item:hover {
  background-color: #fefefe;
}

.board-content {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 5px;
  background-color: white;
  white-space: nowrap;
  height: 100%;
  width: 100%;
}

.cards {
  height: 100%;
  overflow-y: auto;
  padding-bottom: 20px;
}

.cards-container {
  width: 270px;
  display: inline-block;
  height: 100%;
  overflow: hidden;
  min-height: 100px;
  background-color: #e2e4e6;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
  border-radius: 3px;
  padding-bottom: 20px;
  margin-right: 10px;
  vertical-align: top;
}

.cards-container-head {
  position: relative;
  padding: 10px 15px;
  margin-bottom: 5px;
}

.cards-container-title {
  font-weight: bold;
  white-space: normal;
  width: 100%;
}

.card-container {
  width: 100%;
  margin: 0 auto 10px;
  background-color: #fff;
  min-height: 100px;
  border-radius: 5px;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
  transition: 0.15s;
}

.card-header {
  padding: 5px 10px;
  border-bottom: 1px solid #dbdbdb;
  white-space: normal;
  word-break: break-all;
  word-wrap: break-world;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

I cannot make my board scroll horizontally to see all card containers and vertically inside a card container.
Sometimes, as shown in fiddle, the containers get stucked one above another, and sometimes they scroll the whole page, not only the container.

A:

.board-container {
  padding: 0px;
  margin: 0px;
  display: flex;
  flex-direction: column;
}

.board-top-menu {
  width: 100%;
  background-color: grey;
  display: flex;
  flex-direction: row;
  padding: 5px;
}

.board-top-menu-item {
  padding: 5px;
}

.board-top-menu-item:hover {
  background-color: #fefefe;
}

.board-content {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 5px;
  background-color: white;
  white-space: nowrap;
  height: 100%;
  width: 100%;
}

.cards {
  height: 100%;
  overflow-y: auto;
  padding-bottom: 20px;
}

.cards-container {
  width: 270px;
  display: inline-block;
  height: 100%;
  overflow: auto;
  min-height: 100px;
  background-color: #e2e4e6;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
  border-radius: 3px;
  padding-bottom: 20px;
  vertical-align: top;
}

.cards-container-head {
  position: relative;
  padding: 10px 15px;
  margin-bottom: 5px;
}

.cards-container-title {
  font-weight: bold;
  white-space: normal;
  width: 100%;
}

.card-container {
  width: 100%;
  margin: 0 auto 10px;
  background-color: #fff;
  min-height: 100px;
  border-radius: 5px;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
  transition: 0.15s;
}

.card-header {
  padding: 5px 10px;
  border-bottom: 1px solid #dbdbdb;
  white-space: normal;
  word-break: break-all;
  word-wrap: break-world;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

TOP MENU ITEM 1

TOP MENU ITEM 2

Test Panel 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

Test Panel 2

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

Test Panel 3

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

Test Panel 4

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

ITEM 02

Material 1

A: I think you have an issue with how your elements are nested. Elements with the class cards-container seem to be nested within other elements with the same class. See the fiddle.

.board-container {
  padding: 0px;
  margin: 0px;
  display: flex;
  flex-direction: column;
}

.board-top-menu {
  width: 100%;
  background-color: grey;
  display: flex;
  flex-direction: row;
  padding: 5px;
}

.board-top-menu-item {
  padding: 5px;
}

.board-top-menu-item:hover {
  background-color: #fefefe;
}

.board-content {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 5px;
  background-color: white;
  white-space: nowrap;
  height: 100%;
  width: 100%;
}

.cards {
  height: 100%;
  overflow-y: auto;
  padding-bottom: 20px;
}

.cards-container {
  width: 270px;
  display: inline-block;
  height: 100%;
  overflow: hidden;
  min-height: 100px;
  background-color: #e2e4e6;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
  border-radius: 3px;
  padding-bottom: 20px;
  margin-right: 10px;
  vertical-align: top;
}

.cards-container-head {
  position: relative;
  padding: 10px 15px;
  margin-bottom: 5px;
}

.cards-container-title {
  font-weight: bold;
  white-space: normal;
  width: 100%;
}

.card-container {
  width: 100%;
  margin: 0 auto 10px;
  background-color: #fff;
  min-height: 100px;
  border-radius: 5px;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
  transition: 0.15s;
}

.card-header {
  padding: 5px 10px;
  border-bottom: 1px solid #dbdbdb;
  white-space: normal;
  word-break: break-all;
  word-wrap: break-world;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
/*Get rid of scrollbar from html */
html {
    overflow-x: hidden;
}
/* Add vertical scroll to card container */
.card-container{
  height: 50px;
  overflow-y: scroll;
}

TOP MENU ITEM 1

TOP MENU ITEM 2

Test Panel 1

ITEM 01

Material 1

Material 1

Material 1

Material 1

Material 1

Material 1

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

A: the html provided is a little messy but i think you need something like this :

TOP MENU ITEM 1

TOP MENU ITEM 2

Test Panel 1

ITEM 01

Material 1

ITEM 01

Material 1

ITEM 01

Material 1

content

i didn't do much on css but it should be something like this :
body { overflow:hidden; }
.board-container {
    padding: 0px;
    margin: 0px;
}

.board-top-menu {
    width: 100%;
    background-color: grey;
    display: flex;
    flex-direction: row;
    padding: 5px;
}

.board-top-menu-item {
    padding: 5px;
}

.board-top-menu-item:hover {
    background-color: #fefefe;
}

.board-content {
    display: inline-block;
    float: left;
    padding: 5px;
    background-color: white;
    white-space: nowrap;
    height: 100%;
    width: calc(100% - 300px);
}

.cards {
    height: 100vh;
    overflow-y: scroll;
    padding-bottom: 20px;
}

.cards-container {
    width: 270px;
    float: left;
    display: inline-block;
    height: 100%;
    min-height: 100px;
    background-color: #e2e4e6;
    box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    padding-bottom: 20px;
    margin-right: 10px;
    vertical-align: top;
}

.cards-container-head {
    position: relative;
    padding: 10px 15px;
    margin-bottom: 5px;
}

.cards-container-title {
    font-weight: bold;
    white-space: normal;
    width: 100%;
}

.card-container {
    width: 100%;
    margin: 0 auto 10px;
    background-color: #fff;
    min-height: 100px;
    border-radius: 5px;
    box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
    transition: 0.15s;
}

.card-header {
    padding: 5px 10px;
    border-bottom: 1px solid #dbdbdb;
    white-space: normal;
    word-break: break-all;
    word-wrap: break-world;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

See this pen


text:
Q: How to change default style for unstyled input elements Resorting to StackOverflow because weirdly enough I wasn't able to find an answer in Firefox docs or community.
I am trying to change the default style for form and input elements such as:

*

*buttons

*radios

*checkboxes

*select

*number

Once changed these should be the default styles of the browser and any over site CSS that specifies styles for these elements should override the new default Firefox style.
I am surprised there isn't a themes/styles Firefox market (or similar) to customize your Firefox default style, especially since Firefox is very pro customization. So if there are I'd appreciate if I could be pointd towards them.
I did manage to change the scrollbard completely via userChrome using this floating scrollbar. However if my understanding is correct, userChrome.js and userChrome.css is to customize and style the browser elements themselves, not the actual HTML contents of the page.


text:
Q: feeding categorical data to classifier Suppose I have the dataset in the following format:
col1    col2     col3      col4         col5 (to be predicted)
12      13       4         primary      12
1       15       2         secondary    13
5       7        8         primary      18
14      12       44        college      6

col5 needs to be predicted for some test data using col1, col2, col3 and col4
During training, col1, col2, col3 can be feeded as such in an array to the classifier but how to feed col4.
I am aware that this is categorical and need to be converted to numeric type, but even after assigning some number, it will still remain as nominal type.
So if primary=1, secondary=2 and college=3, the numbers 1,2 and 3 cant be compared as per their magnitude because they are still like labels, with no numerical significance.
So how should I proceed after this step... should they be normalized ? or any further should be done ?

A: You should use One Hot Encoding in such cases. Every possible categorial value creates new binary feature.
One Hot Encoding for Machine learning


text:
Q: Add color to the points in geom_point df1 <-data.frame(Mean = as.numeric(c("45.71329", "38.162915")), Std = as.numeric(c("7.366905257", "9.597423074")), Samples=c("C", "T"))

df2 <- data.frame(Samples=c("C","C","C","C", "T", "T","T","T"), Values=c(38.37464, 40.84156, 49.50789,54.12907, 26.72173, 34.76061,42.14296,49.02636 ))

ggplot(df1, aes(Samples, Mean)) +
 geom_col(color = "black", width = 0.4) +
 scale_fill_grey() +
 theme_classic() +
 geom_errorbar(aes(ymin = Mean - Std, ymax = Mean + Std),color = "black",width = .1) +
 ylim(0,60) +
 geom_point(df2, mapping = aes(x=Samples, y= Values))

Hi everyone,
I have some problems plotting this data. After the run of this code I obtain this barplot:

I would need to color the points in C and T in the same way. The lower one in C with the same color as the lower one in T, the higher one in C with the same color as the higher one in T (the same for the other in the middle).
How can I do to color the points of my choice?

A: You can use this code:
library(tidyverse)

  df1 <-data.frame(Mean = as.numeric(c("45.71329", "38.162915")), Std = as.numeric(c("7.366905257", "9.597423074")), Samples=c("C", "T"))

  df2 <- data.frame(Samples=c("C","C","C","C", "T", "T","T","T"), Values=c(38.37464, 40.84156, 49.50789,54.12907, 26.72173, 34.76061,42.14296,49.02636 ))

  df2 <- df2 %>%
    group_by(Samples) %>%
    mutate(points = ifelse(Samples == "C" & Values == min(Values), "lower",
                    ifelse(Samples == "C" & Values == max(Values), "higher",
                    ifelse(Samples == "C" & Values < max(Values) & Values > mean(Values), "middle high",
                    ifelse(Samples == "C" & Values > min(Values) & Values < mean(Values), "middle low",
                    ifelse(Samples == "T" & Values < max(Values) & Values > mean(Values), "middle high",
                    ifelse(Samples == "T" & Values> min(Values) & Values < mean(Values), "middle low",
                    ifelse(Samples == "T" & Values == max(Values), "higher",
                    ifelse(Samples == "T" & Values == min(Values), "lower", "")))))))))

  ggplot(df1, aes(Samples, Mean)) +
    geom_col(color = "black", width = 0.4) +
    scale_fill_grey() +
    theme_classic() +
    geom_errorbar(aes(ymin = Mean - Std, ymax = Mean + Std),color = "black",width = .1) +
    ylim(0,60) +
    geom_point(df2, mapping = aes(x=Samples, y= Values, color = points))

Output:


text:
Q: Get list of all values of an attribute in dynamo table without repeating I have a dynamodb table like this

name     company

Juan      comp1
Camilo    comp2
Andres    comp1
...       ...

And i want to get an array like this using boto3 and python3.8:
[comp1, comp2]

Is there a way to avoid query all rows and then filter the duplicates?

A: Unless company is part of the primary key structure, you will have to scan the entire table to determine all the unique values of the company attribute.  If getting a list of unique company items is a core access pattern in your application, you should consider storing your data differently.
Uniqueness in DynamoDB can happen in at least two ways.

*

*Primary Keys - Include unique attributes into the primary key structure.

*By enforcing the constraint when creating the item (e.g. using ConditionExpression and attribute_not_exists to enforce uniqueness).

If you want the company attribute to repeat throughout your table (which is totally fine), you might consider creating a secondary index with the company name as part of the primary key.  For example, you could have a Primary Key defined as a Partition Key of COMPANIES and a Sort Key of the company name.  That way, you could query the COMPANIES partition and get a unique list of company names.


text:
Q: How to add onMouseEnter on an react element located inside a link tag I wonder how to add event onMouseEnter on an react element that is located inside a link tag:

  <Container>

 console.log('onMouseEnter on div')}>
      ...

  </Container>

 doesn't work for me
I cannot change the structure of the code (put Container outside of the link) because I work on a extension that add some data on Instagram feed website, thus the a tag is from instagram.


text:
Q: Show RSS Feeds of IE as Screensaver Is there a way I can display the rss feeds that I have subsribed to using IE7 or IE8 under Vista and Windows 7 as a screensaver?

A: RSS Screensaver allows you to add new feeds and choose a background to display them on for a screensaver, although it cannot read them directly from IE unfortunately.

A: News Screensaver 2.2 has the ability to import your feeds.
But its not freeware.
or You can use 2Flyer RSS screensaver or John T's one.


text:
Q: Error getting the output of child process in node I have a c program (I didn't code it) that prints some data in the terminal. I launch the program as a child process in node with the spawn function.
const child_process = spawn('./myProgram', ['--arg']);

After that, I code the event to get the printed data:
child_process.stdout.on('data', function(data) {
        console.log(data);
});

When I run the program I can't see the output data from my c program in my nodejs terminal. If I initialize the child process with stdio as inherit it works.
const child_process = spawn('./myProgram', ['--arg'], {stdio :'inherit'});

The key point here is that I need to process that data in my nodejs app. I suppose the way the c file prints the data is not the standard one, so my nodjs program does not get it.

A: The file was outputting to stderr instead to stdout. It was fixed by adding the event to stderr:
child_process.stderr.on('data', function(data) {
        console.log(data);
});

@tadman got the answere.


text:
Q: How to show only current item children using wp_nav_menu? I have a 3-level WooCommerce category structure like this:

*

*Main Category 1

*

*Child Category 1

*Child Category 2

*

*Third-level Category 1

*Third-level Category 2

*Main Category 2

*

*Child Category 3

*Child Category 4

*

*Third-level Category 3

I'm trying to print out a list of subcategories whenever a user is on a category page BUT if the user is on the third level, I want to print out the siblings. Currently I'm using this code (found from here: https://christianvarga.com/how-to-get-submenu-items-from-a-wordpress-menu-based-on-parent-or-sibling/):
add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );

// filter_hook function to react on sub_menu flag
function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {
  if ( isset( $args->sub_menu ) ) {
    $root_id = 0;

    // find the current menu item
    foreach ( $sorted_menu_items as $menu_item ) {
      if ( $menu_item->current ) {
        // set the root id based on whether the current menu item has a parent or not
        $root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID;
        break;
      }
    }

    // find the top level parent
    if ( ! isset( $args->direct_parent ) ) {
      $prev_root_id = $root_id;
      while ( $prev_root_id != 0 ) {
        foreach ( $sorted_menu_items as $menu_item ) {
          if ( $menu_item->ID == $prev_root_id ) {
            $prev_root_id = $menu_item->menu_item_parent;
            // don't set the root_id to 0 if we've reached the top of the menu
            if ( $prev_root_id != 0 ) $root_id = $menu_item->menu_item_parent;
            break;
          }
        }
      }
    }

    $menu_item_parents = array();
    foreach ( $sorted_menu_items as $key => $item ) {
      // init menu_item_parents
      if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;

      if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
        // part of sub-tree: keep!
        $menu_item_parents[] = $item->ID;
      } else if ( ! ( isset( $args->show_parent ) && in_array( $item->ID, $menu_item_parents ) ) ) {
        // not part of sub-tree: away with it!
        unset( $sorted_menu_items[$key] );
      }
    }

    return $sorted_menu_items;
  } else {
    return $sorted_menu_items;
  }
}

And then using this shortcode to print the menus:
function displayRelaxSiblingmenuShortcode() {
    $displayRelaxSiblingMenu = wp_nav_menu( array(
      'menu'     => 'Päävalikko (2)',
      'direct_parent' => true,
      'sub_menu' => true,
      'menu_class' => 'relax-submenu',
      'depth' => 1
    ) );

    return $displayRelaxSiblingMenu;
}
add_shortcode('displayRelaxSiblingMenu', 'displayRelaxSiblingmenuShortcode');

Now this code works perfectly for printing out the siblings on the 3rd level because it prints out the children of the direct parent page I'm currently on. But when on a 2nd level page I would need to print out the children of the current page, NOT current page's parents children.
How should I modify the code to print out only child pages of current page using wp_nav_menu() ?
I'm creating a second shortcode to print out the child pages of current page so the same shortcode doesn't have to take into account if the page is 2nd or 3rd level.
I found a lot of solutions using wp_list_pages() but that doesn't really work with WooCommerce categories. I have a custom manually created menu with the structure I want to use. That's why I need to use wp_nav_menu()


text:
Q: What is the difference between HTML and 'rendered HTML' when rendering a webpage? As seen in numerous articles about webpage rendering. What is the difference between the two?
Another example: ("Once the request is done processing, your browser gets back the fully rendered HTML and displays it on the screen.") [https://www.freecodecamp.org/news/what-exactly-is-client-side-rendering-and-hows-it-different-from-server-side-rendering-bd5c786b340d/]
Another example: ("Server-side rendering (SSR) is an application's ability to convert HTML files on the server into a fully rendered HTML page for the client.") [https://www.omnisci.com/technical-glossary/server-side-rendering]
Bonus points for anyone who can give examples of actual differences in the code.

A: This is a common term when working with Single Page Applications (SPAs) built on React, Angular, Vue, etc. These frameworks render out Typescript/Javascript into browser-readable HTML. This is different then just making a raw .html file because these framework scripts are being 'rendered' as HTML.

A: Based on my understanding, HTML is a markup language that can be used to make web pages. Content wise, rendered or not, it will have the same tags , , and so on.
The only different I see as a user is that for a static HTML page, the id tags (e.g.

) and class tags will likely be same for each visit.
However for rendered HTML page, the ids and classes might be different each time. (e.g.

 for 1st time, but

 for the second).
One possible incentive for using rendered HTML is to prevent other people from using web crawlers or automated programs on the website. I hope this answers your question.


text:
Q: What is an example of Schreyer's Theorem? What is an example of Schreyer's Theorem?
I have read lots about the theorem but can't seem to find a concrete example. Can anyone give me an example or point me in the direction of finding one?
Theorem: