text:
Q: How to make a union query search using Criteria API I tried to make a search in db for several fields using input string.
What i've got using HQL.
   @Override
    public List<Teacher> searchByString(String str) {

        String[] fields  = {"fam", "name", "otch", "phoneNumber"};
        List<Teacher> result = new ArrayList<>();

        for (int i = 0; i < fields.length-1 ; i++) {
            result.addAll(em.createQuery(
                    "SELECT c FROM Teacher c WHERE lower(c." + fields[i] + ") LIKE lower(?1)")
                    .setParameter("1", "%" + str + "%")
                    .getResultList());
        }

        result.addAll(em.createQuery(
                "SELECT c FROM Teacher c WHERE to_char(c." + "dateOfBirth, 'yyyy-mm-dd'" + ") LIKE ?1")
                .setParameter("1", "%" + str + "%")
                .getResultList());

        return result;
    }

This example working, but i need to have it in Criteria. I found nothing about "union" in Criteria API. How can i achive this result?


text:
Q: Which are the correct sum of squares for repeated measures ? (balanced example) Below are three ways to fit a MANOVA model in R and to extract ANOVA tables from the fitted model. The design is balanced. All methods give different results.
The data are 5 groups of 4 individuals with three repeated measures shown in figure below

and simulated with the following R code:
R code:
library(ez)
library(nlme)
library(lattice)

##################################
### BALANCED DESGIN ##############
##################################
groups <- c("A","B","C","D","E")
n.groups <- length(groups)
n.individuals <- rep(4,n.groups) # four individuals per group
id <- unlist(lapply(1:n.groups, function(i) paste0(groups[i],1:n.individuals[i]))) # individual id
n <- length(id)
set.seed(666) # diabolic seed
dat <- data.frame(id=id,
           group=rep(groups, each=4),
           x=round(rnorm(n,2),1),
           y=round(rnorm(n,4),1),
           z=round(rnorm(n,6),1))
ldat <- melt(dat, id=c("id","group")) # data in long format
xtabs( ~ group+variable, data=ldat) # check design
# plot data:
xyplot(value ~ variable | group, groups=id, data=ldat,
       panel = function(...){
          panel.grid(h=-1,v=-3)
          panel.superpose(..., type = "o", lty=2, pch=16)
        }
)

#### 1st method : car package ####
mfit <- lm( cbind(x,y,z)~group, data=dat )
idata <- data.frame(variable=c("x","y","z"))
aov.carII <- Anova(mfit, idata=idata, idesign=~variable, type="II")
aov.carIII <- Anova(mfit, idata=idata, idesign=~variable, type="III")

#### 2nd method : ez package ####
aov.ezI <- ezANOVA(data = ldat,
               dv = value,
               wid = id,
               within = .(variable),
               between = group,
               type=1
)
aov.ezII <- ezANOVA(data = ldat,
                   dv = value,
                   wid = id,
                   within = .(variable),
                   between = group,
                   type=2
)
aov.ezIII <- ezANOVA(data = ldat,
                   dv = value,
                   wid = id,
                   within = .(variable),
                   between = group,
                   type=3
)

### 3rd method : generalized least-squares fitting  ###
gfit <- gls(value ~ group*variable, data=ldat,
            correlation=corSymm(form= ~ 1 | id),
            weights=varIdent(form = ~1 | variable))

Comparison of ANOVA tables:
With gls() there are two possible ANOVA tables:
>  two possible ANOVA tables with gls :
> anova(gfit, type="sequential")
Denom. DF: 45
numDF   F-value p-value
(Intercept)        1 1401.9971  <.0001
group              4    2.3793  0.0658
variable           2   79.5687  <.0001
group:variable     8    1.4759  0.1929
> anova(gfit, type="marginal") # differs from sequential except for interaction
Denom. DF: 45
numDF   F-value p-value
(Intercept)        1 23.527654  <.0001
group              4  1.383566  0.2548
variable           2 14.166517  <.0001
group:variable     8  1.475904  0.1929

The type I ANOVA with ez (type I is not available with car):
> #########################
> ### TYPE I STATISTICS ###
> #########################
> aov.ezI$ANOVA  # close to sequential anova(gfit)
Effect DFn DFd         F            p p<.05       ges
1          group   4  15  1.996615 1.467733e-01       0.1651121
2       variable   2  30 80.595661 8.605897e-13     * 0.7715479
3 group:variable   8  30  1.093567 3.945923e-01       0.1549055

> # car: no Type I available

The type II ANOVA:
> ##########################
> ### TYPE II STATISTICS ###
> ##########################
> aov.ezII$ANOVA # identical to Type I ez
Effect DFn DFd         F            p p<.05       ges
2          group   4  15  1.996615 1.467733e-01       0.1651121
3       variable   2  30 80.595661 8.605897e-13     * 0.7715479
4 group:variable   8  30  1.093567 3.945923e-01       0.1549055

> aov.carII # car is close to ez but differs except for the first factor

Type II Repeated Measures MANOVA Tests: Pillai test statistic
Df test stat approx F num Df den Df    Pr(>F)
(Intercept)     1   0.98072   763.01      1     15 2.810e-14 ***
group           4   0.34744     2.00      4     15    0.1468
variable        1   0.91386    74.26      2     14 3.519e-08 ***
group:variable  4   0.51812     1.31      8     30    0.2758
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The type III ANOVA :
> ##########################
> ### TYPE III STATISTICS ###
> ##########################
> aov.ezIII$ANOVA # identical to Type II except for the second factor
Effect DFn DFd         F            p p<.05       ges
2          group   4  15  1.996615 0.1467732928       0.1651121
3       variable   2  30 11.560705 0.0001895724     * 0.3263455
4 group:variable   8  30  1.093567 0.3945922933       0.1549055

> aov.carIII # identical to Type II except for the second factor and intercept

Type III Repeated Measures MANOVA Tests: Pillai test statistic
Df test stat approx F num Df den Df    Pr(>F)
(Intercept)     1   0.92734  191.436      1     15 6.038e-10 ***
group           4   0.34744    1.997      4     15 0.1467733
variable        1   0.65384   13.222      2     14 0.0005956 ***
group:variable  4   0.51812    1.311      8     30 0.2757596
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Here is in addition the SAS output which does not depend on the chosen type (tpes I, II and III yield the same table):
proc mixed data=ldat ;
class id group variable ;
model value = group variable group*variable / s htype=2 ;
repeated variable / subject=id type=un ;
run;quit;

I am particularly interested in Type II sum of squares. The different ANOVA tables are close from each other but there are some differences (the F value and/or degrees of freedom). I'd like to understand these differences.
For the ez package I don't even know whether the results are given under the sphericity assumption.

