text:
Q: Define a command to typeset a character If I run the code below, the Polish L in "Wesolowski" is not typesetting. To remedy this, I'm trying to define a command to typeset the Polish L. In the code below I've defined the command in this line:
\newcommand{\PolishL}{l\llap{\raise0.2em \hbox{\tiny\slash}\kern-0.05em}}

But this command is still not typesetting the Polish "L"
Alternatively, is there a way to typeset the Polish L without having to define a command?
\documentclass{article}

\usepackage{alltt} % Paper size, default font size and one-sided paperR

\usepackage{nameref}

\usepackage{array}
\usepackage{booktabs}
\usepackage{tabularx}

\usepackage{csquotes}

\usepackage{etex}

\usepackage{lmodern}

\usepackage{caption}
\captionsetup[table]{position=below}

\usepackage{placeins} % to control figure placement with \FloatBarrier

\usepackage{fontspec}
\setmainfont{Lucida Sans}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\PolishL}{l\llap{\raise0.2em \hbox{\tiny\slash}\kern-0.05em}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% biblatex----------------------------------------------------------------------------------------
\usepackage[style=authoryear-comp, maxcitenames=2, maxbibnames=99, uniquename=false, uniquelist=false,firstinits=true,sorting=nyt]{biblatex}
\DeclareNameAlias{sortname}{last-first}
\DeclareNameAlias{default}{last-first}

\usepackage{xpatch}

% No dot before number of articles
\xpatchbibmacro{volume+number+eid}{%
  \setunit*{\adddot}%
}{%
}{}{}

% Number of articles in parentheses
\DeclareFieldFormat[article]{number}{\mkbibparens{#1}}

\renewbibmacro{in:}{}

\addbibresource{refs.bib}
\bibliography{refs}

\addbibresource{\jobname.bib}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}

@incollection{WesolowskiFuller2012,
  title={Spatial variation and temporal shifts in habitat use by birds at the European scale},
  author={Weso{\PolishL}owski, Tomasz},
  editor={Fuller, Robert J},
  booktitle={Birds and Habitat: Relationships in Changing Landscapes},
  publisher={Cambridge University Press},
  address={Cambridge},
  year={2012}
}

\end{filecontents}
\begin{document}

    Some text \autocite{WesolowskiFuller2012}

\printbibliography

\end{document}

A: The reason for your problem might simply be the real name of the open type/truetype Lucida Sansfont. On my system, it is Lucida Sans Unicode and it compiles fine.
Note: I commented \addbiresource{refs.bib}  since I don't have it. Also you shouldn't write \bibliography{refs}– or don't use biblatex.
\documentclass{article}

\usepackage{alltt} % Paper size, default font size and one-sided paperR

\usepackage{nameref}

\usepackage{array}
\usepackage{booktabs}
\usepackage{tabularx}

\usepackage{csquotes}

\usepackage{etex}

\usepackage{lmodern}

\usepackage{caption}
\captionsetup[table]{position=below}

\usepackage{placeins} % to control figure placement with \FloatBarrier

\usepackage{fontspec}
\setmainfont{Lucida Sans Unicode}

% biblatex----------------------------------------------------------------------------------------
\usepackage[style=authoryear-comp, maxcitenames=2, maxbibnames=99, uniquename=false, uniquelist=false,firstinits=true,sorting=nyt]{biblatex}
\DeclareNameAlias{sortname}{last-first}
\DeclareNameAlias{default}{last-first}

\usepackage{xpatch}

% No dot before number of articles
\xpatchbibmacro{volume+number+eid}{%
  \setunit*{\adddot}%
}{%
}{}{}

% Number of articles in parentheses
\DeclareFieldFormat[article]{number}{\mkbibparens{#1}}

\renewbibmacro{in:}{}

%\addbibresource{refs.bib}
%\bibliography{refs}

\addbibresource{\jobname.bib}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@incollection{WesolowskiFuller2012,
  title={Spatial variation and temporal shifts in habitat use by birds at the European scale},
  author={Wesołowski, Tomasz},
  editor={Fuller, Robert J},
  booktitle={Birds and Habitat: Relationships in Changing Landscapes},
  publisher={Cambridge University Press},
  address={Cambridge},
  year={2012}
}
\end{filecontents}

\begin{document}

    Some text \autocite{WesolowskiFuller2012}.

\printbibliography

\end{document}


text:
Q: strange python regex: not able to find match I am facing some strange python regex issue. The following two strings are supposedly to be exactly the same. But somehow they are not matching.
import re
print(" \\\"")
print(" "+chr(92)+chr(34)+"")
print(re.search(" \\\"", " "+chr(92)+chr(34)+""))

However, the following does match
import re
print("\\\"")
print(""+chr(92)+chr(34)+"")
print(re.search("\\\"", ""+chr(92)+chr(34)+""))

Any thought on what is going on here?

A: Issue is the backslash character has special meaning to a string in python. You can use a Python raw string created by prefixing a string literal with 'r' or 'R' where python raw string treats backslash (\) as a literal character.
import re
print(" \\\"")
print(" "+chr(92)+chr(34)+"")
print(re.search(r" \\\"", " "+chr(92)+chr(34)+""))

Output:
 \"
 \"
<re.Match object; span=(0, 3), match=' \\"'>

In second example print(re.search("\\\"", ""+chr(92)+chr(34)+"")) outputs:
<re.Match object; span=(1, 2), match='"'> where only the double quote is matched.
Need to escape the backslash or use a raw string. If use single-quotes around the regexp then the double-quote does not need to be escaped.
s = "" + chr(92) + chr(34) + ""
print(re.search("\\\\\"", s))
print(re.search(r"\\\"", s))
print(re.search(r'\\"', s))

Output:
<re.Match object; span=(0, 2), match='\\"'>
<re.Match object; span=(0, 2), match='\\"'>
<re.Match object; span=(0, 2), match='\\"'>

For further details on raw string and backslash in Python, see answers for this question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting physics bodies with PhysicsJoint Lately I realized that Chipmunk (am I right?) was integrated with >= Cocos2d-x 3.0. Now I am trying make use of it (I am using cocos2d-x 3.2).
So can you tell if it's possible to connect the bodies (PhysicsBody) with PhysicsJoint (eg. PhysicsJointSpring), but with connection points being placed for example on the edge of the body?
I saw the "Joints tests" from the package with library, but it looks like all of them (joints) are placed in the midlle of the body - you could say that anchor point is placed at Vec2(0.5f, 0.5f).
Test are here (PhysicsDemoJoints class):
https://github.com/cocos2d/cocos2d-x/blob/v3/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp
Here is an example what I am talking about (two balls, left bottom corner):
https://www.youtube.com/watch?v=ZgJJZTS0aMM
I would appreciate any help! And give you an internet hight five as a gift!

A: In such cases take a look at the class reference.
You'll find that joints can be created with constructors similar to this one:
static PhysicsJointDistance *   construct (PhysicsBody *a, PhysicsBody *b, const Vec2 &anchr1, const Vec2 &anchr2)

The two vectors are the joint anchor points. Unfortunately it's not documented what they are, but typically they'll be in world (scene) coordinates.


text:
Q: Setting a union in c++ using Thrift I have something like this in my Thrift schema:
struct TestStatusOne { .... }
struct TestStatusTwo { .... }

union TestStatus {
  1: TestStatusOne  ONE
  2: TestStatusTwo  TWO
}

struct TestResult {
  1: required TestStatus status
}

I can define this fine using Java, Perl and Python libraries, but am
having trouble doing it with the C++ libraries. Here is an example in
Java:
TestResult testResult = new TestResult(
  new TestStatus(TestStatus._Fields.findByName("ONE"), testStatus)
);

The closest I have got to getting it defined in C++ is:
TestResult testResult;
testResult.status.ONE = testStatus;

But when I try to send to the server I get an error telling me the
status field is not present, and the dump of the structure shows it as
null.
How can I set the test status?
Using Thrift 0.6.1.

A: Could this be a problem of a missing assignment operator? Depending on the definition of the structs TestStatusOne and TestStatusTwo, you may need to create an assignment operator ( operator=() ).
Have you tried doing a GDB on the Thrift client and look at the contents of the testResult before sending it to the server? Check that its contents make sense.


text:
Q: sh: 39: source: not found While installing oh-my-zsh On my Ubuntu 12.04 LTS I was trying to install oh-my-zsh by following command found on github oh-my-zsh project page.
wget --no-check-certificate https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | sh
But I'm getting the following error.
Tried with sudo, same result.

Looking for an existing zsh config...
Found ~/.zshrc. [0;32]Backing up to ~/.zshrc.pre-oh-my-zsh
Using the Oh My Zsh template file and adding it to ~/.zshrc
Copying your current PATH and adding it to the end of ~/.zshrc for you.
Time to change your default shell to zsh!
Password: chsh: PAM authentication failed
         __                                     __
__  / /_     _ __  __  __   __  _/ /_
 / __ / __ \   / __ `__ / / / /  /_  / / / _ \
/ // / / / /  / / / / / / // /    / /(  ) / / /
_// //  // // //_, /    //// //
                        /_/
....is now installed.
sh: 39: source: not found

Any suggestions?
Thanks.

A: The error sh: 39: source: not found is only part of the problem. The output you posted also indicates problems related to changing the default shell: Password: chsh: PAM authentication failed.
The same problem is reported in this issue.
You should follow the manual installation steps provided on oh-my-zsh github page (or here).

A: Problem is resolved by running the ohmyz.sh script manually:
rm -rf ~/.oh-my-zsh/
curl -L http://install.ohmyz.sh > install.sh
sh install.sh

source


text:
Q: Реализация алгоритма получения перестановки по номеру и алфавиту Всем привет, возникла проблема расчете факториала в функции PermFromNum(): в функцию facroriz(),которая считает факториал числа, почему-то постоянно передается нуль, хотя в функции fromFactorialNS() расчет факториала происходит корректно. Всю голову сломал, ошибку найти не могу.
class Factorial{
       int value;
       int power;
       public Factorial(int value) {
           this.value = value;
           }

       public Factorial(int value, int power) {
           this.value = value;
           this.power = power;
       }

       public int factoriz(int value) {
           if (value<0)return 0;
           else if (value ==0) return 1;
           else return value*factoriz(value-1);
       }
 public int fromFactorialNS(int value){
           int result = 0;
           for (int i = 0; value>0;i++){
               result +=value%10*factoriz(i+1);
               value /=10;
           }
           return result;
       }
       int permFromNum(int number){
           int result = 0;
           int [][] Array = new int[power][3];
           for (int i = 0; i<power;i++){
               Array[i][0] = factoriz(number-1)/(int)pow(10,power-2-i);
               System.out.println(Array[i][0]);
               number -=Array[i][0]*pow(10,power-2-i);
           }
           for (int i = 0;i<power;i++) Array[i][1]=i+1;
           for (int i=0;i<power;i++){
               for (int j = 0;j<power;j++){
                   if (Array[i][0]==j){
                       Array[i][2] = Array[j][1];
                       for (int k=j;k<power-1;k++){
                           Array[k][1] = Array[k+1][1];
                       }
                       Array[power-1][1] = 0;
                   }
               }
           }
           for (int i=0;i<power;i++){
               result +=Array[i][2]*(int)pow(10,power-i-1);
           }
           return result;
       }
   }

A: Всё правильно у тебя работает)
Смотри!
factoriz(number - 1) возвращает тебе всё правильно. Пробуй воспроизвести его отдельно, просто значения проверить. Потом у тебя идет деление на  pow(). pow тоже работает как написано, а вот теперь обрати на типы данных. Ты int делишь на int, и хочешь получить double? Не выйдет, 1 / 100, ты получишь 0. Если хочешь исправить, то поменяй типы данных на double. Также с массивом Array[][], он у тебя int. И еще, писать переменные с большой буквы - плохая практика. Почитай по review кода
Array[i][0] = factoriz(number - 1) / (int) pow(10, power - 2 - i);


text:
Q: MYSQL Create table statement giving me "non-unique" error ? I am currently taking a SQL class in my college and am currently stuck on review question my professor assigned. I keep getting an error for my schedule table. I feel it has something to do with my foreign key call but I'm not 100% sure? For the Schedule table, she wants the doctorID to be the foreign key and date/clinic to be the primaries
CREATE TABLE Doctor (
DoctorID numeric(3) not null,
Drname varchar (25) not null,
phonenum varchar (12) not null,
CONSTRAINT DoctorID_pk PRIMARY KEY (DoctorID)
);
CREATE TABLE Patient (
PatientNum numeric (5) not null,
SSNum numeric (9) not null,
PTName varchar (25) not null,
DOB numeric (8) not null,
PAddress varchar (40) not null,
DateAdmit numeric (8) not null,
Clinic varchar (30) not null,
CONSTRAINT PatientNum_pk PRIMARY KEY(PatientNum)
);

CREATE TABLE Treatment (
Treatmentcode numeric (6) not null,
Description varchar (50) not null,
CONSTRAINT Treatmentcode_pk PRIMARY KEY(Treatmentcode)
);

CREATE TABLE PatDocTreatment (
PatientNum numeric (5) not null,
DoctorID numeric (3) not null,
Treatmentcode numeric (6) not null,
DateofTreat numeric (8) not null,
Comments varchar (80) not null,
CONSTRAINT PK_PatDocTreatment PRIMARY
KEY(Patientnum,DoctorID,Treatmentcode,DateofTreat),
FOREIGN KEY(PatientNum) REFERENCES Patient(PatientNum),
FOREIGN KEY(DoctorID) REFERENCES Doctor(DoctorID),
FOREIGN KEY(Treatmentcode) REFERENCES Treatment(Treatmentcode)
);
CREATE TABLE Schedule (
DoctorID numeric (3) not null,
SchDate numeric (8) not null,
Clinic varchar (30) not null,
Hoursworked numeric (3) not null,
CONSTRAINT PK_Schedule PRIMARY KEY(DoctorID,SchDate,Clinic),
FOREIGN KEY (DoctorID) REFERENCES Doctor (DoctorID)
FOREIGN KEY (CLINIC) REFERENCES Patient (Clinic)
);

A: You have possibly missed a comma between the last two foreign keys declarations in your schedule table.


text:
Q: Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.refArrayOps([Ljava/lang/Object;)[Ljava/lang/Object; I use mvn clean package to create a jar package and no error raised. After that I use spark-submit to execute the jar package, following error occurs:

Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.refArrayOps([Ljava/lang/Object;)[Ljava/lang/Object;

I am pretty sure the the above error is raised from the following clause 3 and other clauses are correct:
1-val q1 = Source.fromFile("blackList.sql")
2-val q = q1.mkString.replace("theDate1", theDate1).split(";")
3-for(s <- q){
  println(s);
}
4-q1.close()

The above code segment is trying to traverse Array[String] object q and print it.
The version of spark I am using is 2.4.5,and the scala version in my pom.xml file is 2.12.10. I have tried many different scala verions for this spark version, but still raised the error described in the title.
Here is the related part of my pom.xml file:
<properties>
    <project.version>2.4.5</project.version>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <scala.version>2.12.10</scala.version>
    <scala.main.verison>2.12</scala.main.verison>
    <spark.version>2.4.5</spark.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_${scala.main.verison}</artifactId>
        <version>${spark.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.typesafe</groupId>
        <artifactId>config</artifactId>
        <version>1.4.1</version>
    </dependency>

    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>2.12.10</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-mllib_${scala.main.verison}</artifactId>
        <version>${spark.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

So, what exactly is the problem and how to fix it?
Thanks for your help.


text:
Q: Why are custom objects not equivalent keys for a HashMap? I'm having trouble using my own class as a key for a HashMap
 public class ActorId {
     private final int playerId;
     private final int id;

     ActorId(int playerId, int id) {
         this.playerId = playerId;
         this.id = id;
     }

     public boolean equals(ActorId other) {
         return this.id == other.id && this.playerId == other.playerId;
     }

     public int hashCode() {
         int hash = 1;
         hash = hash * 31 + playerId;
         hash = hash * 31 + id;
         return hash;
     }

     public String toString() {
         return "#" + playerId + "." + id;
     }

     public int getPlayerId() {
         return playerId;
     }
 }

Here is a failing JUnit test
 import static org.junit.Assert.*;
 import java.util.Map;
 import org.junit.Test;

 public class ActorIdTest {
     @Test
     public final void testAsMapKey() {
         ActorId a = new ActorId(123, 345);
         ActorId b = new ActorId(123, 345);

         assertTrue(a.equals(b));
         assertEquals(a.hashCode(), b.hashCode());

         // Works with strings as keys
         Map<String, String> map1 = new java.util.HashMap<String, String>();

         map1.put(a.toString(), "test");
         assertEquals("test", map1.get(a.toString()));
         assertEquals("test", map1.get(b.toString()));
         assertEquals(1, map1.size());

         // But not with ActorIds
         Map<ActorId, String> map2 = new java.util.HashMap<ActorId, String>();

         map2.put(a, "test");
         assertEquals("test", map2.get(a));
         assertEquals("test", map2.get(b)); // FAILS here
         assertEquals(1, map2.size());

         map2.put(b, "test2");
         assertEquals(1, map2.size());
         assertEquals("test2", map2.get(a));
         assertEquals("test2", map2.get(b));
     }
 }

A: You need to change
public boolean equals(ActorId other) {
    ....
}

to
public boolean equals(Object other) {
    ....
}

Tip of the day: Always use @Override annotation.
If you had used the @Override annotation, the compiler would have caught the error and said:

The method equals(ActorId) of type ActorId must override or implement a supertype method

A: Your code is correct, but you also need to override the equals method inherited from Object.
Add this to your ActorId class:
@Override
 public boolean equals(Object other) {
    if(other == null || other.getClass() != getClass())
        return false;
    return equals((ActorId)other);
 }

A: You definitely must override the method equals(Object), and for certain implementation of a Map (HashMap) it is also necesary that you overrdide the method hashCode().
I had the same problem, and without the custom hashCode implementation the equals method of the class "ActorId" was never called.

A: By default  Java  invokes boolean equals(Object obj);
So, you login is correct but if you want  to OVERRIDE equals() use Object as a parameter and and check the class by instanceOf or getClass() and do a class casting.
if (obj instanceOf ActorId) {
    ActorId other = (ActorId)obj;
    ... compare fields
}


text:
Q: javascript regex lookbehind and jQuery selector I am using the following regex in a custom selector in jQuery
$.expr[":"].matchRegex = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().match(new RegExp(arg, 'i')) != null;
    };
});

However, since javascript does not allow lookbehind, I am unable to pass this regex:
/\b(?<!')(s|otherword)s?\b/

The expression should match at least one s if it not preceded by a single quote. The s|otherword part in the expression is actually provided by the user, so I have to work with that.
I understand how creating a custom function (Javascript: negative lookbehind equivalent?) can be a workaround for the lookbehind (replace example) but I am unable to get this to work.
I tried modifying my selector to this:
$.expr[":"].matchRegex = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return ($(elem).text().match(new RegExp(arg, 'i')) != null) ? false : true;
    };
});

and changing the regex expression to this:
/\b(')(s|otherword)s?\b/

but this will return all elements with text that do not contain 's.
Can I use the match method with a callback function? If not, how can the jQuery selector be modified to accommodate this?
Any insight and help always greatly appreciated.
Thank you!

A:
The expression should match at least one s if it not preceded by a single quote.

Since you really don't want to work with the matches, only test if there is a match at all, you don't really need a lookbehind. You only need to make sure that it works at the start of the string.
(?:^|[^'])(s|otherword)s?\b

That's all, really.


text:
Q: How do I change the scale on the x-axis using ggplot2? The goal of our project was to assess 2 behavioral responses (crossing success and crossing decision) by deer when interacting with fences. We used a modified BACI design for our study where we monitored fence sections during a pre-modification period and then implemented certain modification during what we termed a post-modification period.
We used logistic regression to evaluate the crossing success and crossing decision of mule deer and white-tailed deer at these fence sections. We modeled the effects of certain demographic factors and fence characteristics on our 2 response variables using generalized linear models with a logit link (i.e., logistic regression).
Now that we have identified the top model for both analysis, we are trying to create a caterpillar plot to graphically show the change of crossing success between the pre-modification period and the post-modification period for a specific variable we titled "Type_Period".
However, we have not been able to figure out how to change the scale of our plot (which I have attached). We used GGally, broom and ggplot2 to create the Caterpillar plot.

We have looked on multiple GGally, and ggplot2 help pages and I haven't been able to find any mention of how to manipulate the scale. We have tried "zooming" in on the graph but ggplot2 couldn't read the command. We tried changing the xlim but got an error message that said "ignoring unknown parameter xlim."
Here is the script that we used for the caterpillar plot only. I will provide the full script and sample database if necessary.
library(GGally)
library(broom)
library(ggplot2)
log.reg <- glm(Decision~ Type_Period, data=analysis, weights = analysis$Freq, x=TRUE,family=binomial(link="logit"))
ggcoef(log.reg, xlim=c(-1, 2))


text:
Q: HTML Entity not converting to its result when passing into HTML from ViewData When I pass an HTML entity into HTML via the View Data object, it does not convert to it's result. (i.e. the ™ entity remains ™ and does not convert to ™)
This is the destination page
@{
    ViewData["Title"] = "Assess Mental Health";
    ViewData["HeaderTitle"] = "Assess Mental Health";
    ViewData["HeaderLine1"] = "with";
    ViewData["HeaderLine2"] = "Intelligent Assessments™";
    ViewData["HeaderImage"] = "url(../img/headers/AI_Head.png)";
}

    <partial name="_Header" />

This is the partial

@ViewData["HeaderTitle"]

@ViewData["HeaderLine1"]

previdence™

@ViewData["HeaderLine2"]

                <partial name="_CallToActionLight" />

This is my layout
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="robots" content="noindex">
    <title>@ViewBag.Title | Previdence | Mental Healthcare Platform</title>
    <partial name="_Favicons" />
    <link href="https://fonts.googleapis.com/css?family=Josefin+Sans&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link href="~/lib/non-npm/owl.carousel/owl.carousel.css" rel="stylesheet">
    <link href="~/lib/non-npm/remodal/remodal.css" rel="stylesheet">
    <link href="~/lib/non-npm/remodal/remodal-default-theme.css" rel="stylesheet">
    <link href="~/lib/non-npm/theme/theme.css" rel="stylesheet">
    <link rel="stylesheet" href="~/css/site.css" />
    <link rel="stylesheet" href="~/css/cookiealert.css" />

    <partial name="_Preloader" />
    <partial name="_TopNavbar" />
    @*<partial name="_CookieConsentPartial" />*@
    @RenderBody()
    <partial name="_Footer" />
    <partial name="_GDPR_Alert" />

    @RenderSection("Scripts", required: false)

A: Try with @Html.Raw(string) to render html string :
@Html.Raw(@ViewData["HeaderLine2"])

A: Thanks to @Nan Yu's answer above, I was able to find the answer.

Try with @Html.Raw(string) to render html string

@Html.Raw() was part of the answer, the other part was that I am using a text-uppercase text transformation so I also needed to add a text-transform-none to remove the text-uppercase text transformation (this text-transformation was not shown in my code example).
@Html.Raw(™)
I now get the correct output where the ™ output is ™ instead of ™


text:
Q: how to make a Short top app bar using material design? Fortnightly's short top app bar: Material Design
On the scroll, the top app bar collapses to become a short top app bar, allowing more space for content. The short top app bar contains...
The short top app bar contains two elements: the navigation icon to open the navigation drawer, and the Fortnightly logo.
I found this guideline in material design io site, could anyone share your idea, how to make this using material design, not 3rd party plugin.

A: This is done using a MaterialShapeDrawable with a ShapeAppearanceModel. You can also check the source code for the toolbar.


text:
Q: How can I Continue to use Debian Testing after Bookworm becomes the stable distribution? I am currently using Debian testing (bookworm).
Based on current experience, my confidence in the stability of testing is firm. I would like to use the next Debian testing when Bookworm becomes the current stable distribution.
Will this happen automatically if I continue to use testing or will it require some intervention on my part.

A: Short version:  Edit /etc/apt/sources.list file. Replace bookworm with testing or even better with next testing version
name.
I personally prefer to avoid "unexpected" changes in testing versions.
It is much better to intentionally choose exact switch moment.
For longer version see man sources.list


text:
Q: What happened to SE? Sometimes it doesn't show up-vote points notification and sometimes 1 month ago activity show up in RSS reader! What happened to SE? Sometimes it doesn't show upvote points notification.
And now I received an RSS notification of a user. When I opened it, I saw that the comment/answer was posted in 2019 and has not been edited recently. what is the problem?
Update 1: The following screenshot illustrates another problem in upvote points notification. (my post has been up-voted twice but in notification total points are 28 for my post!!)

Update 2 (may 13, 2020): Yesterday and today I earned 20 points for my old posts but without any notification. Here are my posts has been up-voted: TSE post and MSE post
Update 3 (September 27 2020): The problem has gotten worse I think. The following is the today reputations:

The reputation (+8) is incorrect and it must be (+10) instead of (+12), since the (+2) rep has been rewarded 3 hours ago but without notification.

Update 4 (Nov 23, 2020):  I just realized that RSS feeds pops up when the user I follow him, has an activity on a post, but now the RSS notification popped up when I edited a post that an user that I follow him commented to that post 7 hours ago (i.e. I received two RSS feeds, one for comment 7hours ago and one for editing now). (I am talking about this post)


text:
Q: Flex div with table not following the flex width I have a composition of flex itens in a column and row, as the follow image:

This images are built using the following code:

    THIS IS A TEST CODE WITH TEXT

      CONTENT OF LEFT SIDE

      CONTENT OF RIGHT SIDE

    THIS IS A TEST CODE WITH TABLE

            Column 1
            Column 2
            Column 3
            Column 4

            Data 1
            Data 2
            Data 3
            Data 4

      CONTENT OF RIGHT SIDE

CSS:
.container {
  display: flex;
  flex-direction: column;
  background-color: grey;
  width: 100%;
  height: 200px;
}

.header {
  flex: 1;
  text-align: center;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: row;
}

.leftcontent {
  flex: 5;
  background-color: green;
}

.rightcontent {
  flex: 5;
  background-color: yellow;
}

The upper schema is a test made with text. The bottom schema is a try using a table on the left side.
As you can see, at the bottom schema, the table is larger than expected and is not following my flex rules. I know tables has a special rendering mechanism, but I need help to set the table width as 50% like the schema with text only. In that case I need the overflowed table to show up an horizontal scroll, just in the left side of the content (that related to the table so I can scroll it horizontally and see its contents).
Here is the JSFiddle for it

A: min-width defaults to auto, which mean it won't shrink smaller than its contents size.
Add min-width: 0 to left-content and it will allow it to shrink.
Updated fiddle
Stack snippet

.container {
  display: flex;
  flex-direction: column;
  background-color: grey;
  width: 100%;
  height: 200px;
}

.header {
  flex: 1;
  text-align: center;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: row;
}

.leftcontent {
  min-width: 0;
  flex: 5;
  background-color: green;
}

.rightcontent {
  flex: 5;
  background-color: yellow;
}

    THIS IS A TEST CODE WITH TEXT

      CONTENT OF LEFT SIDE

      CONTENT OF RIGHT SIDE

    THIS IS A TEST CODE WITH TABLE

            Column 1
            Column 2
            Column 3
            Column 4

            Data 1
            Data 2
            Data 3
            Data 4

      CONTENT OF RIGHT SIDE

If you want to be able to scroll the content, use overflow: auto or òverflow: scroll instead
Stack snippet

.container {
  display: flex;
  flex-direction: column;
  background-color: grey;
  width: 100%;
  height: 200px;
}

.header {
  flex: 1;
  text-align: center;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: row;
}

.leftcontent {
  overflow: auto;
  flex: 5;
  background-color: green;
}

.rightcontent {
  flex: 5;
  background-color: yellow;
}

    THIS IS A TEST CODE WITH TEXT

      CONTENT OF LEFT SIDE

      CONTENT OF RIGHT SIDE

    THIS IS A TEST CODE WITH TABLE

            Column 1
            Column 2
            Column 3
            Column 4

            Data 1
            Data 2
            Data 3
            Data 4

      CONTENT OF RIGHT SIDE


text:
Q: Get rows with most recent date for each different item Let's say  this is the sample date coming from a join of 2 tables. Database is Postgres 9.6
id  product_id  invoice_id  amount       date
1    PROD1       INV01       2          01-01-2018
2    PROD2       INV02       3          01-01-2018
3    PROD1       INV01       2          05-01-2018
4    PROD1       INV03       1          05-01-2018
5    PROD2       INV02       3          08-01-2018
6    PROD2       INV04       4          08-01-2018

I want to know if it's possible in a optimized way to:

*

*Get all the PRODx with their respective INVx which have the latest date, but per product_id. Please note that records unused from a day may be reported to a new one.
This means:

id  product_id  invoice_id  amount       date
3    PROD1       INV01       2          05-01-2018
4    PROD1       INV03       1          05-01-2018
5    PROD2       INV02       3          08-01-2018
6    PROD2       INV04       4          08-01-2018

*Get daily summed amounts for each PRODx but fill the gaps with the previous ones if day does not exist.

This means:
 product_id    amount       date
   PROD1         2          01-01-2018
   PROD2         3          01-01-2018
   PROD1         2          02-01-2018
   PROD2         3          02-01-2018
   PROD1         2          03-01-2018
   PROD2         3          03-01-2018
   PROD1         2          04-01-2018
   PROD2         3          04-01-2018
   PROD1         3          05-01-2018
   PROD2         3          05-01-2018
   PROD1         3          06-01-2018
   PROD2         3          06-01-2018
   PROD1         3          07-01-2018
   PROD2         3          07-01-2018
   PROD1         3          08-01-2018
   PROD2         7          08-01-2018

A few thoughts:

*

*For first question I could obtain the max(date) for each PRODx and the pick for each PRODx the rows that have the date=with max(date) but I was wondering if there's faster way to obtain this given a large number of recors in the database

*For the second question, I could generate a series of dates for the interval needed and then use WITH rows As and do the query grouping by product_id and sum by amount and then select for each date the previous values from rows with a limit 1 but that does not sound that optimized either.
Looking forward for any input. Thank you.
Later edit:
Trying to give DISTINCT ON () a try.

*

*If I have distinct on(product_id, invoice_id) then I don't get only the most recent ones for the most recent date. If there were invoice_ids in the the past, beside the latest date, then they will be returned

*If I have distinct on (product_id) then it returns from the most recent date, but as normal, only the last rows even if in the last day I have two positions for PROD1.

Basically I need something like 'I need for the most recent date, all the product_ids and their invoice_ids while keeping in mind that a product_id can have multiple invoice_ids'
Later edit 2:
Running a query like for first question seems to be reasonably fast:
select product_id, invoice_id, amount
from mytable inner join myOtherTable on...
             inner join (select max(date) as last_date, product_id
                         from mytable
                         group by product_id) sub on mytable.date =
                         sub.last_date

A: I understand that you want all the rows with the latest date for every product (ties included, i.e. all rows with the last date). This can be done with rank() function:
select id, product_id, invoice_id, amount, date
from
  ( select id, product_id, invoice_id, amount, date,
           rank() over (partition by product_id
                        order by date desc) as rnk
    from
        -- your joins
  ) as t
where rnk = 1 ;

A: Skinning Q#1 independently and slightly differently than @ypercube
with cte as (select row_number() over (partition by product_id,
                                       invoice_id
                                 order by dt desc) as rn,
                    product_id,
                    invoice_id,
                    amount,dt
               from product )
select product_id, invoice_id,amount,dt
  from cte
 where rn=1
 order by product_id,invoice_id;

 product_id | invoice_id | amount |     dt
------------+------------+--------+------------
 PROD1      | INV01      |      2 | 2018-01-05
 PROD1      | INV03      |      1 | 2018-01-05
 PROD2      | INV02      |      3 | 2018-01-08
 PROD2      | INV04      |      4 | 2018-01-08
(4 rows)

For Q#2, you are on the right track, but the SQL will have a cross join(gasp!)
I think a function with a loop/cursor would be more optimized (i'll try that in my next free block of time)
--the cte will give us the real values
with cte as (select product_id,
                    sum(amount) as amount,
                    dt
               from product
              group by product_id,dt)
select p.product_id,
       (select cte.amount --choose the amount
          from cte
         where cte.product_id = p.product_id
           and cte.dt <= d.gdt -- for same day or earlier
         order by cte.dt desc
         limit 1) as finamt,
       d.gdt
from (select generate_series( (select min(dt)
                                 from product), --where clause if some products
                                                --don't have an amount
                              (select max(dt)
                                 from product),
                              '1 day'
                            )::date as gdt)  d
cross join --assuming each listed product has an amount on the min date
     (select distinct product_id
        from product) p
left join --since we need to fill the gaps
     cte on ( d.gdt = cte.dt
             and p.product_id = cte.product_id)
order by d.gdt, p.product_id
;

A: I agree your later edit way, it should be:
select product_id, invoice_id, amount
    from mytable inner join
    (select max(date) as last_date, product_id, invoice_id
        from mytable
        group by product_id) sub
    on mytable.date = sub.last_date
    and mytable.product_id = sub.product_id
    and mytable.invoice_id = sub.invoice_id;

The "key" should be the date, product_id and invoice_id.


text:
Q: Table and embedded Sparkline I am working with SSRS 2008. I want to show monthly data of different products in a table with a embedded sparkline graph. The table should look like below:
Product   Avg Sales  Min Sales Sparkline
P1         100          10      30 days sales sparkline
P2         500          20      30 days sales sparkline

and so on.
I was using matrix for this but it doesn't allow me to bind my sparkline with a different data set other than the matrix data set. How can I get all the data in one dataset?


text:
Q: Getting error while saving byte array in HashMap In my app I'm doing request with Retrofit for getting byte array.Then I need to save this byte[] in HashMap and after that load with Glide. Ok, here's my code.
public class SimpleClass extends AppCompatActivity {

    private Activity activity = SimpleClass.this;
    private ImageView imageView;
    private HashMap<String, byte[]> imageHashMap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getImageBytes("Image1");
    }

    public void getImageBytes(final String imageName) {
        Call<ResponseBody> getChatImage = retrofitClient.getImagesBytes(imageName);
        getChatImage.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        imageHashMap.put("Key1", response.body().bytes());
                        Glide.with(activity).load(response.body().bytes()).fitCenter().into(imageView);

                    } catch (Exception e) {
                        Toast.makeText(activity, "Error cought in catch block:  " + e.toString(), Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }

                } else {
                    Toast.makeText(activity, "Response is not successful: " + response.errorBody(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(activity, "An error occurred", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

So when I want to put the byte[] in HashMap, I'm getting error like this in catch block - java.io.IOException: Content-Length (25139) and stream length (0) disagree. So when I'm removing this line - imageHashMap.put("Key1", response.body().bytes());, all works fine. So why I can't put byte[] in HashMap? Yes and one more question too. What would be good to use: HashMap or LinkedHashMap?

A: A byte[] (or any array) can't work properly as a key in a HashMap, since arrays don't override equals, so two arrays will be considered equal only if they refer to the same object.
You'll have to wrap your byte[] in some custom class that overrides hashCode and equals, and use that custom class as the key to your HashMap.


text:
Q: Can I smoke and drink myself to perfect health? Cigarettes give me salt at the expense of health. Booze gives me health at the expense of salt. Do these effects balance out, or is there a net positive effect? In other words, can I sustain myself on cigarettes and alcohol and (apart from the last debuff) maintain maximum health and salt?

A: Yes, you can.
Cigarettes give you a higher amount of your salt than they make you lose HP. Alcohol gives you more/the equal amount (Couldn't get it confirmed) health than it makes you lose salt.
This allows you to effectively smoke and drink as much as you want, and staying healthy at the same time.
There are a two exceptions:

*

*Absinthe (Fully increases Salts but decreases Health by half and
instantly inebriates)

*Flask of Unknown Booze (Fully increases Health but decreases Salts by
half and instantly inebriates)


text:
Q: Why won't C# accept a (seemingly) perfectly good Sql Server CE Query? By perfectly good sql query, I mean to say that, inside WebMatrix, if I execute the following query, it works to perfection:
SELECT page AS location, (len(page) - len(replace(UPPER(page), UPPER('o'), ''))) / len('o') AS occurences, 'pageSettings' AS tableName FROM PageSettings WHERE page LIKE '%o%'
UNION
SELECT pageTitle AS location, (len(pageTitle) - len(replace(UPPER(pageTitle), UPPER('o'), ''))) / len('o') AS occurences, 'ExternalSecondaryPages' AS tableName FROM ExternalSecondaryPages WHERE pageTitle LIKE '%o%'
UNION
SELECT eventTitle AS location, (len(eventTitle) - len(replace(UPPER(eventTitle), UPPER('o'), ''))) / len('o') AS occurences, 'MainStreetEvents' AS tableName FROM MainStreetEvents WHERE eventTitle LIKE '%o%'

Here i am using 'o' as a static search string to search upon. No problem, but not exeactly very dynamic.
Now, when I write this query as a string in C# and as I think it should be (and even as I have done before) I get a server-side error indicating that the string was not in the correct format.  Here is a pic of that error:

And (although I am only testing the output, should I get it to quit erring), here is the actual C# (i.e., the .cshtml) page that queries the database:
@{
    Layout = "~/Layouts/_secondaryMainLayout.cshtml";

    var db = Database.Open("Content");
    string searchText = Request.Unvalidated["searchText"];
    string selectQueryString = "SELECT page AS location, (len(page) - len(replace(UPPER(page), UPPER(@0), ''))) / len(@0) AS occurences, 'pageSettings' AS tableName FROM PageSettings WHERE page LIKE '%' + @0 + '%' ";
    selectQueryString += "UNION ";
    selectQueryString += "SELECT pageTitle AS location, (len(pageTitle) - len(replace(UPPER(pageTitle), UPPER(@0), ''))) / len(@0) AS occurences, 'ExternalSecondaryPages' AS tableName FROM ExternalSecondaryPages WHERE pageTitle LIKE '%' + @0 + '%' ";
    selectQueryString += "UNION ";
    selectQueryString += "SELECT eventTitle AS location, (len(eventTitle) - len(replace(UPPER(eventTitle), UPPER(@0), ''))) / len(@0) AS occurences, 'MainStreetEvents' AS tableName FROM MainStreetEvents WHERE eventTitle LIKE '%' + @0 + '%'";

    @:beginning

    foreach (var row in db.Query(selectQueryString, searchText))
    {
        @:entry
        @:@row.location
        @:@row.occurences
        @:@row.tableName

    }
}

Since it is erring on the foreach (var row in db.Query(selectQueryString, searchText)) line, that heavily suggests that something is wrong with my query, however, everything seems right to me about the syntax here and it even executes to perfection if I query the database (mind you, un-parameterized) directly.
Logically, I would assume that I have erred somewhere with the syntax involved in parameterizing this query, however, my double and triple checking (as well as, my past experience at doing this) insists that everything looks fine here.
Have I messed up the syntax involved with parameterizing this query, or is something else at play here that I am overlooking?
I know I can tell you, for sure, as it has been previously tested, that the value I am getting from the query string is, indeed, what I would expect it to be, but as there really isn't much else on the .cshtml page yet, that is about all I can tell you.

A: I would find the answer to my 2-day long search for a solution to this problem, just after posting a question here, but alas, when looking a little closer at some old code I used, I found that in the LIKE phrase I actually used CAST such that, if used in the LIKE phrase in my above example, it would look like this:
LIKE '%' + CAST(@0 AS nvarchar) + '%'

I suppose a regular C# string isn't the same thing as a sql nvarchar data type.
There's still an accept and upvote in it for anyone who can possibly shed a little more light on this for anyone (including myself) that may benefit from a more precise explanation (that is, if there is anything more to it than a simple "it's just not the same data type" explanation).
(NOTE: If it helps any future viewer to know, the parameters in the LIKE phrase is ALL that I changed. I did not have to cast or change anything about the syntax involved in the parameters written outside of the LIKE phrases).

A: This is a long shot but may shed some light.  Try executing the following query and read the results:
select top 1 sql_variant_property(@0, 'BaseType') as type from MainStreetEvents;

For any passed object parameter that doesn't error out, you should get back information about what sql type is being used to represent it.


text:
Q: Using ProgressDialog with async/wait, C# Android I have a function which calls a server to update a database and I wait around for it to complete before returning the result :
public async Task<int> CarryOutPreRegisterDevice(string emailAddress)
{
    int intRet=-1;
    Task<int> tski = PreRegisterDevice(emailAddress);

    intRet = await tski;
    return intRet;
}

What I would like to do is display a progressdialog whilst this is happening.  However, as soon as I wrap the await line in a progress dialog it allows the original thread to run on and return intRet before the awaited task has completed.
public async Task<int> CarryOutPreRegisterDevice(string emailAddress)
{
    int intRet = -1;
    Task<int> tski = PreRegisterDevice(emailAddress);

    ProgressDialog progressDialog;
    progressDialog = ProgressDialog.Show(AppGlobals.CurrentActivity, "", "Sending....", true);
    progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner);
    new Thread(new ThreadStart(async delegate
    {

        intRet = await tski;

        progressDialog.Dismiss();
    })).Start();

    return intRet;
}

Is there a better way of structuring this so that the return line does not get executed before the task has completed.
Thanks.

A: Not sure why you have created a thread, that defeats the purpose of tasks. If you want to show an spinner while the long task is running just await it after showing the progressdialog:
public async Task<int> CarryOutPreRegisterDevice(string emailAddress)
{
    ProgressDialog progressDialog;
    progressDialog = ProgressDialog.Show(AppGlobals.CurrentActivity, "", "Sending....", true);
    progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner);

    var intRet = await PreRegisterDevice(emailAddress);

    progressDialog.Dismiss();

    return intRet;
}


text:
Q: Unittest helper and my executable's helper coincides while invoking my script from the command line terminal I have been automating hardware tests for a delivery robot for a while now and I was programming a helper function which is invoked when the user types the executable without any arguments or simply by typing '-help'. The problem is when I invoke the script which has unittests for the robot, my helper and the unittests's own helper coincides with.
For example, a usual testing takes place by typing:
/exec.py -h ip-placeholder -u robotname -p portnumber
After this point, i get both my helper displayed and unittest's tests helper with positional arguments and options.
My question is, is there a way of executing my test cases inside of the script and invoking it from some other script while getting command line arguments there.
if __name__ == '__main__':

   #we need to have a script that handles command line arguments function
    args = sys.argv[1:]
    if (not args or args[0] == "-help"):
        helper()

    if(len(args) == 6):
        if(args[0] == '-h' or args[0] == '--hostname'):
            my_hostname = args[1]
        if(args[0] == '-u' or args[0] == '--user'):
            my_username = args[1]
        if(args[0] == '-p' or  args[0] == '--port'):
            my_port = args[1]

        if(args[2] == '-he' or args[2] == '--hostname'):
            my_hostname =  args[3]
        if(args[2] == '-u' or args[2] == '--user'):
            my_username = args[3]
        if(args[2] == '-p' or args[2] ==  '--port'):
            my_port = args[3]

        if(args[4] == '-h' or args[4] == '--hostname'):
            my_hostname =  args[5]
        if(args[4] == '-u' or  args[4] == '--user'):
            my_username = args[5]
        if(args[4] == '-p' or args[4] == '--port'):
            my_port = args[5]

    unittest.main()

#    host_info = host_select() # we get the host info with calling this function
#    [my_hostname, my_username, my_port] = host_info
#
#
#
#    unittest.main()
#


text:
Q: Does the javascript/NodeJS compiler automatically make these small efficiency tweaks, or should be careful to implement them myself? (Example given) I am making a program that accesses pretty large API's and it made me curious about something that might help its overall efficiency
Lets say I have a JSON resource that is located at data.Orders[i].TgtResource , where data is Parsed JSON that has a resource called Orders which is an array of other resources and TgtResource is the resource I am after.
Would something like this:
for(var i = 0; i < data.Orders.length; i++){
    for(var j = 0; j < data.Orders[i].length; j++){
         (extract resource)
    }
}

Become interpreted by a compiler as something slightly more efficient, like this:
    var totalSize = data.Orders.length;
    for(var i = 0; i < totalSize; i++){
        var innerArraySize = data.Orders[i].length;
        for(var j = 0; j < innerArraySize; j++){
             (extract resource)
        }
    }

Or is it up to me to make that small adjustment? I worked a bit with C and C++ and I saw, after viewing some of the assembly code my programs generated, that this kind of stuff was automatically done by the compiler I was using, so I would like to know if this kind of stuff happens with JS.
Thanks for any help!


text:
Q: Quartz upgrade to 2.X We upgrade our quartz from 1.8.6 to 2.1.
It appears that some ddl are missing in the official site (http://quartz-scheduler.org/documentation/quartz-2.1.x/migration-guide).
The issue we encountered was that SCHED_TIME should be added to QRTZ_FIRED_TRIGGERS table.
We found an issue about it which says that the site will be updated in version 2.2 (quartz jira site).
Still, it seems that the issue was found in 2013 and the instruction in quartz site has not updated yet.
This missing fail the migration from 1.8.6 to 2.1
Has anyone encounter this issue as well?


text:
Q: Updating from an input element in ReactJS I'm attempting to create a page using React, whereby I can update a single element of the state; here is how the state is defined:
interface MyState {
    data?: MyData;
    loading: boolean;
}

interface MyData {
    id: number;
    description: string;
    test: string;
}

I have the following inside my render function:
return

Description: {myData.description}

    <input type="text" value={emailType!.test} onChange={this.handleChange} />

;

And the handleChange (which is the heart of my issue):
handleChange(event: React.FormEvent<HTMLInputElement>) {
    this.setState({ emailType!.test: event.currentTarget.value });
}

As I'm using tsx, the function above won't even compile.  However, it does illustrate what I'm trying to do.  Typically, when I've called this.setState, I've done so with a full state (that is, I know the entire new state).  In this case, I only want to change the contents of a single field: is that possible?

A: setState allows changing only top-level key in the state like
handleChange = (event: React.FormEvent<HTMLInputElement>) => {
    const emailType = { ...emailType, test: event.currentTarget.value }
    this.setState({ emailType })
}

Don't forget to bind your function to the proper context.
Another option is to use function as a parameter in setState:
this.setState((oldState) => {
  return {
    ...oldState,
    emailType: {
      ...oldState.emailType,
      test: event.currentTarget.value
    }
  }
})


text:
Q: Is there any way I can pull a json file with node here instead of react.js? I want to add items to a shopping cart using a json file and node.js. I have found this tutorial that uses react.js but I want to know can node.js be used instead and how it can be applied?
https://github.com/scotch-io/react-flux-cart

A: express module will be who handle the request from the client. express helps you to recieve and send json files to browser.
For saving the cart in the server, you have to use a database or file storage. like mongodb or mysql or simply using fs.writeFile
After you install node, and express (npm i express) this is a code example for send to the user a JSON of his cart:
app.get('/cart',function(req,res){
   res.send({total:250, items: [{name:'mybook',price:250}])
})

Good luck learning NodeJS.


text:
Q: Is default stringstream formatting the same as snprintf's? I'm looking to replace some snprintf calls with stringstreams.  I need to ensure the output is identical.
given long l = some_input_var;
do
std::ostringstream str;
str << l;
return str.str();

and
buf str[24];
snprintf(str, 24, "%ld", l);
return std::string(str);

return identical strings?
What about for int and "%d" or  double and "%f" ?

A: Yes. But it's a long story: iostreams formatting works via the stream's codec's formatting facet. The details are fairly involved; see C++11 27.7. The default facet's conversion uses sprintf for input formatting and the strtoull-type functions for output; see 22.4.2.1 for details.
Also and similarly, the new <string> conversion functions std::to_string use the default sprintf format, and the various std::stoul-like functions use the C library's strtoul-like functions.

A: In the standard, the C++ formatting is defined in terms of printf format
specifiers, so you can be pretty sure that simple formatters will work
the same.  There are, however, things the iostream doesn't support (and
vice versa): there's no iostream equivalent of "% d", for example, and
the precision specification is ignored when outputting a string
(probably because iostream doesn't know whether the string would be part
of the format string, or correspond to a "%s").
Also, don't forget that all of the format options except width are
sticky; you should save them, and restore them when you've formatted the
element which needs them.

A: Let say that for that case the answer is yes, I wouldn't trust it to be the same for all cases, especially with the pains of making all the alignments right.
Did you consider Boost::format?
Something like return boost::str(boost::format("%ld") % l); should work
and will provide for an easier migration path.  Though differences do exist.


text:
Q: Extract all individual slope coefficient from pooled OLS estimation in R I hit a problem where I want to extract all individual coefficient of a particular variable in a pooled regression.
My data look like this and I regress Y on X.
Observation name date Y  X
1           A    1    Y1 X1
2           A    2    Y2 X2
3           B    1    Y3 X3
4           B    2    Y4 X4

Using the plm package and summary, R only gives me one coefficient of X. However, I want to have coefficient of X variable in each individual regression. Can anyone help me with this?
To clarify, what I want is all the beta associated with the X_n,1 in the below picture. Sorry for the confusion.

A: You can use tidy and augment from the broom package to take the results from plm and put them into a data frame.
library(plm)
library(broom)

data("Grunfeld", package = "plm")

p <- plm(inv ~ value + capital, data = Grunfeld, model = "pooling")

df <- tidy(p)

#          term    estimate  std.error statistic      p.value
# 1 (Intercept) -42.7143694 9.51167603 -4.490730 1.207357e-05
# 2       value   0.1155622 0.00583571 19.802589 9.542703e-49
# 3     capital   0.2306785 0.02547580  9.054808 1.347370e-16

df$estimate

# [1] -42.7143694   0.1155622   0.2306785

augment(p)

#         inv   value capital     .fitted      .resid
# 1    317.60 3078.50    2.80  313.689629    3.910371
# 2    391.80 4661.70   52.60  508.135423 -116.335423
# 3    410.60 5387.10  156.90  616.023978 -205.423978
# 4    257.70 2792.20  209.20  328.216223  -70.516223
# 5    330.80 4313.20  203.40  502.648328 -171.848328
# 6    461.20 4643.90  207.20  541.741311  -80.541311
# 7    512.00 4551.20  255.20  542.101267  -30.101267
# 8    448.00 3244.10  303.70  402.237879   45.762121
# 9    499.60 4053.70  264.10  486.662133   12.937867
# 10   547.50 4379.30  201.60  509.871765   37.628235

A: If you want different coefficients for the entities (split by name in your example), you can use the function pvcm() from the package plm to fit a OLS model per individual or do it by hand, see code example below.
Building upon the example from the help page (?pvcm):
library(plm)
data("Produc", package = "plm")

form <- log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp

pvcm(form, data = Produc, model = "within") # individual coefficients
## Coefficients:
##                (Intercept)  log(pcap)    log(pc)  log(emp)       unemp
## ALABAMA            8.49604 -1.4426440  0.2795010  1.835250  0.00735450
## ARIZONA            4.66528 -0.1627084 -0.0052207  1.075828 -0.00365798
## ARKANSAS           3.24565 -0.5056503  0.3212473  1.234017  0.00149221
## CALIFORNIA         0.27935  0.2639377  0.2484033  0.699135 -0.01074510
## [...]

###### same using OLS on splitted data for first entity (ALABAMA):
l <- split(Produc, Produc$state)
plm(form, data = l[[1]], model = "pooling")
## Coefficients:
## (Intercept)   log(pcap)     log(pc)    log(emp)       unemp
##   8.4960384  -1.4426440   0.2795010   1.8352498   0.0073545


text:
Q: struggling with normalisation using map and reduce I want to do a radar chart but I have no control for the api output, so I have to turn a complicated data into some form. I'm stuck for at least half an hour.
How can I turn this raw data
const raw = [{
  "device_info": {
    "device_id": 123,
    "name": "iphone",
  },
  "age_data": [{
    "age_range": "0-10",
    "total_count": 15,
    "man": 6,
    "women": 9
  }, {
    "age_range": "11-20",
    "total_count": 11,
    "man": 7,
    "women": 4
  }]
}, {
  "device_info": {
    "device_id": 456,
    "name": "android",
  },
  "age_data": [{
    "age_range": "0-10",
    "total_count": 1,
    "man": 1,
    "women": 0
  }, {
    "age_range": "11-20",
    "total_count": 2,
    "man": 0,
    "women": 2
  }]
}]

into this
const data = [{
  age_group: '0-20',
  iphone: 26,
  android: 3
}, {
  age_group: '21-30',
  iphone: 0,
  android: 0
}, ];

https://jsfiddle.net/cqmyganr/2
This is what I have tried:
const age_group = raw[0].age_data.map(obj => ({
  age_group: obj.age_range
}))

const cams = raw.map(obj => ({
  device_id: obj.device_info.device_id,
  device_name: obj.device_info.name
}))

console.log(cams)

const age_group_with_cams = age_group.map(obj =>
  Object.assign({}, obj, ...cams)
)

console.log(age_group_with_cams)

A: OK, I would do use reduce because your are converting the data into another form list-of-devices-with-age-info => list-of-ages-with-devices the lists can have different lengths.
This would be my first step, map all devices to all existing ages
const usageByAge = raw.reduce((by_age, dev) => {
  dev.age_data.forEach(age => {
    if (!by_age[age.age_range]) by_age[age.age_range] = {};
    by_age[age.age_range][dev.device_info.name] = age.total_count;
  })

  return by_age;
}, {})

// output, something like this:
usageByAge = {
  "0-10": { android: 123, iphone: 321 },
  "10-20": { android: 123, iphone: 321 },
}

From here again a reduce function, this time create a rule:
isGroupInBounds = (g, lo, hi) => {
  const [gl, gh] = g.split('-');
  return gl >= lo && gh <= hi;
}

["0-20", "21-30"].map(age_group => {
  const group = { age_group, iphone: 0, android: 0 };
  const [l, h] = age_group.split('-')

  Object.keys(usageByAge).forEach(inputGroup => {
    if (isGroupInBounds(inputGroup, l, h)) {
      Object.keys(usageByAge[inputGroup]).forEach(deviceName => {
         group[deviceName] += usageByAge[inputGroup][deviceName];
      })
    }
  })

  return group;
})

Yeeah, this s**t is really tricky, have tried it in your fiddle and it worked ;) Thank you for this exercise!
https://jsfiddle.net/cqmyganr/1/

A: After reading @webdeb's answer I figured that there was a better way to do what he did. Here's what I came up with:

const raw = [ { device_info: { device_id: 123
                             , name: "iphone" }
              , age_data: [ { age_range: "0-10"
                            , total_count: 15
                            , man: 6
                            , women: 9 }
                          , { age_range: "11-20"
                            , total_count: 11
                            , man: 7
                            , women: 4 } ] }
            , { device_info: { device_id: 456
                             , name: "android" }
              , age_data: [ { age_range: "0-10"
                            , total_count: 1
                            , man: 1
                            , women: 0 }
                          , { age_range: "11-20"
                            , total_count: 2
                            , man: 0
                            , women: 2 } ] } ];

// First, we convert the raw data into a relation:

const relation = [], devices = {};

const toInt = x => parseInt(x, 10);

for (const { device_info: { device_id, name }, age_data } of raw) {
    devices[name] = 0; // The default total_count of every device.

    for (const { age_range, total_count, man, women } of age_data) {
        const [age_begin, age_end] = age_range.split("-").map(toInt);

        relation.push({ device_id, name
                      , age_begin, age_end
                      , total_count, man, women });
    }
}

// Next, we write a function that given an age range returns its stats:

const getAgeRange = (begin, end) =>
    relation.reduce((table, tuple) => {
        if (tuple.age_begin >= begin && tuple.age_end <= end) {
            const row = table.find(row => row.name === tuple.name);

            if (row) {
                row.total_count += tuple.total_count;
                row.man         += tuple.man;
                row.women       += tuple.women;
            } else table.push(Object.assign({}, tuple));
        } return table;
    }, []);

// Finally, we create an array of the age groups we're looking for:

const getAgeGroup = (begin, end) =>
    getAgeRange(begin, end).reduce((summary, { name, total_count }) => {
        summary[name] = total_count;
        return summary;
    }, Object.assign({ age_group: begin + "-" + end }, devices));

const data = [ getAgeGroup(0,  20)
             , getAgeGroup(21, 30) ];

console.log(data);

Hopefully that makes sense. I tried to stick to the relational model as closely as possible.


text:
Q: How to fetch the transaction activities/logs for a specific table? I can see the transaction logs with fn_dblog, but I need to do this for specific table. How can I do that?

A: You could try the following:
Retrieve the id for your user table:
SELECT id, name FROM sys.sysobjects WHERE NAME = '<Your_Table_Name>'

e.g. 658101385
Retrieve the Transaction Log information with the undocumented function:
SELECT * FROM ::fn_dblog(NULL,NULL) WHERE [Lock Information] LIKE '%658101385%'

And then carry on from there.
Reference: Identifying Object Name for CREATE and ALTER Using fn_dblog()

A: Why don't just filter on the table name?
select *
from fn_dblog(null, null)
where AllocUnitName = 'dbo.zzz'

Here is my repro when I create a table, insert 3 rows in it and delete 1 row.
Then I search for this table in the log using both methods.
I didn't miss anything important filtering directly on table name.
The two methods produce different result sets:

*

*"filter by table name" misses all the LOP_LOCK_XACT operations;

*"filter by lock info" misses everything regarding IAM/PFS page modifications

I might seem (e.g. from reading Identifying Object Name for CREATE and ALTER Using fn_dblog()) that lock information can help us to identify table name on creation, but that's not true: The CREATE TABLE row of fn_dblog() has no lock information at all.

A: The transaction log is not human readable.
Depending on the reason behind wanting "to do this for specific table" (not specified in the question), you could look into buying a third party tool, rather than attempting it on your own.


text:
Q: Why does vector field  have 0 divergence? enter image description here
Numerically, the divergence is 0. However, when looking at the vector field, it appears like the flow is away from the origin. Hence, why does it have 0 divergence just by examining the vector field. (Image in link above)
Adding on, why is divergence calculated as a sum of the partial derivatives of every component, instead of solely examining each component and taking the partial derivatives individually.
Breaking up the vector field <x, -y> into its individual components, it has positive divergence in the x-direction, and negative divergence in the y-direction, which seems to give more intuition on the divergence of the vector field than their sum.
TL;DR Why does vector field <x, -y> have 0 divergence and why is divergence calculated as a sum?

A: We can look at this vector field $ \ \overrightarrow{F} \ = \ \langle \ x \ , \ -y \ \rangle \ \ $ in a couple of ways.  If we look at unit vectors, it becomes $ \ \hat{F} \ = \ \langle \ \frac{x}{r} \ , \ -\frac{y}{r} \ \rangle \ = \ \langle \cos \theta \ , \ -\sin \theta \rangle \ \ . $  This means that on a circle of any radius (centered on the origin), every possible direction for the unit vectors appears.  So the sum of these vectors over any circular boundary is zero, indicating that there is no "net flow" across that closed curve.
If we look at the tangent of the angle that the vectors make to the $ \ x-$axis, we find $ \ \tan \theta \ = \ \frac{-y}{x} \ \ , $ which tells us that the direction of "flow" is identical in diagonally-opposed quadrants and exactly reversed in adjacent quadrants.  So again, there is the suggestion of "canceling flows".  (Somewhat less intuitive -- so requiring a proof -- is that the net flow through any closed curve within the zero-divergence field is equal to zero.)  Taking the tangent of the angle above as the slope of a tangent line to a curve, we get a separable differential equation
$$ \frac{dy}{dx} \ \ = \ \ \frac{-y}{x} \ \ \Rightarrow \ \ \int \ \frac{dy}{y} \ \ = \ \ \int -\frac{dx}{x} \ \ \Rightarrow \ \ \ln |y| \ = \ -\ln |x| \ + \ C $$ $$ \Rightarrow \ \ y \ \ = \ \ \frac{K}{x} \ \ , \ \ K \neq 0 \ \ .  $$
So the flow curves are the family of rectangular hyperbolas centered on the origin, showing the "diagonal symmetry" of the flow and why it is plausible to expect a net flow of zero through at least a closed curve symmetrical about the origin.

The divergence of a vector field is the scalar ("dot") product of the vector differential operator (in two dimensions, $ \ \frac{\partial  }{\partial x} + \frac{\partial}{\partial y} \ $) with the components of the vectors, (here $ \ F_x \mathbf{i} \ + \ F_y \mathbf{j} \ ) \ \ ,  $ which is why it is a (scalar) sum.  This is not particularly intuitive in itself.  Since the divergence of a field is only meaningful over a closed region, this sum of partial derivatives of corresponding vector components, integrated over a region, gives the sum of the net changes in each component.  If this total net change in all of the components is zero $ \ ( \ \mathbf{div} \overrightarrow{F} \ = \ 0 \ ) \ $ in the region, there is no net flow through its boundary.


text:
Q: Angular6 upgrade issue: Property 'data' does not exist on type 'Object' I am upgrading my angular app from v5 to 7.
I have done all of the migration steps mentioned in Angular update guide.
But I am facing an issue with my existing code.
myservice.service.ts
import {Injectable, Inject} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Response, Headers, RequestOptions} from "@angular/http";

@Injectable()
export class MyApiService{
    constructor(private http: HttpClient, @Inject(MY_HOST) private host: string)
    {
        this.host = this.host + "/api/common";
    }
    getNotification (appName) {
        return this.http.get(this.host + "/notifications")
    }
}

my-component.component.ts
import {combineLatest as observableCombineLatest, Subject, Observable, Subscription} from 'rxjs';
import {MyApiService} from "../../shared/services/myservice.service";

@Component({..// template and style url...});

export class NotificationComponent implements OnInit{
    constructor(private myApiService: MyApiService)

 getNotification(): void {
     this.myApiService.getNotification('myApp').subscribe(response => {
        console.log(response.data); **// ERROR: It throws error here. Property** 'data' does not exist on type 'Object'.
    }, (error: void) => {
      console.log(error)
   })
 }

}

A: You must use any or a custom response type since data doesn't exist on type {}:
.subscribe((response: any) => ...)

A custom response interface is the best solution:
export interface CustomResponse {
  data: any;
}

.subscribe((response: CustomResponse) => ...)

Note that you can also use the type like this:
this.httpClient.get<CustomResponse>(...)
  .subscribe((response) => ...) // response is now CustomResponse

A: See this example from the angular documentation for HTTPClient:
Service code:
getConfigResponse(): Observable<HttpResponse<Config>> {
  return this.http.get<Config>(
    this.configUrl, { observe: 'response' });
}

Consumer Code:
showConfigResponse() {
  this.configService.getConfigResponse()
    // resp is of type `HttpResponse<Config>`
    .subscribe(resp => {
      // display its headers
      const keys = resp.headers.keys();
      this.headers = keys.map(key =>
        `${key}: ${resp.headers.get(key)}`);

      // access the body directly, which is typed as `Config`.
      this.config = { ... resp.body };
    });
}

By declaring the return type explicitly on the service they can avoid having to declare it on the subscription inner logic because the code is strongly typed.


text:
Q: How to embed special character in XML and have XDocument parse it How to embed special character in XML and have XDocument parse it?
<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer>
<CustomerID>BLAUS</CustomerID>
<CompanyName>Blauer See Delikatessen</CompanyName>
<ContactName>Hanna Moos</ContactName>
<Region>testing</Region>
</Customer>
<Customer>
<CustomerID>SPLIR</CustomerID>
<CompanyName>Split Rail Beer &#x25BA Ale</CompanyName>
<ContactName>Art raunschweiger</ContactName>
<Region>WY</Region>
</Customer>
</Customers>

A: The file you posted is not valid XML which is why it will fail to parse.
The problem is in this line:
<CompanyName>Split Rail Beer &#x25BA Ale</CompanyName>

Which should be:
<CompanyName>Split Rail Beer ► Ale</CompanyName>

A properly encoded numeric entity is ► (note the trailing ;) - this translates to the character ►.


text:
Q: Filtering list inside Observable collection I want to filter List <Notification> which is inside Observable collection by the specified event.
Here is a Retrofit call:
@GET("/notifications")
Observable<NotificationCollection> getNotifications(@Query("page") Integer page);

NotificationCollection model:
class NotificationCollection {
         var items: List<Notification>? = null
         var pagination: Pagination? = null
}

Notification model:
class Notification {
        var event: String? = null
        var id: Long? = null
        var data: NotificationData? = null
}

In my helper class, I return Observable to interactor:
override fun getNotifications(page: Int): Observable<NotificationCollection> {
        return service.getNotifications(page)
    }

I tried a couple of approaches:
override fun getNotifications(page: Int): Observable<NotificationCollection> {
return service.getNotificationsTimeline(page)
    .filter { it.items?.get(0)?.event == "STORY"}
}

Here I want to apply a predicate to all list items and not only to the ones I define by an index. Is there a way to make something like .filter { it.items.event = "STORY"} ?
Another approach I tried using flatMap here which makes more sense to me but I don't see the way how to map my filtered result to the original response type of Observable<NotificationCollection> and not to the Observable<Notification> like here :
return service.getNotifications(page)
    .flatMap { Observable.fromIterable(it.items) }
    .filter {it.event == "STORY"}

The easiest way would be to apply filter function in my presenter class with flatMap but I want to generalize my solution because the method in the helper class is called in different places. So I want to make the list filtered here.
So, is there a way to filter the list inside Observable collection and return the original response type of Observable<NotificationCollection>?

A: You should use 'filter' and 'any' together.
class Test {
    init {
       val testList = listOf(
               TestData("1","1", listOf("1a")),
               TestData("2","2", listOf("2b")),
               TestData("3","3", listOf("3c")))

        val result = testList.filter { item ->
            item.c.any { it == "STORY" }
        }
    }
}

data class TestData(val a: String, val b: String, val c: List<String>)


text:
Q: python beginner: can't init an object from zero class Node:
    def __init__(self,dic_nodes = dict()):
        self.dic_nodes = dic_nodes

root = Node()
print("original_root:", root)
word = "sci"
length = len(word)
for i in range(0, length):
    if word[i] not in root.dic_nodes:
        print("root:", root)
        new_node = Node()
        print("new_node:", new_node, len(new_node.dic_nodes))
        root.dic_nodes[word[i]] = new_node
        next = root.dic_nodes[word[i]]
        print("next:", next, len(root.dic_nodes[word[i]].dic_nodes))
        root = next
        print("root:", root)
    print()

Outputs are like this:
original_root: <__main__.Node object at 0x109eb1510>
root: <__main__.Node object at 0x109eb1510>
new_node: <__main__.Node object at 0x109ec3350> 0
next: <__main__.Node object at 0x109ec3350> 1
root: <__main__.Node object at 0x109ec3350>

root: <__main__.Node object at 0x109ec3350>
new_node: <__main__.Node object at 0x109eb1510> 1
next: <__main__.Node object at 0x109eb1510> 2
root: <__main__.Node object at 0x109eb1510>

root: <__main__.Node object at 0x109eb1510>
new_node: <__main__.Node object at 0x109ec3fd0> 2
next: <__main__.Node object at 0x109ec3fd0> 3
root: <__main__.Node object at 0x109ec3fd0>

My Problem:
The 2nd time I call Node() to construct a new object, I think "len(new_node.dic_nodes)" should also be 0 just like the 1st time I create a new object. I can't figure out where my problem is.

A: Because it is using the same dict as the default argument each time, the default dict grows over time. Instead do this:
class Node:
    def __init__(self, dic_nodes=None):
        if dic_nodes is None:
            dic_nodes = dict()
        self.dic_nodes = dic_nodes


text:
Q: Hacer count en varios campos mysql Buenas, tengo una db en mysql, quisiera realizar el conteo de un valor determinado en muchos campos en una misma tabla (no en un solo campo), por ejemplo en este caso tengo la tabla
A= Aceptable
S= Sobresaliente
E = Excelente
Tabla: notas

Como pueden ver no es un simple count, ya que hay varios campos de notas para diferentes estudiantes, quiero por ejemplo contar las A, las S y las E en los diferentes campos de todos los estudiantes, gracias y espero me haya sabido explicar.

A: Esta consulta te cuenta cada nota, y te da un nombre de fila para cada una. No está mal ¿no?
SELECT nota, COUNT(*) total
    FROM (
            SELECT nota1 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota2 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota3 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota4 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota5 as nota FROM estudiantes_20171010

    ) tbl_tmp
GROUP BY nota;

Aunque yo mejoraría el diseño de la base de datos, así nos evitas dolores de cabeza ... :)  Una simple tabla que guarde id_estudiante,  id_asignatura y nota daría un respiro interesante a la tabla estudiantes, te permitiría contar lo que quieras, aunque fueran miles de tipos de notas, etc...
Espero te sea útil.
Código
VER DEMO
CREATE TABLE IF NOT EXISTS estudiantes_20171010
(
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(20), nota1 CHAR(1), nota2 CHAR(1),nota3 CHAR(1),nota4 CHAR(1),nota5 CHAR(1)
)ENGINE=INNODB;

INSERT INTO estudiantes_20171010 (nombre,nota1,nota2,nota3,nota4,nota5)
    VALUES
    ('Estudiante1','E','S','S','A','S'),
    ('Estudiante2','A','S','A','E','S'),
    ('Estudiante3','S','E','S','S','S')
;

-- Datos de prueba

SELECT *
FROM estudiantes_20171010
;

-- Contando notas

SELECT nota, COUNT(*) total
    FROM (
            SELECT nota1 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota2 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota3 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota4 as nota FROM estudiantes_20171010
            UNION ALL
            SELECT nota5 as nota FROM estudiantes_20171010

    ) tbl_tmp
GROUP BY nota;

--Datos de prueba
id  nombre         nota1    nota2   nota3   nota4   nota5
1   Estudiante1    E        S       S       A       S
2   Estudiante2    A        S       A       E       S
3   Estudiante3    S        E       S       S       S

--Conteo
nota    total
A       3
E       3
S       9

A: En este caso, como todas los caracteres a contar ocupan una posicion, se puede hacer un pequeño truco para contar los caracteres.
Separemos el query en dos..
Primero tenemos que obtener una sola cadena por Estudiante:
SELECT
    CONCAT(nota_1,nota_2,...) as concatenado
FROM
    TABLA

y luego, contamos por cada fila la cantidad de cada aparicion, esto solo vale porque es una letra! si no la funcion seria un poco mas complicada.
SELECT
    LENGTH(concatenado) - LENGTH( REPLACE ( concatenado, "A", "") ) as NOTAS_A,
    LENGTH(concatenado) - LENGTH( REPLACE ( concatenado, "E", "") ) as NOTAS_E,
    LENGTH(concatenado) - LENGTH( REPLACE ( concatenado, "S", "") ) as NOTAS_S
FROM
   TABLA_ANTERIOR

A: También puedes usar variables, por ejemplo:
// Se cuentan todas las S de la columna nota1 y se mete en variable
select count(*) from asignatura where Nota1='S' into @valor1;

// Se cuentan todas las S de la columna nota2 y se mete en variable
select count(*) from asignatura where Nota2='S' into @valor2;

// Hay que repetir las sentencias anteriores por cada columna de cada tabla.

// Se suman todas las variables y te da el número total de S por tabla.
select @valor1 + @valor2;

Probablemente se pueda optimizar esta consulta cambiando el Where, diciendo que cuente cualquiera de las S que encuentre, pero ahora mismo es lo primero que se me viene.


text:
Q: Displacement and mass of water in a column I attempted to modify a classic experiment to demonstrate Archimedes principle to my 5th graders and I created an error I can't explain.
We started with a graduated cylinder containing  20 mL of water.
We added 10 pennies to the cylinder forcing a rise of about 5 mL to the column, or a total of 25 mL
We then placed the 10 pennies into one pan of a balance
We the used a syringe to place 5 mL of water on the other side of the balance
At this point I was ready to scream Eureka and have them bask in the equivalence of the displaced water to the object(s) that caused the displacement.
Unfortunately, the two masses were no where near equal... no Eureka.
The 5 mL of displaced water in the cylinder was not equal to the mass of the 10 pennies
I had the kids keep adding water until it balanced and it was about 25 mL to match the mass of 10 pennies
I have seen this video experiment before using an overflow vessel and watched countless online professors show the mass of the displaced water equal to the mass of the object.
Yet for some reason that I can't explain I could t get this to work when you measure the displacement in a cylinder
Anyone have any ideas on what kind of obvious error in thinking and / or procedure am I making here?
Thanks

A: OK, first let's start with a reality check. You were expecting that the weight of the objects you placed in the water and which sank to the bottom (i.e., the ten pennies) would be equal to the weight of the volume of water which the objects displaced (i.e., 5 ml). But suppose that instead of the copper pennies you had dropped in much heavier coins of the same size as those pennies but made of a denser metal such as gold or lead? By your understanding of Archimedes' principle, these heavier coins should also weigh the same as 5 ml of water, which obviously can't be correct.
Read this statement of Archimedes' principle carefully: "Archimedes' principle states that the upward buoyant force that is exerted on a body immersed in a fluid, whether fully or partially submerged, is equal to the weight of the fluid that the body displaces and acts in the upward direction at the center of mass of the displaced fluid."
Archimedes' principle does not say that the weight of an object dropped into a fluid is equal to the the weight of the fluid which is displaced by the object. What it says is that the buoyant force of the immersed object is equal to the weight of the fluid displaced by the object. When you put your pennies into the water there are effectively two forces acting on them: (1) the normal downward gravitational force and (2) the upward buoyant force which, by Archimedes' principle, has a magnitude equal to the weight of the water displaced by the pennies. So Archimedes' principle basically says that your pennies get lighter (i.e., weigh less) when you put them into the water by an amount equal to the weight of the water that those pennies displace.
Only for an object of neutral buoyancy will the gravitational force (or weight) of the object (i.e., force #1 above) be equal to the buoyant force of the object (i.e., force #2 above), but your pennies are not of neutral buoyancy. They're denser than water and they sink. That means that force #1 is greater than force #2, which is what you demonstrated when you found that the weight of the pennies is greater than the weight of the volume of water displaced by the pennies.
If you want an object that has a weight (in air) exactly equal to the weight of the water displaced by that object, then you need to figure out some way of making an object which is neutrally buoyant in water.


text:
Q: Compressing large text data before storing into db? I have application which retrieves many large log files from a system LAN.
Currently I put all log files on Postgresql, the table has a column type TEXT and I don't plan any search on this text column because I use another external process which nightly retrieves all files and scans for sensitive pattern.
So the column value could be also a BLOB or a CLOB, but now my question is the following,
the database has already its compression system, but could I improve this compression manually like with common compressor utilities? And above all WHAT IF I manually pre-compress the large file and then I put as binary into the data table, is it unuseful as database system provides its internal compression?

A: I don't know who would compress the data more efficiently, you or the db, depends on the algo used etc. But what is sure is that if you compress it, asking the db to compress it again will be a waste of CPU. Once compressed, trying to compress it again yields less gain each time until you end up consuming more space eventually.

A: The internal compression used in PostgreSQL is designed to err on the side of speed, particularly for decompression. Thus, if you don't actually need that, you will be able to reach higher compression ratios if you compress it in your application.
Note also that if the database does the compression, the data will travel between the database and the application server in uncompressed format - which may or may not be a problem depending on your network.
As others have mentioned, if you do this, be sure to turn off the builtin compression, or you're wasting cycles.
The question you need to ask yourself is do you really need more compression than the database provides, and can you spare the CPU cycles for this on your application server. The only way to find out how much more compression you can get on your data is to try it out. Unless there's a substantial gain, don't bother with it.

A: My guess here is that if you do not need any searching or querying ability here that you could gain a reduction in disk usage by zipping the file and then just storing the binary data directly in the database.


text:
Q: Uncaught TypeError: Cannot read properties of undefined reading pathname I am getting this error while running the below code
import React from 'react';
import { Link } from 'react-router-dom';

const DanimProduct = () => {
    return (
        <div className='mt-5'>
            <Link>Hello</Link>`enter code here`
        </div>
    );
};

export default DanimProduct;


text:
Q: MS Access SQL Switch Function I have several tables with the same data structure (they're filled with a bunch of stuff, in separate .accdb files to account for the 2GB limit) and need to retrieve info from one of them based on a field in a form.
Upon researching I came up with the following, but it won't seem to work.
SELECT MyNumber, MyName, MyPage, MyDrawing
FROM Switch([Forms]![View_Info]![Contract] = "Contract1", "tblContract1", [Forms]![View_Info]![Contract] = "Contract2", "tblContract2")
WHERE (MyNumber = [Forms]![View_Info]![MyNumber])

Syntax error in FROM clause.
In this example I only used 4 fields and 2 tables but in fact there are around 9 tables and 20 fields in each that I wish to retrieve.
Can someone shed some light on this? I have a really hard time with SQL, so I apologize if this is quite basic.
Thanks in advance, Rafael.

A: You cannot return the table name from a function in the SQL FROM clause. If your table is determined dynamically, then you must build the SQL command string dynamically.
Dim tableName As String, sql As String

tableName = Switch(...)
sql = "SELECT ... FROM [" & tableName & "] WHERE ..."

As @forpas explains in his answer, you can use a UNION query, but this will always query all the tables. Since the filter is not based on a table column, the filtering will occur on the client side, i.e. in your application.

A: Try this UNION:
SELECT MyNumber, MyName, MyPage, MyDrawing
FROM tblContract1
WHERE (MyNumber = [Forms]![View_Info]![MyNumber]) AND [Forms]![View_Info]![Contract] = "Contract1"
UNION
SELECT MyNumber, MyName, MyPage, MyDrawing
FROM tblContract2
WHERE (MyNumber = [Forms]![View_Info]![MyNumber]) AND [Forms]![View_Info]![Contract] = "Contract2"

Each query of the UNION contains in the WHERE clause the condition:
[Forms]![View_Info]![Contract] = "Contract?"


text:
Q: mod_perl custom configuration directives don't work when placed in .htaccess and there is  I'm trying to complete Redmine's feature request #2693: Use Redmine.pm to authenticate for any directory (1).
I have not much knowledge on all these things and need help.
Redmine uses mod_perl module Redmine.pm for authentication & authorization.
This module defines several custom configuration directives.
I've successfully modified patch from (1) and it works when all config is in <Location>:
<Location /digischrank/test>
        AuthType basic
        AuthName "Digischrank Test"
        Require valid-user
        PerlAccessHandler Apache::Authn::Redmine::access_handler
        PerlAuthenHandler Apache::Authn::Redmine::authen_handler
        RedmineDSN "DBI:mysql:database=SomedaTaBAse;host=localhost"
        RedmineDbUser "SoMeuSer"
        RedmineDbPass "SomePaSS"
        RedmineProject "digischrank"
</Location>

But when I move one of these directives (RedmineProject, see (1)) in .htaccess file, Redmine.pm doesn't see it! I've tried to change <Location> to <Directory> and add AllowOverride All. Directives from .htaccess is visible, but remaining ones from <Directory> - not. I don't want to move all directives to each .htaccess. When I add <Location> in addition to <Directory>, again - only directives from <Location> are visible.
As far as I know, directives should be merged. I miss something?

A: I've found that Redmine.pm doesn't provide DIR_MERGE function to merge configuration objects. See details in Creating and Merging Configuration Objects section of mod_perl manual. I've simplified given example because I need only override mode:
sub DIR_MERGE    { merge(@_) }

sub merge {
      my ($base, $add) = @_;
      my %mrg = ();
      for my $key (keys %$base, keys %$add) {
          next if exists $mrg{$key};
          # override mode
          $mrg{$key} = $base->{$key} if exists $base->{$key};
          $mrg{$key} = $add->{$key}  if exists $add->{$key};
      }
      return bless \%mrg, ref($base);
}


text:
Q: Estimate mean score including missingness in R I am trying to estimate a mean score based on four columns in a data frame. The condition is at least two values in a row should have non-missing values out of four values. Otherwise, if more than two NAs exist in that row, then the mean score should be NA. Let's say only three values are available in the dataset, and one NA. Then, the total score is divided by 3 because I need the sum score to be divided by the number of available values.
My data look like this:
a = c(1, 1, 1, 1, NA, 2, NA)
b = c(2, 4, NA, 4, 1, NA, 8)
c = c(2, NA, 6, 4, NA, 4, NA)
d = c(2, 4, NA, 4, NA, 3, NA)
df <- data.frame(a,b,c,d)

> df
   a  b  c  d
1  1  2  2  2
2  1  4 NA  4
3  1 NA  6 NA
4  1  4  4  4
5 NA  1 NA NA
6  2 NA  4  3
7 NA  8 NA NA

I want the scores as
>df$mean
1.75
3
3.5
3.25
NA
3
NA

Any thoughts?
Thanks in advance.

A: You can do with rowSums,rowMeans and ifelse
ifelse(rowSums(is.na(df))<=2,rowMeans(df,na.rm=T),NA)
[1] 1.75 3.00 3.50 3.25   NA 3.00   NA


text:
Q: Sequential calloc()'s return same address Consider the following data structure for managing memory buffers as table:
#include <cstdlib>
#include <cstring>
#include <unordered_map>

class BufferItem {
    char* data = nullptr;
    size_t data_size = 0;
public:
    BufferItem () = default;
    BufferItem (size_t size) : data_size(size) {
        data = (char*) std::calloc (size, 1);
        printf("calloc %p\n", data);
    }
    ~BufferItem () { std::free (data); }
    inline bool ok () { return data != nullptr; }
};

class Buffer {
public:
    using key_t = const char*;
private:
    std::unordered_map<key_t, BufferItem> data;
public:
    inline bool exists (key_t key) { return data.find (key) != data.end(); }
    inline bool create (key_t key, size_t size) {
        if (!exists (key)) data[key] = BufferItem (size);
        return data[key].ok();
    }
};

/* somewhere outside */
Buffer buf;
buf.create("ip_buf", 16);
buf.create("port_buf", 16);

For some reason, calloc() returns same address:
calloc 000000000338e800
calloc 000000000338e800

Why does this happen? I build with MinGW64 gcc 10.1.0.


text:
Q: Ceph/Rados AWS S3 API Bucket Policy via CURL I am currently struggling with a problem I am having with rest calls to an AWS s3 API hosted by a rados/ceph gateway.
For reasons I wont go into, I can't use an SDK that is provided to talk to it, which would solve all of my woes - I'm recreating some of the more simple jobs I need via CURL - which in the most part work, I can make buckets, delete them, add objects, create roles but my newest problem is bucket policies, both GET for them and PUT. I receive a 403 every time and I cannot figure out why.
What I have attempted to do is use another box with an SDK that talks to the API (boto3) and the AWS s3API calls to do the same thing and they work perfectly fine with the users Access and Secret key, so I do not think its an account thing.
Using the logs from the SDK jobs, I have attempted to recreate everything that is being sent, headers, payload etc...
Now I can only think that as a 403 maybe its the Auth4 strategy but .... this strategy works for every other job I need to do.
Code:
#!/bin/bash
set -x
ACCESS_KEY="accesskey"
SECRET_KEY="secret"
SERVICE="s3"
REGION="default"
ENDPOINT="s3-test.example.com"
BUCKET="bucketname"
PATH="?policy"
TIMEDATE="$(date -u '+%Y%m%d')"
TIMEDATEISO="${TIMEDATE}T$(date -u '+%H%M%S')Z"

# Create sha256 hash in hex
function hash_sha256 {
  printf "${1}" | openssl dgst -sha256 | sed 's/^.* //'
}

# Create sha256 hmac in hex
function hmac_sha256 {
  printf "{2}" | openssl dgst -sha256 -mac HMAC -macopt "${1}" | sed 's/^.* //'
}

PAYLOAD="$(printf "" | openssl dgst -sha256 |  sed 's/^.* //')"
CANONICAL_URI="/${BUCKET}${PATH}"
CANONICAL_HEADERS="host:${ENDPOINT}
x-amz-content-sha256:${PAYLOAD}
x-amz-date:${TIMEDATEISO}"

SIGNED_HEADERS="host;x-amz-content-sha256;x-amz-date"
CANONICAL_REQUEST="GET
${CANONICAL_URI}\n
${CANONICAL_HEADERS}\n
${SIGNED_HEADERS}\n
${PAYLOAD}"

# Create signature
function create_signature {
  stringToSign="AWS4-HMAC-SHA256\n${TIMEDATEISO}\n${TIMEDATE}/${REGION}/${SERVICE}/aws_request\n$(hash_sha256 "${CANONICAL_REQUEST}")"
  dateKey=$(hmac_sha256 key:"AWS4${SECRET_KEY}" "${TIMEDATE}")
  regionKey=$(hmac_sha256 hexkey:"${dateKey}" "${REGION}")
  serviceKey=$(hmac_sha256 hexkey:"${regionKey}" "${SERVICE}")
  signingKey=$(hmac_sha256 hexkey:"${serviceKey}" "aws4_request")

  printf "${stringToSign}" | openssl dgst -sha256 -mac HMAC -macopt hexkey:"${signingKey}" |  sed 's/(stdin)= //'
}

SIGNATURE="${create_signature}"
AUTH_HEADER="\
AWS4-HMAC-SHA256 Credential=${ACCESS_KEY}/${TIMEDATE}/\
${REGION}/${SERVICE}/aws4_request, \
SignedHeaders=${SIGNED_HEADERS}, Signature=${SIGNATURE}"

curl -vvv "https://${ENDPOINT}${CANONICAL_URI}" \
    -H "Accept:" \
    -H "Authorization: ${AUTH_HEADER}" \
    -H "x-amz-content-sha256: ${PAYLOAD}" \
    -H "x-amz-date: ${TIMEDATEISO}" \

Any help or pointers would be massively appreciated - had to transpose this by hand, so if there is an obvious typo... I will fix and rerun.
As I say, would love to use an SDK but from the appliance I will be using to do these requests, its just not possible

A: Managed to solve my own issue.
Noticed in the ceph logs (not sure how I missed it first time round) that the signature from my client didnt match how the ceph radosgw was signing the same signature.
Took it back to task on the canonicalRequest and for some reason if i take out all the line breaks (\n), it calculates.... But all of my other jobs like updating roles, adding buckets etc... fail as they need the line breaks. Not sure why, some Ceph weirdry?
I did packet captures and stripped the SSL to see what both requests from a working SDK and my curl were sending and it was identical...
Oh well, working :)


text:
Q: node.js and generating modules at/during runtime I'm currently working on a node.js project that requires generating and altering objects in memory at and during runtime.  I know this sounds confusing, so here's an example.
Monday 10am:
var PI = Math.PI;

exports.area = function (r) {
   return PI * r * r;
};

Monday 11am:
var PI = Math.PI;
var minSize = 10;

exports.area = function (r) {
   if (r >= minSize) {
      return PI * r * r;
   } else {
      return "Error: Minimum size not met.";
   }
};

Monday 12noon:
var PI = Math.PI;
var minSize = 10;
var msg = "Error: Minimum size of " + minSize + "not met.";

exports.area = function (r) {
   if (r >= minSize) {
      return PI * r * r;
   } else {
      return msg;
   }
};

Tuesday 10am:
var PI = Math.PI;
var minSize = 15;
var error['eng'] = "Error: Minimum size of " + minSize + "not met.";
var error['chn'] = "錯誤:不符合最小尺寸:" + minSize + "。"

exports.area = function (r) {
   if (r >= minSize) {
      return PI * r * r;
   } else {
      return error;
   }
};

exports.circumference = function (r) {
   if (r >= minSize) {
      return 2 * PI * r;
   } else {
      return error;
   }
};

This is a bit of a contrived example, because most of the changes could avoided with proper planning, I know, but it sort of goes to illustrate the point.  This module kept changing in both variables and functions, expanding while the server is running.
Here are the restrictions I have:

*

*Use Prototypal Inheritance (no keyword "new")

*Changes take effect at the next call of the function

*Changes include addition of new variables and functions

*Changes need to be saved for server restarts

*Cannot use eval()

I've thought of two possible strategies:

*

*Using .prototype, continue to add/change functions and variables.

*

*Pros: Able to do it as the server is running

*Cons: I'm not sure how to save it to file.  As far as I know, I cannot save functions to file without using eval() in some way

*Editing the files directly and reloading them through something like node-supervisor.

*

*Pros: Changes would be saved over, versions could be saved and reverted back to

*Cons: I think editing the files directly would more or less have the same consequence using eval(), ie, if someone sneaks something malicious the system could break.

That's all I can think of right now.  Would appreciate any opinions or options in this area.

A: For future reference:

*

*node.js' vm module has several runInContext() functions that will effectively sandbox the execution and prevent access to variables outside its scope. There is a blog entry here that discusses the difference between the different versions, with benchmarks available

*There is also a sandbox module available for node.js

*The disadvantage of running things in a sandbox is that the execution is a lot slower

Conclusion: It's not impossible to store functions and execute them safely within the confines of a sandbox, it's just not very practical.
Alternate Solution: If the functions themselves are not too complex, it's not impossible to store the calls in the form of a DSL and parse them back out after.