text:
Q: Dictionary Style Fancyhdr Headers with Multiple Entry Commands Defined So I am trying to create a dictionary, I have mostly everything worked out except for that signature dictionary style header where the first and last word of the page are displayed in the header.
I am using a sort environment (see here) to alphabetically sort 3 different defined commands: \wn, \wv, and \wa (for nouns, verbs, and adjectives, respectively) which are how my entries are stored.
I cannot figure out how to have the first and final entries of each page be properly 'marked' for fancyhdr to utilize in the header. I've tried using \markboth{1}{1} in all 3 of the defined commands, however that doesn't work.
MWE:
\documentclass[11pt,twoside]{article}
\usepackage[paperheight=9in,paperwidth=6in,bottom=1in]{geometry}
\usepackage{multicol}
\usepackage{fancyhdr}
\usepackage{datatool}
\usepackage{fix2col}

%Command Setups

\newcommand{\wn}[5]{%
    \markboth{#1}{#1}
    \DTLnewrow{list}%
    \DTLnewdbentry{list}{label}{#1}%
    \DTLnewdbentry{list}{description}{\textit{\textsc{{\footnotesize n.}}} \textbf{#2} }
    \DTLnewdbentry{list}{ipa}{(#3) }%
    \DTLnewdbentry{list}{plural}{\textit{pl.\hspace{2pt}#4 }}%
    \DTLnewdbentry{list}{extra}{#5}%
}
\newcommand{\wv}[4]{%
    \markboth{#1}{#1}
    \DTLnewrow{list}%
    \DTLnewdbentry{list}{label}{#1}%
    \DTLnewdbentry{list}{description}{\textit{\textsc{{\footnotesize v.}}} \textbf{#2} }
    \DTLnewdbentry{list}{ipa}{(#3) }%
    \DTLnewdbentry{list}{plural}{}%
    \DTLnewdbentry{list}{extra}{#4}%
}
\newcommand{\wa}[4]{%
    \markboth{#1}{#1}
    \DTLnewrow{list}%
    \DTLnewdbentry{list}{label}{#1}%
    \DTLnewdbentry{list}{description}{\textit{\textsc{{\footnotesize adj.}}} \textbf{#2} }
    \DTLnewdbentry{list}{ipa}{(#3) }%
    \DTLnewdbentry{list}{plural}{}%
    \DTLnewdbentry{list}{extra}{#4}%
}

%Enviroment Setup

\newenvironment{sortedlist}%
{%
    \DTLifdbexists{list}{\DTLcleardb{list}}{\DTLnewdb{list}}%
}%
{%
    \DTLsort{label}{list}%
    \begin{description}%
        \DTLforeach*{list}{\theLabel=label,\theDesc=description,\theIp=ipa,\thePl=plural,\theEx=extra}{%
            \item[\theLabel] \theDesc \theIp \thePl \theEx
        }%
    \end{description}%
}

\begin{document}
    \pagestyle{fancy}
    \fancyhf{}
    \fancyhead[LE,LO]{\textsc{\rightmark}}
    \fancyhead[CO,CE]{\thepage}
    \fancyhead[RE,RO]{\textsc{\leftmark}}
    \begin{flushleft}
        \begin{multicols}{2}\hangindent=3pt\setlength{\columnseprule}{.5pt}
            \raggedright
            \begin{sortedlist}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
            \end{sortedlist}
        \end{multicols}
    \end{flushleft}
\end{document}

A: Here is an answer. Don't use \markboth{#1}{#1} within creating database command but in loading the sorted base
 \DTLsort{label}{list}%
    \begin{description}%
        \DTLforeach*{list}{\theLabel=label,\theDesc=description,\theIp=ipa,\thePl=plural,\theEx=extra}{%
    \markboth{\theLabel}{\theLabel}%
    \item[\theLabel] \theDesc \theIp \thePl \theEx
        }%
    \end{description}%

MWE
\documentclass[11pt,twoside]{article}
\usepackage[paperheight=9in,paperwidth=6in,bottom=1in]{geometry}
\usepackage{multicol}
\usepackage{fancyhdr}
\usepackage{datatool}
\usepackage{fix2col}

%Command Setups

\newcommand{\wn}[5]{%
    \DTLnewrow{list}%
    \DTLnewdbentry{list}{label}{#1}%
    \DTLnewdbentry{list}{description}{\textit{\textsc{{\footnotesize n.}}} \textbf{#2} }
    \DTLnewdbentry{list}{ipa}{(#3) }%
    \DTLnewdbentry{list}{plural}{\textit{pl.\hspace{2pt}#4 }}%
    \DTLnewdbentry{list}{extra}{#5}%
}
\newcommand{\wv}[4]{%
    \DTLnewrow{list}%
    \DTLnewdbentry{list}{label}{#1}%
    \DTLnewdbentry{list}{description}{\textit{\textsc{{\footnotesize v.}}} \textbf{#2} }
    \DTLnewdbentry{list}{ipa}{(#3) }%
    \DTLnewdbentry{list}{plural}{}%
    \DTLnewdbentry{list}{extra}{#4}%
}
\newcommand{\wa}[4]{%
    \DTLnewrow{list}%
    \DTLnewdbentry{list}{label}{#1}%
    \DTLnewdbentry{list}{description}{\textit{\textsc{{\footnotesize adj.}}} \textbf{#2} }
    \DTLnewdbentry{list}{ipa}{(#3) }%
    \DTLnewdbentry{list}{plural}{}%
    \DTLnewdbentry{list}{extra}{#4}%
}

%Enviroment Setup

\newenvironment{sortedlist}%
{%
    \DTLifdbexists{list}{\DTLcleardb{list}}{\DTLnewdb{list}}%
}%
{%
    \DTLsort{label}{list}%
    \begin{description}%
        \DTLforeach*{list}{\theLabel=label,\theDesc=description,\theIp=ipa,\thePl=plural,\theEx=extra}{%
    \markboth{\theLabel}{\theLabel}\item[\theLabel] \theDesc \theIp \thePl \theEx
        }%
    \end{description}%
}

\begin{document}
    \pagestyle{fancy}
    \fancyhf{}
    \fancyhead[LE,LO]{\textsc{\rightmark}}
    \fancyhead[CO,CE]{\thepage}
    \fancyhead[RE,RO]{\textsc{\leftmark}}
    \begin{flushleft}
        \begin{multicols}{2}\hangindent=3pt\setlength{\columnseprule}{.5pt}
            \raggedright
            \begin{sortedlist}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
                \wv{B}{b}{b}{the second letter of the alphabet}
                \wa{C}{c}{c}{the third letter of the alphabet}
                \wn{A}{a}{a}{as}{the first letter of the alphabet}
            \end{sortedlist}
        \end{multicols}
    \end{flushleft}
\end{document}


text:
Q: sequelize findandcountall function return same data when using pagination I am using sequelize: 6.9.0, sequelize-cli: ^6.3.0, express: 4.17.1, pg: 8.7.1
i have a problem when using sequelize findAndCountAll, when i using include other models it will return same data when i'm using paging.
Here is my code for House Table
index: async (req, res) => {
    const { page, size, developer, city, priceone, pricetwo, project, isNew } =
      req.query;
    const { limit, offset } = getPagination(page, size);
    try {
      let filter = {};
      if (developer) {
        filter.developerId = developer;
      }
      if (city) {
        filter.cityId = city;
      }
      if (project) {
        filter.projectId = project;
      }
      if (isNew) {
        filter.isNew = isNew;
      }
      if (priceone && pricetwo) {
        const firstPrice = parseInt(priceone);
        const secondPrice = parseInt(pricetwo);
        if (firstPrice === 100000000 && secondPrice === 100000000) {
          filter.price = { [Op.lte]: firstPrice };
        } else if (firstPrice === 2000000000 && secondPrice === 2000000000) {
          filter.price = { [Op.gte]: firstPrice };
        } else {
          filter.price = { [Op.between]: [firstPrice, secondPrice] };
        }
      }
      const HousesData = await Houses.findAndCountAll({
        limit,
        offset,
        where: filter,
        attributes: [
          "id",
          "name",
          "description",
          "location",
          "price",
          "tanah",
          "bangunan",
          "lantai",
          "kamar_tidur",
          "kamar_mandi",
          "isNew",
        ],
        include: [
          { model: Developers, attributes: ["id", "name"] },
          { model: Cities, attributes: ["id", "name"] },
          { model: Projects, attributes: ["id", "name"] },
        ],
      });
      if (HousesData) {
        const response = getPagingData(HousesData, page, limit);
        res.status(200).json({
          status: "success",
          message: "Data Available",
          data: response,
        });
      } else {
        res.status(200).json({
          status: "success",
          message: "There is No Data",
          data: "No Data",
        });
      }
    } catch (error) {
      console.log(error);
      return next(
        new HttpError(
          "Something went wrong, could not get project.",
          500,
          error
        )
      );
    }
  }

my paging function
const getPagination = (page, size) => {
  const newPage = page ? page - 1 : 0;
  const limit = size ? +size : 10;
  const offset = newPage != 0 ? newPage * limit : 0;
  return { limit, offset };
};

const getPagingData = (data, page, limit) => {
  const { count: totalItems, rows: dataRows } = data;
  const currentPage = page ? +page : 1;
  const totalPages = Math.ceil(totalItems / limit);

  return { totalItems, totalPages, currentPage, dataRows };
};

module.exports = { getPagination, getPagingData };

Let's say i have 10 data
a,b,c,d,e,f,g,h,i,j
if i see first page

http://localhost:3006/api/v1/house?size=5&page=1

it will return a,b,c,d,e (this is right)
and if i see next page

http://localhost:3006/api/v1/house?size=5&page=2

it will return e,d,c,b,a (only reverse not showing f,g,h,i,j)
and if i see all the data it will return correct data

http://localhost:3006/api/v1/house?size=10&page=1

it will return j,i,h,g,f,e,d,c,b,a
but if i disabled
include: [
  { model: Developers, attributes: ["id", "name"] },
  { model: Cities, attributes: ["id", "name"] },
  { model: Projects, attributes: ["id", "name"] },
],

it return the right data when use paging.
my model for House is here
"use strict";
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable("Houses", {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.STRING(22),
      },
      name: {
        type: Sequelize.STRING,
      },
      projectId: {
        type: Sequelize.STRING(22),
        onDelete: "CASCADE",
        references: {
          model: "Projects",
          key: "id",
        },
      },
      cityId: {
        type: Sequelize.STRING(22),
        onDelete: "CASCADE",
        references: {
          model: "Cities",
          key: "id",
        },
      },
      developerId: {
        type: Sequelize.STRING(22),
        onDelete: "CASCADE",
        references: {
          model: "Developers",
          key: "id",
        },
      },
      description: {
        type: Sequelize.TEXT,
      },
      location: {
        type: Sequelize.STRING,
      },
      price: {
        type: Sequelize.BIGINT,
      },
      tanah: {
        type: Sequelize.INTEGER,
      },
      bangunan: {
        type: Sequelize.INTEGER,
      },
      lantai: {
        type: Sequelize.INTEGER,
      },
      kamar_tidur: {
        type: Sequelize.INTEGER,
      },
      kamar_mandi: {
        type: Sequelize.INTEGER,
      },
      house_thumbnail: {
        type: Sequelize.STRING,
      },
      isNew: {
        type: Sequelize.BOOLEAN,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("Houses");
  },
};

i also use same paging method on other table. but other table works fine, only this table that got  messed up.
the other table  named Project function is here for reference
index: async (req, res) => {
    const { page, size, developer, city, priceone, pricetwo } = req.query;
    const { limit, offset } = getPagination(page, size);
    try {
      let filter = { haveDeveloper: true };
      if (developer) {
        filter.developerId = developer;
      }
      if (city) {
        filter.cityId = city;
      }
      if (priceone && pricetwo) {
        const firstPrice = parseInt(priceone);
        const secondPrice = parseInt(pricetwo);
        if (firstPrice === 100000000 && secondPrice === 100000000) {
          filter.minPrice = { [Op.lte]: firstPrice };
        } else if (firstPrice === 2000000000 && secondPrice === 2000000000) {
          filter.minPrice = { [Op.gte]: firstPrice };
        } else {
          filter.minPrice = { [Op.between]: [firstPrice, secondPrice] };
        }
      }
      const projectsData = await Projects.findAndCountAll({
        limit,
        offset,
        where: filter,
        attributes: ["id", "name", "image", "location",'minPrice'],
        include: [
          { model: Cities, attributes: ["id", "name"] },
          { model: Developers, attributes: ["id", "name"] },
          { model: ProjectFacilities, attributes: ["facility"] },
        ],
      });
      if (projectsData) {
        const response = getPagingData(projectsData, page, limit);
        res.status(200).json({
          status: "success",
          message: "Data Available",
          data: response,
        });
      } else {
        res.status(200).json({
          status: "success",
          message: "There is No Data",
          data: "No Data",
        });
      }
    } catch (error) {
      console.log(error);
      return next(
        new HttpError(
          "Something went wrong, could not get project.",
          500,
          error
        )
      );
    }
  },

the Project model
'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Projects extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Projects.belongsTo(models.Developers, { foreignKey: 'developerId' })
      Projects.belongsTo(models.Cities, { foreignKey: 'cityId' })
      Projects.hasMany(models.ProjectFacilities, { foreignKey: 'projectId' })
      Projects.hasMany(models.Houses, { foreignKey: 'projectId' })
    }
  };
  Projects.init({
    name: DataTypes.STRING,
    image: DataTypes.STRING,
    description: DataTypes.TEXT,
    location: DataTypes.STRING,
    minPrice:DataTypes.BIGINT,
    haveDeveloper: DataTypes.BOOLEAN,
    cityId: DataTypes.STRING,
    developerId: DataTypes.INTEGER
  }, {
    sequelize,
    modelName: 'Projects',
  });
  return Projects;
};

sql generated by sequelize for House page 1 with 5 data
SELECT "Houses"."id", "Houses"."name", "Houses"."description", "Houses"."location", "Houses"."price", "Houses"."tanah", "Houses"."bangunan", "Houses"."lantai", "Houses"."kamar_tidur", "Houses"."kamar_mandi", "Houses"."isNew", "Developer"."id" AS "Developer.id", "Developer"."name" AS "Developer.name", "City"."id" AS "City.id", "City"."name" AS "City.name", "Project"."id" AS "Project.id", "Project"."name" AS "Project.name" FROM "Houses" AS "Houses" LEFT OUTER JOIN "Developers" AS "Developer" ON "Houses"."developerId" = "Developer"."id" LEFT OUTER JOIN "Cities" AS "City" ON "Houses"."cityId" = "City"."id" LEFT OUTER JOIN "Projects" AS "Project" ON "Houses"."projectId" = "Project"."id" LIMIT 5 OFFSET 0;

sql generated by sequelize for Project page 1 with 5 data
SELECT "Projects".*, "City"."id" AS "City.id", "City"."name" AS "City.name", "Developer"."id" AS "Developer.id", "Developer"."name" AS "Developer.name", "ProjectFacilities"."id" AS "ProjectFacilities.id", "ProjectFacilities"."facility" AS "ProjectFacilities.facility" FROM (SELECT "Projects"."id", "Projects"."name", "Projects"."image", "Projects"."location", "Projects"."minPrice", "Projects"."cityId", "Projects"."developerId" FROM "Projects" AS "Projects" WHERE "Projects"."haveDeveloper" = true LIMIT 5 OFFSET 0) AS "Projects" LEFT OUTER JOIN "Cities" AS "City" ON "Projects"."cityId" = "City"."id" LEFT OUTER JOIN "Developers" AS "Developer" ON "Projects"."developerId" = "Developer"."id" LEFT OUTER JOIN "ProjectFacilities" AS "ProjectFacilities" ON "Projects"."id" = "ProjectFacilities"."projectId";

is there any solution for this? thank you very much for your all help and attention!

A: Please try thi
const getPagination = (page = 1, size = 10) => {
    const offset = (page - 1) * size ;
    const limit = size ;
    return { limit, offset };
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I tell exactly which version of Microsoft Build Tools I need to install? I'm trying to build a wheel for my Python project and it works just fine on my development machine, but when I try and do the same thing on a CI runner, it fails on building the Cython extension:
running build_ext
building 'farm.rasters.water_fill' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

I do have build tools installed, but either I don't have the exact version/components required or I'm missing an environment variable telling Python where to find it. How do I find out what I need to install?
This post was very helpful in telling me which version of Build Tools I need:
> python -c "import sys;print(sys.version)"
3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]

v.1914 is Build Tools version 15.7 and I think I've installed that, but I'm still getting the error. Here are the currently installed components (there are a few versions of the SDK included because there are other Python executables on the machine and I wanted to try them all).

What am I missing? I've tried building the wheel in Powershell, cmd, and Visual Studio 2017 command prompt and get the same error every time. I've also tried running vcvarsall.bat in the shell and setting environment variables and PATHs manually before running the build, but that doesn't help either.

A: After much more uninstalling, reinstalling, and searching, I finally found the answer:
set DISTUTILS_USE_SDK=1

I can't believe a) it was that simple and b) that environment variable wasn't set already. Thanks to https://learn.microsoft.com/en-us/answers/questions/419525/microsoft-visual-c-140-or-greater-is-required.html for providing the solution.


text:
Q: Unable to initialize a 2d Vector in my C++ class I have read every posting on this subject that I can find, but can't figure out what I am doing wrong.  I am unable to successfully initialize my 2d vector which is a member variable of my class.  The header files is:
class Beam2
    {
    private:
        /*The following unit vectors should never be accessed directly
        and are therefore private.*/
        std::vector<std::vector<double> > unitVectors;

    public:
    //constructor
    Beam2(
        Node * node1PtrInput, Node * node2PtrInput,
        double orientAngleInput);

My cpp file
Beam2::Beam2(
Node * node1PtrInput, Node * node2PtrInput, double orientAngleInput){
node1Ptr = node1PtrInput;
node2Ptr = node2PtrInput;
orientAngle = orientAngleInput;
unitVectors(3, std::vector<double>(3));
updateUnitVectors();

the error is: error: no match for call to '(std::vector >) (int, std::vector)'
  unitVectors(3, std::vector(3));
                                       ^
any help would be appreciated.

A: Here is the proper way to initialize classes:
Beam2::Beam2(Node * node1PtrInput, Node * node2PtrInput, double orientAngleInput) :
node1Ptr(node1PtrInput),
node2Ptr(node2PtrInput),
orientAngle(orientAngleInput),
unitVectors(3, std::vector<double>(3))
{
    updateUnitVectors(); // I believe this is function in the class
}

You can also fix your code by just replacing unitVectors(3, std::vector<double>(3)); with unitVectors.resize(3, std::vector<double>(3)); too, but prefer the former.


text:
Q: Makefile: Expansion of "$<" does not work in "optimized" makefile I have a directory structure like this:
./
|
|- values-1/
|  |- thing0.yaml
|
|- values-2/
|  |- thing1.yaml
|
|- dachart-1/
|  |- thing0.yaml   (this should be generated by make
|                    from values-1/thing0.yaml)
|- dachart-2/
|  |- thing1.yaml   (this should be generated by make
                     from values-2/thing1.yaml)

the "build rules" are basically identical, but about 30 lines long.
this very simple Makefile illustrates what works:
# WORKING makefile, but with two redundant build rules

.SOURCES:

SHELL=bash

src1_files := $(wildcard values-1/*.yaml)
src2_files := $(wildcard values-2/*.yaml)
dst1_files := $(patsubst values-%,dachart-%,$(src1_files))
dst2_files := $(patsubst values-%,dachart-%,$(src2_files))

all: $(dst2_files) $(dst1_files)

dachart-1/%.yaml: values-1/%.yaml
    # SIMPLIFIED EXAMPLES
    @echo "source $<"
    @echo "target $@"

dachart-2/%.yaml: values-2/%.yaml
    @echo "source $<"
    @echo "target $@"

But since the build rules are really long and exactly the same, I would like to have one build rule definition for all the files.
After some fooling around I came up with a Makefile that seems to do what I want (and does not error out), alas the $< expansion does no longer work (see output below).
# NON-working makefile, but kinda what I want (only one build rule)

dachart-1/%.yaml: $(src1_files)
dachart-2/%.yaml: $(src2_files)

%.yaml:
    @echo "source $<"
    @echo "target $@"

The outputs are:
# working makefile
source values-1/thing0.yaml
target dachart-1/thing0.yaml

# alternate makefile
source
target dachart-1/thing0.yaml

QUESTION: Is there a way to have only one build rule in the sense of my non-working Makefile?

A: okay, surprisingly this works:
.SOURCES:

SHELL=bash

src1_files := $(wildcard values-0.1/*.yaml)
src2_files := $(wildcard values-2.0/*.yaml)
dst1_files := $(patsubst values-%,dachart-%,$(src1_files))
dst2_files := $(patsubst values-%,dachart-%,$(src2_files))

all: $(dst2_files) $(dst1_files)

fresh: clean all
.PHONY: fresh

dachart-0.1/%.yaml: THING=one
dachart-0.1/%.yaml: $(src1_files)

dachart-2.0/%.yaml: THING=two
dachart-2.0/%.yaml: $(src2_files)

dachart-*/%.yaml: values-*/%.yaml
    @echo THING=${THING}
    @echo "source $<"
    @echo "target $@"


text:
Q: multiple connection using hibernate I want to connect to two servers on hibernate. But i am using java class as configuration. How give Session factory know it will use connection one or connection two.
this is my class:
    @Configuration
@ComponentScan(basePackages = {"id.bni.hcms"})
@EnableTransactionManagement
public class RepositoryConfig {

        @Bean(name = "dataSource")
    public DataSource initDataSource(){
        System.out.println("datasource inited initDataSource" );
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException ex) {

        }
        String url = "jdbc:oracle:thin:@//xxx.xxx.xx.xxx:xxx/xxxx";
        String username = "xxx";
        String password = "xxxx";

        ConnectionFactory cf = new DriverManagerConnectionFactory(url, username, password);
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
        GenericObjectPool<PoolableConnection> cp = new GenericObjectPool<>(pcf);

        pcf.setPool(cp);

        return new PoolingDataSource<>(cp);
    }

    @Bean(name = "sessionFactory")
    public LocalSessionFactoryBean sessionFactoryBean(DataSource dataSource){
        LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
        sfb.setDataSource(dataSource);
        sfb.setPackagesToScan("id.bni.hcms");

        Properties props = sfb.getHibernateProperties();

        props.put("hibernate.format_sql", true);
        props.put("hibernate.show_sql", true);
        props.put("hibernate.dialect", "org.hibernate.dialect.Oracle9iDialect");

        return sfb;
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager getHibernateTransactionManager(SessionFactory sessionFactory){
        HibernateTransactionManager trxMgr = new HibernateTransactionManager(sessionFactory);

        return trxMgr;
    }
}

i want to add another connection :
String url = "jdbc:oracle:thin:@//yyyy:yyyy/yyyy";
    String username = "yyyy";
    String password = "yyyy";

how to give information to SessionFactory using one connection or another connection?
this is example using session factory:
@Repository
public class KaryawanDaoImpl implements KaryawanDao{
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Karyawan find(String username, String password) {
            String hql = " SELECT * from table";
            Query query = sessionFactory.getCurrentSession().createSQLQuery(hql).addEntity(Karyawan.class);
            query.setString("user", username);
            query.setString("pwd", password);
            Karyawan result = (Karyawan)query.uniqueResult();

            return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void save(Karyawan e) {
        sessionFactory.getCurrentSession()
            .saveOrUpdate(e);
    }
}

A: Using annotation mappings as an example:
Configuration cfg1 = new AnnotationConfiguration();
cfg1.configure("/hibernate-oracle.cfg.xml");
cfg1.addAnnotatedClass(SomeClass.class); // mapped classes
cfg1.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf1 = cfg1.buildSessionFactory();

Configuration cfg2 = new AnnotationConfiguration();
cfg2.configure("/hibernate-mysql.cfg.xml");
cfg2.addAnnotatedClass(SomeClass.class); // could be the same or different than above
cfg2.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf2 = cfg2.buildSessionFactory();

Then use sf1 and sf2 to get the sessions for each database. For mapping files,
you just use cfg.addClass instead of addAnnotatedClass. Put the cfg.xml files in the root package in this case.
 Those will have the Oracle or MySQL dialect and connection information.


text:
Q: Visual Studio : ASP.Net MVC4 project publishing missing dlls Following dlls are missing while publishing a ASP.Net MVC 4 project.
System.Net.Http.Formatting.dll
System.Web.Http.dll
System.Web.Http.WebHost.dll

Any idea ?
Note :
Am publishing my files to a local path. There am not able to find these dlls in bin folder. And when hosted in an IIS, getting the error as dll is missing.

A: I had same problem. I used NuGet package for these missing library.
Type the following command into Tools > Library Package Manager > Package Manager Console:
Install-Package Microsoft.AspNet.WebApi.Client


text:
Q: Elastic Search : Applying Filter on nested segments and returning only those segments I have a customer info with orders in Elastic Search in the following format
{
  "_index": "customer_domain_r4",
  "_type": "CustomerData",
  "_id": "6fff6ce8-e792-4047-b636-a1dda0aa2b72",
  "_version": 173,
  "_score": 3.551258,
  "_source": {
    "first": "John",
    "last": "Doe",
    "dateOfBirth": null,
    "primaryPhone": "6154525131",
    "customerOrders": [
      {
        "orders": [
          {
            "orderNumber": 1,
            "orderName": "Grocery",
            "recordVersion": 1,
            "createdDateTimeGmt": "May 09, 2018 03:19:11 PM",
            "deletedDateTimeGmt": "May 12, 2018 08:28:42 PM",
            "createdSessionTokenId": "PUWzJmipCIyvciMDEr3IfhXuV3Gx",
            "updatedSessionTokenId": "1234567890",
            "lastUpdatedDateTimeGmt": "May 12, 2018 08:28:48 PM",
            "orderType": "Online"
            "id": "8e2973e3-b43b-4430-b6d7-7c24846e9bba"
          },
          {
            "orderNumber": 2,
            "orderName": "Medications",
            "recordVersion": 1,
            "createdDateTimeGmt": "May 09, 2018 03:19:11 PM",
            "deletedDateTimeGmt": null,
            "createdSessionTokenId": "PUWzJmipCIyvciMDEr3IfhXuV3Gx",
            "updatedSessionTokenId": "1234567890",
            "lastUpdatedDateTimeGmt": "May 12, 2018 08:28:48 PM",
            "orderType": "Offline"
            "id": "8e2973e3-b43b-4430-b6d7-7c2665e9bba"
          }
]
}

Now my requirement is to fetch only orders of a certain type for a given customer id. The query i ran
{"index":"customer_domain_r4","type":"CustomerData"}
{"query":{"bool":{"must":[{"match":{"id":"6fff6ce8-e792-4047-b636-a1dda0aa2b72"}},{"nested":{"path":"customerOrders","query":{"bool":{"must":[{"match":{"customerOrders. orderType":"Online"}}]}}}}]}},"_source":{"includes":["customerOrders"],"excludes":[]}}

The above query returns all the orders of the customer because the criteria looks for any customer which has an order of type online. I am looking for the query to return only orders of customer 6fff6ce8-e792-4047-b636-a1dda0aa2b72 of type online.
Is there a way i can directly add criteria for the includes section.
If not i have to filter this in the java middle tier section


text:
Q: HTML Select specific element with no class As the title says, I don't know how to only select the first h1 "I want to select this"
Specially using no classes, only the first h1 from the HTML text

A: Very simple querySelector will do

// first h1 in header

console.log(
  document.querySelector("header > h1").textContent
)

// first h1 in document:

console.log(
  document.querySelector("h1").textContent
)
header > h1 {
  color: green
}

I want to select this

Welcome to the world!

I don't like apples

A: Use this
h1:first-of-type{

}

Goodluck.

A: u can use this , select parent then select the first child of type h1

   header > h1:first-child{
       color:red;
   }


text:
Q: How to select top 30% of cells in a raster (by cell value) in R I have a raster in R, I need to select the highest cell values up until 30% of the raster area is selected.
The way that I've tried to accomplish this is by calculating the average cell area, and then calculating how many cells I need to meet this 30% target (I know this is not entirely accurate). Then I sort the raster values, descending. Here is where I'm stuck. Of these sorted values, I need to set all cells beyond #12,678 to NA. I can't figure out how to set values to NA based on their place in an order. Does anyone know how to do this? Or have a better idea for the entire process?

A: you can use tidyterra for this.
Once that you have identified your thresold (12,678) use tidyterra::filter() on your raster.
I don't know if you are using raster or terra, I use here terra and I show you how to convert back to Raster* object.
On this example I present a full workflow with an example raster file, just adapt it to your data.
library(terra)
#> terra 1.5.21
library(tidyterra)
#> -- Attaching packages --------------------------------------- tidyterra 0.1.0 --
#>
#> Suppress this startup message by setting Sys.setenv(tidyterra.quiet = TRUE)
#> v tibble 3.1.7     v dplyr  1.0.9
#> v tidyr  1.2.0

# Create a SpatRaster from a file
f <- system.file("ex/elev.tif", package = "terra")
r <- rast(f)

# If you are using raster package use this line for switch it to terra:
# r <- rast(your_data)

r
#> class       : SpatRaster
#> dimensions  : 90, 95, 1  (nrow, ncol, nlyr)
#> resolution  : 0.008333333, 0.008333333  (x, y)
#> extent      : 5.741667, 6.533333, 49.44167, 50.19167  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 (EPSG:4326)
#> source      : elev.tif
#> name        : elevation
#> min value   :       141
#> max value   :       547

totarea_km <- expanse(r, unit = "km")
prettyNum(totarea_km, big.mark = ",")
#> [1] "2,563.61"

plot(r)

# There is a bug on slice_max, use filter

# Get thresold for filtering by working on the values of the raster
# as it is a data frame
min_value <- as_tibble(r, na.rm = TRUE) %>%
  slice_max(order_by = elevation, prop = .3) %>%
  min()

# Here it goes!!
top30perc <- r %>% filter(elevation > min_value)

# Check
area_30perc <- expanse(top30perc, unit = "km")

prettyNum(area_30perc, big.mark = ",")
#> [1] "761.0991"

# Check
area_30perc / totarea_km
#> [1] 0.2968857

# Seems ok

plot(top30perc)

# If you need to convert to Raster* object

raster::stack(top30perc)
#> class      : RasterStack
#> dimensions : 90, 95, 8550, 1  (nrow, ncol, ncell, nlayers)
#> resolution : 0.008333333, 0.008333333  (x, y)
#> extent     : 5.741667, 6.533333, 49.44167, 50.19167  (xmin, xmax, ymin, ymax)
#> crs        : +proj=longlat +datum=WGS84 +no_defs
#> names      : elevation
#> min values :       387
#> max values :       547

Created on 2022-05-31 by the reprex package (v2.0.1)

A: If you assume a constant cell size, then you might as well ignore it and you can do something like this (find the quantile of interest and use that as a threshold):
library(terra)
r <- rast(system.file("ex/elev.tif", package = "terra"))

q <- global(r, \(i) quantile(i, 0.7, na.rm=T))
x <- ifel(r <= q[[1]], NA, r)
plot(x)

Check
g <- global(c(x,r), "notNA")
g[1,1]/g[2,1]
# 0.2979601

If variation in cell size is important, you could do something like the below (sort the values, and find the cells below the cumulative cell size threshold), but note that this approach is not memory-safe (would fail with very large rasters)
s <- c(r, cellSize(r, unit="km"))
d <- as.data.frame(s, cell=T, na.rm=T)
d <- d[order(d$elevation, decreasing=TRUE), ]
d$sumarea <- cumsum(d$area) / sum(d$area)
cells <- d[d$sumarea <= 0.3, "cell"]
msk <- rast(r)
msk[cells] <- 1
x <- mask(r, msk)
plot(x)


text:
Q: How do I integrate exponential functions including $e^{x^2}$? I am trying to prove the following equality:
$$\lambda\int^\infty_{-\infty}\frac{\mathrm df}{\sqrt{2\pi}}\exp\left(i2\pi f(x-a)\right)\exp\left(\frac{-i\pi\lambda tf^2}{n}\right)=\frac{1}{\sqrt{\frac{2\pi it}{n\lambda}}}\exp\left(\frac{i\pi n(x-a)^2}{\lambda t}\right)$$
but am struggling to work out which method to use. I assume somewhere in this I need to use
$$\int^\infty_{-\infty}e^{-f^2}\,\mathrm df=\sqrt{\pi}$$
but I haven't currently got much further than that, can anyone advise on this?

A: Hint:
$$\int_{-\infty}^\infty e^{ax^2+bx+c}\,dx=\int_{-\infty}^\infty e^{a(x-b/2a)^2+c-b^2/4a}\,dx=e^{c-b^2/4a}\int_{-\infty}^\infty e^{ax^2}\,dx.$$


text:
Q: iPhone simulator shows app's images but iPhone does not I have create an application on iphone using objective-c.In this application i am just displaying different players images stored in one folder, which will be run perfectly on simulator. But when I deploy it on iphone it is not showing the images of the player.
for that the code is:
UIImageView *imageplayer = [[UIImageView alloc]initWithFrame: CGRectMake(imgx, imgy+45,135,150)];
imageplayer.image = [UIImage imageNamed:playerpng];

if(imageplayer.image == nil)
    [imageplayer setImage:[UIImage imageNamed:playerjpg]];

if(imageplayer.image == nil)
    [imageplayer setImage:[UIImage imageNamed:@"noimage.png"]];

[self.view addSubView:imageplayer];

Plz solve this query.
Thanks in advance

A: Sometimes xCode doesent update correctly the bundle, try cleaning and building again.

A: I am currently experiencing this problem as well. I was able to correct it after a bit of debugging and reviewing the build file.
When I do an ls -l, I noticed that some of my png files have a @ symbol beside the permissions. When I followed that up with a ls -l@, it showed that the files with an '@' had an attribute set 'com.apple.quarantine'.  This attribute is given to a file (often from a zip, jar, or other executable) that is downloaded from the net.  You can get rid of this attribute by performing:
xattr -d com.apple.quarantine *.png

Then, select the images in XCode, and check that the checkbox under the target is checked. In my case, it was not, so the images weren't being included in the bundle.

A: I had the same problem, solved by using all lowercase for the file name in code - image.jpg, but it does not seem to make any difference what case the actual file name is, e.g. Image.jpg

A: check name of image file. It must be "noimage.png"
not Noimage.png or noimage.PNG

A: Just to clarify, does the "noimage.png" display, or is the program loading a player image but failing to display it?  Or is nothing loading.
These should easily be determined in debug mode.
A few additional things to check...
1) Just for testing, start out with PNG versions of the player files.  This is the primary format on the iPhone and might eliminate a file format issue or other anomaly that the simulator is not sensitive to.
2) With regard to fixing in an image editor, specifically make sure that the image is set to a DPI of 72 pixels/inch.  The iPhone and particularly Interface Builder are very sensitive to this being correct and will sometimes not display or will display a very blurred version of the image if incorrect.
3) Make sure the image(s) haven't been added multiple times (from different directories and/or to different group folders).  We encountered a situation where we had inadvertently imported the same images at two different layers within the project hierarchy and this can cause unexpected behavior within the iPhone (selecting randomly or failing to select).
4) Make sure the Get Info -> Targets has your particular target checked.  The simulator may still see the image but it will not get deployed to the iPhone.
5) Make sure you can view the image within XCode and that it looks correct.
Barney

A: This happens to me sometimes. I once spent half a night trying to figure out what was wrong. In this end, this is what worked: open the image with an image editor and save it again. That's all. I'm using the free Acorn image editor to do this. Haven't tried it with Photoshop. (After all, it seems that Photoshop might be responsible for introducing the error in the first place, although that's far from sure.)
I don't know what causes the problem. I usually get it when I use png files that have been sent to me. Could be a simple file permissions problem, or some more subtle problem with the image format. I would be very interested in hearing the opinion of better-informed people.
In any case, if all else fails just try this: open the image with Acorn, save over the original file. Works for me.

A: Make sure the image files are added to your XCode project.

A: After some investigation, Michael's comment seems to have a solved it for me.  I had all lower case as the file name but was following variable convention and had the png file with an upper case for the second part of the file name.  Here my file was putback.png but was referenced in my code as putBack.png
 UIImage *putBackImage = [UIImage imageNamed:@"putBack.png"]; //wrong
 UIImage *putBackImage = [UIImage imageNamed:@"putback.png"]; //correct

A: Select correct target while adding image files to your project. Following are steps to make it further clear

*

*Select Add Files to "YourProjectName"

*In opening window there is an "Add to targets" option at bottom that shows all available targets

*Check target or multiple targets in which you want to add images

*Press "Add" button and you are ready to go


text:
Q: Create HTML/JS interface for java application I'm looking for a way to create my java application interface from html/javascript and even jquery.
I already seen a lot of post in this subject talking mainly of jxbrowser which is a really good library but I have to buy a license if I want to implement it in a commerciale use.
But I didn't find a library as simple as jxbrowser to use. Basically I looked up for a tutorial and I saw it :
HTML :
<!DOCTYPE html>

   <meta charset="utf-8" />
   <title>Registration Form</title>
   <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
   <link href='http://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet' type='text/css'>

       <form action="#" method="POST">
           <fieldset>

New Account

                       <input class="form-control" type="text" id="firstname" name="firstname" placeholder="First Name">

                       <input class="form-control" type="text" id="lastname" name="surname" placeholder="Last Name">

                       <input class="form-control" type="text" id="phone" name="phone" placeholder="Phone">

                       <input class="form-control" type="email" id="email" name="email" placeholder="Email">

                       <button class="btn btn-default btn-lg" type="button" onclick="newAccount();">New Account</button>

           </fieldset>
       </form>

Java :
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFunction;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.atomic.AtomicReference;
public class HTMLUISample {
   public static void main(String[] args) {
       final JFrame frame = new JFrame("HTMLUISample");
       final JButton newAccountButton = new JButton("New Account...");
       newAccountButton.addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent e) {
               Account account = createAccount(frame);
               // Displays created account's details
               JOptionPane.showMessageDialog(frame, "Created Account: " + account);
           }
       });
       JPanel contentPane = new JPanel();
       contentPane.add(newAccountButton);
       frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
       frame.add(contentPane, BorderLayout.CENTER);
       frame.setSize(300, 75);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }
   private static Account createAccount(JFrame parent) {
       final AtomicReference<Account> result = new AtomicReference<Account>();
       final JDialog dialog = new JDialog(parent, "New Account", true);
       // Create Browser instance.
       final Browser browser = new Browser();
       // Register Java callback function that will be invoked from JavaScript
       // when user clicks New Account button.
       browser.registerFunction("onCreateAccount", new BrowserFunction() {
           @Override
           public JSValue invoke(JSValue... args) {
               // Read text field values received from JavaScript.
               String firstName = args[0].getString();
               String lastName = args[1].getString();
               String phone = args[2].getString();
               String email = args[3].getString();
               // Create a new Account instance.
               result.set(new Account(firstName, lastName, phone, email));
               // Close dialog.
               dialog.setVisible(false);
               // Return undefined (void) to JavaScript.
               return JSValue.createUndefined();
           }
       });
       // Load HTML with dialog's HTML+CSS+JavaScript UI.
       browser.loadURL("file://<path_to_file>/index.html");
       dialog.addWindowListener(new WindowAdapter() {
           @Override
           public void windowClosing(WindowEvent e) {
               // Dispose Browser instance because we don't need it anymore.
               browser.dispose();
               // Close New Account dialog.
               dialog.setVisible(false);
               dialog.dispose();
           }
       });
       dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
       // Embed Browser Swing component into the dialog.
       dialog.add(new BrowserView(browser), BorderLayout.CENTER);
       dialog.setSize(400, 500);
       dialog.setResizable(false);
       dialog.setLocationRelativeTo(parent);
       dialog.setVisible(true);
       return result.get();
   }
   public static class Account {
       public final String firstName;
       public final String lastName;
       public final String phone;
       public final String email;
       public Account(String firstName, String lastName, String phone, String email) {
           this.firstName = firstName;
           this.lastName = lastName;
           this.phone = phone;
           this.email = email;
       }
       @Override
       public String toString() {
           return "Account{" +
                   "firstName='" + firstName + '\'' +
                   ", lastName='" + lastName + '\'' +
                   ", phone='" + phone + '\'' +
                   ", email='" + email + '\'' +
                   '}';
       }
   }
}

This is pretty simple as we can just use an already built html file with javascript and call a java method from it. Here you just a form and display the informations entered by the user.
Do you know a library with the one I can keep this html file and adapt the java code to make it works for a java desktop application ?


text:
Q: Quantum entanglement in quantum field theory How is entanglement described in quantum field theory?  For example, if a fluctuation in the electron field represents an entangled electron, is there an equal and opposite fluctuation in the positron field representing its entangled partner?

A: There is "so much" entanglement in quantum field theory, that people don't usually make a big fuss about it. A pure bipartite state is $|\psi \rangle_{AB}$ is separable iff there exists $|\phi_1\rangle_A, |\phi_2\rangle_B$ such that$|\psi\rangle = |\phi\rangle_A \otimes |\phi\rangle_B$, or equivalently, if
$$ \langle \psi | A \otimes B |\psi \rangle = \langle \psi |A \otimes I |\psi \rangle \langle \psi | I \otimes B |\psi\rangle $$
for all operators $A, B$.
In quantum field theory, this is basically never the case. Indeed, we are often interested in quantities such as
$$ \langle 0 | \phi(x_1, t) \phi(x_2, t) |0 \rangle, $$
where $|0\rangle$ is the vacuum state. The calculation of the above expression, for example in the familiar case of a free scalar field, is done in every QFT book and it is non-zero (although exponentially decreasing with the distance), while $\langle 0 |\phi(x,t)|0 \rangle = 0$. Therefore, the vacuum state of a QFT is entangled.
In more sophisticated discussions, people often refer to the Reeh-Schlieder theorem (https://en.wikipedia.org/wiki/Reeh%E2%80%93Schlieder_theorem), which essentially states that any state of a QFT can be obtained by acting locally on the vacuum. This is reminiscent of the way in which any bipartite maximally entangled state can be obtained by starting by applying local unitaries on only one part of a Bell state.


text:
Q: Forcing virtual field recalc in attribute table in QGIS I have a layer with a virtual field, "LongLabel", an expression concatenating several of its data fields. When I edit a feature's data fields in the layer's attribute table/form, how can I force the virtual field to update for that feature? I care since "LongLabel" is the feature selector field on the left hand side of the form.
I'm unsurprised "LongLabel" doesn't update immediately, while I remain in that feature in the table. But I was hoping it would update after I switch to a different feature and come back, or when I save my edits and/or reload the table (icons at top), or - at worst - if I toggle editing on and off to force a data provider commit. No change.
The edits to the underlying data fields are correctly captured, it's just the virtual field that doesn't recalc. After the data edit, if I open a 2nd attribute table (F6 from canvas) it correctly displays the updated "LongLabel" in the 2nd table but the unupdated one in the original table.
If there's no way to do it from the QGIS UI, I'd be fine with a PyQGIS solution. An iface.activeLayer().dataProvider().forceReload() from the Python console doesn't help though. An .activeLayer().commitChanges() followed by .startEditing() toggles editing on and off, reflected in the attr table's editing icon, but still not updating the field. I can also find the attribute table widget by searching for
'QgsAttributeTableDialog/'+iface.activeLayer().id() in [x.objectName() for x in QApplication.instance().allWidgets()] but can't figure out how to force it to do anything other than .close() once I've located it.
Editing to add:
I've gone and replaced "LongLabel" with its expression definition in the layer's display name property. In this case, the LHS feature selector (that used to be "LongLabel") correctly updates when I move away from the edited feature. However, "LongLabel" as a field in the attribute form still does not update. So it's related specifically to virtual fields. Using QGis 3.10.0.

A: I have yet to get Virtual Field data to update in the Attribute Table.
However, instead of using virtual fields, could you consider using 'default expressions' in Attributes? These now auto-update in the attribute table from 3.10 onwards (see changelog) (It does mean you need to add an actual field though, so if you do not have write access this will not be an option - but seeing as you are editing data anyway...)
To set this up, add "LongLabel" as an actual field, then to go to Layer Properties > Attributes Form > select LongLabel under Available Widgets, and enter the relevant expression under Defaults, checking Apply default value on update.

Now whenever you change the dependent fields, the dynamic field will auto-update whether you're in the attribute table or editing the feature form. Very cool!


text:
Q: NNTP command to get count of available newsgroups Is there an NNTP command to return the count of NewsGroups on an USENET server? (Without having to retrieving the entire list.)

A: No, such a command is not available in RFC 3977.


text:
Q: Should a diode and/or transistor be used with an automotive (Bosch style) relay for accessory power? I am a total beginner with electronics, so I apologize if this question has been answered already, I find similar questions but they seem to always be some variant and not quite what I am seeking, so I am asking here..
My automobile has power ports (cigarette lighter) that is always on.  If I forget to unplug my dashcam I have a dead battery in a couple of days.  To avoid this I would like to add a relay and tap into the accessory position circuit.  Seems pretty straight forward, but then I see a bunch of videos on the importance of diodes due to kickback voltage as the magnetic field on the coil collapses which could cause a problem with the trigger circuit.  When looking at the image below we see a manual switch activates the relay...

... but my automobile has something called "Retained Accessory Power" (A.K.A., RAP) which is what I will attempt to tap into.  My concern is that a voltage spike on this RAP circuit could be problematic. So I am seriously considering using a diode.  Then when I investigate all the circuits I find describing diodes includes the use of a transistor too.  Question:  Should I use a diode?  Should I use a transistor?  If so, what kind/size?  Using this image as an example, how would the diode and/or transistor be wired to protect the trigger circuit?

A: You should put one in though it is not as critical in this case since the a manual switch is a lot hardier to voltage spikes than a transistor which is often the first thing to blow from the spike. Even so, having one will prevent the switch from arcing and wearing it out.
You should put one in anyways just so the spike doesn't affect other things connected to your battery. Place the diode parallel to the relay coil in the direction that does NOT normally conduct current and short the battery out.

A: Given that the RAP circuit is powering other things as well, you can probably just use it to power the relay coil directly.
What will happen is that if the RAP circuit in your car shuts it off suddenly, the relay coil will continue to pull current for a bit, because it's an inductor.  This could cause a negative spike on the RAP circuit -- but chances are very high that any such spike will be small, and will be absorbed by other devices on the network.
If you're worried, then put a diode in parallel with the relay coil, such that the diode is reverse-biased when the coil is energized, as in the diagram below.  With the diode shown, the RAP will only be able to go about 1V negative.  It is probably vast and paranoid overkill, given that most automotive circuits are already protected against things like inductive load dump.
Alternately, look around for an automotive-rated solid-state relay and use that instead of the Bosch unit; these gizmos act like relays, but don't have the inductive kickback of a relay.

simulate this circuit – Schematic created using CircuitLab


text:
Q: Metapost suffix to string Is there a way to convert suffix to string?
More specifically, i need to do something like this:
def myMacro (suffix a, b) =
    something.a = fOne(a);
    something.b = fOne(b);
    something.scantokens("somethingelse"&**suffixtostring**(a)&**suffixtostring**(b)) = fTwo(a,b);
enddef;

A: Try something like this:
def your_macro(suffix a, b) =
  something.a = 42;
  something.b = 64;
  something.scantokens("prefix" & str a & str b & "suffix") = 94;
enddef;

your_macro(p,q);

show something.prefixpqsuffix;
% shows 94

end.

Of course, if you want to assign some value of a non-numeric type to something you should declare it appropriately before trying to assign to it.  For example, pair something[]; or string something[];
You also might want to think about the scope of the something variables.


text:
Q: Parallel.ForEach losing data Parallel.ForEach helps improve performance however, I am seeing data loss.
Tried - variables results, processedData are ConcurrentBag<IwrRows>
1)
Parallel.ForEach(results, () => new ConcurrentBag<IwrRows>(), (n, loopState, localData)    =>
{
 return ProcessData(n); // ProcessData complicated business logic
}, (localData) => AddRows(localData, processedData, obj)
);

2)
await Task.Run(() => Parallel.ForEach(results, item =>
        {
            ProcessData(item, processedData);
        }));

3)
Parallel.ForEach(results, item =>
 {
 ProcessData(item, processedData);
 });

All of them lost some rows.
When I use the foreach block it returns consistently the same value however, its 4 times slower.
foreach (var item in results)
        {
            // ProcessData returns a List<IwrRows>
            processedData.AddRange(ProcessData(item));
        }

Not sure what I am missing here.
results - 51112
Foreach returns 41316 rows back.
ForeachParallel returns 41308 or 41313 or 41314 varies with each run

A: You seem to struggle with the results and getting them back into a coherent list. You could use PLinQ, so you don't have to bother with the results container being thread-safe:
var processedData = yourData.AsParallel().Select(ProcessData).ToList();

A: You problem seems to be in: AddRows(localData, processedData, obj). This method is probably adding data to a list which is not thread safe. You should add the to a thread safe list or make some synchronizing around the adding of the data.

A: using await Task.Run in 2) is useless i think.
If Foreach returns 41316 rows back for Results - 51112
than problem is not in Parallel.ForEach but in your adding / processing mechanism. Remember that even if ConcurrentBag guarantees that each operation on it is thread-safe, it doesn't take care of duplicates.

A: Well there might be definitely problem with your buisness logic (ProcessData).
Maybe not a pararell.foreach but I think this one might speed up a little your code, it's async as well using LINQ.
Thats the way, I'm handling Parallel async operations on some data.
You'll probably need to flatten the result of taskList (its full pseudo-code written from head).  You could always use yield return always to materialize later your list, that might fasten it a bit more. But use yield with caution :)
var taskList = results.Select(async item =>
    {
        return await ProcessData(item, processedData);
    });

await Task.WhenAll(taskList);

Use WhenAll or WaitAll depend on the case you want

Task.WaitAll:

At least one of the Task instances was canceled -or- an exception was thrown during the execution of
at least one of the Task instances.If a task was canceled, the AggregateException contains an
OperationCanceledException in its InnerExceptions collection.

Task.WhenAll:
If any of the supplied tasks completes in a faulted state, the returned task will also complete in a
Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions
from each of the supplied tasks.


text:
Q: Sending link through AJAX I was trying to check for a user in the database through ajax. On success it should return a link with the username as the name of the link. Earlier without the link portion everything was working fine but now it displays 'undefined'. Also i know that I am using deprecated mysql_* functions and my code is prone to sql injection, but my concern is the above mentioned problem.
This is the php code which is returned through AJAX.
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
require_once("includes/connection.php");
echo '<response>';
$user=$_GET['user'];

if($user==""){
echo "type the username";
}
else{
$query="SELECT email_id FROM users
    WHERE email_id='{$user}'
    ";
$user_result = mysql_query($query,$connection);
if(mysql_num_rows($user_result)>0){
echo " {$user}  exists";
    }
else{
                echo "no such user as {$user} exists";
    }
}

echo '</response>';
?>

I have not included the function creating the xmlHTTP object but this is the rest of the AJAX code:
function start()
{

if(xmlHttp){
try{
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
    {
        user= encodeURIComponent(document.getElementById("user_input").value);
        xmlHttp.open("GET","search.php?user="+user,true);
        xmlHttp.onreadystatechange = mainFunctionHandler;
        xmlHttp.send(null);
    }else{
        setTimeout('start()',1000);
    }
}catch(e){
    alert(e.toString());
        }
}
}

function mainFunctionHandler()
{
if(xmlHttp.readyState==4){
    if(xmlHttp.status==200){
        xmlResponse = xmlHttp.responseXML;
        xmlDocumentElement = xmlResponse.documentElement;
        message = xmlDocumentElement.firstChild.data;
        document.getElementById("divD").innerHTML=message;
        setTimeout('start()',1000);
    }else{
        alert("something went wrong");
    }
}
}

A: Your client-side JavaScript needs to correctly extract the a tag, and insert it into the main page.
See this example below:
<!doctype html>

<input type="text" id="user_input">
<button id="submit" onclick="start()">Search for user</button>


text:
Q: How to align gridView using XML and Layout? How to align gridView using XML and Layout?

I have tried a lot of attributes and methods, alignment occurs ONLY in the horizontal direction, and I need and vertically
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_gravity="center">
    <GridView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/gridView"
            android:numColumns="3"
            android:scrollbars="none"
            android:overScrollMode="never"
            android:gravity="center"/>

A: You can try following
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/gridView"
        android:numColumns="3"
        android:scrollbars="none"
        android:overScrollMode="never"
        android:layout_centerInParent="true"/>
</RelativeLayout>

For Linear , you can use
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

<GridView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/gridView"
    android:numColumns="3"
    android:scrollbars="none"
    android:overScrollMode="never"/>

</LinearLayout>

A: <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
android:gravity="center">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/gridView"
        android:numColumns="3"
        android:scrollbars="none"
        android:overScrollMode="never"
        android:layout_centerInParent="true"/>
</RelativeLayout>


text:
Q: How to format a write statement in Python? I have data that I want to print to file. For missing data, I wish to print the mean of the actual data. However, the mean is calculated to more than the required 4 decimal places. How can I write to the mean to file and format this mean at the same time?
I have tried the following, but keep getting errors:
outfile.write('{0:%.3f}'.format(str(mean))+"\n")

A: First, remove the % since it makes your format syntax invalid.  See a demonstration below:
>>> '{:%.3f}'.format(1.2345)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid conversion specification
>>> '{:.3f}'.format(1.2345)
'1.234'
>>>

Second, don't put mean in str since str.format is expecting a float (that's what the f in the format syntax represents).  Below is a demonstration of this bug:
>>> '{:.3f}'.format('1.2345')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
>>> '{:.3f}'.format(1.2345)
'1.234'
>>>

Third, the +"\n" is unnecessary since you can put the "\n" in the string you used on str.format.
Finally, as shown in my demonstrations, you can remove the 0 since it is redundant.

In the end, the code should be like this:
outfile.write('{:.3f}\n'.format(mean))

A: You don't need to convert to string using str(). Also, the "%" is not required. Just use:
outfile.write('{0:.3f}'.format(mean)+"\n")

A: First of all, the formatting of your string has nothing to do with your write statement. You can reduce your problem to:
string = '{0:%.3f}'.format(str(mean))+"\n"
outfile.write(string)

Then, your string specification is incorrect and should be:
string = '{0:.3f}\n'.format(mean)

A: outfile.write('{.3f}\n'.format(mean))


text:
Q: База данных, андроид Нужно реализовать в программе сохранение данных, введённых пользователем во Фрагментах. Попробовал самостоятельно написать DBHelper из обучалки Start Android. Постарался как можно точнее привести тамошнюю таблицу, к своей, но не могу разобраться, почему при нажатии кнопки Save программа вылетает и не сохраняет данные.
Вот код активности, в которой находится кнопка и фрагмент:
package com.example.alexey.finalprojectalexeymushailov;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SecondaryActivity extends AppCompatActivity implements
View.OnClickListener {
DBHelper dbHelper;
fragmentA frgOne;
fragmentB frgTwo;
FragmentTransaction frgTransaction;
int currentlyFragment;
Button butClear, butSave;
EditText misparRehev, shemEhida, sugTipul, kamutKilometrim, date;

@Override
protected void onCreate(Bundle savedInstanceState) {    //basic
    super.onCreate(savedInstanceState);                 //code
    setContentView(R.layout.activity_secondary);        //in android

    //here I find buttons and editTexts+Switches via findViewById and apply listener to them
    butSave = (Button) findViewById(R.id.btnSave);   //save button
    butSave.setOnClickListener(this);                //save listener
    butClear = (Button) findViewById(R.id.btnClear); //clear button
    butClear.setOnClickListener(this);               //clear listener
    //here are editTexts for fragmentA
    misparRehev = (EditText) findViewById(R.id.editMisparRehev);
    shemEhida = (EditText) findViewById(R.id.editShemEhida);
    sugTipul = (EditText) findViewById(R.id.editSugTipul);
    kamutKilometrim = (EditText) findViewById(R.id.editKilometrim);
    date = (EditText) findViewById(R.id.editDate);
    //here are editTexts for fragmentA ^

    //here I initialize my fragments for fragment manager so I could use it for change between fragments
    frgOne = new fragmentA();
    frgTwo = new fragmentB();
    //this code makes fragment one turn on immediatly when activity 2 is on the screen
    frgTransaction = getSupportFragmentManager().beginTransaction();
    frgTransaction.add(R.id.frameLayout, frgOne);
    currentlyFragment = 1;    //this is variable for code, that makes program know which fragment is on the screen right now
    frgTransaction.commit();

    dbHelper = new DBHelper(this);  // here I initialize my database and call for it's class
}
public void onClickChange(View v){           //this is onClick for changing between activities
    if (currentlyFragment == 1){   //1 is first fragment
        frgTransaction = getSupportFragmentManager().beginTransaction();
        frgTransaction.replace(R.id.frameLayout, frgTwo);
        currentlyFragment = 2;
        frgTransaction.commit();
    }
    else if (currentlyFragment == 2){  //2 is second fragment
        frgTransaction = getSupportFragmentManager().beginTransaction();
        frgTransaction.replace(R.id.frameLayout, frgOne);
        currentlyFragment = 1;
        frgTransaction.commit();
    }

}

@Override
public void onClick(View v) {    // this is onClick function for saving data to database in SQLite
    String rehev = misparRehev.getText().toString();            ///
    String ehida = shemEhida.getText().toString();              /////
    String tipul = sugTipul.getText().toString();               /////// here we get entered in EditText data
    String kmetres = kamutKilometrim.getText().toString();      /////
    String taarih = date.getText().toString();                  ///

    SQLiteDatabase database = dbHelper.getWritableDatabase();

    ContentValues contentValues = new ContentValues();

    switch (v.getId()){
        case R.id.btnSave:
            contentValues.put(DBHelper.KEY_MISPAR_REHEV, rehev);            ///
            contentValues.put(DBHelper.KEY_SHEM_EHIDA, ehida);              /////
            contentValues.put(DBHelper.KEY_SUG_TIPUL, tipul);               /////// here I put data in DB TABLE
            contentValues.put(DBHelper.KEY_KAMUT_KILOMETRES, kmetres);      /////
            contentValues.put(DBHelper.KEY_TAARHIH, taarih);                ///

            database.insert(DBHelper.TABLE_ONE, null, contentValues);
            break;

    }
}

}
Вот код DBHelper (класса, в котором я реализовал таблицу):
package com.example.alexey.finalprojectalexeymushailov;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;  //myDatabase version
public static final String DATABASE_NAME = "myDatabase";   //DB name
public static final String TABLE_ONE= "myTable1";               //DB TABLE name

public static final String KEY_MISPAR_REHEV = "_id";
public static final String KEY_SHEM_EHIDA = "_id";
public static final String KEY_SUG_TIPUL= "_id";
public static final String KEY_KAMUT_KILOMETRES = "_id";
public static final String KEY_TAARHIH = "_id";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION)   ;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_ONE +
            "(" + KEY_MISPAR_REHEV + " integer primary key, "
            + KEY_SHEM_EHIDA + " text," + KEY_SUG_TIPUL + " text,"
            + KEY_KAMUT_KILOMETRES + " text," + KEY_TAARHIH + " text" + ")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists " + TABLE_ONE);

    onCreate(db);
}
}

A: Кто же так делает?
//here are editTexts for fragmentA
misparRehev = (EditText) findViewById(R.id.editMisparRehev);
shemEhida = (EditText) findViewById(R.id.editShemEhida);
sugTipul = (EditText) findViewById(R.id.editSugTipul);
kamutKilometrim = (EditText) findViewById(R.id.editKilometrim);
date = (EditText) findViewById(R.id.editDate);
//here are editTexts for fragmentA ^

Нельзя из onCreate активити найти UI элемент фрагмента.
У вас тут все пять null, вот и NullPointerException в итоге.


text:
Q: Calculations in AWK I need to perform calculations in awk. For each array[$1,$2] i need to check $3. If it is "5310" the value in $4 is positiv, else the value is negativ.
In the end I need to substract all negativ values from the positiv values per array[$1,$2]
input
K019001^ABC^531^12
K019001^ABC^601^12
K019002^ABC^531^100
K019002^ABC^601^40
K019003^ABC^531^50
K019003^ABC^601^30
K019003^ABC^601^40
K019004^ABC^531^10

desired output
K019001^ABC^0
K019002^ABC^60
K019003^ABC^-20
K019004^ABC^10

A: Use this awk:
awk 'BEGIN {FS=OFS=SUBSEP="^"} {a[$1,$2] += $4 * ($3==531 ? 1 : -1)}

END {for (i in a) print i, a[i]}' file
K019001^ABC^0
K019004^ABC^10
K019002^ABC^60
K019003^ABC^-20

UPDATE:: To get correct ordering:
awk 'BEGIN{FS=OFS="^"} {k=$1 FS $2; if (!a[k]) b[c++]=k} $3==531{a[k]+=$4; next} {a[k]-=$4}
        END {for (i=0; i<length(b); i++) print b[i], a[b[i]]}' file

K019001^ABC^0
K019002^ABC^60
K019003^ABC^-20
K019004^ABC^10


text:
Q: select some values between 2 dataframe I have two dataframes, one of them has a column of 100 genes and the other dataframe has a column that consist 700 rows and each row has several genes that are separated by comma, now I do not know how is it possible to select genes in each row of dataframe 2 according to the gene column in dataframe 1. In another word I want genes in each row of dataframe 2 that are in gene column of dataframe 1.
dataframe1:
column gene:
a
b
c
d
e
f

dataframe2:
column gene:
row1"a,b,c,d,r,t,y"
row2"c,g,h,k,l,a,b,c,p"

I only want comma separated genes in each row of dataframe2 that are in column gene of dataframe1 and other genes in dataframe 2 and are not in dataframe1 be removed.

A: Loop over each row of dataframe2$gene with sapply and keep only those values which are %in% dataframe$gene1, after strspliting to get each comma-separated value.
dataframe1 <- data.frame(gene = c("a", "b", "c", "d", "e", "f"),
                         stringsAsFactors=FALSE)
dataframe2 <- data.frame(gene = c("a,b,c,d,r,t,y", "c,g,h,k,l,a,b,c,p"),
                         stringsAsFactors=FALSE)

dataframe2$gene_sub <- sapply(
    strsplit(dataframe2$gene, ","),
    function(x) paste(x[x %in% dataframe1$gene], collapse=",")
)

dataframe2
##               gene gene_sub
##1     a,b,c,d,r,t,y  a,b,c,d
##2 c,g,h,k,l,a,b,c,p  c,a,b,c

A: Using tidyverse:
library(tidyverse)
library(rebus)
#>
#> Attaching package: 'rebus'
#> The following object is masked from 'package:stringr':
#>
#>     regex
#> The following object is masked from 'package:ggplot2':
#>
#>     alpha

dataframe1 <- tibble(gene = c("a", "b", "c", "d", "e", "f"))
dataframe2 <- tibble(gene = c("a,b,c,d,r,t,y","c,g,h,k,l,a,b,c,p"))

result <- str_extract_all(dataframe2$gene, rebus::or1(dataframe1$gene)) %>%
            map(~ reduce(.x, str_c, sep = ','))

mutate(dataframe2, gene = result) %>% unnest(c(gene))
#> # A tibble: 2 x 1
#>   gene
#>   <chr>
#> 1 a,b,c,d
#> 2 c,a,b,c

Created on 2021-06-28 by the reprex package (v2.0.0)

A: A tidyverse option using data from @thelatemail.
library(dplyr)
library(tidyr)

dataframe2 %>%
  mutate(row =  row_number()) %>%
  separate_rows(gene, sep = ',') %>%
  left_join(dataframe1 %>%
            mutate(gene_sub = gene), by = 'gene') %>%
  group_by(row) %>%
  summarise(across(c(gene, gene_sub), ~toString(na.omit(.)))) %>%
  select(-row)

#  gene                      gene_sub
#  <chr>                     <chr>
#1 a, b, c, d, r, t, y       a, b, c, d
#2 c, g, h, k, l, a, b, c, p c, a, b, c


text:
Q: Visual Studio Code, Anaconda Virtual Environment, specific projects? can anyone help me understand using conda environment with visual studio code? I had activate the virtual environment (imageprocessing) with this:
conda activate imageprocessing

and the terminal seem to have been on virtual environment, so there's look like no problem with the PATH, it looks like this.
(imageprocessing) ../users/[project_folder_somewhere]

But when I open visual studio code and activate the kernel used for opening Notebooks there, exactly with the python from imageprocessing virtual environment, I keep needed to install the previously forged library, for example, Pillow. Which part that doesn't work out? Did I install Pillow package redundantly if I keep doing this? Does visual code doesn't integrated that well with conda even though it has been connected through the path? I used this feature for opening .ipynb files on Visual Studio Code because browser-based Jupyter Notebooks are too slow and messy directory than if using this (or so I thought?).

A: In VS Code, when we use different python environments, the locations where the modules are installed are different. Therefore, we need to be clear which python environment we are currently using. (We could check it with the command "python --version" in the VS Code terminal.)
When we use the conda environment, it comes with python, so we can use "pip" to install modules, or "conda" to install modules. The modules it installs are stored in: "...\anaconda3\envs\conda-name\lib\site-packages".
The command "pip show pillow" checks the installation position of the module:

In addition, after the installation is complete, it still shows that the module cannot be found. I noticed that there is a problem with the file name here. We need to rename "PIL" to "pillow", or use "import PIL"

Reference: conda-environment in VS Code.
Add:


text:
Q: @Autowired refuses to inject without @Lazy annotation As it says if I take out the @Lazy annotation my class won't get injected.
SomeClassTest
package com.somePackage;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.somePackage.SomeClass;

@Configuration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath*:junit-spring-context.xml")
public class SomeClassTestTest {

    @Autowired
        @Lazy     // If i take this out, the test fails
    private SomeClass someClass;

    @Test
    public void someTest() {
        assertNotNull(someClass);
    }
}

SomeClass
package com.differentPackage;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.DependsOn;

@Service("someClass")
@DependsOn("someOtherClass")
public class SomeClass {
     // Bunch of code here
}

SomeOtherClass
package com.someOtherPackage.config
import org.springframework.context.annotation.Configuration;

@Configuration
public class SomeOtherClass {
     // Just more code
}

junit-spring-context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
     xmlns:p="http://www.springframework.org/schema/p"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <!-- Detect classes annotated with @Repository, @Component and @Service and register them as beans -->
    <context:component-scan base-package="com.differentPackage" />

</beans>

Why does it only work with @Lazy being present? Btw SomeClassTest and SomeClass are in different packages if that helps!

A: Spring (by default) creates all beans with singleton scope in app context eagerly.
That is the phylosophy of Spring framework. In your case, You have to create a bean, not at the application context startup, but when we request it. That is the reason why @Lazy is mandatory.


text:
Q: Why isn't this trigger good? The problem is as follows: a maximum of 50 employees is allowed in any department
My teacher said that the trigger below isn't the solution but I didn't catch the explanation, so he presented us another solution using a row-level trigger and packages (because of mutation).
What is the scenario in which the trigger below doesn't behave the intended way? I really can't think of one.
Thanks!
CREATE OR REPLACE TRIGGER pb10_trp AFTER
    INSERT OR UPDATE OF department_id ON employees
DECLARE
    nr   NUMBER;
BEGIN
    SELECT
        MAX(COUNT(employee_id) )
    INTO
        nr
    FROM
        employees
    GROUP BY
        department_id;

    IF
        nr > 50
    THEN
        raise_application_error(-20456,'Too many employees!');
    END IF;
END;

A: The complete case of the problem is as follows:
  - the "no more than 50 employees per department" can be added later in the table
Having this said, the provided solution is not correct because if a department has more than 50 employees when this trigger is enabled, no one can execute insert or update actions on the table anymore.
Eg:

*

*Department 1 has 51 employees and department 2 has 3 employees.

*User A inserts 2 employees in department 2, so the total number of employees would become 5.

*Trigger raises error, even though user A did not do anything wrong.


text:
Q: Ignoring sharedPreference code I have tired using sharedpreference to store session and used Log to test if information are stored. However, android studio seems to skip past code that involve sharedpreference. Am i doing anything wrong?
Global
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String EmployeeID = "employeeID";
public static final String EmployeeName = "employeeName";
SharedPreferences sharedpreferences;

OnCreate
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    String user = sharedpreferences.getString("EmployeeName", "");
    if (user.equalsIgnoreCase("")) {
        Log.i("Status", "No session detected");
    } else {
        Intent i = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(i);
    }

protected void onPostExecute(Employee results){
        if (results != null){

            SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(EmployeeID, results.getEmployeeID());
            editor.putString(EmployeeName, results.getFirstName()+" "+results.getLastName());
            editor.apply();
            editor.commit();
            Log.i("aaaaaaaa", "hellloooo"); // It print this libe
            String a = sharedpreferences.getString("EmployeeID", "");
            Log.i("aaaaaaaa", a); // but not this line
            Toast.makeText(LoginActivity.this, " Authenticated", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);

        }
        else {
            Toast.makeText(LoginActivity.this, "Invalid ID", Toast.LENGTH_SHORT).show();
        }
    }

A: Try to use PreferenceManager.getDefaultSharedPreferences(context) and see if that solves your problem. It's basically the same thing, the only difference is that with this way you write in the default prefs file.

A: String a = sharedpreferences.getString("EmployeeID", "");

This might just be bug fixing but I would try and use the constant value "public static final String EmployeeID = "employeeID";" instead. Maybe the key variable is case sensitive?


text:
Q: How is memory properly allocated? so I am learning and trying to figure out memory allocation in c, in this piece of code, is the memory allocated correctly or no? Do I need to allocate the array too or is the array already allocated because everything that user inputs goes to the array(will be stored in the array)?
#include <stdio.h>
#include <stdlib.h>
int main() {
    int i;
    int arr[20];
    int b;
    int *ptr;
    ptr = &b;

    ptr = (int*) malloc(20 *sizeof(int));

    //find largest element in array
    printf("Enter the number of elements: ");
    scanf("%d", &b);
    if(ptr == NULL)
    {
        printf(" No memory allocated.");
        exit(0);
    }

    for (i = 0; i < b; ++i) {
        printf("Enter number%d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    for (i = 1; i < b; ++i) {
        if (arr[0] < arr[i])
            arr[0] = arr[i];
    }
    free(ptr);
    printf("Largest element = %d", arr[0]);

    return 0;
}

A: You can clean up the malloc call:
ptr = malloc( 20 * sizeof *ptr );

You don't need to cast the result of malloc unless you using an ancient pre-C89 implementation or C++ (in which case you should use new/delete instead of malloc/free, or more preferably a container type like vector).
sizeof *ptr is equivalent to sizeof (int) in this case.
However, you aren't actually using that memory - you allocate it and free it, but you never write anything to it.
You initially assign &b to ptr, but then you overwrite it with the result of the malloc call, so if you're expecting that memory to be attached to b somehow, be aware that it isn't.


text:
Q: use android repo tool with github or gitlab I'm trying to mirror every android repo to my gitlab account.
After I imported ALL of repositories, I tried to use git-repo (repo tool from google) to build android from source.
I changed these line in my default.xml manifest:
<remote  name="aosp" fetch="https://android.googlesource.com" review="android-review.googlesource.com" revision="refs/tags/android-5.1.1_r37" />

to this:
<remote name="aosp" fetch="https://gitlab.com/android_source/" review="android-review.googlesource.com" revision="refs/tags/android-5.1.1_r37"/>

I also changed every project name. for example:
<project path="dalvik" name="platform/dalvik" groups="pdk-cw-fs" remote="aosp"/>

to this:
<project path="dalvik" name="platform_dalvik" groups="pdk-cw-fs" remote="aosp"/>

now, here is my problem. when I run repo command
repo sync

I get these type of errors:
Fetching projects:   0% (1/541)  Fetching project platform_prebuilts_ndk.git
fatal: Couldn't find remote ref refs/tags/android-5.1.1_r37
fatal: Couldn't find remote ref refs/tags/android-5.1.1_r37
error: Cannot fetch platform_prebuilts_ndk.git

error: Exited sync due to fetch errors

Whats wrong??
you can see default.xml and changed one.
EDIT:
I found a solution but I don't like it.
I changed this:
<remote name="aosp" fetch="https://gitlab.com/android_source/" review="android-review.googlesource.com" revision="refs/tags/android-5.1.1_r37"/>

to this:
<remote name="aosp" fetch="ssh://git@gitlab.com/android_source/" review="android-review.googlesource.com" revision="refs/tags/android-5.1.1_r37"/>

now I can fetch using git_repo tools. But this is odd. other people should be able to clone my repo.

A: Not sure if that's what you need, but here it goes.

If you want to mirror your repo, you should:

*

*Click on Create New Project

*Import it and mirror:

This way GitLab will update the mirrored repo with the upstream automatically.
Hope to have helped!

A: If you can clone via ssh and not via https is probably because you configure GitLab projects as private and not public
I try to browse you personal gitlab group and, in fact, I cannot browse any project (however maybe it's just because you delete them, the question is, in fact, quite old, but maybe my answer may be useful to other too)


text:
Q: How to check aws ec2 is running or not using aws lambda (boto3) I want to know whether my instance is in running state or not, if its in running state then only file will get copied from s3 into my ec2 instance and then file will run in that machine.

A: You can query of instance "state" attribute.
For example: instance.state['Name']
This returns a state string, example stopped
Possible states are:

0 : pending   16 : running  32 : shutting-down   48 : terminated   64
  : stopping   80 : stopped

And here is Python code example to retrieve EC2 instance information.


text:
Q: Can't retract Very Low Quality flag on question Earlier today, I cast a Very Low Quality flag on this now deleted question. While it was still pending

I couldn't retract the flag; instead of a Retract Flag button, a disabled Flag Question button was shown:

I suspect this has something to do with the question not qualifying for a Very Low Quality flag anymore due to it already being in a review queue.


text:
Q: Using macro parameter # after control sequence character \ I'm making a new command like which goes kind of like this:
\newcommand\mycommand[1]{\#1section}

So, what I what is to type \mycommand{sub}{blah} to output \subsection{blah} and \mycommand{subsub}{blah} to output \subsubsection{blah}. Is this even possible?

A: \csname allows to construct command sequence names:
\newcommand*{\mycommand}[1]{\csname#1section\endcsname}

If the constructed command is not defined, then it does not throw an error. Instead, the constructed command has the meaning \relax.


text:
Q: React app scroll to top only works in firefox I was having a problem in react where when changing routes, the page would remain in the same spot on the page as the previous page rather then go to the top. I found a solution on here but it only works on firefox. Anyone know how to get this working on chrome and safari?
import { useEffect } from "react";
import { withRouter } from "react-router-dom";

const ScrollToTop = ({ children, location: { pathname } }) => {
  useEffect(() => {
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: "smooth"
    });
  }, [pathname]);

  return children || null;
};

export default withRouter(ScrollToTop);

in my index.js
ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <ScrollToTop>
       <App />
      </ScrollToTop>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);


text:
Q: Looking for recommended methods for storing/cacheing counts I'm building a website using php/mysql where there will be Posts and Comments.
Posts need to show number of comments they have. I have count_comments column in Posts table and update it every time comment is created or deleted.
Someone recently advised me that denormalazing this way is a bad idea and I should be using caching instead.

A: My take is: You are doing the right thing. Here is why:
See the field count_comments as not being part of your data model - this is easily provable, you can delete all contents of this field and it is trivial to recreate it.
Instead see it as a cache, the storage of which is just co-located with the post - perfectly smart, as you get it for free whenever you have to query for the post(s)

A: I do not think this is a bad approach.
One thing i do recognize is that its very easy to introduce side effects as code base is expanded by having a more rigid approach.  The nice part is at some point the amount of rows in the database will have to be calculated or kept track of, there is not really a way of getting out of this.
I would not advise against this.  There are other solutions to getting comment counts.  Check out  Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)
The solution is slower upon selects, but requires less code to keep track of comment count.

I will say that your approach avoids LIMIT DE-optimization, which is a plus.

A: This is an optimization that is almost never needed for two reasons:
1) Proper indexing will make simple counts extremely fast. Ensure that your comments.post_id column has an index.
2) By the time you need to cache this value, you will need to cache much more. If your site has so many posts, comments, users and traffic that you need to cache the comments total, then you will almost definitely need to be employing caching strategies for much of your data/output (saving built pages to static, memcache, etc.). Those strategies will, no doubt, encompass your comments total, making the table field approach moot.

A: I have no idea what was meant by "Caching" and I'll be interested in some other answer that the one I have to offer:
Remove redundant information from your database is important and, in a "Believer way" (means that I didn't really test it, its merely speculative), I think that using SUM() function from your database is a better way to go for it.
Assuming that all your comments has a post_id, all you need is something like:
SELECT SUM(id) FROM comments WHERE id = {post_id_variation_here}

That way, you reduce 1 constant CRUD happening just to read how much comments there are and increase performance.

A: Unless you haven't hundreds or thousands of hits per seconds on your application there's nothing wrong about using a SQL statement like this:
select posts_field1, ..., (select count(*) from comments where comments_parent = posts_id) as commentNumber from posts

you can go with caching the html output of your page anyway. than no database query has to be done at all.

A: Maby you could connect the post and comment tables to each other and count the comments rows in mysql with the mysql function: mysql_num_rows. Like so:
Post table
postid*
postcontent

Comment table
commentid
postid*
comment

And then count the comments in mysql like:
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM commenttable WHERE postid = '1'", $link);
$num_rows = mysql_num_rows($result);


text:
Q: Installing Oracle Database and can't find "Workgroup Manager" in Mac OS X 10.10.5 (Yosemite) I just started to work with Mac and I'm trying to install Oracle Database using the instructions at this link. Section 6 of this tutorial says that some groups should be constructed using "Workgroup Manager" which is located in /Applications/Server/Workgroup Manager. But in the Applications folder there is no Server application.
Can anybody tell me what should I do and how can I create groups?

A: You say this:

Section 6 of this tutorial says that some groups should be
  constructed using "Workgroup Manager" which is located in
  /Applications/Server/Workgroup Manager. But in the Applications
  folder there is no Server application.

First, remember those instructions date back to December 2004; screenshot below:

So 11+ years later, some specifics won't be valid or useful. But you can work around it if you try. Read on.
And yes, those instructions are asking for you to use "Workgroup Manager" and that is not a part of the normal/basic core Mac OS X operating system. That is a part of Mac OS X Server which is the server software suite that is installed. And since you are using a normal/basic Mac OS X operating system install, there is no way you will find "Workgroup Manager" anywhere.
That said you ask this:

Can anybody tell me what should I do and how can I create groups?

Like I said at the outset, specifics in an old document like that are out of date but you can work around it. According to this official Apple support page:

Workgroup Manager is not included with OS X Server. When upgrading to
  OS X Mountain Lion or later, the installer removes Workgroup Manager.
To administer iOS and OS X systems, use Profile Manager included with
  OS X Server. Profile Manager delivers configuration profiles and
  Mobile Device Management (MDM) for Macs running OS X Mountain Lion,
  Lion, and iOS devices.

So basically one route to doing this is to purchase and install the modern Mac OS X server software from the Apple app store. It costs $19.99 and is fairly easy to use. But if this is a personal computer or a test machine where you don't need additional server capabilities, that server software package might be overkill.
Instead you can create users and groups easily by just going to "System Preferences… -> Users & Groups" unlocking the small administrator lock in the lower left-hand corner if you need to, and then click the + item near the bottom of the user list on the left-hand side. The default + action is to create a new standard user but if you click that "New Account:" pulldown list you will see the "Group" option right at the bottom; see picture below:

Create the new group there and you should be good to go.
But that said, be cautious about those Oracle Database installation instructions for Mac OS X. Like I said, they date back to 2004 and 11+ years is a fairly long time in the world of step-by-step instructions.