A: I'm afraid SAS gives "wrong" Type II test statistics.
I have learnt a lot of things.
Type II hypothesis
According to these slides by G. Monette and J.
Fox
the Type II test of an "effect" corresponds to a test for the nullity of a multivariate linear hypothesis about the parameters, say $H_0\colon\{L_{1\mid 2}\beta=0\}$ for a certain matrix $L_{1 \mid 2}$.
Actually $H_0$ is a ``conditional'' hypothesis (see the slides) and $L_{1\mid 2}$ depends on the asymptotic covariance matrix $V$ of $\hat\beta$.
For mixed models and/or models with a repeated structure the $L_{1\mid 2}$ matrix is obtained by estimating $V$,
but for classical linear models the $V$ matrix is proportional to ${(X'X)}^{-1}$ and there's no need to estimate it.
Classical linear model example
Consider for instance a classical two-way ANOVA model:
> library(car)
> dat <- Soils[-c(1,2),] # delete two rows of the Soils dataset
> xtabs(~Contour+Depth,data=dat) # the design is unbalanced
            Depth
Contour      0-10 10-30 30-60 60-90
  Depression    4     4     4     4
  Slope         4     4     4     4
  Top           2     4     4     4
> fit <- lm(pH~Contour*Depth, data=dat)

I have written a function which computes the $L_{1 \mid 2}$ matrix which is valid for any model with two crossed fixed factors facAand facB as long as the vcov()function returns the estimated asymptotic covariance matrix :
L12matrix <- function(fit, facA, facB, V=vcov(fit)){
  coefs <- names(coef(fit))
  facA.match <- str_detect(coefs,facA)
  L1 <- NULL
  p <- length(facA.match)
  for(i in 1:p){
    if(facA.match[i]){
      l <- rep(0,p)
      l[i] <- 1
      L1 <- rbind(L1,l)
    }
  }
  rownames(L1) <- coefs[facA.match]
  facAB.match <- facA.match & str_detect(coefs,facB)
  L2 <- NULL
  for(i in 1:p){
    if(facAB.match[i]){
      l <- rep(0,p)
      l[i] <- 1
      L2 <- rbind(L2,l)
    }
  }
  rownames(L2) <- coefs[facAB.match]
  L12 <- t(car:::ConjComp(t(L2),t(L1), V))
return(L12)
}

And indeed, with the linearHypothesis() function we get the same results as the Anova() function:
> L12 <- L12matrix(fit,"Contour","Depth")
> linearHypothesis(fit,L12)
Linear hypothesis test

Hypothesis: ...

Model 1: restricted model
Model 2: pH ~ Contour * Depth

  Res.Df    RSS Df Sum of Sq      F Pr(>F)
1     36 5.6592
2     34 5.3003  2   0.35891 1.1511 0.3283

> L12 <- L12matrix(fit,"Depth","Contour")
> linearHypothesis(fit,L12)
Linear hypothesis test

Hypothesis: ....

Model 1: restricted model
Model 2: pH ~ Contour * Depth

  Res.Df     RSS Df Sum of Sq      F    Pr(>F)
1     37 18.3119
2     34  5.3003  3    13.012 27.822 2.847e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> Anova(fit)
Anova Table (Type II tests)

Response: pH
               Sum Sq Df F value    Pr(>F)
Contour        0.3589  2  1.1511    0.3283
Depth         13.0116  3 27.8220 2.847e-09 ***
Contour:Depth  0.5268  6  0.5633    0.7564
Residuals      5.3003 34
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

A GLS example
Consider the simulated data and the fitted gls model of my previous post:
groups <- c("A","B","C","D","E")
n.groups <- length(groups)
n.individuals <- rep(4,n.groups) # four individuals per group
id <- unlist(lapply(1:n.groups, function(i) paste0(groups[i],1:n.individuals[i]))) # individual id
n <- length(id)
set.seed(666) # diabolic seed
dat <- data.frame(id=id,
                  group=rep(groups, each=4),
                  x=round(rnorm(n,2),1),
                  y=round(rnorm(n,4),1),
                  z=round(rnorm(n,6),1))
ldat <- melt(dat, id=c("id","group")) # data in long format

##
glsfit <- gls(value ~ group*variable, data=ldat,
            correlation=corSymm(form= ~ 1 | id),
            weights=varIdent(form = ~1 | variable))

The Type II test of the group factor is performed as follows:
> L12 <- L12matrix(glsfit, "group", "variable")
> linearHypothesis(glsfit, L12)
Linear hypothesis test

Hypothesis: ...

Model 1: restricted model
Model 2: value ~ group * variable

  Df  Chisq Pr(>Chisq)
1
2  4 9.5172    0.04939 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Here the linearHypothesis()function has returned the Wald $\chi^2$-test statistics for $H_0$, and
the  Wald $F$-test statistics is simply obtained by dividing by the degrees of freedom:
> 9.5172/4
[1] 2.3793

Unfortunately the Anova() function from the car package does not work for gls fitted models.
But here the Type II Wald $F$-test statistic is equal to the Type I Wald $F$-test statistic because the design is balanced, and this statistic is returned by the anova() function:
> anova(glsfit)
Denom. DF: 45
               numDF   F-value p-value
(Intercept)        1 1401.9971  <.0001
group              4    2.3793  0.0658
variable           2   79.5687  <.0001
group:variable     8    1.4759  0.1929

If the design were not balanced then the Type II Wald $F$-test statistic can be obtained by inverting the order of the factors:
gfit.reverse <- update(gfit, model = value ~ variable*group)
anova(gfit.reverse)

Note that the L12matrix(glsfit, ...) command only uses the fitted model glsfit to get the parameters names and to get the asymptotic covariance matrix from the default value of the V argument.
Thus we would get the same results by typing :
L12 <- L12matrix(fit, "group", "variable", V=vcov(glsfit))

The SAS bug ?
Now, what's the problem with SAS ?
For a classical linear model such as fit, no problem: it gives the same results as the Anova() function.
But for a model with a repeated structure, such as glsfit, the
SAS output is obtained as follows with the R tools introduced above:
> # SAS result :
> lmfit <- lm(value ~ group*variable, data=ldat)
> L12 <- L12matrix(glsfit, "group", "variable", V=vcov(lmfit))
> linearHypothesis(glsfit, L12)
Linear hypothesis test

Hypothesis: ...

Model 1: restricted model
Model 2: value ~ group * variable

  Df  Chisq Pr(>Chisq)
1
2  4 7.9864    0.09208 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Divide 7.9864 by 4 and you find the SAS output :

In other words, SAS gives the Wald $F$-test statistic for $H_0:\colon\{L_{1\mid 2}\beta=0\}$ but by taking the
$L_{1\mid 2}$ matrix obtained with
the covariance matrix of the classical linear model obtained by ignoring the repeated structure.
Conclusion
Is it a "bug" with SAS, something wrong ? That depends whether the SAS developers have an interpretation of their Type II table but it seems to be a naïve generalization of the classical linear model to more general linear models, whereas J. Fox and G. Monette provide in their slides a well interpretable general approach to Type II hypotheses (is it an old or  a recent approach ? I'd like to know).

A: About the difference between Type II and Type III with the car package:
In spite of the balanced design there is a difference because Type III tests depend on the specified contrasts. With orthogonal constrats there's no difference:
> mfit <- update(mfit, contrasts=list(group=contr.sum))
> Anova(mfit, idata=idata, idesign=~variable, type="III")

Type III Repeated Measures MANOVA Tests: Pillai test statistic
               Df test stat approx F num Df den Df    Pr(>F)
(Intercept)     1   0.98072   763.01      1     15 2.810e-14 ***
group           4   0.34744     2.00      4     15    0.1468
variable        1   0.91386    74.26      2     14 3.519e-08 ***
group:variable  4   0.51812     1.31      8     30    0.2758
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Finally with this example we could also suspect that SAS provides the Pillai statistic for factor group and the Wald statistic for factor variable. Yet I don't really know what's exactly going on... I will edit my posts in case of further understanding.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Map Dapper query multiple to strongly typed object? I have the following sproc:
CREATE PROCEDURE [dbo].[dapper_test_sproc]

AS
    BEGIN
        SET NOCOUNT ON ;

        DECLARE @Status INT = 1
        DECLARE @Msg VARCHAR(256) = 'Hello World'

        DECLARE @StatusLines TABLE
        (
          rule_code VARCHAR(20),
          rule_name VARCHAR(30),
          [status] INT,
          rule_error_msg VARCHAR(256)
        )

        INSERT INTO @StatusLines
        VALUES ('TEST1', 'TEST2', 1, 'TEST3')

        SELECT  @Status,
                @Msg

        SELECT  rule_code,
                rule_name,
                status,
                rule_error_msg
        FROM    @StatusLines
        FOR     XML RAW
    END

At the end of the sproc you can see two result sets.
I have used the following code in LinqPad to successfully query the data but I am struggling to get individual values out of the data. I do not understand the return types.
using var connection = this.Connection;

var sql = "dapper_test_sproc";

var p = new DynamicParameters();

var grid = await connection
    .QueryMultipleAsync(
        new CommandDefinition(
            sql,
            p,
            commandType: CommandType.StoredProcedure,
            cancellationToken: this.QueryCancelToken));

LINQPad.Extensions.Dump(grid.Read());
LINQPad.Extensions.Dump(grid.Read());

LinqPad shows the following information:

For example, calling grid.Read() does not return the full @Status and @Msg from the first result set. But I found out that grid.ReadSingle() does. And I have no idea why.
grid.ReadSingle()["Status"] throws an error Cannot apply indexing with [] to an expression of type 'object' okay so its an object, but what kind of object? And why cant I access any properties?
I now have working code, but the code is horribly ugly. The casting, and accessing elements at indexes seems highly error prone. Is there a better way to do this?
public async Task dapper_test_sproc()
{

    using var connection = this.Connection;

    var sql = "dapper_test_sproc";

    var p = new DynamicParameters();

    var grid = await connection
        .QueryMultipleAsync(
            new CommandDefinition(
                sql,
                p,
                commandType: CommandType.StoredProcedure,
                cancellationToken: this.QueryCancelToken));

    var firstResultSet = await grid.ReadSingleAsync();
    var secondResultSet = await grid.ReadSingleAsync();

    var firstResultSetDict = (IDictionary<String,Object>)firstResultSet;
    var statusBit = (int)firstResultSetDict.ElementAt(0).Value;
    var message = (string)firstResultSetDict.ElementAt(1).Value;

    var secondResultSetDict = (IDictionary<String,Object>)secondResultSet;
    var statusLinesXML = (string)secondResultSetDict.Single().Value;

    var passwordValidationStatusMessage = new PasswordValidationStatusMessage
    {
        Error = !Convert.ToBoolean(statusBit),
        Message = message
    };

    XmlSerializer serializer = new XmlSerializer(typeof(StatusLinesEnvelope));
    using var reader = new StringReader($"<root>{statusLinesXML}</root>");
    var statusLines = (StatusLinesEnvelope)serializer.Deserialize(reader);

    LINQPad.Extensions.Dump(passwordValidationStatusMessage);
    LINQPad.Extensions.Dump(statusLines);
}

[XmlRoot(ElementName = "row", Namespace = "")]
public class StatusLines
{
    [XmlAttribute(AttributeName = "rule_code")]
    public string RuleCode { get; set; }

    [XmlAttribute(AttributeName = "rule_name")]
    public string RuleName { get; set; }

    [XmlAttribute(AttributeName = "status")]
    public bool Status { get; set; }

    [XmlAttribute(AttributeName = "rule_error_msg")]
    public string RuleErrorMsg { get; set; }
}

[XmlRoot(ElementName = "root")]
public class StatusLinesEnvelope
{
    [XmlElement(ElementName = "row")]
    public List<StatusLines> Row { get; set; }
}

public class PasswordValidationStatusMessage
{
    public bool Error { get; set; }
    public string Message  { get; set; }
}

A: I do a little change to your Stored and added column names.
ALTER PROCEDURE [dbo].[dapper_test_sproc]

AS
    BEGIN
        SET NOCOUNT ON ;

        DECLARE @Status INT = 1
        DECLARE @Msg VARCHAR(256) = 'Hello World'

        DECLARE @StatusLines TABLE
        (
          rule_code VARCHAR(20),
          rule_name VARCHAR(30),
          [status] INT,
          rule_error_msg VARCHAR(256)
        )

        INSERT INTO @StatusLines
        VALUES ('TEST1', 'TEST2', 1, 'TEST3')

        -- Add column names
        SELECT  @Status [Status],
                @Msg [Msg]

        -- Add column names
        select (
            SELECT  rule_code,
                    rule_name,
                    status,
                    rule_error_msg
            FROM    @StatusLines
            FOR     XML RAW
        ) as XmlValue
    END

Now the code

using System.Data.SqlClient;
using Dapper;

var c = "connection_string";
var sql = "EXEC [dbo].[dapper_test_sproc]";

using (var connection = new SqlConnection(c))
{
    var res = await connection.QueryMultipleAsync(sql);
    var first = res.Read<First>().ToList();
    var second = res.Read<Second>().First();

    first.Dump();
    second.Dump();
}

class First
{
    public int Status {get; set;}

    public string Msg {get; set;}
}

class Second
{
    public string XmlValue {get; set;}
}

Update without ColumnName
Without a column name, you must get the values using the index positioning (also who uses the sproc), naming columns is always a good idea.
using (var connection = new SqlConnection(c))
{
    var res = await connection.QueryMultipleAsync(sql);
    var first = res.Read();
    var second = res.Read();

    var data1 = first.ToList().Select(p => (IDictionary<string, object>)p)
                .Select(o =>
                    new First {
                        Status = (int)o.Values.ToArray()[0],
                        Msg = (string)o.Values.ToArray()[1]
                    }
                );

    var data2 = second.ToList().Select(p => (IDictionary<string, object>)p)
                .Select(o =>
                    new Second {
                        XmlValue = (string)o.Values.ToArray()[0]
                    }
                );

    data1.Dump();
    data2.Dump();
}


text:
Q: How to make a phone call from Apple watch? Is there a way to make phone calls from WatchKit extension?
Below is my code.
NSExtensionContext *ctx = [[NSExtensionContext alloc] init];
NSString *cleanedString = [[@"1234567890" componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789-+()"] invertedSet]] componentsJoinedByString:@""];
NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", cleanedString]];
[ctx openURL:telURL completionHandler:^(BOOL success) {
    NSLog(@"fun=%s after completion. success=%d", __func__, success);
}];


text:
Q: Vertical center text using ms-box in IE 10 Here is a mixin to vertically center text in a box
@mixin box-center(){
/* Firefox */
  display:-moz-box;
  -moz-box-orient:horizontal;
  -moz-box-pack:center;
  -moz-box-align:center;

/* Safari and Chrome */
  display:-webkit-box;
  -webkit-box-orient:horizontal;
  -webkit-box-pack:center;
  -webkit-box-align:center;

  /* IE10 -Doesn't work! */
  display: -ms-box;
  -ms-box-orient:horizontal;
  -ms-box-pack:center;
  -ms-box-align:center;
}

This works perfectly in Chrome and Firefox.
But of course it doesn't work right in IE 10 (I haven't tested in older version of IE yet). The text stays at the top.
Here is a jsfiddle
Am I missing something?

A: IE10 doesn't implement the 2009 Flexbox spec, it implements the draft from March 2012.
This should be what you need:
.foo {
  display: -webkit-box;
  display: -moz-box;
  display: -webkit-flexbox;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -moz-box-orient: horizontal;
  -webkit-box-direction: normal;
  -moz-box-direction: normal;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-box-pack: center;
  -moz-box-pack: center;
  -webkit-flex-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -moz-box-align: center;
  -webkit-flex-line-pack: center;
  -ms-flex-line-pack: center;
  -webkit-align-content: center;
  align-content: center;
}

I do have a collection of Sass mixins for Flexbox that handles all prefixes properly for you that you're free to use now:  https://gist.github.com/cimmanon/4461470.  They've been submitted to the Compass project and should be available in the next version.

A: This works fine for me on IE 10. Here's the fiddle
Screenshot: http://img189.imageshack.us/img189/9135/eae7aabb6f494aeb8410553.png
display: -ms-flexbox;
-ms-flex-align: center;
-ms-flex-pack: center;
-ms-box-orient:horizontal;


text:
Q: Avoiding reordering of panels and toolbars in new QGIS project I can't find anything suiting the simple need of making a personal default ordering and look of toolbar items and panels.
I've saved a default project, but my toolbars are not in the same ordering as how I had them when saving the project. Then, for instance the "annotation panel" always shows, but I don't want to show it by default.
I know that there is the GUI customization and that I can uncheck the annotaion dock. But at a new session the panel is there again. And there's seemingly no way for keeping my desired layout and ordering of toolbars, docks/panels.

*

*QGIS version 3.12.3-București

*QGIS code revision 8234261527

*Compiled against Qt 5.11.2

*Running against Qt 5.11.2

*OS Version Windows 10 (10.0)


text:
Q: Group by in complex query with cases I have a table:
Visit (FromId, ToId, VisitTime)

where FromId and ToId are FKs to table
UserProfile (uid, name, age ...)

As a user with my UID I want to select all profiles I have visited or who visited me in one result set ordered by VisitTime and with the indication of the "direction of the visit".
I get data using this select:
SELECT  CASE WHEN a.FromID = 'yourIDHere'
            THEN c.Name
            ELSE b.Name
    END Name,
    CASE WHEN a.FromID = 'yourIDHere'
            THEN c.Age
            ELSE b.Age
    END Age,
    a.VisitTime,
    CASE WHEN a.FromID = 'yourIDHere'
            THEN 'You'
            ELSE 'Friend'
    END DirectionOfVisit
FROM    Visit a
    INNER JOIN UserProfile b
        ON a.FromID = b.Uid
    INNER JOIN UserProfile c
        ON a.ToID = c.Uid
WHERE   'yourIDHere' IN (a.FromID, a.ToID)
ORDER   BY a.VisitTime

Now it prints (pseudo output)
Jack (id1) | IN |12.12.2012
Jack (id1) | IN |11.12.2012
Jack (id1) | IN |11.12.2012
Jack (id1) | OUT | 13.12.2012
Jack (id1) | OUT | 12.12.2012
Michael (id5) | IN | 5.12.2012
Michael (id5) | OUT | 6.12.2012
Michael (id5) | OUT | 5.12.2012

I would like the list to be like this:
Jack | IN | 12.12.2012 (the most recent)
Jack | OUT | 13.12.2012 (the most recent)
Michael (id5) | IN | 5.12.2012 (the most recent)
Michael (id5) | OUT | 6.12.2012 (the most recent)

I know the GROUP command would solve it but it's too complex for me (beginner).

A: You could use GROUP BY along with an aggregate function to get the result. Since you want the most recent date for each name and type (IN/OUT), then you can use the max() aggregate function on the date column.  You will then use a GROUP BY on the other columns you want to return:
The basic syntax will be:
select
  name,
  type,
  max(date) date
from yourtable
group by name, type;

See SQL Fiddle with Demo
If you want to return the max date with your existing query, you can just expand the query to use:
select name, age, max(VisitTime), DirectionOfVisit
from
(
    SELECT  CASE WHEN a.FromID = 'yourIDHere'
                THEN c.Name
                ELSE b.Name
        END Name,
        CASE WHEN a.FromID = 'yourIDHere'
                THEN c.Age
                ELSE b.Age
        END Age,
        a.VisitTime,
        CASE WHEN a.FromID = 'yourIDHere'
                THEN 'You'
                ELSE 'Friend'
        END DirectionOfVisit
    FROM    Visit a
        INNER JOIN UserProfile b
            ON a.FromID = b.Uid
        INNER JOIN UserProfile c
            ON a.ToID = c.Uid
    WHERE   'yourIDHere' IN (a.FromID, a.ToID)
) d
group by name, age, DirectionOfVisit;

See SQL Fiddle with Demo


text:
Q: Is it true that the pt unit will ALWAYS physically measure consistently? Let's say I want to use the pt unit to make sure that my html pages look consistent across device/browser/os. My understanding of the pt is that it's supposed to be equal to 1/72 of an inch on the screen.
Codepen
HTML

CSS
div {
  background-color:black;
  height: 72pt;
  width: 72pt;
}

This produces more or less what looks like a 1" x 1" square on my screen (this is just a screenshot of what I see). However, I can physically put a ruler up to my display and measure it, and the result is more like 1 3/16".
My browser zoom level is 100%, so that is not affecting things. I'm using Chrome on Windows 8.1 with the default font size set (16 in Chrome). My OS scaling level is 100%.  I have a 24" monitor set to 1920x1080 resolution. Also of note, Chrome reports that the square is exactly 96x96 px.
This leads me to believe that what I have have heard, that 72pt = 1 physical inch in the real world on any given display/browser/OS combo, is NOT accurate. Is this correct?
Given this behavior, I assume that if I had a 22" monitor with the same resolution, the pixel density would be greater, and thus the square would appear smaller (perhaps closer to being exactly 1" as measured by a physical ruler).
How do Retina displays work with all of this? I assume the square will not appear twice as small (that would be silly). Is the browser doing some kind of internal handling of super high DPI displays? For instance, Chrome seems to have some concept of "device pixel ratio (DPR)" so that it can treat an iPad with a "true" resolution of 2048 x 1536 (DPR 2) as a more standard 1024 x 768. So I assume DPR ends up somewhat normalizing screens of drastically different DPI, but after that has been accounted for, different devices with different DPI/PPI will still see slightly different physical sizes of our square.

A:
Is it true that the pt unit will ALWAYS physically measure consistently?

No, CSS abandoned that requirement in 2011 as most ignored it anyway.
https://www.w3.org/Style/Examples/007/units.en.html has more detailed explanation

The so-called absolute units (cm, mm, in, pt and pc) mean the same in CSS as everywhere else, but only if your output device has a high enough resolution. On a laser printer, 1cm should be exactly 1 centimeter. But on low-resolution devices, such as computer screens, CSS doesn't require that. And indeed, the result tends to be different from one device to another and from one CSS implementation to another. It's better to reserve these units for high-resolution devices and in particular for printed output. On computer screens and handheld devices, you'll probably not get what you expect.
In the past, CSS required that implementations display absolute units correctly even on computer screens. But as the number of incorrect implementations outnumbered correct ones and the situation didn't seem to improve, CSS abandoned that requirement in 2011. Currently, absolute units must work correctly only on printed output and on high-resolution devices.
CSS doesn't define what "high resolution" means. But as low-end printers nowadays start at 300 dpi and high-end screens are at 200 dpi, the cut-off is probably somewhere in between.


text:
Q: How to pass multiple variables from jsp to servlet using ajax in javascript I'm new to jsp and ajax.
How to pass multiple variables to servlet using  xmlhttp.open("GET",servlet,false); from ajax in jsp.
I have two Select boxes like name and a phone no, I need to send that selected values to servlet, in servlet I pass address,city like multiple details to the jsp using ajax.

A: jQuery.ajax({
        url : "<portlet:resourceURL id='URL'/>",
        data : {
            "A":value,
            "B":Value
        },type : "POST",
        dataType : "json",
        success : function(data) {
        }

A: If you want to use GET, you can pass the variables by URL encode it and add them to the url request, like this :
var url = "/path/to/myservlet";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

If you have long datas to pass, using POST is the preferred way, here is an example of such code :
var http = new XMLHttpRequest();
var url = "/path/to/myservlet";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
      alert(http.responseText);
  }
}
http.send(params);

You will be able to read those datas in your servlet HttpServletRequest using the getParameter(String name) method.
Hope this helps. :-)


text:
Q: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type image/png on trying to send email I updated my project from Java 8 to 14. I also updated a bunch of dependencies in my project pom.xml. Now I have a problem whenever I try to send an email via the application. I tried many different solutions that I found online but none of them seems to work for me. Here is the error log:
javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    javax.activation.UnsupportedDataTypeException: no object DCH for MIME type image/png
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1365)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:88)
    at
    java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type image/png
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:885)
    at javax.activation.DataHandler.writeTo(DataHandler.java:316)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1687)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:991)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:561)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:84)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:883)
    at javax.activation.DataHandler.writeTo(DataHandler.java:316)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1687)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1906)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1315)
    ... 16 more
2020-09-02 17:00:03 INFO  EmailDirectSignOneTimeLogin:79 - direct sign url: http://localhost:3000/direct_sign/czDSIg3Fms
FINISHED JOB

Any help would be appreciated. If you need more info, please comment on the question.

A: This could use more information about what you're trying to do, but I happened to find this question while working on the same issue and also found this question and got the code below that works in Java 11:
            part = new MimeBodyPart();
            ByteArrayDataSource source = new ByteArrayDataSource(logoBytes, "image/png");
            DataHandler handler = new DataHandler(source);
            part.setDataHandler(handler);
            part.setHeader("Content-ID", "<Logo>");
            multipart.addBodyPart(part);


text:
Q: Creating YAML for Kubernetes with Python3 I am trying to create my Role YAML file for Kubernetes and I am getting stuck with this specific section of the needed YAML:
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", "list"]

I have tried to add it as a dictionary and then a list with a dictionary inside that for the -apiGroups line, but that then causes issues with the rest of the arguments for rules. I also am having issues with the [] showing up just like that when I am using yaml.dump even though I specify default_flow_style=False
def create_role_yml(role_filename, team_name, group_user):
    """
    https://kubernetes.io/docs/reference/
    access-authn-authz/rbac/#role-and-clusterrole
    """

    yml_file_kubernetes_data = dict(

        apiVersion='rbac.authorization.k8s.io/v1',
        kind='Role',
        metadata=dict(
            namespace=team_name,
            name=group_user,
            ),
        rules={
            [{'apiGroups':""}],
            'resourses': '[pods]',
            'verbs':'[get, watch, list]'}

        )

    with open(role_filename, 'w') as outfile:
        yaml.dump(yml_file_kubernetes_data, outfile,
                  default_flow_style=False)

I would like to open the YAML and it to look exactly like the Kubernetes reference YAML:
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", "list"]

but I am getting the [ ] seperated, and no - for apiGroup. This is my result:
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: pod-reader
rules:
apiGroups:
- "" # "" indicates the core API group
resources:
- "pods"
verbs:
-"get"
-"watch"
-"list"

A: What you try to do is not possible with the normal parameters you can hand to PyYAML's dump(),
which gives you only very course control using default_flow_style

*

*True: everything is flow style (JSON like)

*False: everything is block style

*None: leaf collections are flow style, and the rest block style

You reference YAML has both block style leaf collections: the value
for the key metadata, as well as flow style leaf collections: the
value for the key verbs. Without hacking the representer you cannot
achieve this in PyYAML.
The way more easy way to generate YAML in your particular form is by
read-modify-write your expected YAML with a parser that knows how to
keep the formatting. You can do that with ruamel.yaml, which is
specifically developed to preserve these kind of things (disclaimer: I
am the author of that package).
If your input file is input.yaml:
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace:
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", 'list']

(the single entry under metadata is on purpose, but you could specify both, or none if
you assign instead of update)
And the following program:
import sys
from pathlib import Path
import ruamel.yaml

yaml_str = """\
"""

in_file = Path("input.yaml")
out_file = Path("output.yaml")

team_name = "default"
group_user = "pod-reader"

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(in_file)
data["metadata"].update(dict(namespace=team_name, name=group_user))
yaml.dump(data, out_file)

gives output.yaml:
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", 'list']

Please note that apart from the block/flow style, also the single/double quotes
from the original and the comment are preserved. Your indentation
already matches the default, so that is not explicity set (yaml.indent(mapping=2, sequence=2, offset=0)).

A: The rules are actually an array of maps, so you'll want to change it to look like this:
#!/usr/bin/env python

import yaml

yml_file_kubernetes_data = dict(

    apiVersion='rbac.authorization.k8s.io/v1',
    kind='Role',
    metadata=dict(
        namespace='something',
        name='group',
        ),
    rules=[
        {
            'apiGroups': '',
            'resources': [ 'pods' ],
            'verbs': [ 'get', 'watch', 'list' ],
        }
    ],
    )

with open('rbac.yml', 'w') as outfile:
    yaml.dump(yml_file_kubernetes_data, outfile,
              default_flow_style=False)

If you want to explicitly use the [] array notation, you'll need to use something like ruamel.yml - honestly, it's really not worth it though. This is valid YAML


text:
Q: Sitemapnode parent menu item not clickable I have seen several other questions which address this but none of them address the issue I'm having.
If you remove the url property from a sitemap node it is still clickable, ie it still renders as an  tag so can be clicked and fires a postback. I have done this for 'parent' sitemapnodes in my menu, and it's causing issues as I don't want postbacks to be fired when these items are clicked.
In code I have made the parent menu items 'selectable = false', and they render as a span instead of an anchor, but the styling is completely different and I can't even get to the 'child' menu items as they disappear when I try to hover over them.
Is there a way of making 'parent' sitemapnode items non-clickable, non-anchor tags so that no postback is fired if they are clicked?
My code: Web.sitemap
<siteMapNode title="Maintenance" description="Admin functions" >
    <siteMapNode url="~/UserAdmin/UserAdmin.aspx" title="Manage Users" roles="Admin" description="Manage Users" />
    <siteMapNode url="~/UserAdmin/UserDetails.aspx?mode=new" title="Create User" roles="Admin" description="Create User"/>
</siteMapNode>

c#
if (node.Title == "Maintenance")
    e.Item.Selectable = false;

I've started looking into hacking the styling on my masterpage to apply the the class which is used on the anchor tag to the span which is rendered when setting selectable=false. But I'd rather not have to.
thanks in advance

A: Remove the URL Tag in the SiteMapNode and in the Web.Config add the
SecurityTrimmingEnabled = false

It will make that menu item non clickable.


text:
Q: Flexbox container in Chrome doesn't get 100% height Flexbox column container inside another flex container doesn't get 100% height in Chrome, but in Firefox and Edge all ok.
Codepen example
.container {
  display: flex;
  flex-direction: column;

  height: 100%;
  width: 100%;

  .inside-container {
    display: flex;
    flex-direction: column;

    height: 100%;

  }
}

A: You're missing a height: 100% on a parent element: <header>
Once you add that in, the layout works in Chrome, as well.
header {
   min-height: 100%;
   width: 100%;
   height: 100%; /* NEW */
}

Revised Codepen
When using percentage heights, Chrome requires that each parent element have a defined height. More details here:

*

*Working with the CSS height property and percentage values
When using percentage heights in flexbox, there are rendering differences among the major browsers. More details here:

*

*Chrome / Safari not filling 100% height of flex parent


text:
Q: cell text is not changing when segment value changed So my goal is to have the tableview cell text change when the segment value is changed. The first segment I have is for all events and the second segment is for purchased events. When the view loads it successfully displays all the events available, but when I change the segment value to purchased, the cell text stays the same and I want to know how I can fix this.
I created a function to grab the purchased event names from the Firestore database.
func getPurchasedEventName() -> String{
    getStudentID { (studid) in
        if let id = studid {
            self.docListener = self.db.collection("student_users/\(self.user?.uid)/events_bought").whereField("school_id", isEqualTo: id).order(by: "time_purchased", descending: true).addSnapshotListener(includeMetadataChanges: true) { (querySnapshot, error) in
                if error != nil {
                    print("Error fetching docs/ User deletion.")
                } else {
                    self.gotherePurchasedEvents = querySnapshot!.documents.map { document in
                        return PurchasedEventName(purchasedEventName: (document.get("event_name") as! String))
                    }
                    self.tableView.reloadData()
                }
            }
        }
    }

    return "\(gotherePurchasedEvents)"
}

This function is identical to the function I used to get all the event names, so I thought it would get the job done. Here is that identical function:
func getSchoolID() -> String {
    //Putting the function in a completion handler
     getStudentGrade { (studentGrade) in
        if let gradeForStudent = studentGrade {
            self.getStudentID { (studentID) in
                if let idForStudent = studentID {
                    self.docListener = self.db.collectionGroup("events").order(by: "time_created", descending: true).whereField("school_id", isEqualTo: idForStudent).whereField("for_grades", isEqualTo: gradeForStudent).addSnapshotListener(includeMetadataChanges: true) { (querySnapshot, error) in
                        if error != nil {
                            print("Error/ User Deletion")
                        } else {
                            self.gothereEvents = querySnapshot!.documents.map { document in
                                return EventName(eventName: (document.get("event_name") as? String) ?? "")
                            }
                            self.tableView.reloadData()
                        }
                    }
                }
            }
        }
    }

This grabs all the events.
Now I was getting a couple of index out of range errors as well while playing with the code, so I was checking tableView methods but couldn't see the issue, I'll attach those as well.
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CellDetails.studentDashCell, for: indexPath)
    if eventListSelector.selectedSegmentIndex == 0 {
        cell.textLabel?.text = gothereEvents[indexPath.row].eventName
    } else if eventListSelector.selectedSegmentIndex == 1 {
        cell.textLabel?.text = gotherePurchasedEvents[indexPath.row].purchasedEventName
    }

    return cell
}

The cellForRowAt() method.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if eventListSelector.selectedSegmentIndex == 0 {
        tableView.separatorColor = #colorLiteral(red: 0.3084011078, green: 0.5618229508, blue: 0, alpha: 1)
        tableView.separatorStyle = .singleLine
        return gothereEvents.count
    } else if eventListSelector.selectedSegmentIndex == 1 {
        tableView.separatorColor = #colorLiteral(red: 0.3084011078, green: 0.5618229508, blue: 0, alpha: 1)
        tableView.separatorStyle = .singleLine
        return gotherePurchasedEvents.count
    } else {
        tableView.separatorStyle = .none
        return 0
    }

}

The numberOfRowsInSection() method.
Now the thing with the events_bought collection, is that it can be empty and only have a test document, so i added indexes to filter out the query if you look in the getThePurchasedEventName() method. I tested it out by purchasing two events and making a function to check if they were actually in there.
  func checkIfEventsHaveActuallyBeenBought() {
    getStudentID { (studid) in
        if let id = studid {
            self.db.collection("student_users/\(self.user?.uid)/events_bought").whereField("school_id", isEqualTo: id).order(by: "time_purchased", descending: true).addSnapshotListener { (querySnapshot, error) in
                if error != nil {
                    print("Error loading docs")
                } else {
                    for document in querySnapshot!.documents {
                        print("\(document.data())")
                    }
                }
            }

        }
    }
}

This worked and printed two documents, but I can't figure out why when I switch the segmented control value, the cell text doesn't change to show the purchased events. If you need more clarification feel free to ask questions.

A: The relevant UISegementedControl code is missing, so I can't be certain, but it appears that you are expecting the tableview to automatically respond to changes in the segmented control?  This isn't how it works.  While your tableview methods will work to produce the correct cells for the current status of the segmented control, you are not telling them to do so when segmented control changes.
You need to use the control's target-action methods and to register for and respond to the value changed event.
When you set up the control you need to register for the event, and then implement the selector to respond to that event

//wherever you set up the seg control
let segmentedControl = UISegmentedControl(items:["All","Purchased"])
segmentedControl.addTarget(self, action: #selector(segDidChange), for: .valueChanged)

//then implement the selector method
@objc func segDidChange(control: UISegmentedControl) {
      tableView.reloadData()
}

This is a crude implmentation that just forces a tableview reload to refresh all the cells.   You may be able to do something more clever, maybe with the new tableview diffing methods.


text:
Q: Terminal=true only works with xterm in .desktop file I have explorer.desktop in ~/.local/share/applications with the following content:
[Desktop Entry]
Type=Application
Name=Explorer
Exec=lf
Terminal=true

I want to execute it with gtk-launch command, but I get:
gtk-launch: error launching application: Unable to find terminal required for application

It won't work unless I install xterm and use it as the wrapper around lf (which I don't want to, I use st).
Can I somehow change the behavior in a way that st is used?
Note: I have already tried alacritty and kitty and they have the same story as st.


text:
Q: How to setup DMZ with Airport behind a router (double NAT issue)? My cable provider shipped a new modem which includes WLAN, and thus also a router. It hands out 192.168.0.X adresses via DHCP.
My Airport's WAN side is connected to this router, and gets an address out of the above range. The ISP's router has no address reservation facility, so the address that the Airport gets can vary.
The Airport is configured to hand out 192.168.243.X addresses via it's own DHCP server. As expected it complains about "double NAT". For the moment I have fixed the issue by disabling the ISP's router and WLAN completely (bridge mode).
However, I'd actually like to use the feature. My desired setup would be:

*

*ISP's Router

*Airport, using e.g. 192.168.0.10

*Web Server, opening port 80, using e.g. 192.168.0.20. The ISP's router supports port forwarding, so I can do this.

On the Airport's LAN side, I'd like to span an independent 192.168.243.x subnet, that cannot be reached from the web server. In a way, the web server would be in a "DMZ", isolated from the rest of my home network.
The problem is: The Airport doesn't let me do this! When I connect any device to the LAN side of the Airport, I get a 192.168.0.x address from the ISP's router, and not a 192.168.243.x address from the Airport. The Airport acts like it is in bridge mode, even though it isn't.
How can I set this up the way I want to?

A: Out of the box, the Airport (and Apple's Time Capsule) insist that there not be two NAT/DHCP devices chained in a row. You're trying to do this, one being your broadband router, and the other your Airport. In this situation, the Airport will insist on being in bridging mode and letting the broadband router be the DHCP server.
The Airport detects this situation by looking at the IP address it gets. If it is one in a number of known ranges like 192.168.x.x, 172.x.x.x, or 10.x.x.x, it will balk.
So the way you get around this is by having your broadband router give out addresses in a range that's safe but not knows as a "private" address range. I found an article [1] recommending a block of addresses designated for "testing" purposes in the Amateur Packet Radio network (AMPRNet). The range is 44.128.x.x.  I set up my broadband router to use that range, and my TimeCapsule is happy to provide NAT as well. Problem solved.
[1] http://www.wa4dsy.com/robot/ooma-airport-hack

A: Turn of the DHCP server on your ISP's router. It might be answering faster than the AirPort DHCP server.


text:
Q: MissingMethodException in Xamarin.iOS I was facing the MissingMethodExeption while using the reflection method in Xamarin.iOS. My code works fine when Linker Behavior is set to Don't Link. But i am getting the above exception when Linker behavior is set to Link SDK assemblies. I have tried the workaround to set the --linkskip=System.Core but exception raised. Can you please let me know if you have any answer for this problem.
I am getting the error while performing the following operation. Activator.CreateInstance(resultType) as ScriptObject. Here resultType is a Type and ScriptObject is a class which perform some operations for me.

A: A quick and dirty way to avoid some methods/types to be linked out is to reference them in unused code:
if (false) {
    var a = new TypeToPreserve();
    a.MethodToPreserve();
}


text:
Q: Marketing Cloud - Does Corporate License include FTP and SFTP? as in the question I wonder whether MC Corporate License include FTP and SFTP?
From this link is not very clear. Is there an official comparison page between the different licences?
Thanks

A: Yes, each Marketing Cloud BU comes with an "enhanced" (s)FTP connected to it.
Most of my client have corporate editions, we use sFTP for all of them - without that, SFMC would have a rather large feature gap.
Have not seen an edition below corporate in the flesh, and this documentation says "contact your representative": https://help.salesforce.com/s/articleView?id=sf.mc_es_enhanced_ftp_guide.htm&type=5
...but from experience - corporate and above, definite yes.
And to reiterate: I would also be very surprised if lower editions didn't have it.


text:
Q: firebase rules, android, hardcoding write credentials into App so there is no Login I am working on an ANDROID/FIREBASE app that will run on 5 to 10 phones. It's for our truck drivers, and just for private use. These Drivers have never had a phone let alone an email before, so not tech savy to remember their login credentials. They barely speak English.
SO I want to hard code some kind of authentication method into the ANDROID app so there is no real login, but I can still write to the Firebase DB.  I do not want to leave this open to the world, so I do want to have write rules. I also want to do a WEB app with read, write.  It's an unusual case, but I can think of other cases like this.  I have another project where I want to control READ
Ive seen this answer... (but its 3 years old)
I was thinking of doing something like..
Function AllowTruckDriversWrite(TDID){
  if one of these {td01, td02, td03}
return true
else return false
}

{
  "rules": {
    ".read": true,
    ".write": AllowTruckDriversWrite(ValFromAndroidApp)
  }
}

But I am not sure how to pass ValFromAndroidApp from phone to the rules engine.
I was also thinking of using a VALIDATE
".validate": AllowTruckDriversWrite(ValFromAndroidApp)
I am still experimenting with these rules... looking for more documentation on them.  Does anyone have some suggestions, Ideas, thoughts on how to setup RULES for something like this?  Perhaps someone could clean up the rules code?    many thanks

A: I believe it would be a better if you actually create a user for them, take their phone, login into app but do not provide a signout option in the app. In this way, unless they literally uninstall the app, the app will not signout and you can track every driver. And even if something happens to their phone you can just simply login again on the new phone without loosing any data.
Since the app is private the userId (uid) of every user is up to you and you can have these rules :
"users":{
  "$uid":{
    ".read": true,
    ".write": "auth.uid == $uid"

  }
}

or maybe :
"users":{
  "$uid":{
    ".read": true,
    ".write": "auth.uid != null"

  }
}

I just thought this might help. Hope my answer was not very idiotic. ;-)


text:
Q: Hi i have a blocking error in vb 2008.In my project i used excel 2010 I have a blocking error in vb 2008( windows forms application ).
In my project I used excel 2010. I have added the statement 'Microsoft.Office.Interop.Excel' in my program.  I got a error that it is not a namespace member.
I learned that I need go add reference of a library component and so I downloaded and installed primary interop assembly service for excel 2010. Even now if I add my reference I get no change in components.
Still the same error.
help please.its urgent

A: Have you Office installed?
If not, you cannot use Interop.
If you have installed Office you should add a reference:
Go to my project -> references -> add -> com -> microsoft.excel.12(14).library. Then it should work. The 14 denotes that, depending on your version, the exact number will vary.
If you have no excel installed, you could try EPPLUS: http://epplus.codeplex.com/
It is a great library to read / write xlsx files, much more quickly and more comprehensible than interop.


text:
Q: Desktop virtualization Is there currently a proper Type 1 "desktop" hypervisor? Either free or not?
This is just for tinkering around at home on some beefy Phenom machines.
Basically i want to be able to run say 2 OSs on the same PC but without loading windows or a heavy flavour of linux and then use a hotkey to switch between them. I should get full performance out of them.

*

*So do i need something better than vmware workstation and/or virtualbox. I think these are "Type 2"? I already run VMWare w/s and VBox but is there a more performant solution?

*I saw a YouTube video from Citrix where a laptop was running XP and Vista. With the touch of a hot key they could switch between them. There was no visible underlying OS (there might be a hypervisor)? I have access to Citrix XenDesktop 3 enterprise edition evaluation. I realise this isn't for desktops but can i achieve my goal (geekiness) ?

*If i use the free XenServer 5.5.0 how do my client PCs access windows/linux/whatever from the xenserver? Is it via a thin client RDP type application? If so if there one for both windows and linux? Also if i do use XenServer can i use USB in either direction?

*What is Citrix receiver can i use that for (3) ? If so, is there some hotkey i can configure?

*whatever client is used to access the server software (whether it be on a different server or local) can i get full opengl/directx acceleration?

*what about Xen? i tried the Xen LiveCD but no clue as how to configure it.
As you can see much confusion. Any help/pointers welcome.
Cheers.

A: The nearest thing in concept to a dedicated Type 1 "Desktop" Hypervisor at the moment is probably Parallels Workstation Extreme although it is still a hosted Hypervisor. It relies heavily on relatively new hardware virtualization capabilities (Intel VT-d and Xeon 5500 series CPU's for starters) to allow the guests to selectively gain direct access to the graphics hardware as far as I can tell.  The problem I have with your question is that almost by definition a Type 1 Hypervisor generally does not support high end user interface components (specifically accelerated console graphics). I don't believe there's any huge technical roadblock but nobody seems to have been bothered to build one yet.
Your point on not wanting to take the burden of a heavy duty host OS is fair enough but if you take the approach that the Host OS is going to be one of the OS's you want to run then the "overhead" of this OS becomes less of an issue and that is the main reason that I believe no one has bothered to develop what you are asking for.
As to your other questions.

*

*The only Hypervisors that have better performance are "proper" Type 1 Hypervisors like ESX\i, Xen etc but these do not provide you with an accelerated GUI supporting console on the Host system so I would say that the current answer to your question is no in most cases. If VM graphics performance is what you are looking for then the aforementioned Parallels Workstation Extreme does perform better than the others but it has very limited hardware support as I noted above. The next version of VMware Workstation is rumoured to support significantly improved graphics performance (e.g. supporting Aero in Windows 7 Guests) but when it will be available I can't say. I'd assume the other hosted Hypervisor vendors are working on similar improvements as demand for this is pretty high.

*I run Vista with XP, Windows 7 & Ubuntu under VMWare Workstation as guests. The transition between them is seemless from my perspective (provided I have enough RAM)- I've never looked for a single click hotkey to switch between them but I can't see that it would be hard to implement. On my system the only reason I can immediately tell that I'm running in a VM vs natively is that the Guests currently don't support advanced graphics. For the most part the user experience when switching is "seemless" from my point of view.

*XenDesktop (like VMware View) is a desktop virtualization architecture but the VM's in question are intended to run on Host clusters in a company\organizations datacenters. Users access these machines via a Thin Client or a remote desktop application (ie they are either RDP or ICA remote desktop sessions). There are RDP and ICA clients available for Linux & OSX as well as Windows. There is also nothing stopping you running an in-band remote desktop app (like VNC) but the Hypervisor's remote console will be more useful and probably give better performance. I've used a number of Thin Clients that have quite slick hotkey switching between consoles so perhaps this is what you saw, it's not what I'd call a killer feature but it is neat enough.

*See above - you can download the clients from Citrix and various other repositories, Google is your friend and all that. I've no idea about Hot Key settings, I'd suggest you read the documentation for whichever client you pick as they are likely to vary.

*For the most part the answer to this is that advanced graphics support is not great at the moment but it should improve quite a lot fairly soon. There are some full 3D graphics remote console technologies out there that are becoming more mainstream such as  Teradici\PC-over-IP. While you can get that today for use with dedicated (ie non virtualized) workstation hardware like the Dell Precision R5400 rack mount workstation it is not yet available for VM's. Both VMware and Teradici have said that support for it will be integrated with VMware View V4 when that comes out. Citrix for their part have announced the HDX 3D ICA enhancements that will provide similar accelerated graphics capability for their guest OS's. You can find a pretty good blog post on HDX 3D here which covers this in some detail.

*Not sure what you are asking with this one.

A: The YT video you are referring to is in regards to XenClient. Take a look. http://www.citrix.com/English/ps2/products/feature.asp?contentID=1685500


text:
Q: ASP.NET and Active Directory - Messages Globalization I have an application developed in ASP.NET and uses Active Directory for authentication.
The error messages from Active Directory, when published on my computer, appear in Portuguese, but, when published on server, they appear in English and must appear in Portuguese. I have already put the globalization tag in the Web.config and not resolved. Does anyone know how I can solve this problem?


text:
Q: How to show a widget along a ListView on the same screen in Flutter? I'm trying to build a very simple ToDo app. It consists of a TextField and a Button (a form) on the top of the screen that allow the user to add items to the ListView that is just under the TextField.
I'm capable to display the TextField and the Button, and I'm also capable to display a ListView, but when I try to display both at the same time, the screen is empty.
Am I missing something? I try to display the ListView into a Column widget but it looks like it doesn't work.
Here is my short code without the form:
import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return MaterialApp(
      title: "Mon app",
      home: Scaffold(
        appBar: AppBar(
          title: Text("My app")
        ),
        body: Column(
          children: <Widget>[
            ListView(
          children: <Widget>[
            ListTile(
              leading: Icon(Icons.map),
              title: Text('Map'),
            ),
            ListTile(
              leading: Icon(Icons.photo_album),
              title: Text('Album'),
            ),
            ListTile(
              leading: Icon(Icons.phone),
              title: Text('Phone'),
            ),
          ],
        )
          ])),
      );
  }
}

Thanks!

A: You should use an Expanded widget around your ListView. What is does is to expand its child (in this case, the ListView) to fit the maximum available space on the parent, excluding the space taken by other widgets.
Then, when you want to add the input on the bottom, you can just put the normal widget there inside the Column, but outside the ListView, so the list will scroll and the TextField will always stay on the bottom of the page.
Here's the code with the bottom input ready, but I suggest you try to understand carefully what's going on with Columns, Rows and Expanded widgets.
import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return MaterialApp(
      title: "Mon app",
      home: Scaffold(
          appBar: AppBar(
              title: Text("My app")
          ),
          body: Column(
            mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Expanded(
                  child: ListView(
                    children: <Widget>[
                      ListTile(
                        leading: Icon(Icons.map),
                        title: Text('Map'),
                      ),
                      ListTile(
                        leading: Icon(Icons.photo_album),
                        title: Text('Album'),
                      ),
                      ListTile(
                        leading: Icon(Icons.phone),
                        title: Text('Phone'),
                      ),
                    ],
                  ),
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: TextField(
                        decoration: InputDecoration(
                          hintText: "What to do?"
                        ),
                      ),
                    ),
                    IconButton(
                      icon: Icon(Icons.send),
                      onPressed: (){
                        //do something
                      },
                    )
                  ],
                )
              ],
          ),
      ),
    );
  }
}

A: Vertical viewport for ListView was given unbounded heigh. Wrap your ListView with Expanded widget
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Mon app",
      home: Scaffold(
          appBar: AppBar(title: Text("My app")),
          body: Column(children: <Widget>[
            RaisedButton(onPressed: () {}),
            Expanded(
              child: ListView(
                children: <Widget>[
                  ListTile(
                    leading: Icon(Icons.map),
                    title: Text('Map'),
                  ),
                  ListTile(
                    leading: Icon(Icons.photo_album),
                    title: Text('Album'),
                  ),
                  ListTile(
                    leading: Icon(Icons.phone),
                    title: Text('Phone'),
                  ),
                ],
              ),
            )
          ])),
    );
  }
}

A: Another better solution is to warp it to Flexible:
Flexible:
  child:
    Listview.builder {
      // following two lines needed to make it work
      shrinkWrap: true
      physics: ScrollPhysics(),
      // the rest of your code
    }

Remember the two lines that are needed to avoid boundary error and warning from flutter and to have the list display correctly.


text:
Q: ASP.NET MVC check if ActionResult is null I'm calling a partial view like this:
@Html.Action("_EditTranslationsList", new { id = Model.Id })

And that ActionResult returns a list of items from database and I show them in a table. But if the list is not found in the SQL Query, the action result returns null. I wanted to try this but it is not working:
@if (@Html.Action("_EditTranslationsList", new { id = Model.Id }) == null)
{
//something
}
else
{
//something
}

Everytime, even if there is a list, the first case happens. I tried returning Content("") instead of null but then I have problem with converting to string because if there is a list, it cannot be converted to string to check it and then I get an error.
How can I create a case which will happen if the Action Result List is null?


text:
Q: Distinguishing multiple docker containers on one Mac I have made two Docker containers using:
docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Password1234" -p1433:1433 --name sql2019 -d mcr.microsoft.com/mssql/server:vNext-CTP2.0-ubuntu

and I distinguished them by changing the -p and --name section, but when I go over to Azure Data Studio and connect, I can only connect to one of them, because I enter 'localhost' in the Server section, but since both containers use 'localhost', how can I differentiate the two in Azure Data Studio? Is there any way to use the --name flag?

I would appreciate a clear answer; I am new to server stuff.


text:
Q: How can we use 'or' with '*' in python? Looking at the first answer in the link:
convert number words to Integers Python Code
The author uses
for idx, word in enumerate(scales):
   numwords[word] = (10 ** (idx * 3 or 2), 0)

How has the author used 'or' with multiply (*) here:
10 ** (idx * 3 or 2)

A: In the expression 10 ** (idx * 3 or 2), if the value idx is zéro, then 0 * 3 = 0.
In Python, all values like 0, 0.0, "", [], (), {}, False, None are evaluated to False. See the official documentation: Truth Value Testing.
So the equation idx * 3 or 2 is equivalent to False or 2 if ixd is 0. The result is 2.
If idx is not 0, the result is idx * 3, the or operator is not evaluated.

A: It's because of the positioning of idx.
For example:
if we omit "or 2" in the code and idx = 0, then...
10 ** (0 * 3) will give us 1 instead of the correct answer.
A better example:
Lets say the number is "one hundred". The position of idx for "hundred" in scales is 0. So without "or 2" in the code, "hundred" would be equal to...
10 ** (0 * 3) = 1 which isn't logically true, so you have to square 10 (hence where "or 2" comes into play) making the correction...
10 ** (2) = 100.


text:
Q: Upload failed with error code 1 in php I made changes into php.ini, setting
upload_max_filesize = 2000m
post_max_size = 800M

and I'm getting an error:

Upload failed with error code 1 in php

If I upload images then it works fine but for larger files it shows me above error code of php file upload.
Restarted xampp several times, and even restarted my PC also.

A: set post_max_size = upload_max_filesize = 200M(or 800M) will resolve this issue(remember restart apache)


text:
Q: Processing files as well as directories I am using the find command, to which I am passing an array composed of directory paths (stored in fdir).  The matches which I then pass to head.
for dpa in "$@"; do
  [[ ! -d $dpa || -f $arg ]] && continue
  [[ ${tag[mo:$dpa]} ]] && continue
  fdir+=("$dpa")
  tag[mo:$dpa]=1
done

hn=21
sufx=( -name *.sh -o -name *.c )
mxdpt=( -maxdepth 3 )
find "${fdir[@]}" -type f "${sufx[@]}" "${mxdpt[@]}" \
  -exec head -v -n "$hn" '{}' +

I am encountering a problem when some elements of fdir are files rather than directories.  Let an element of fdir be /home/flora/com.org, the find command would fail because of sufx.

A: You could change the first line in the for loop to
[[ ! -e $dpa ]] || continue
if [[ -f $dpa ]]; then
  head $dpa
  continue
fi


text: Q: Is it possible for this truck to get across the desert? An unlimited supply of petrol is available from a camp at one edge of a desert which is 800 miles wide but no petrol is available anywhere else. A truck can only carry enough petrol to travel 500 miles and is able to leave petrol to be collected later. (There is no limit on the size of such stocks and it should be assumed that no petrol is lost by evaporation or spillage.) Establish whether or not it is possible for the truck to get across the desert and, if it is, explain how.


text:
Q: Miniprofiler.Current method does not return the time I'm trying to get time with this code using MiniProfiler.
var profiler = StackExchange.Profiling.MiniProfiler.Current;

But it returns 0 ms in result. How to get current time in miniprofiler.
This method gives me result with MiniProfiler version 2.1.0.
Right now I am using MiniProfiler version 3.1.1.139.

A: You can get the total elapsed time for the current MiniProfiler by accessing StackExchange.Profiling.MiniProfiler.Current.DurationMilliseconds - but only after the current MiniProfiler has been stopped (it is only populated at that point). Before it is stopped, an active MiniProfiler instance will not have this property set.
There is no way right now to get the elapsed time for an active MiniProfiler instance. There is an internal property called ElapsedTicks but as this is an internal property, you cannot access it outside of the MiniProfiler assembly.
If it is super-important for you to be able to access this data for an active MiniProfiler instance, than you could fork the current build and switch the property to be public (though before you do this I would question what your use case is - perhaps there is another way to achieve this).


text:
Q: Creating a multi-dimensional hashtable with generics in VB ASP.NET? I need to create a multi-dimensional (nested) hashtable/dictionary so that I can use syntax like
val = myHash("Key").("key")

I know I need to use Generics but I can't figure out the correct syntax using VB in ASP.NET 2.0, there are plenty of c# examples on the net but they aren't helping much.
Cheers!

A: OK, I'm better at C# than vb.net, but I'll give this a go....
Dim myHash as Dictionary(Of string, Dictionary(Of string, Integer));

A: There's also the System.Collections.Specialized.StringDictionary(Of T) collection, which is just a pre-defined Dictionary(Of String, T).
And the syntax to use either the normal Dictionary or the StringDictionary would look like this:
val = myHash("key")("key")

Not like this:
val = myHash("key").("key")

A: Consider that you may only need  to use Dictionary, and that can compose your multiple keys into a single key object with its own composite hash code. E.g. make a multikey class and then use it as the key.
in pseudocode:
class Multikey {
 private keys;
 public setKey1(...)
 public setKey2(...)
}
Dim myKey as MultiKey(...)
myKey.key1 = ...
myKey.key2 = ...

Dim mydic as Dictionary(Of MultiKey, Integer)

val = mydic(myKey)


text:
Q: EC2: When do userdata scripts run compared to rc.d bootup scripts? Do the userdata scripts run before or after the ones set up to run on every boot? Is there a way to change the priority?

A: Userdata scripts are run from /etc/init.d/cloud-init-user-scripts which has both a start-up and shutdown priority of "99", meaning its the last one run.  There is no way to change it, short of burning a new AMI with a new priority specified in the init.d script.


text:
Q: Dynamically add new input fields based only if the emails are not duplicated I'm doing a small task which requires doing some checks for email duplication. If the emails aren't duplicated in the input, then you can add more fields.
The code works fine for the most part with just one problem.
I'm going to list the steps to reproduce it:

*

*Complete the first inputs fields however you like and then click the add more button

*On the second row of inputs complete as you like: if  you add the same email as in the first row, then the button gets disabled. If you enter another email address, the button gets enabled. Click the add more button again.

*On the third row complete as you please, but add another email address.

*If you want to change the email address on the second row and put the same email from the third row in here, the button gets disabled. Now if you go to the first email input and delete any character from the input, the button gets enabled, which shouldn't happen because there are 2 duplicate emails on the second and third row.

JS:
let clone = document.querySelector('.js-form-content').cloneNode(true);
document.querySelector('.js-form-content').remove();
let btn = document.querySelector('.add-more');
let count = 0;

function emailHandler(clonedElement) {
  const email = clonedElement.querySelector(`input[type="email"]`);
  const allEmails = document.querySelectorAll(`input[type="email"]`);
  email.addEventListener('keyup', (event) => {
    const emails = document.querySelectorAll(`input[type="email"]`);
    let emailsValues = []
    emails.forEach((email, index) => {
      if (!email.isSameNode(event.target)) {
        emailsValues.push(email.value)
      }
    })
    console.log(emailsValues);
    if (emailsValues.includes(event.target.value) && email.value.length > 0) {
      this.flag = false;
      btn.setAttribute('disabled', ' ');
    } else {
      this.flag = true
      btn.removeAttribute('disabled', ' ');
    }
  })

}

function createElement(clonedElement) {
  clonedElement.classList.remove('d-none');
  clonedElement.querySelectorAll('[name]').forEach(input => {
  })
  clonedElement.querySelectorAll('[name]').forEach(input => {
    const name = input.getAttribute('name');
    input.setAttribute('name', `participant[${count}][${name}]`);
  })
  count ++;
  document.querySelector('.form-content-holder').appendChild(clonedElement);
}

function addNewFields () {
  // btn.setAttribute('disabled', ' ');
  const clonedElement = clone.cloneNode(true);
  createElement(clonedElement);
  emailHandler(clonedElement);

  const inputs = document.querySelectorAll('.input-participant-data');

}

btn.addEventListener('click', () => addNewFields());

Codepen: https://codepen.io/make96/pen/yLEOVRP

A: I managed to solve this by creating a function which checks if there are any duplications in the array.
Add this after the emails.forEach method:
let multipleDuplications = emailsValues.some((element, index) => {
    return emailsValues.indexOf(element) !== index
});

I also modified the if to check if the newly added function returns true or false:
if (emailsValues.includes(event.target.value) && email.value.length > 0 || multipleDuplications) {
//
}


text:
Q: WooCommerce Credit Card Fees I need to figure out how to add a product fee that's based on the credit card the customer uses.
For example, if they pay VISA or MasterCard, I must charge an extra 3%. If they pay American Express, I have to add 5%.
Is this possible, and if so, how do I do it? I am unable to use the WooCommerce Extra Charge for Payment Gateway (Standard) plugin as there are no options in the backend.

A: It's possible.
You can use a the WooCommerce Extra Charges To Payment Gateway plug-in
On the Total custom Fixed field choose Total % add


text:
Q: How to compare two tables in Postgresql? I have two identical tables:
A :   id1, id2, qty, unit
B:    id1, id2, qty, unit

The set of (id1,id2) is identifying each row and it can appear only once in each table.
I have 140 rows in table A and 141 rows in table B.
I would like to find all the keys (id1,id2) that are not appearing in both tables. There is 1 for sure but there can't be more (for example if each table has whole different data).
I wrote this query:
(TABLE a EXCEPT TABLE b)
UNION ALL
(TABLE b EXCEPT TABLE a) ;

But it's not working. It compares the whole table where I don't care if qty or unit are different, I only care about id1,id2.

A: Here is an example of using EXCEPT to see what records are different.  Reverse the select statements to see what is different. a except s / then s except a
SELECT
a.address_entrytype,
a.address_street,
a.address_city,
a.address_state,
a.address_postal_code,
a.company_id

FROM
prospects.address a

except

SELECT
s.address_entrytype,
s.address_street,
s.address_city,
s.address_state,
s.address_postal_code,
s.company_id

FROM
prospects.address_short s

A: use a full outer join:
 select a.*,b.*
 from a full outer join b
   on a.id1=b.id1 and a.id2=b.id2

this show both tables side by side. with gaps where there is an unmatched row.
 select a.*,b.*
 from a full outer join b
   on a.id1=b.id1 and a.id2=b.id2
   where a.id1 is null or b.id1 is null;

that will only show unmatched rows.
or you can use not in
select * from a
  where (id1,id2) not in
   ( select id1,id2 from b )

that will show rows from a not matched by b.
or the same result using a join
select a.*
  from a left outer join b
  on a.id1=b.id1 and a.id2=b.id2
  where b.id1 is null

sometimes the join is faster than the "not in"


text:
Q: Magento 2.4 - Build Child Theme parent of theme installed via composer )
I need a tip. I've installed a theme via composer and I need to create a child theme having as parent a theme installed via composer.
path of theme installed via composer: vendor/{vendor}/{theme}/
path of child theme: app/design/frontend/{vendor}/{theme}/
in the child theme folder i've created:
theme.xml
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
    <title>TitleTheme</title>
    <parent>{folder-name-vendor}/{folder-name-theme}</parent>
    <media>
        <preview_image>media/preview.jpg</preview_image>
    </media>
</theme>

Composer.json
{
    "name": "{my-vendor-folder}/{my-child-theme}",
    "description": "N/A",
    "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0",
        "magento/framework": "100.0.*"
    },
    "type": "magento2-theme",
    "version": "100.0.2",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "autoload": {
        "files": [
            "registration.php"
        ]
    }
}

registration.php
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'frontend/{my-vendor-folder}/{my-child-theme}',
    __DIR__
);

When I change the theme from the magento backend panel under
Content > Design > Configuration
and then run:
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
It does not load me the parent theme I have chosen, but the default magento theme.I don't know what I'm wrong.
Can someone help me?
Thank you ;)

A: I had the same problem. I was using _extend.less in the child theme to add my own styles. But as it turned out the parent theme had an _extend.less extending the blank theme. This approach using a _extend-child.less helped me solve it;
https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/css-guide/css_quick_guide_approach.html


text:
Q: Is there a name for this: dealing with class imbalance by learning to rank? I've seen the following approach used in link prediction settings, and I think it exists in many other areas as well.
Say we have a very imbalanced binary classification dataset, with imbalance in the order of 10 000:1. Imagine that you have a neural network with a sigmoid output to predict Pos/Neg. You can then remove the sigmoid activation, and feed it N examples, one of which is positive, giving you N linear output values. If you apply a softmax over these N values, you get a new kind of learning problem where the task is to predict which out of N examples is the positive one.
After training, the output of the network is still higher for more positive, so when you stick the sigmoid back on, it becomes a regular classifier again, which may be better at detecting positives.
Like I said, I've seen this used in settings that could be cast as a highly imbalanced classification problem, but I can't find any references to this method applied to straight classification problenm with high imbalance, and tested against other approaches like weighted cross entropy or SMOTE. Is there a general name for this type of approach, and has it been evaluated against other methods?


text:
Q: Why does Maven use the wrong plugin despite explicit plugin and pluginManagement version? My parent pom exlicitly declares a dependence on maven-javadoc-plugin 2.9.1 in both
<pluginManagement>
   <plugins>
     <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>2.9.1</version>
     </plugin>
        ...

and
    <reporting>
      <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-javadoc-plugin</artifactId>
         <version>2.9.1</version>
         ...

(see Maven plugin version in pom (seemingly) ignored ) and mvn help:effective-pom shows 2.9.1 is being used. However, the build is using 2.10 which is causes build failures (see
maven-javadoc-plugin breaks mvn release:perform and http://jira.codehaus.org/browse/MJAVADOC-407 )
mvn help:describe -DgroupId=org.apache.maven.plugins \
                  -DartifactId=maven-javadoc-plugin

shows
    Name: Apache Maven Javadoc Plugin
    Description: The Apache Maven Javadoc Plugin is a plugin that uses the
      javadoc tool for generating javadocs for the specified project.
    Group Id: org.apache.maven.plugins
    Artifact Id: maven-javadoc-plugin
    Version: 2.10
    Goal Prefix: javadoc

Meanwhile,
mvn dependency:resolve-plugins

shows
[INFO] Plugin Resolved: maven-javadoc-plugin-2.9.1.jar

Yet when I run the build, mvn uses 2.10 instead, causing a build failure.
How can I force maven to use 2.9.1 and not the broken 2.10?
(I'm using Maven 3.2.1)

A: Be sure that you are looking at the right dependency.  We are seeing that 2.9.1 as specified is being used for site reports but 2.10 is being used by the build.  I believe you should specify it in your

<build><plugins>

section as well.
We just verified that we were suffering the same problem.  We had the plugin version in the reporting plugins section but not build plugins.  Once we added it to the build plugins section, the issue was resolved.  The reason it needed to be in build plugins was because it was being used in the prepare deploy phase to build a javadoc jar.  This happens separately from generating javadoc for the site reports.


text:
Q: Ignore spans generated by Spring PubSub I'm using Spring Sleuth starter for a Spring Boot application for tracing calls from external sources. At the same time, the application has a dependency on Spring GCP Starter PubSub for handling events from other services. I checked the last spans generated by the application and found spans from pubsubsubscriberthreadpool (screenshot attached).
An interesting thing here is that I couldn't disable sending spans to Zipkin by adding settings to application.yaml. The settings are:
spring
  zipkin:
    base-url: http://localhost:9411
    service:
      name: notes-api
  sleuth:
    span-filter:
      additional-span-name-patterns-to-ignore: pubsubsubscriberthreadpool
      enabled: true

Adding a regexp-like name for the filter (^pubsubsubscriberthreadpool$) didn't help too.
Are there any solutions to disable such behavior?

A: I was confused about the span's name because it was not easy to find a source for it. After some research, I found a configuration bean GcpPubSubAutoConfiguration which registers a thread pool for PubSub. And an original name of the thread pool is pubsubSubscriberThreadPool. So in my case, I had to ignore the name of the span considering camelCase.
The workaround for my case is as follows:
spring:
  sleuth:
    span-filter:
      additional-span-name-patterns-to-ignore: ^pubsubSubscriberThreadPool$
      enabled: true


text:
Q: unsigned int vs unsigned long both are 32bit but I can't intermix them without casting... why? My computer shows the sizeof unsigned long and unsigned int to be the same.
However when passing in arguments to methods... more specifically pointers... I must recast the unsigned int as an unsigned long.  Otherwise a build error of Compiler Error C2664":'function' : cannot convert argument n from 'type1' to 'type2'
Why?

A: They are completely unrelated types as far as the compiler is concerned. Passing a pointer of any type except the one the argument expects is an error.
But even if the compiler was made to recognize that this type of pointer cast is possible and do it for you, here's why that would be bad...
C++ has been around long enough that int and long have changed size as new CPU architectures come and go. The size of int and long depends on the compiler and platform you're working with so, casting int* into long* (or vice versa) can lead you right into a all sorts of problems if they are not the same size.
According to the C++ standard these are the sizes of int and long across various platforms:
type | C++ standard | LP32 | ILP32 | LLP64 | LP64
-------------------------------------------------
int  | at least 16  | 16   | 32    | 32    | 32      bits
long | at least 32  | 32   | 32    | 32    | 64      bits

Only with ILP32 and LLP64 can you safely assume that int and long are the same size, but supporting that assumption in the compiler would allow you to write code that does not compile or run safely on the other platforms.
Lastly, if you need a guarantee that the size of an integer is the same across all platforms, then you can #include <cstdint> and use types such as int16_t, uint16_t, int32_t, etc. These fixed-width integers are available with compilers that support C++11 and later.


text:
Q: C# & SQL Server : turn sql data into class module using DataContext I may be going about this the hard way but I am wanting to gather 1 row from the SQL Server database (by ID column), and place those values inside an instance of my class (which is chromeExtData).
My class:
public class chromeExtData
{
    public string lname { get; set; }
    public string fname { get; set; }
    public string mname { get; set; }
    public string numsr { get; set; }
    public string sor { get; set; }
    public string pob { get; set; }
    public string birthday { get; set; }
    public string cstatus { get; set; }
    public string miscnumbers { get; set; }
    public List<string> transp { get; set; }
}

And my database layout:
---+-------+-------+-------+-------+-----+-----+----------+---------+-------------+--------
ID | lname | fname | mname | numsr | sor | pob | birthday | cstatus | miscnumbers | transp
---+-------+-------+-------+-------+-----+-----+----------+---------+-------------+--------
5  | Barker| Bob   | null  | aB342 | U76 | CA  | 5/25/1970| Active  | A123        | A,X,Y

And what I want to do is just pull that information into the object and vice-versa.
I found this code that I think does what I am wanting to do:
int ID = 5;

using (var dc = new DataContext())
{
    var people = dc.ExecuteQuery<chromeExtData>(@"SELECT *
                                                  FROM [People]
                                                  WHERE [ID] = {0}", ID).ToList();
}

I'm not sure if the code above would place the found data values into the chromeExtData object or not? I've never used this DataContext before so I'm unsure if that's the correct way to go about what I want to do.


text:
Q: Get prior date based on criteria in R I have data like below.
df <- data.frame(CustID = c(1,2,3,4,5,1,5),
CustName = c("Fred","Maria","John","Mark", "Julia","Fred","Julia"),
ServiceDate = c('2010-11-1','2008-3-25','2007-3-14','2010-11-1','2008-3-25','2010-12-14','2008-3-14'), stringsAsFactors = F)

df$ServiceDate <- as.Date(df$ServiceDate, "%Y-%m-%d")

df

  CustID CustName ServiceDate
1      1     Fred  2010-11-01
2      2    Maria  2008-03-25
3      3     John  2007-03-14
4      4     Mark  2010-11-01
5      5    Julia  2008-03-25
6      1     Fred  2010-12-14
7      5    Julia  2008-03-14

and I need to figure out a way to get the prior value based on CusID and ServiceDate so that I get a something like this:
  CustID CustName ServiceDate PriorServiceDate
1      1     Fred  2010-11-01             <NA>
2      2    Maria  2008-03-25             <NA>
3      3     John  2007-03-14             <NA>
4      4     Mark  2010-11-01             <NA>
5      5    Julia  2008-03-25       2008-03-14
6      1     Fred  2010-12-14       2010-11-01
7      5    Julia  2008-03-14             <NA>

I have tried using sqldf with no success.  Thank you.

A: Using dplyr I think this should solve your problem.
library(dplyr)
df %>%
    group_by(CustID) %>%
    arrange(ServiceDate) %>%
    mutate(PriorServiceDate = lag(ServiceDate))

Source: local data frame [7 x 4]
Groups: CustID

  CustID CustName ServiceDate PriorServiceDate
1      1     Fred  2010-11-01             <NA>
2      1     Fred  2010-12-14       2010-11-01
3      2    Maria  2008-03-25             <NA>
4      3     John  2007-03-14             <NA>
5      4     Mark  2010-11-01             <NA>
6      5    Julia  2008-03-14             <NA>
7      5    Julia  2008-03-25       2008-03-14

Please note this assumes you are looking at the prior date with lag, not the minimum date (unsure with your question).
If you did want min then you can easily index the others out
df2 <- df %>%
    group_by(CustID) %>%
    arrange(ServiceDate) %>%
    mutate(PriorServiceDate = min(ServiceDate))

df2$PriorServiceDate[which(df2$ServiceDate == df2$PriorServiceDate)] = NA

Source: local data frame [7 x 4]
Groups: CustID

  CustID CustName ServiceDate PriorServiceDate
1      1     Fred  2010-11-01             <NA>
2      1     Fred  2010-12-14       2010-11-01
3      2    Maria  2008-03-25             <NA>
4      3     John  2007-03-14             <NA>
5      4     Mark  2010-11-01             <NA>
6      5    Julia  2008-03-14             <NA>
7      5    Julia  2008-03-25       2008-03-14

A: Unlike the dplyr answer, this uses base R and gets the minimum date rather than the lag.
First get the first service date per customer.
first.service <- with(df, aggregate(ServiceDate,
                                    by=list(CustID=CustID, CustName=CustName),
                                    FUN=min))

Now merge it with the original data frame.
both <- merge(df, first.service, by=c("CustID", "CustName"))

You can set prior service date to NA for customers with no prior service like so:
both$x[with(both, ServiceDate == x)] <- NA

Then rename the column:
colnames(both)[4] <- "PriorServiceDate"

A: With sqldf it can be done with a left self join.  For a particular row from b keep rows from a whose CustID is the same as the CustID from b and whose ServiceDate is less.  Then of those a rows take the one whose ServiceDate is greatest.  This makes no assumptions regarding the ordering of the input.  It keeps the original ordering of rows but if that is not important then  the order by line can be omitted:
library(sqldf)

DF <- sqldf("select b.CustID,
                    b.CustName,
                    b.ServiceDate ServiceDate__Date,
                    max(a.ServiceDate) PriorDate__Date
             from df b
             left join df a
               on b.ServiceDate > a.ServiceDate and b.CustID = a.CUSTID
             group by b.CustID, b.ServiceDate
             order by b.rowid",
        method = "name__class")

giving:
> DF
  CustID CustName ServiceDate   PriorDate
1      1     Fred  2010-11-01        <NA>
2      2    Maria  2008-03-25        <NA>
3      3     John  2007-03-14        <NA>
4      4     Mark  2010-11-01        <NA>
5      5    Julia  2008-03-25  2008-03-14
6      1     Fred  2010-12-14  2010-11-01
7      5    Julia  2008-03-14        <NA>


text:
Q: PyPDF2 no permissions to save a pdf on ubuntu I have a web tool to encrypt pdf files with a password. The problem i have is, that my Flask app or the PyPDF2 module has no permission to save a pdf file into a specific directory. I tried the Flask app with the tool on my local Windows machine and it works fine. When i try to run the tool on my Ubuntu root machine and the code gets to the line where the pdf file gets saved using this command pdf_file.save(file_path) the app crashes. The log files tell me this:
File "/home/admin/flask/application.py", line 251, in site_pdfencryption
    pdf_file.save(file_path)
  File "/home/admin/flask/venv/lib/python3.8/site-packages/werkzeug/datastructures.py", line 3066, in save
    dst = open(dst, "wb")
PermissionError: [Errno 13] Permission denied: '/home/admin/flask/static/pdf/Python_Flask_Code_Prettier.pdf'

The directory is existing and the file too. I think there is a permission issue but i have no idea what file has less permissions.

A: The issue was that the folder was created by the root user and then tried to access with an other user with less permissions. I just removed the folder and recreated that with the other user


text:
Q: How to concatenate the values of a column based on some columns in Pandas? Let's say I have the following dataframe:

id
id_2
id_3
text
integers

0
1
2
lorem
integers1

0
1
2
epsilon
integers2

0
1
2
text3
integers3

0
1
3
text4
integers4

My question is:

*

*How can we merge text columns given the condition id, id_2 and id_3 are the same. I mean, I want to extract the values from 'text' column separated by comma or space and respecting the condition that id=0,id_2=1 and id_3=2
Output wanted: 0 | 1 | 2 | lorem epsilon text3 | sum(integers1,integers2, integers3)

Thanks