text:
Q: Spring Data JPA - Get all elements I'm new to Spring Data JPA and I want to ask if there is a method that can be used to fetch all items, not by a certain criterion. Any help would be helpful.

A: Use the findAll method from repository
repository.findAll()

Take a look here
Spring Data JPA API
Look here a small example that will fetch all MyObj objects that are stored
@Repository
public interface MyObjRepository extends JpaRepository<MyObj, Long> { }

@Service
public class MyService {

@Autowired
MyObjRepository repository;

public List<MyObj> findAllElements() {
  return repository.findAll();
 }

}


text:
Q: An interesting question about greatest common divisor (gcd) of three positive integers which form a primitive Pythagorean triple Suppose $a$, $b$, and $c$ are three distinct integers which share no common divisor. Note that this implies that $a$, $b$, and $c$ are pairwise coprime. If $a$,$b$, and $c$ are a primitive Pythagorean triple satisfying the equation $a^2 + b^2 = c^2$ , is it then always true that
$$\gcd ( (a+b) , (a+b-c) ) = 1?$$
Can it be proven that $\gcd ( (a+b) , (a+b-c) ) = 1$ invariably ?
Can you find a counterexample where $\gcd ( (a+b) , (a+b-c) ) \neq 1$?

A: We have that
$$
\gcd(a+b, a+b-c) = \gcd(a+b, -c) = \gcd(a+b, c).
$$
Now suppose that $p$ is a prime dividing $\gcd(a+b, c)$. Because $a^2 + b^2 = c^2$, we have that $p^2$ also divides $(a+b)^2 - (a^2 + b^2) = 2ab$. In particular $p$ divides either $a$ or $b$ (even if $p=2$). But this contradicts our assumption.

A: Hint $\ (a\!+\!b, a\!+\!b\!-\!c)= (a\!+\!b,c)\mid (a\!+\!b,\!\!\!\overbrace{c^2}^{a^2\,+\,b^2}\!\!\!)\mid 2(a^2,b^2)\!=\!2,\,$ but $c$ is odd in a PPT

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gulp: call an async function which provides its own callback from within a transform function I want to create a function for use in a pipe() call in Gulp that'll enable conversion of xlsx files to json.
I had this working with NPM package 'excel-as-json' for gulp 3, however Gulp 4 has forced me to actually understand what it is doing ;-)
Six hours in, and my incapacity of getting this to work due to a lack of js/async/streaming knowledge is punching my curiosity.
Code is as follows:
paths = {excel_sourcefiles: "./sourcefiles/*.xls*", excel_targetdir_local_csvjson: "./targetfiles_local/*.*"}

var replaceExt = require('replace-ext');
var PluginError = require('plugin-error')
var gulpFunction = require('gulp-function').gulpFunction // default ES6 export
var through = require("through2")
var convertExcel = require('excel-as-json').processFile;
var changed = require('gulp-changed');
var assign = Object.assign || require('object.assign');
var notify = require('gulp-notify');
var gulpIgnore = require('gulp-ignore');
var rename = require('gulp-rename');

gulp.task('excel-to-jsoncsv', function() {
  return gulp.src(paths.excel_sourcefiles)
    // .pipe(debug())
    .pipe(gulpIgnore.exclude("*\~*")) // Ignore temporary files  by Excel while xlsx is  open
    .pipe(gulpIgnore.exclude("*\$*")) // Ignore temporary files  by Excel while xlsx is  open
    .pipe(plumber({errorHandler: notify.onError('gulp-excel-to-jsoncsv error: <%= error.message %>')}))
    .pipe(changed(paths.excel_targetdir_local_glob, { extension: '.csv' }))
    .pipe(GulpConvertExcelToJson()) // This is where the magic should happen
    .pipe(rename({ extname: '.csv' })) // Saving as .csv for SharePoint (does not allow .json files to be saved)
    .pipe(gulp.dest(paths.excel_targetdir_local))
});

function GulpConvertExcelToJson() {
  return through.obj(function(chunk, enc, callback) {
    var self = this
    if (chunk.isNull() || chunk.isDirectory()) {
      callback() // Do not process directories
      // return
    }

    if (chunk.isStream()) {
      callback() // Do not process streams
      // return
    }

    if (chunk.isBuffer()) {
      convertExcel(chunk.path, null, null, // Converts file found at `chunk.path` and returns (err, `data`) its callback.
        function(err, data) {
          if (err) {
            callback(new PluginError("Excel-as-json", err))
          }
          chunk.contents = new Buffer(JSON.stringify(data))
          self.push(chunk)
          callback()
          // return
        })
    } else {
      callback()
    }
  })
}

I (now) know there are other excel > json gulp modules that could allow me to solve this problem without writing my own module, yet I'd like to understand what I should do different here.
The error returned is 'Did you forget to signal Async completion?', which I tried to not do. However, probably my attempt to fix the error 'this.push is not a function' with a var self = this is not what I was supposed to do.
Looking at examples like gulp-zip introduced me to unfamiliar notations, making me unable to autodidact my way out of this.
In summary:

*

*how would I go about calling an async function during a through.obj function call, where the chunk's contents is updated with the (not under my control) async function that only provides me with a callback (err, data)?

A: This problem is coming deep from the excel library. The end event should be finish.
Unsuccessful Try
I did the following, to install the modified excel.js:
rm -rf node_modules/excel
git clone https://github.com/bdbosman/excel.js node_modules/excel
cd node_modules/excel && npm i && cd ../..

This is not enough since the excel-as-json uses an old version of excel.
Either you have to modify the excel-as-json module, to use excel@1.0.0 (after the Pull Request is merged) or manually edit the file in node_modules. I will describe the second way here.
Temporary Solution
Edit the excel file after installing the modules.
I used:
sed -i "s/'end'/'finish'/g" node_modules/excel/excelParser.js

And then I ran:
$ gulp excel-to-jsoncsv
[19:48:21] Using gulpfile ~/so-question-gulp-async-function-call-xlsx/gulpfile.js
[19:48:21] Starting 'excel-to-jsoncsv'...
[19:48:21] Finished 'excel-to-jsoncsv' after 126 ms

And it apparently worked.


text:
Q: Apache httpd.conf - Link multiple domains to corresponding subfolders I need a rule to internally rewrite several domains, with and without www:
www.a.com --> /m/n/o/
b.c.org --> /x/y/z/

The setup is Apache running locally on Windows (XAMPP). I've got the hosts file set up so all the domains point to localhost. I'd like every page to get redirected, i.e. I want to point each domain to it's own different root directory and have it work normally from there. e.g.
/                          <-- Top level folder, everything is under here.
   /root/of/domain/A/      <-- www.a.com
   /root/of/domain/C/      <-- b.c.org

A: You have two choices.
(1) The one you asked (with mod_rewrite)
<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{HTTP_HOST} ^(?:www\.)?a\.com$ [NC]
  RewriteRule ^/(.*)$ /root/of/domain/A/$1 [L]

  RewriteCond %{HTTP_HOST} ^b\.c\.org$ [NC]
  RewriteRule ^/(.*)$ /root/of/domain/C/$1 [L]
</IfModule>

Note: don't forget to replace example values by real ones. Also, make sure mod_rewrite is enabled.
(2) the cleanest way: configure virtualhosts directly (without mod_rewrite)
NameVirtualHost *:80

<VirtualHost *:80>
  DocumentRoot "X:/path/to/root/of/domain/A/"
  ServerName a.com
  ServerAlias www.a.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot "X:/path/to/root/of/domain/C/"
  ServerName b.c.org
</VirtualHost>


text:
Q: SQL to Linq with aggregate function I'm trying to do this in LINQ.
Can you guys help me to do this?
There some tool to help me with this conversion?
SELECT
CODIGO_DEPENDENCIA,
SUM(COALESCE(LOCAL_MOVEL, 0))           AS LOCAL_MOVEL,
SUM(COALESCE(LOCAL_FIXO, 0))            AS LOCAL_FIXO,
SUM(COALESCE(DDD_MOVEL, 0))             AS DDD_MOVEL,
SUM(COALESCE(DDD_FIXO, 0))              AS DDD_FIXO,
SUM(COALESCE(EXTERNA_INTERNACIONAL, 0)) AS EXTERNA_INTERNACIONAL
FROM (
SELECT
CODIGO_DEPENDENCIA,
CASE WHEN TIPO = 'SELM'  THEN SUM(VALOR) END AS LOCAL_MOVEL,
CASE WHEN TIPO = 'SELF'  THEN SUM(VALOR) END AS LOCAL_FIXO,
CASE WHEN TIPO = 'SENM'  THEN SUM(VALOR) END AS DDD_MOVEL,
CASE WHEN TIPO = 'SENF'  THEN SUM(VALOR) END AS DDD_FIXO,
CASE WHEN TIPO = 'SEI'   THEN SUM(VALOR) END AS EXTERNA_INTERNACIONAL
FROM CAD_BILHETES
WHERE ID_PRODUTO IS NULL
AND ID_COMPETENCIA = 60
AND CODIGO_DEPENDENCIA IN (14, 160)
AND TIPO IN ('SEI', 'SELM', 'SENF', 'SELF', 'SENM')
AND VALOR <> 0
GROUP BY TIPO,CODIGO_DEPENDENCIA
) TAB
GROUP BY CODIGO_DEPENDENCIA

A: Obviously untested. Also, uncertain if null tests are needed or how they will react through SQL translation. It may be preferable to change the first query to return 0 when not matching and then just sum the results, but I wasn't sure the datatype of the columns.
var tab = from cb in CAD_BILHETES
      where cb.ID_PRODUTO == null && cb.ID_COMPETENCIA == 60 && (new[] { 14, 160 }).Contains(cb.CODIGO_DEPENDENCIA) &&
      (new[] { "SEI", "SELM", "SENF", "SELF", "SENM" }).Contains(cb.TIPO) && cb.VALOR != 0
      group cb by new { cb.TIPO, cb.CODIGO_DEPENDENCIA } into cbg
      select new { cbg.Key.CODIGO_DEPENDENCIA,
          LOCAL_MOVEL = (cbg.Key.TIPO == "SELM" ? cbg.SUM(cb => cb.VALOR) : null),
          LOCAL_FIXO = (cbg.Key.TIPO == "SELF" ? cbg.SUM(cb => cb.VALOR) : null),
          DDD_MOVEL = (cbg.Key.TIPO == "SENM" ? cbg.SUM(cb => cb.VALOR) : null),
          DDD_FIXO = (cbg.Key.TIPO == "SENF" ? cbg.SUM(cb => cb.VALOR) : null),
          EXTERNA_INTERNACIONAL = (cbg.Key.TIPO == "SEI" ? cbg.SUM(cb => cb.VALOR) : null),
      };

var ans = from cb in tab
      group cb by cb.CODIGO_DEPENDENCIA into cbg
      select new {
        CODIGO_DEPENDENCIA = cbg.Key,
          LOCAL_MOVEL = cbg.Sum(cb => cb.LOCAL_MOVEL == null ? 0 : cb.LOCAL_MOVEL),
          LOCAL_FIXO = cbg.Sum(cb => cb.LOCAL_FIXO == null ? 0 : cb.LOCAL_FIXO),
          DDD_MOVEL = cbg.Sum(cb => cb.DDD_MOVEL == null ? 0 : cb.DDD_MOVEL),
          DDD_FIXO = cbg.Sum(cb => cb.DDD_FIXO == null ? 0 : cb.DDD_FIXO),
          EXTERNA_INTERNACIONAL = cbg.Sum(cb => cb.EXTERNA_INTERNACIONAL == null ? 0 : cb.EXTERNA_INTERNACIONAL)
      };


text:
Q: Why is the correlation between a standardized variable and a factor score not 1 when m=1? Assume that there is only one factor (m=1), the model looks like the following:
$$
Z_i=\mu_i+L_i*F_1+\epsilon_i
$$
where $i$ is the index of the standardized variables and $L$ is a vector of factor loadings. Correlation between standardized variable $Z_i$ and its only factor score $F_1$ is the corresponding factor loading $L_i$.
$$
Corr(Z_i,F_1)=Cov(Z_i,F_1)=Cov(L_i*F_1,F_1)=L_i
$$
However, I find this counter-intuitive because Z is basically a linear transformation of $F_1$. Shouldn't the correlation be 1?


text:
Q: cp except a file does not work in Makefile The trick of using "!" to exclude a directory when using cp works under shell, but does not work in make:
mkdir db09601c && cp -r !(db09601c) db09601c
/usr/bin/bash: -c: line 0: syntax error near unexpected token ('
/usr/bin/bash: -c: line 0:mkdir db09601c && cp -r !(db09601c) db09601c'

I have put SHELL=/bin/bash on top of the Makefile already:
PROJECT_NAME=nnr
HASH=$(shell git log -n1 --pretty=format:%h)
REVS=$(shell git log --oneline|wc -l)
SHELL=/bin/bash

build:
        mkdir $(HASH) && cp -r !($(HASH)) $(HASH)
        cp INSTALL.tpl INSTALL
        sed -i 's/{_G_HASH}/$(HASH)/' INSTALL
        chmod +x INSTALL
        echo $(REVS).$(HASH) > $(HASH)/VERSION
        tar czf $(PROJECT_NAME)-$(REVS).$(HASH).tar.gz $(HASH) INSTALL
        rm -rf INSTALL $(HASH)

A: The extended glob syntax is specific to Bash. If you are willing to hardcode SHELL=/bin/bash in your Makefile (this was not mentioned when you originally posted your question), you can still use this syntax (though you should probably separately verify that the extended globbing syntax is enabled with shopt -s extglob).
For a portable solution, probably simply loop over the objects:
$(HASH):
    mkdir -p $(HASH)
    for f in *; do \
        case $$f in $(HASH)) continue;; esac; \
        cp -r "$$f" $(HASH); \
    done

(For robustness, you should probably create a temporary directory, and only move it to the final destination when it is properly populated, but that's left as an exercise.)


text:
Q: Use displaymath shorthand \[ \] for align and other amsmath environments This question is closely related to this one: Using the displaymath shorthand \[ \] for equation or align instead.  I use Multimarkdown (MMD) to generate my LaTeX documents.  MMD uses the escape character set \\[ and \\] to create displaymath shorthand \[ and \] in LaTeX.  I'd like to re-assign \[ and \] to \begin{align} and \end{align}.  The previous question had a solution for other environments (e.g., equation), but I would like to use the align environment.  According to the amsmath technical notes, it's impossible to create abbreviations for its math environments.  Does anyone know a work-around?  I have tried
\renewenvironment{displaymath}{\align}{\endalign}

but this doesn't seem to work.

A: You can use TeX's \def command for redefining \[...\]:
\def\[#1\]{\begin{align}#1\end{align}}

Minimal working example:
\documentclass{article}
\usepackage{amsmath}
\def\[#1\]{\begin{align}#1\end{align}}
\begin{document}
\[
   ax + b &= 0 \\
   ab &= 1
\]
\end{document}


text:
Q: Stretch divider and iframe to screen height On my page I have 3 dividers, for a header, content, and footer. I want to make my iframe inside my content divider stretch to the screen height, along with the divider that contains it (minus the height of the header and footer). How do I do this?

A: You can absolutely position your header/content/footer divs and relatively position the iframe within the content div:
HTML--

CSS--
#header {
    position   : absolute;
    top        : 0;
    left       : 0;
    width      : 100%;
    height     : 100px;
    background : red;
}
#content {
    position   : absolute;
    top        : 100px;
    bottom     : 100px;
    left       : 0;
    width      : 100%;
    background : green;
}
#content > iframe {
    position   : relative;
    width      : 100%;
    height     : 100%;
    background : purple;
}
#footer {
    position   : absolute;
    bottom     : 0;
    left       : 0;
    width      : 100%;
    height     : 100px;
    background : blue;
}

Here is a jsfiddle: http://jsfiddle.net/jasper/dghW4/


text:
Q: How do I change the webconsole port when running the QuestDB binary? I'm running the QuestDB Java binary using the questdb.sh script, but I don't see any way to change the web console port from 9000 to something else.
Is there a way to serve on port 80 without doing any nginx proxy shenanigans?

A: You can change the http.bind.to property in the server.conf file. It defaults to 0.0.0.0:9000, if you change it to 127.0.0.1:80 and restart the server then the web console will be served from http://localhost/.
You can visit the configuration documentation page for more information on all the properties in the server.conf file.


text:
Q: TypeError while flattening list of lists of string type I have a dataset which goes as follows:
ds = [['North','Raw','Tree'],['Saw','Raw','Apple'],['Saw','Apple'],['Gum','Saw'],......]
The dataset has 211945 values. I have imported this dataset in Jupyter and tried running the below code for making this list of lists as a single list.
Code:
     list_1 = []
     for sublist in ds:
       for val in sublist:
           list_1.append(val)

The error I got was:
  1 list_1 = []
  2 for sublist in ds:
  3     for val in sublist: <---
  4         list_1.append(val)

TypeError: 'float' object is not iterable
The expected output is:
list_1 = ['North','Raw','Tree','Saw','Raw','Apple','Saw','Apple','Gum','Saw',......]

A: You can use itertools.chain https://docs.python.org/3/library/itertools.html. This is perferct for your case, I think.
import itertools

ds = [['N','R','T'],['S','R','A'],['S','A']]

print(list(itertools.chain(*ds)))

A: Using itertools.chain() is very common idiom for this, but if you prefer list comprehensions, it can be done with the one liner
flattened = [j for i in lsts for j in i]
which is maybe easier to read.

A: new_list =[]
for x in ds:
   try:
      new_list.extend(x)
   except:
      new_list.extend([x])

I feel your lists might have some elements that aren't list. For example 'ds' might be like either [['a','b'],['c','d'],'e',['f','g']....] i.e a mixture of lists & single_elements. The above code should work as this will consider each singular element as a list in the 'except' case as & when an error occurs in 'try' case


text:
Q: Vertically aligning an inline list within a div Im trying to vertically align inline list elements within a div, however i cant figure out why its not working. I have included
.nav li{
    display: inline;
    display: table-cell;
    vertical-align: middle;
    }
.nav ul {
    vertical-align: middle;
    display: table-cell;
    margin: 0% 6% 0% 0%;
    }

Help would be much appreciated
https://jsfiddle.net/y1paacbh/
I see it may be unclear what is happening due to the way jsfiddle is presenting it. Here is an image from my browser

A: By giving this styles you can fix this issue
  .nav li {
   position : relative;
   top : 8px;
    }

A: Your are using two display property.
Use this instead
.nav li{
    display: block;
    vertical-align: middle;
    }

A: Just delete your CSS code and insert this one.
.nav {
  background-color:green;
}

ul li {
  display:block;
}

If I helped you , please check my answer , if not , explain your problem.

A: I update view for you as follow as you need it vertically

https://jsfiddle.net/y1paacbh/1/

A: I think this is the effect you are after.

* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
html,
body {
  height: 100%;
}
.nav {
  background-color: green;
  height: 30%; /* for demo purposes */
}
.nav li {
  display: table-cell;
  vertical-align: middle;
}
.nav ul {
  display: table;
  height: 100%;
}

Home

About

Contact

JSfiddle Demo

A:

body {
  height: 1000px;
}
.nav ul{
  background-color:green;
  height: 10%;
  line-height: 100px;
  width: 100%;
}
.nav li{
  display: inline;
}

Home

About

Contact

A: Not sure i understoud your question correctly, but in this way you can have elements:
1) vertically centered
AND
2) orizzontally distributed
.nav {
  background-color:green;
  height: 30px;
  width: 100%;
    }

.nav li {
  margin-left: auto ;
  margin-right: auto ;
  width:33%;
  height:30px;
  display:table-cell;
  vertical-align:middle
}

.nav ul {
  list-style-type: none; /*if you want to remove bullets*/
  text-align: center;
  margin: 0 auto;
  padding: 0px;
  display:table;
  overflow: hidden;
  width:100%;
 }

working Fiddle

A: This can be solved by using flex. It's really easy and you only need to use two rules on your parent.
align-items:center;
display:flex;

ul {
  align-items:center;
  display:flex;

  background:orange;
  height:100%;
  list-style:none;
  margin:0;
  padding:0;
}

li {
  padding:20px;
}

.nav { height:300px; }

Home

About

Contact


text:
Q: Deleting an object created with "new" Objects from my class Note are stored by keeping a pointer in a list called m_noteList:
QList< QSharedPointer<Note> > m_noteList;

I am creating an object of that class by:
QSharedPointer<Note> note(new Note(this));
m_noteList << note;

Deleting goes by (after getting the right index idx to identify the object):
delete m_noteList[idx].data();

Error message in QtCreator (Debug-mode)
HEAP[MyApp.exe]:
HEAP: Free Heap block 024FC240 modified at 02500330 after it was freed

And dissambler:
0x777349ab  <+0x0000>         cmpb   $0x0,0x2(%eax)
0x777349af  <+0x0000>         je     0x777349c6
0x777349b1  <+0x0000>         movb   $0x1,0x7774d640
0x777349b8  <+0x0000>         mov    %ecx,0x7774d644
0x777349be  <+0x0000>         int3
0x777349bf  <+0x0000>         movb   $0x0,0x7774d640   //<-- Here is a stop mark
0x777349c6  <+0x0000>         ret
0x777349c7  <+0x0000>         nop
...

I have also tried this:
m_noteList.removeAt(idx);

Which does not work either. SIGSEGV signal emitted by operating system stopped the process (Segmentation fault)
So I really don't know what I do wrong and how to get around it
My solution is quite dirty: Setting some kind of an deleted-tag to my objects, but I  need to check this in every other function to ignore that object...
EDIT:
I realised one thing: If i delete one note (with removeAt()), it is deleted (i see it by watching the console print outputs), but its gui does not disappear. Then if I click again on that object's specific button that is to delete the note, the application crashes (because it does not really exist any more, but only the gui). But if I write this deleteLater before, after deleting it, the gui also disappears and everything seems fine.
Can someone please explain, why?
m_noteList.at(idx)->deleteLater();
m_noteList.removeAt(idx);

A: You are mixing up three memory management strategies:

*

*QObject parent-child memory management: when a parent QObject is deleted, it automatically deletes all child QObjects. Explained here. Deleting the object is done automatically, so explicit deletion is not necessary.

*QSharedPointer memory management: when the last QSharedPointer referring to an object is deleted, the object is deleted. Explained here. The object is deleted automatically, so explicit deletion is not necessary.

*"Manual" memory management: new an object and delete an object at the right time. Explained in the C++ standard. The object must be deleted manually.
You should select only one of the above to make sure you don't double-delete objects. I suggest choosing between #1 and #2 depending on how you plan to use the objects. If you plan to share the objects across "parents", use #2, otherwise use #1.

A: Given a QList<QSharedPointer<Note>> m_noteList:
The deletion of the Note object is accomplished by m_noteList.removeAt(idx), assuming that there are no other extant copies of the pointer. You simply destruct the last shared pointer to a given note, and that's it. Invoking delete on a shared pointer's data is always an error.
I cannot reproduce your issue with removeAt - it will only happen if you delete the Note first, which you're not supposed to do.


text:
Q: How to keep count of go routines that are dead? I have a piece of code where we run multiple go routines multiple to receive values. I am trying to keep count of how many go routines have died due to some exception or error. I don't want to update the count for normal execution.
  for {
    go func(){
       err := receiveValues()

    }()
  }

Here, receiveValues will call other function and return err if they fail
func recieveValues() error{
  if err, val := callSomeFunc(); err != nil{
    return err
  }

  if err2, val2 := callOtherFunc(val); err2 != nil{
    return err2
  }
}

I could check when receiveValues() returns error and increment my count, but I also want to increment my count when go routine exits due to some panic or errors that I didn't expect, what will be the fool proof way to keep track to how many go routines have died?

A: Use deferred function that will recover from panic.
func count() {
    err := recover()
    if err != nil {
        // count error
    } else {
        // count no error
    }
}

func trap() {
    defer count()
    if rand.Intn(2) >= 1 {
        panic("bad luck")
    }
}


text:
Q: How do I separate subplots? I have the following code
import glob
import numpy as np
import os

import matplotlib.pyplot as plt
import random
import matplotlib.image as mpimg
# Visualizations will be shown in the notebook.
%matplotlib inline

test_list= glob.glob('Outside_Test/*.jpg')
print(test_list)

print("test images shape")
for i in range(len(test_list)):
    print(test_list[i])

print("-----")
fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(5,50))
fig.tight_layout() #  tried this too -> (pad=1.0)
for i in range(len(test_list)):
    image=np.array(mpimg.imread(test_list[i]))
    axs[i].imshow(image)
    axs[i].axis('off')

    _, test_file = os.path.split(test_list[i])
    print(test_file)
    print(image.shape)

    label_str = test_file[3:-4]
    print(label_str)

    axs[i].set_title(label_str,fontsize=10)

However when I do this I get

in which the titles are one over the other.
How do I separate these subplots farther? I tried pad but did not work
EDIT: If I put the tight layout after the for I get

A: Your titles too long while the vertical dimension is to short. Try playing with figsize:
# roughly 1 x 5 aspect ratio here
fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(10,50))

axs = axs.ravel()
for i in range(5):
    axs[i].imshow(np.arange(1024).reshape(32,32))

    # and also playing with `fontsize` here:
    axs[i].set_title('A very long long long title', fontsize=10)
    axs[i].axis('off')

fig.tight_layout()

Output:


text:
Q: Existence of a symplectic orthogonal transformation between A and B Let's consider two symmetric real  matrices $A$ and $B$ of dimension $2N$ and with the same (algebraic) eigenvalues, possibly degenerate.
Is there a simple criterion to tell whether there exists or not a symplectic orthogonal matrix $S$ that transforms $A$ into $B$  ?
$$B=S^\top A  S  $$
Can I build explicitly such a matrix ?
Thanks,
Olivier


text:
Q: In what ratio does the line joining the two intersection points of a circle divide the line joining their centres Say a circle of radius R1 and another circle of radius R2 intersect each other at two points. Then, what would be the ratio in which the line that joins the intersection points divide the line joining the centre? I need to know this for a high school physics problem.
EDIT: If required, consider that the distance b/w the centres is given.
EDIT 2: The reason I'm not directly asking the physics problem is that this sub-problem is interesting in itself and something that I would like to know regardless. If someone needs to know the physics problem:
A mass 'm' is attached to two ideal ropes of of length L1 and L2, whose other ends are attached two a wall above, D distance apart. Calculate the tension in each rope.


text:
Q: Elasticsearch - how store data, nested or array? Help me please.
How to make the best document scheme for such data?
There are data on the number of products in each city:

*

*product1, [city = city1, available = 0], [city = city2, available = 2], [city = city3, available = 1], ...
...

*product100, [city = city1, available = 1], [city = city2, available = 1], [city = city3, available = 1], ...

How can this data be saved for each of the products if the products can be 1000 and cities can be 100 and that the city-available search work?

A: It completely depends on the way you want to query the data.
When we store data as an array of objects, we lose correlation.
So if you store your data like-
prodId : id,
availability: [
    { city: city1, available: true},
    { city: city2, available: false}
   ]

ES will internally flatten the objects while indexing and it will be indexed as -
availability.city= [city1,city2]
availability.available= [true,false]

Now if you want to check for products which are available in city2, this document will qualify.
If you want to maintain the correlation, you should go with nested objects. Nested objects are considered as separate documents and managed internally by ES. The joins are performed internally by ES so you don't have to worry about it and you can run aggregations over it. On the down side, nested objects slow down the system as more shard level communication is required.

A: I would store them as follows:
{
  "product" : "product1",
  "city-avail" : [
      {
        "city" : "city1",
        "available" : 0
      },
      {
        "city" : "city2",
        "available" : 1
      }
    ]
}
{
  "product" : "product2",
  "city-avail" : [
      {
        "city" : "city3",
        "available" : 1
      },
      {
        "city" : "city2",
        "available" : 0
      }
    ]
}

A: For complex data (like key value pairs) I would use a nested field type. For simple data, like an array with numbers or strings I use array field type.
So in your case, if you are going to associate "objects" with city and available items I would use a nested field. Then you can search and aggregate by nested fields.

A: Your dataset (1000 products/100 cities) is very small. If you do not expect it to scale to be much larger, you can probably use a nested data structure (which is the most obvious solution here). Your mapping would look something like this:
{
  "product": {
    "properties": {
      "product": {"type": "keyword"},
      "cities": {
        "type": "nested",
        "properties": {
          "name": {"type": "keyword"},
          "available": {"type": "integer"}
        }
      }
    }
  }
}

Then you would index documents that look like this:
{
  "product": "product1",
  "cities": [
    {
      "name": "city1",
      "available": 0
    },
    {
      "name": "city2",
      "available": 1
    }
  ]
}

However, nested queries and aggregations are expensive/slow, so if you expect your dataset to grow substantially, you may want to consider denormalizing your data. In your case, I can see a few possible ideas for this, which will depend on how you want to query your data.
Simple flattening (one doc per city/product combo):
Doc 1:
{
  "product": "product1",
  "city": "city1",
  "available": 0
}
Doc 2:
{
  "product": "product1",
  "city": "city2",
  "available": 1
}

The down side here is that you can't easily search by product (since the products are duplicated). You may be able to resolve that by keeping a separate index of products to query when you need to query in that way.
In case you never expect to get more cities than 100 (or 1000), you could have one field per city, like this:
{
  "product": "product1",
  "city1": 0,
  "city2": 1,
  ...
}

Note that in case you do this, you don't actually need to have all the cities in each source document -- missing keys are fine. The "down side" of this is that you need to know in advance the name of the cities you're interested in (in order to query), in order to query. Probably this is not the right solution for you, but it is useful in some use cases.
In case your available numbers are always low, and you expect this to always be the case (like if you never expect to have more than 10 available), you could do something like this:
{
  "product": "product1",
  "available": {
    "0": ["city1", "city2"],
    "1": ["city2"],
    "2": [],
    ...
  }
}

So if you want to see if city1 has the product (regardless of whether they're available), you can query available.0, and if you want to see if it has at least 1 available, you can query available.1, etc. If you want to see cities where product1 has at least 1 available, you can do a terms aggregation on available.1. In case you are using this kind of a data structure, you would probably want to add another field, which will contain the exact numbers for each city (not nested, so not very useful for querying, but for convenience after you've retrieved the data).


text:
Q: Find item from Viewbag.List My controller code is as follows
ViewBag.Districts = (from a in _dbContext.DISTRICTS
                     select new ComboItem {
                                            ID = a.DISTRICT_ID,
                                            Name = a.DISTRICT_NAME
                                          }
                     ).ToList();

My Razor View code as follows
@foreach (var dist in ViewBag.Districts)
{
    if (item.DISTRICT_ID == dist.ID)
    {
        @dist.Name
    }
}

Is there a way I can find item in ViewBag.Districts like ViewBag.Districts.where(m=>m.ID==item.DISTRICT_ID.
or linq expression so that i can avoid looping.
Anyone helps me greatly appreciated.

A: Viewbag is dynamic so compiler won't be able to identify its actual Type, so you need explicit type cast like this to work with Enumerable methods:-
((IEnumerable<ComboItem>)ViewBag.Districts).Where(x => x.ID == item.DISTRICT_ID);

I am assuming you want to use this in your View, Also the foreach loop you have posted won't work without explicit casting:-
@foreach (var dist in (IEnumerable<ComboItem>)ViewBag.Districts)
{
    if (item.DISTRICT_ID == dist.ID)
    {
        @dist.Name
    }
}


text:
Q: Can we ignore a c# list from class property? Is there any mechanism in c# to ignore List if its null?
public class VehicleResponse
  {
        public Pagination pagination { get; set; }
        public Vehicles data { get; set; }
        public Include include { get; set; }
    }

Here Include class property might be null. If it's null then i want to ignore that property.
 public class Include
    {

        public List<Devices> devices { get; set; }
        public List<Institutions> institutions { get; set; }
        public List<Cars> cars{ get; set; }
    }

This is the class of include. If any List like devices or institution or cars is null then it should ignored.
I don't want to display null value in my json response. If they null just ignore them.

A: You have to create an empty constructor that initializes those lists the JSON result would be empty lists.
public class Include
    {
        public Include(){
           devices = new List<Devices>();
           institutions = new List<Institutions>();
           cars= new List<Cars>();
        }
        public List<Devices> devices { get; set; }
        public List<Institutions> institutions { get; set; }
        public List<Cars> cars{ get; set; }
    }

EDIT
I've just found this .NET Core: Remove null fields from API JSON response i hope it can help. Otherwhise i suggest you write your own OutputFormatter


text:
Q: Angular 2 | Firefox & Ms Edge - type error + docType error I'm building a Angular 2 app for different browsers. I got the latest versions of firefox, edge and Chrome. The angular app works perfectly on Chrome.
In firefox i get this error message:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

And this one too:

EXCEPTION: TypeError: result.subscribe is not a function.

Are there functions that I can not write in Typescript for Firefox?
And is there something like CanIUse but for angular 2 / typescript?
**fixed see Edit 1.
In Edge i cant even open the page, i get this error:

HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: "".

But i have a <!DOCTYPE html> in my index.html.
EDIT 1 // 24-05
The Edge problem was due to 'localhost' i had to build a IIS webpage.
But now it still does not work.
I see all the JS code running without (alot) of errors, but i can not see anything on the page. All the HTML is loading in the DOM, but the screen stays empty. I get a warning that html tags are not recognized (but they are angular 2 tags..)
I think I should use the <div app-view></div> notation. Will try tomorrow.
EDIT 2 // 09-06
found the solution a couple of days ago.
The api sent a XML back in Firefox in stead of a JSON object.
Added a ACCEPT header: Json and solved this. Chrome does this by itself, but firefox does not.
Hope it helps someone !


text:
Q: How to automatically "normalise" a voltage signal in LTspice? I would like to create an output signal that is normalised by the maximum value of a signal in LTspice. This is to produce a signal between [-1, 1] that is suitable for producing a wave file like found here i.e.

.wave "z:/home/runejuhl/out3.wav" 16 44100 out1

Signals will clip the wav file if they exceed a magnitude of 1.
Currently I am using a voltage controlled voltage source to reduce the overall level by a constant factor:

This works ok, but doesn't maximally utilise the range of [-1, 1], and requires manual adjustment to adapt to changes in signal level.
I would like to set the gain factor such that it is equal to 1/max(Vout). Completing this in a single analysis command seems impossible as it would introduce a delay-free loop, the normalisation factor would be dependent upon something currently being calculated.
Is it possible to calculate a value from one simulation and use that in a following simulation? Preferably automatically without having to manually perform the calculation and place the result in the schematic.

A: If you don't mind two runs, you can add a .meas peak max abs(v(x)) directive (v(x) being the needed voltage, an example), then use the reverse of that measured value as the gain. Otherwise, you'll have to either provide an estimate gain, or export your trace and do the normalizing elsewhere (or even LTspice).

This is just a corollary for @Huisman's answer, to add a picture of what I meant in the comment:

This is just for exemplification. I've let it run for 8s, but the useful signal goes from 0..4s, and the output (V(z)) starts at 4s. The simulation card can (should) be modified to start saving only after 4s.

A: Avoiding the voltage drop from the diode in a peak detector circuit
An arbitrary behavioral source with delay(x,t[,tmax]) is the key.

*

*add a spice directive .param samplerate=44kHz duration=1sec

*set the simulation command to .tran 0 {2*duration} 0 {1/samplerate} (EDIT: original .tran 0 {2*duration} {duration} {1/samplerate} doesn't work)

*add an independent voltage source with the .wav file as value and label its output "original".

*add an arbitrary behavioral source, label its output "running_max" and set its value to V=max(delay(v(running_max),1/(bitrate)),abs(v(original)))

*add another arbitrary behavioral source with value V=1/(1mV+v(running_max))*delay(v(original),filesize/bitrate) and label its output "result"

*File -> Export data as text

When plotting "running_max", you'll see the signal is collapsing/dropping after each peak of "original". I've no idea why. This eventually makes "running_max" to become less than the maximum absolute value of "original". And so, the result will be exceeding [-1,1].
Decreasing the minimum step time, or increasing samplerate=10*44k, improves "running_max", but, at the cost of (much more) simulation time.
P.S. The solution with the diode won't work, because even the ideal diode seems to have a leakage current, which lowers the voltage on the capacitor.
EDIT: I used .tran 0 {2*duration} 0 {1/samplerate} all the time. Unfortunatelly, .tran 0 {2*duration} {duration} {1/samplerate} doesn't work, because the delay function won't work... You could work around this by opening another instance of LTSpice and repeat step 1 and 3 with .tran 0 {2*duration} {duration} {1/samplerate} and the new .wav file, and step 6.
So long for automation...
Automated method using a peak detector circuit
The problem with above method is that in introducing a delay() element the simulation takes a much longer time to complete. Because of this the use of a peak detector circuit may be an acceptable solution.
An ideal diode can be defined as noted in this question

.model Didl D(Ron=0.0001 Roff=100G Vfwd=0)

This can be rolled into a peak detector circuit using a capacitor and a voltage controlled voltage source to prevent loading the previous circuitry:

which over time does decay due to the non-ideal behaviour of the diode, but this is an acceptable trade for my purpose. The effect will be a slight amplitude modulation resulting in some side-bands, but should be largely imperceptible.
Here is an example drop in voltage from the peak detector:

The normalised output voltage can then be found from a behavioural voltage source bv:

Two elements must be considered: first the peak voltage is exaggerated here to prevent any clipping, multiplying by 1.1. Second, the initial condition on the capacitor should be set to something reasonable, as if it is 0 initially the simulation will get some crazy voltages. This is achieved through setting SpiceLine: IC=1e-3 or some other similar value.
The final step not possible when using the delay operation is to run the simulation twice but only save data on the second run. The peak detector will have charged to the peak value already and therefore is already normalising the signal. This is an additional benefit as you can immediately save the wav file without having a first section that clips horribly.
I used .tran 0 {2*dur} {dur} {samplePeriod} where `.param samplePeriod=1/44.1e3' and 'dur=3'.
Testing this in my circuit for click-pop measurements, here are the un-normalised voltage in blue and the normalised voltage in green:


text:
Q: Wiris MathType does not parse MathML on Vue Component reload I am working on a Vue JS app which has MathType plugin and the plugin works fine when the formula is entered and it is displayed in the correct format. But when the component is destroyed and created again and the previously entered data is passed into the component using v-model, the MathML code is intact (as observed in Vue inspector) but only the raw text content is shown in the editor and the equations are not parsed to the image format. If I reload the entire page with the v-model containing formulae, MathType parses it and displays the correct images. Is there a way to trigger this parsing for dynamically/programatically added text in CKEditor 4? Here is my code:
<template>
    <div>
        <input v-bind:name="fieldName" type="hidden" v-model="content" />
        <ckeditor v-bind:editor-url="editorUrl" ref="editor" v-bind:config="editorConfig" v-model="content"></ckeditor>
    </div>
</template>

<script>
    import CKEditor from 'ckeditor4-vue';
    export default {
        props: {
            currentContent: {
                type: String,
                default: null,
            },
            fieldName: {
                type: String,
                default: 'content',
            },
            toolbarType: {
                type: String,
                default: 'Full',
            },
        },
        data: function () {
            return {
                editorConfig: {
                    embed_provider: '//ckeditor.iframe.ly/api/oembed?url={url}&callback={callback}',
                    mathJaxLib: '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML',
                    protectedSource: [/<u[^>]><\/u>/g],
                    toolbar_Exam: [
                        ['Cut', 'Copy', 'Paste', 'PasteFromText', 'PasteFromWord', 'Undo', 'Redo'],
                        ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'],
                        ['Outdent', 'Indent', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
                        ['Table', 'HorizontalRule', 'Smiley', 'SpecialChar'],
                        ['Styles', 'Format', 'Font', 'FontSize', 'TextColor', 'BGColor'],
                        //['oembed', 'MediaEmbed'],
                        ['ckeditor_wiris_formulaEditor', 'ckeditor_wiris_formulaEditorChemistry'],
                    ],
                    toolbar_Full: null,
                    toolbar: this.toolbarType,
                    allowedContent: true,
                    extraAllowedContent: 'math[xmlns]; maction; maligngroup; malignmark; menclose; merror; mfenced; mfrac; mglyph; mi;' +
                        'mlabeledtr; mlogdiv; mmultiscripts; mn; mo; mover; mpadded; mphantom; mroot; mrow; ms; mscarries; mscarry;' +
                        'msgroup; mstack; msline; mspace; msqrt; msrow; mstack; mstyle; msub; msup; msubsup; mtable; mtd; mtext; mtr;' +
                        'munder; munderover; semantics; annotation; annotation-xml;',
                },
                editorUrl: siteUrl+'/vendor/ckeditor/ckeditor.js',
            };
        },
        components: {
            'ckeditor': CKEditor.component,
        },
    };
</script>

A: I have fixed this problem by using the Generic Wiris MathType Plugin https://www.npmjs.com/package/@wiris/mathtype-generic and importing the wirisplugin-generic.js script and using the WirisPlugin.Parser.initParse on the content variable in the component in the mounted function.
mounted() {
 this.content = WirisPlugin.Parser.initParse(this.content);
}

And this has resolved the issue.


text:
Q: Sleep identifier not found visual studio 2017 Just as mentioned in the documentation as well as online forums, I've used the Sleep function in the following way:
#include <windows.h>
...
Sleep(4)

Still I'm getting the build error:
'Sleep': identifier not found

I'm using Visual Studio 2017 on Windows 10

A: Solution:
Include the required headers in stdafx.h which is in the project folder created


text:
Q: HTML form submitting data only on second submission for certain browsers I have a simple loginpage that shows a username and password login section and when the login button is pressed the form data gets sent back to the page for processing. If the data is valid and they`ve logged in successfully it directs them to a homepage, if not it shows them the login screen again and tells them what they did wrong (incorrect password, empty field, etc).
My problem is that for certain browsers (Chrome and Opera) the form needs to be submitted twice in order for the data to be set(Literally set, I've checked this using isset, empty & is_null checks).
I've read that there have been problems with this before on certain browsers (Chrome & IE), but the only other solution I found was to use javascript to pass the information instead. Is there anything I can do to make the form more "browser friendly"?
Update 1
Here's the form, its as basic as you can get, nothing special about it.
<form action="loginpage.php" method="POST">
Username: <input type="text" name="Username" autofocus="autofocus" />

Password: <input type="password" name="Password" />

<input type="submit" name="submit" />
</form>

Update 2
PHP Code
if (isset($_POST['submit']))
{
    if ($_POST['Username']=="" || $_POST['Password']=="")
    {
        echo '";
    }
    else
    {
        $username = $_POST['Username'];
        $password = $_POST['Password'];

        $sql = "SELECT * FROM Logins WHERE `Username` = '$username'";
        $validate = mysql_query($sql);

        while ($check = mysql_fetch_array($validate))
        {
            if ($password != $check['Password'])
            {
                echo "";
            }
            else
            {
                header("Location: streaming/videosearch.php?order=dated&q=*");
            }
        }
    }
}

A: Try adding a value attribute to the submit button. It occurs to me that without even a blank value, some browsers might not send the submit button back in the POST:
<input type="submit" value="login" name="submit" />

Also, try printing out the contents of the $_POST superglobal to help debug:
print_r($_POST);

A: Solution by OP.
The variables were being sent as lowercase despite being Propercase.
Solution:
Never put capital letters in the names of the form elements.


text:
Q: Windows hard disk read-only now Windows is removed I recently installed Ubuntu over Windows,
Windows is removed now and Ubuntu is installed
I forgot to turn off fast-boot, and now all Windows drives are read-only
I cannot open Windows and turn off fast-boot because Windows is removed
Please give some suggestions or solution.
Thank you


text:
Q: Find the distance between greater than 100K locations I have two MySQL tables with locations, table1 and table2 (see below). There are > 100K rows in each table. I'd like to find the distance between every location in these two tables using their geolocations.
Here is the MySQL query to find the distance between a single geolocation, e.g, (-37.22, 88.88) and all the locations in table1.
$lat = -37.22;
$long = 88.88;

SELECT id, latitude, longitude, name
        ((2 * 3960 *
          ATAN2(
            SQRT(
              POWER(SIN((RADIANS($lat - latitude))/2), 2) +
              COS(RADIANS(latitude)) *
              COS(RADIANS($long)) *
              POWER(SIN((RADIANS($long - longitude))/2), 2)
            ),
            SQRT(1-(
              POWER(SIN((RADIANS($lat - latitude))/2), 2) +
              COS(RADIANS(latitude)) *
              COS(RADIANS($long)) *
              POWER(SIN((RADIANS($long - longitude))/2), 2)
            ))
          )
        )) AS distance FROM table1 ORDER BY distance;

Table1
id name latitude longitude
1   foo1    -37.12   62.34
2   foo2    -47.12   72.34
3   foo3    -57.12   82.34

Table2
id name latitude longitude
1   bar1    -38.22   66.11
2   bar2    -48.22   76.11
3   bar3    -58.22   86.11

Given that this is also a big data, I'm not sure where to start. Thoughts?

A: *

*If you want optimize travel or get near location you should go for spatial functions http://dev.mysql.com/doc/refman/5.7/en/spatial-extensions.html

*But looks like you want every calculation so yes you will need do 10 billions operations.

*

*I guess time isnt really a problem here. Because once you have it you can use it. And if new locations arrive just calculate distance against that location.

*But you have to optimize. The most cost part of the query is calculate SIN() and COS() so create aditional field to each row with those value. So you have to do it only once and not 100k times for each row

*Finally run a loop so you create the data in blocks.

EDIT:
After reading your last comment. You need a spatial index. The same way as you search one ID on your db, the spatial index will optimize your nearby search.
Also you can do box search. Instead of seach the whole universe you create a box around your point and search inside that box. Using normal float index you do something like this
  SELECT t1.name, t2.name,  mysql.Distancefunction(t1,t2) as distance
  from t1
  cross join t2
  WHERE t2.x between (t1.x - 0.001) and (t1.x + 0.001)   -- use x float index
    and t2.y between (t1.y - 0.001) and (t1.y + 0.001)   -- use y float index
    and mysql.Distancefunction(t1,t2) < 100 km           -- use spatial index

You can play with the delta 0.001. If you get too many results you use 0.0001. If you get few result you do a second step with 0.01 only for those locations without 100 neighbors.


text:
Q: List Hibernate configuration parametrs Is there a way to programatically get Hibernate configuration parameter values, if I have access to a SessionFactory object?
I would like to list the configuration in a GUI view, for debuging purposes.

A: If you cast your SessionFactory into the concrete SessionFactoryImpl implementation, then you'll have access to the properties coming from the Configuration through getProperties().


text:
Q: How does D3 node selection work in D3 force graph? I'm trying to create a force graph and inserting foreignObject for each node.
    simulation
            .nodes(graph.nodes)
            .on("tick", ticked)
            .on("end", graphended);

       var node   = svg.append("g")
                    .attr("class", "nodes")
                    .selectAll("circle")
                    .data(graph.nodes)
                    .enter().append("foreignObject")
                                 .attr("width",img_w)
                                 .attr("height",img_h)
                            .append("xhtml:body")
                            .html(function(d){
                                return 'Some sample content';
                            })
                            .call(d3.drag()
                                    .on("start", dragstarted)
                                    .on("drag", dragged)
                                    .on("end", dragended));

and in TICK function I've following way to assign x and y coordinates.
function ticked() {
            node
                .attr("x", function(d) {
                    var xPos = findPosX(d.x, img_w);
                    return xPos-img_w/2;
                })
                .attr("y", function(d) {
                    var yPos = findPosY(d.y, img_h);
                    return yPos-img_h/2;
                });
        }

But in this tick method, instead of giving x and y Position to foreignObject it is assigning position to body element inside the foreignObject, which is making the node not position at actual coordinates.
Now, the code does work (if I remove foreignObject and place another element tag and the position is given to that element), so I think there is a problem in my selector and append statement that creates foreignObject above, as it is selecting inside body of the element.

A: d3 method chaining returns the last thing that returns something, in your case this is the .append("xhtml:body"), so node is holding a reference to that not to the foreignObject.  Change your code to:
var node = svg.append("g")
 .attr("class", "nodes")
 .selectAll("circle")
 .data(graph.nodes)
 .enter().append("foreignObject")
 .attr("width",img_w)
 .attr("height",img_h);

node.append("xhtml:body")
  .html(function(d){
    return 'Some sample content';
  })
  .call(d3.drag()
  .on("start", dragstarted)
  .on("drag", dragged)
  .on("end", dragended));


text:
Q: Laravel api CORS error when posting from js I have made an API with Laravel and I am getting an error when I am trying to make a post. I don't know if I need to send the crsf from javascript or if I have made the cors middleware wrong.
When I make a get to the API I don't have any cors issue.
This is my middleware. It has been added on the kernel.php file.
class Cors{
    public function handle($request, Closure $next) {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With, x-xsrf-token, ip');
    }
}

On javascritp I have added this: 'Content-Type': 'application/json' on the header.
And this is the error that it's giving to me
Access to XMLHttpRequest at 'http://localhost:8000/api/user/1/videos/1/newComment' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Thanks you a lot for your help.

A: Try adding this to the top of the index.php in the root of your project...
    <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    ?>


text:
Q: My screen lost the signal after the boot of my Raspberry Pi 4 I have an issue with my Rpi4 and my screen. I just installed a Raspian version on my SD card and I can see the starting of my Rpi4 (with all the lines) but I lost the signal of my screen just after. I can access to my Rpi with SSH but I would like to keep the screen in case of problem.
I tried to plug in both of the small HDMI port without any change.
My screen is a Dell brand (model S2421HS) and works well.
Could you please help me to resolve this problem ?
Many thanks.
Smilorel


text:
Q: How come CSS backgrounds are intermittently invisible in Google Chrome? Here's a website I've designed:

*

*https://www.pensioenfondssdb.nl/
This is what it looks like in Firefox 4 beta 9 on Mac OS X 10.6.6:

*

*https://skitch.com/znerd/rkf67/schermafbeelding-2011-01-19-om-21.56.11
It looks similar in IE 8, Opera and Safari.
But this is what it looks like in Google Chrome 8.0.552.237 on Mac OS X 10.6.6:

*

*https://skitch.com/znerd/rkf9g/schermafbeelding-2011-01-19-om-21.52.11
Somehow most of the background images are gone. I checked with the Inspector, but the rules are there.
Sometimes Chrome does show the background images for a while and then after a while when I do a reload the images are gone. Odd.
Is this just me?
If not: What can I do to work around this issue?

A: When I looked at this in fiddler the first time I hit your site with chrome it only did the request for the page and didn't request the images.  The second time I got the 4-5 requests for the images.
Could you try and switch the page to http just for the moment to see if that changes anything?

A: I just had this same problem - posted about it here:
backgound-image doesn't display intermittently. Google Chrome on Mac
I think it has to do with Chrome sometimes failing to cache the image properly.


text:
Q: imagemagick convert command i have question regarding the convert and linux command in generate. i need to convert images using imagemagick
i do:
convert -quiet -regard-warnings image.jpg -colorspace RGB +repage /tmp/tempfile.img

that works
now, when i do:
convert $tmpA1 -median 2 -clut $tmpA2

i get:
convert: missing an image filename `/tmp/cartoon_2_17950.mpc' @ error/convert.c/ConvertImageCommand/2970.

after 3 day of searching i found this:
convert \( $tmpA1 -median 2 \) -clut $tmpA2

and it works
what is the purpose of the ( and )??

A: Parenthesis limit the scope of an action. In this case it applies the median filter to just this input image, and then does something with that. You can read more about this in the manual (scroll down to Image Stack) and here's the extract:

In school, your teacher probably permitted you to work on problems on a scrap of paper and then copy the results to your test paper. An image stack is similar. It permits you to work on an image or image sequence in isolation and subsequently introduce the results back into the command line. The image stack is delineated with parenthesis. Image operators only affect images in the current stack.


text:
Q: How to set space between TextBox values into array How to set space between TextBox values into array?
TextBox values:

1 32 54 76 89 89 454 23

Expected output array:
value[1]=1;
value[2]=32;
value[3]=76
...

A: Try this:
var numbers = textBox1.Text.Split(' ');
List<int> lst = numbers.Select(item => int.Parse(item)).ToList();

It will be even better if you use method group like this:
List<int> lst = numbers.Select(int.Parse).ToList();

Then you can get it's values like this:
lst[0] --> 1
lst[1] --> 32
and ...

A: You first have to split the users input:
var values = myTextBox.Text.Split(' ');

Now you can easily set your array of integers:
var myArr = values.Select(x => Convert.ToInt32(x)).ToArray();

Alternativly you can also use Int.Parse instead of Convert.ToInt32.

A: String[] values = tv.Text.Split(' '); // the values as string

int[] arr = new int[values.Length];   // the values as integer
for (int i = 0; i < arr.Length; i++)
    arr[i] = int.Parse(values[i]);

A: If I understand you correct you need to create int array from string you can do it like this:
string TextBoxText = "1 32 54 76 89 89 454 23";
var value = TextBoxText.Split(' ').Select(Int32.Parse).ToList();

Then you can use your array like this:
Console.WriteLine(value[1]);
Console.WriteLine(value[2]);

TextBoxText should be Text property of your TextBox component.


text:
Q: Show that for real numbers $a,b\ge0$ $ab\le\frac{a^p}{p}+\frac{b^q}{q}$ Let $p$ and $q$ be positive real numbers such that $\frac{1}{p}+\frac{1}{q}=1$. Show that for real numbers $a,b\ge0$
$ab\le\frac{a^p}{p}+\frac{b^q}{q}$
I do not know how to approach this. Any help/hint will be appreciated.

A: I have posted a link with the proof in a comment. If you prefer a hint, use that the function $\ln$ is concave.


text:
Q: Questions migrated to Meta do not have required tags To ask a question on Meta you have to choose one of the required tags (discussion, feature-request, bug, support, etc.) but when a question gets migrated over from another site, these tags are almost always absent.
Is this something that anyone should be concerned about?

A: Well, I don't see how we can have a better system than to just edit the required tag on there. I guess we could totally blow out the close dialog:

*

*Belongs on meta.stackoverflow.com as a Discussion

*Belongs on meta.stackoverflow.com as a Bug

*Belongs on meta.stackoverflow.com as a Support

*Belongs on meta.stackoverflow.com as a Feature Request

*Belongs on meta.stackoverflow.com as an Impressive Example of Stupidity
But, really, I think we just have to be diligent and edit the tags as they come through. Otherwise, there's no way to systematically tell what should go where.


text:
Q: ETCS and existence of complements of sets In An Elementary Theory of the Category of Sets Lawvere argues in Theorem 5 that

Given any subset $A\stackrel{a}{\rightarrow}X$ there is a subset $A'\stackrel{a'}{\rightarrow}X$ such that $X\cong A+A'$ and $a$ and $a'$ are the two injections: thus $x\in a'$ iff $x\in X$ and $x\notin a$, and $a$ has a characteristic function $X\rightarrow 2$.

Basically he builds the family of sets not intersecting $a$ in the following way: he considers the arrow
$$A\times1\rightarrow 1\stackrel{i_0}{\rightarrow}2$$
Where $i_0:1\rightarrow2$ is chosen to represent "false" and $i_1:1\rightarrow2$ represents "true".
Then by exponential adjuction he gets an arrow $j_0:1\rightarrow 2^A$, that is an element $j_0\in 2^A$, and defines $\mu:\mathcal{A}\rightarrow2^X$ as the equalizer of the arrows $2^a:2^X\rightarrow 2^A$ and $2^X\rightarrow1\stackrel{j_0}{\rightarrow}2^A$; we can see this arrow $\mu$ as representing the family of subsets of $X$ which do not intersect $A$. He then builds the union of this family (which can be done by Theorem 4) and shows that indeed $A+A'\cong X$.
We know that each one of these subsets given by is "special", meaning it has a characteristic function. But how can we derive that $A$ also has a characteristic function?
EDIT: I guess it is sufficient to consider the arrows $$A\rightarrow1\stackrel{i_1}{\rightarrow}2$$ and $$A'\rightarrow1\stackrel{i_0}{\rightarrow}2$$
One gets a unique arrow
$$A+A'\cong X\stackrel{\phi}{\rightarrow}2$$
And $\forall x\in X$, then $x\in A \Rightarrow \phi(x)=i_1$ and $x\notin A\Leftrightarrow x\in A' \Rightarrow \phi(x)=i_0$. But then
$$\forall x\in X,\ x\in A\iff \phi(x)=i_1$$
which is exactly the definition of a characteristic function for $A$.


text:
Q: DL element with DT / DD as equal column widths on one row So for specific reasons I'm trying to use the dl (Description List) html element. I wanted the elements contents to display each dt and dd on their own row which I accomplished as such..

div {
  padding: 1rem;
  color: #fff;
  background-color: rgba(0,0,0,.8);
}

dl dt, dl dd {
  display: inline;
  line-height: 1.75rem;
}

Cryptids of Cornwall:

Beast of Bodmin

A large feline inhabiting Bodmin Moor.

Morgawr

A sea serpent.

Owlman

A giant owl-like creature.

Which is really close to what I'm after, but I'm wondering if anyone knows a way with maybe Flex or Grid for a more uniformed layout like a table while still using the dl the element so the output is more like this...

table {
  border-collapse: collapse;
  color: #fff;
  background-color: rgba(0,0,0,.8);
}

table th {
  text-align: left;
  padding-left: 1rem;
}

table td {
  padding: 1rem;
}

table tr td:first-of-type {
  text-align: right;
  border-right: lightgray 1px solid;
}

Cryptids of Cornwall:

      Beast of Bodmin
      A large feline inhabiting Bodmin Moor.

      Morgawr
      A sea serpent.

      Owlman
      A giant owl-like creature.

Is there a way to accomplish this with css and explicitly using the dl element? I've tried things display: table on the parent dl with the dt and dd as display: table-cell but then I can't seem to break the into new rows after the dd along with failed attempts at using flex and css grid so wondering if someone knows a trick to teach? Thanks!

A: Here's a quick-and-dirty display: grid; implementation:

*

*The vertical tracks ("columns") are 1fr 1fr, so they're both 50% wide. I'm unsure of the best approach to make the tracks sized-to-content.

*

*I ultimately got this working by simply doing grid-template-columns: auto auto;, phew!

*There's no white border between the vertical tracks.

*

*I did try to hack it by using dl::before (making it 1px wide with a border: 1px solid white but it seems like it's currently impossible to make a grid item span all horizontal tracks when there are implicit tracks.

*UPDATE: After being inspired by this post, I was able to hack a vertical line by using an absolutely-positioned ::after element (in the
 so it has the correct horizontal position without an explicit left or right value).

*To my surprise, it does actually work very well when a
 element has multiple
 siblings (I've added one for the Mermaid of Zennor as an example). I was originally apprehensive that multiple
 elements would break the layout.

*BTW, you don't need the
 breaks in your HTML. I've removed them in my example below.

div {
  padding: 1rem;
  color: #fff;
  background-color: #333;
}

dl, dt, dd {
  margin: 0;
  padding: 0;
}

dl {
  color: #eee;
  background-color: #666;
  border-radius: 5px;
  padding: 1rem;

  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-columns: auto auto;
  grid-template-columns: auto 5px auto;
  grid-template-rows: auto [last-line];
  grid-auto-rows: min-content;

  grid-gap: 1rem;

  /* This is to allow the `dl > dt:first-child::after` to fill the height */
  position: relative;
}

/* Using this to make a vertical line won't work, see https://stackoverflow.com/questions/44052336/make-a-grid-item-span-to-the-last-row-column-in-implicit-grid
dl::before {
  content: '';
  display: block;
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: -1;
  grid-row-end: last-line;

  background-color: red;
  border-left: 1px solid white;
  width: 1px;
}
*/

dl > dt:first-child::after {
  content: '';
  display: inline;
  border-left: 1px solid white;
  width: 1px;

  position: absolute;
  top: 0;
  bottom: 0;
  /* Offset it to the right a bit using margin: */
  margin-left: 1rem;
}

dl > dt {
  grid-column-start: 1;
  grid-column-end: 2;

  /*
  `align-self` is for vertical alignment in a grid cell.
  `justify-self` is for horizontal alignment in a grid cell.
  */

  align-self: center;
  justify-self: end; /* i.e. right-align */
  text-align: right; /* This is needed so narrow-viewports don't break. */
}
dl > dd {
  grid-column-start: 2;
  grid-column-end: 3;

  grid-column-start: 3;
  grid-column-end: 4;

  align-self: center;
  justify-self: start; /* i.e. left-align */
}

Cryptids of Cornwall:

Beast of Bodmin

A large feline inhabiting Bodmin Moor.

Morgawr

A sea serpent.

Mermaid of Zennor

A popular Cornish folk tale

The parishioners at St. Senara's commemorated the story by having one end of a bench carved in the shape of a mermaid

Owlman

A giant owl-like creature.

Screenshot proof:
It looks good at a variety of viewport sizes:
Very narrow:

Normal

Very wide

A:
I've tried things display: table on the parent dl with the dt and dd as display: table-cell but then I can't seem to break the into new rows after the dd along with failed attempts at using flex and css grid so wondering if someone knows a trick to teach?

Table cells need table rows, and table rows need a table (technically a tbody, thead, or tfoot). Originally I thought that the
,
, and
 were not fit to configure into a table/grid layout since
 was the only parent element, not even
 was allowed to have
 and
 as children. Then I found out that
 is valid if a direct descendant of a
 which is the perfect position to be a table row.
If you want table behavior, assign display table type values:

Element
Property
Value
Hierarchy

display
table

display
table-caption
dl > dt

❉
display
table-row
dl > div

diaplay
table-cell
dl > div > dt

display
table-cell
dl > div > dd

❉A
 can be a direct descendant (ie child) of a
 and a parent of
 and

Using
 and table component elements for layout has been discouraged for years, but not display: table and associated values.

html {
  font: 2ch/1.75 'Garamond'
}

main {
  padding: 1rem;
  color: #fff;
  background-color: rgba(0, 0, 0, .8);
}

dl {
  display: table;
  table-layout: fixed;
  border-collapse: collapse;
  width: 80%;
}

dl>dt {
  display: table-caption;
  width: 100%;
  margin-bottom: 5px;
  padding: 0;
  border: 0;
  font-size: 1.17rem;
  font-weight: 900;
}

dl>div {
  display: table-row;
}

dl>div:first-of-type>dt {
  width: 50%;
}

dl>div:first-of-type>dd {
  width: 50%;
}

div>dt,
div>dd {
  display: table-cell;
}

div>dt {
  padding-right: 10px;
  border-right: 2px solid #fff;
  text-align: right;
}

div>dd {
  padding-left: 10px;
  border-left: 2px solid #fff;
}

Cryptids of Cornwall:

Beast of Bodmin

A large feline inhabiting Bodmin Moor.

Morgawr

A sea serpent.

Owlman

A giant owl-like creature.


text:
Q: How to set Resource file path relative to the project file? Let's say I have a directory A, and has a project file x.csproj and sln in that directory.
I also have resource file x.resources in it.
How can I set the resource file without the absolute path C:\A\x.resources, but relative path .\x.resources? I tried with x.resources but it doesn't work.

A: Just ran into the same problem.  My co-worker didn't even try to fix it in the UI but just hacked the CSPROJ file in a text editor:
CSPROJ Path: C:\foo\bar\SolutionNm\ProjectNm\ProjectNm.csproj
Res Path: C:\foo\bar\Icons.res
Original:
  <PropertyGroup>
    <Win32Resource>C:\foo\bar\Icons.res</Win32Resource>
  </PropertyGroup>

Modified:
  <PropertyGroup>
    <Win32Resource>..\..\Icons.res</Win32Resource>
  </PropertyGroup>

As long as you don't try to modify the value in the UI again, it won't complain
Cheers,
Aaron

A: I realize that the asker was using .NET, but just as an FYI, for C++ projects you have to edit your VCXPROJ file, and the resources are stored in a slightly different format near the bottom of the file.
Original:
<ItemGroup>
    <Image Include="C:\projects\dragdroptree\DragDropView\res\bmp00001.bmp" />
    <Image Include="C:\projects\dragdroptree\DragDropView\res\toolbar1.bmp" />
</ItemGroup>

Modified:
<ItemGroup>
    <Image Include="res\toolbar.bmp" />
    <Image Include="res\bmp00001.bmp" />
</ItemGroup>

Just to clarify, the paths you put in there are relative to the directory that the VCXPROJ file is in.

A: NOTE: Visual Studio sometimes puts the <PropertyGroup> <Win32Resource> too early in the .csproj, so you would need to manually edit the XML and move the <PropertyGroup> after the <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> element so the reference will be relative to the .csproj file.


text:
Q: Zenoss - Create Application Based Alert I am attempting to monitor a java-based application for running/not running status and alert based on that monitor within Zenoss.
The process class I have created works and correctly identifies the java processes is running, however, I seem unable to create an alert that will sound off when the process is killed.
To test, I have placed a test server in our production alerts category, which is tried and true, and killed the process. When testing the process class against that server, as stated, it correctly identifies the process is not running but does not send an alert. The process class has numerous devices it is monitoring, including the test server I am using.
Is there a specific trigger condition to use for a process class I have yet to find?
If anyone has any pointers I would greatly appreciate it. It seems like I need an event class of sorts or my trigger is incorrect but I have yet to figure it out.


text:
Q: Selenium : New tab is not getting opened on same browser in Chrome I'm trying to open a new tab in same browser but it doesn't seem to work. I'm using Chrome Version 58.0.3029.110 (64-bit) and Selenium 3.0.0.
I used the below code:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t");

A: try using JavascriptExecutor as below:
 ((JavascriptExecutor) driver).executeScript("window.open('https://www.google.com');");

A: You can also use Robot class with Selenium Webdriver to open a new tab. We need to follow the below three steps-

*

*Simulate pressing of Ctrl+t keys of keyboard using Robot class.

*Switch to the new tab in selenium using driver.switchTo() command.

*Open the desired link on new tab.

Code snippet-
//Launch the first URL
driver.get("http://www.google.com");

//Use robot class to press Ctrl+t keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);

//Switch focus to new tab
ArrayList<String> tabs = new ArrayList<String (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));

//Launch URL in the new tab
driver.get("http://google.com");

Source: Code snippet from Open a new tab in Selenium - ArtOfTesting


text:
Q: botocore.exceptions.ClientError: An error occurred (AuthFailure) Not sure what's going on here... I am having this error when doing a simple describe-instance using the boto3 client.
Error:
botocore.exceptions.ClientError: An error occurred (AuthFailure) when calling the DescribeInstances operation: AWS was not able to validate the provided access credentials
Code snippet:
  def get_ec2_client(aws_access_key_id, aws_secret_access_key, region_name):

    return boto3.client(
            'ec2',
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key,
            region_name=region_name
        )

  instances=client.describe_instances()

I ran this in debug so I am sure that the creds are correct. I also use the same creds with the cli and it worked, so it is a bit confused what's going on.
This was working up till yesterday so I checked the boto3 and botocore modules updates. They are updated almost daily but I don't see any breaking changes in the latest updates.
I've been at this for some time and still couldn't find the issue. Any idea anyone?
Since I am facing this issue today I am using:
boto3                    1.15.11
botocore                 1.18.11


text:
Q: Syntax for filtering out code coverage (absolute) paths in PHPUnit I'm just unit testing a single file and although it's the only one to get unit tested (good), code coverage is done on more than just this single file (bad). It covers some files in my PEAR directory for some reason I can't understand yet, so all my coverage stats are distorted.
So I'm trying to eliminate these extra files, but can't get the format right for an absolute directory:
<phpunit>

<testsuites>
  <testsuite name="My Test Suite">
    <file>AntProxyTest.php</file>
  </testsuite>
</testsuites>

<logging>
  <log type="coverage-html" target="/tmp/report" charset="UTF-8"
       yui="true" highlight="false"
       lowUpperBound="35" highLowerBound="70"/>
</logging>

<filter>
  <blacklist>
     <directory suffix=".php">c:\php\pear</directory>
   </blacklist>
</filter>

</phpunit>

is not excluding as I wish, either are forward slashes or file://c:/php/pear.

A: I assume phpunit has an issue with getting that path right on windows since i couldn't reproduce that on linux. (Using an absolute and an relative path worked fine).
Also i've heard people talk about that issue with filtering and pathes on windows.
So my first suggestion would be to just use a whitelist. I've created a small project that includes code from different folders (and all showed up in the code coverage).
But after setting this whitelist:
<filter>
  <whitelist>
     <directory suffix=".php">.</directory>
  </whitelist>
</filter>

only the code from that folder (or your file if you really one have one) show up in the coverage report.

A: I managed to catch Sebastian on IRC, co-incidentally someone else was also having problems with blacklisting. Sebastian indicated that these PEAR files I'm seeing included is a known issue and will be fixed next version.
As edorian above indicated, Sebastian also said it's a best practice to whitelist what you want anyway, and in doing so, this problem will disappear.


text:
Q: How to execute some code when user switches to a nested tabsheet? I have a TPageCOntrol which has 3 TTabSheet and some of those have further TPageCOntrol which have a TTabSheet
Sort of
Page Control 1
  TabSheet 1
  TabSheet 2
    Page Control 2
      TabSheet 2a
      TabSheet 2b
  TabSheet 3

Now, whenever one of those tabsheets becomes visible to the user I want to execute some code, but I'm not sure which event to hook.
For instance, if the user is looking at TabSheet 1 and switches to TabSheet 2 where TabSheet 2a is showing,  then I want to execute Tabsheet 2a's code, but I can't hook TabSheet 2a's OnEnter or OnShow.  And it isn't Page Control2's OnChange.
In fact, all that I can see is to put a whole bunch of switch/case into Page Control 1's OnChange event ... is tehre a better way?

A: each TabSheet has the "OnShow" event which is triggered whenever a user clicks on it and makes it visible, this should do the trick, however having a pagecontrol inside a tabsheet which has another pagecontrol as parent and so on it's pretty heavy on the UI, try using frames which you will create on tabsheet's OnShow event and destroy on tabsheet's OnHide event.
Edit:
if you choose to use TFrames inside a tabsheet, go to the "public" section of the frame, press CTRL+SPACE and type "create" so that you will override the "Create" constructor and repeat for "Destroy" so you will override that aswell

A: I hooked each PageControl's OnChange() and checked ActivePage.  It works for me, without redesigning to use frames.

A: I stricktly use the "onEnter" Event on the Tabsheets. but i they are only fired, when the focus get "into" the tabsheet. so i have manually set the focus into the tabsheet when the pagecontrol changes.
procedure TForm1.PageControl1Change(Sender: TObject);
begin
    pagecontrol1.ActivePage.SetFocus;
end


text:
Q: How to get the field values from the forms in base libreOffice? part of the code
dim oMainForm   as object
dim oColumnList as object
dim theValue    as variant

oMainForm = ThisDatabaseDocument.FormDocuments.getByName("update_rform")
oColumnList = oMainForm.getByName("rid")  #rid is the name of the field from which I need to get the value
theValue=oColumnList.getCurrentValue()
rid=theValue

When I run the macro, run time error pops up

property or method not found: getByName

I have been searching for a solution the entire day. I came across suggestions like connecting to xray tool or loading the access2base library, but I could not do it. But I do not know, why this is such a difficult task.
I am new to LibreOffice Basic programming, and databases in general.

A: The following code gets the form document definition only, not an open form, as explained at https://ask.libreoffice.org/en/question/63260/how-to-access-to-the-controls-of-a-base-form-with-basic/?answer=63280#post-id-63280.
ThisDatabaseDocument.FormDocuments.getByName()

The correct solution depends on how the macro gets called.  For example, here is some code that can be called from the main Base screen before any form is opened.  Part of the code is from https://ask.libreoffice.org/en/question/7555/open-form-via-macro-in-libreoffice-base/.
Sub getFormVal
    form_container = ThisDatabaseDocument.FormDocuments.getByName("update_rform")
    form_container.open()
    Wait 500
    oMainForm = form_container.Component.getDrawPage().getForms().getByIndex(0)
    oControl = oMainForm.getByName("rid")
    theValue = oControl.getCurrentValue()
    MsgBox theValue
End Sub

For ThisDatabaseDocument to work, the code must be in the document, not under My Macros, as explained at https://ask.libreoffice.org/en/question/94670/thisdatabasedocument-vs-thiscomponent/.
A more elegant approach than getting values from controls is to read columns from the form recordset, as described at https://stackoverflow.com/a/39770933/5100564

But I do not know, why this is such a difficult task.

Databases can be difficult to work with anyway, and learning to write LibreOffice Base macros is notoriously difficult.  However with enough effort, Base makes many things possible.

I came across suggestions like connecting to xray tool.

Yes, an introspection tool like XrayTool or MRI is essential when developing LibreOffice macros.


text:
Q: Rectangle does not fill height with other components in Layout [QML] This is what I have

This is what I want

my qml :
ColumnLayout
{
    anchors.fill: parent
    anchors.topMargin: 10
    anchors.bottomMargin: 10
    anchors.rightMargin: 10
    anchors.leftMargin: 10
    spacing: 10

    Rectangle
    {
        Layout.fillWidth: true
        Layout.fillHeight: true
        color : "#600000"
        border : 20
    }
    Button
    {
        Layout.fillWidth: true
        Layout.fillHeight: true
        text: "Button1"
    }
    Button
    {
        Layout.fillWidth: true
        Layout.fillHeight: true
        text: "Button2"
    }
}

The problem with the above layout, is that I want the Rectangle to fill 1/3 of the screen. Right now it fills maybe only 10 pixels worth of height. When I have several components in a layout, I personally expect them to fill each as much as the other. Since I know I will add more button, remove others, I don't want to just take the Layout.preferredHeight : parent.height/3. this will require lots of maintenance long term.
another thing I don't understand : 2 rectangle together will separate their space half half. 2 buttons will do the same. But as soon as I mix those two components, the button seem to take 95% of the height as opposed to the rectangle.

A: Button has implicitHeight defined automatically while Rectangle doesn't so Layout.fillHeight is not working as you wanted.
One sulotion would be to determine the size by the parent, I.e:
import QtQuick 2.4
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.12

Rectangle{
    anchors.fill: parent;

    color: "grey"
    ColumnLayout{
        anchors.fill: parent
        anchors.topMargin: 10
        anchors.bottomMargin: 10
        anchors.rightMargin: 10
        anchors.leftMargin: 10
        spacing: 10

        Rectangle{
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "#600000"
            implicitHeight: parent.height / 3
        }

        Button{

            Layout.fillWidth: true
            Layout.fillHeight: true
            text: "Button1"
            implicitHeight: parent.height / 3
        }

        Button{
            Layout.fillWidth: true
            Layout.fillHeight: true
            text: "Button2"
            implicitHeight: parent.height / 3
        }
    }
}

Another would be to override the implicitHeight property of Button like this:
import QtQuick 2.4
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.12

Rectangle {
    anchors.fill: parent;

    color: "grey"
    ColumnLayout{
        anchors.fill: parent
        anchors.topMargin: 10
        anchors.bottomMargin: 10
        anchors.rightMargin: 10
        anchors.leftMargin: 10
        spacing: 10

        Rectangle{
            id: rect1
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "#600000"
        }

        Button{
            Layout.fillWidth: true
            Layout.fillHeight: true
            text: "Button1"
            implicitHeight: rect1.implicitHeight
        }

        Button{
            Layout.fillWidth: true
            Layout.fillHeight: true
            text: "Button2"
            implicitHeight: rect1.implicitHeight
        }
    }
}

A: Like mentioned by @ניר the issue is that the Buttons have an implicitHeight set. If a ColumnLayout has multiple children with Layout.fillHeight set to true, it will use their implicitHeight or Layout.preferredHeight as a "weight" to distribute the remaining height (see QtQuick Layouts Overview: Size Constraints).
In your case you can do what you want by setting a fixed preferredHeight for all the children, no need to reference the parent or one of the siblings:
    Rectangle {
        anchors.fill: parent
        color: "grey"
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 10

            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.preferredHeight: 1
                color : "#600000"
            }
            Button {
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.preferredHeight: 1
                text: "Button1"
            }
            Button {
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.preferredHeight: 1
                text: "Button2"
            }
        }
    }


text:
Q: select2 search not working I have been working the select2 plugin for a while now and until now its been perfect.
I have a page with 3 selects that are loading data and working well, and multiple selects that are inside the popup. They are looking good but you can't write on the search field. in the main page the search is working well so i can't figure out what is the problem..
I'm workign with the blockUI plugin for the popup. I have tried z-index, destroy and starting the plugin on a callback for the blockUI function but nothing is working and I have no idea why.
the code:
<!doctype html>

<title>ff</title>
<link type="text/css" rel="stylesheet" href="http://cdn.jsdelivr.net/select2/3.2/select2.css" />

  <select  class="startselect" id="merchantList">
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
</select>

click me!

<select class="popupselect">
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
</select>

any suggestion?

A: Same problem here.
I load select2 in a tooltip (qtip2) that opens when an event contained in a jquery.fullCalendar is clicked.
The fullCalendar is itself displayed in a div, used as blockUI message that overlays my application.
Natively, the search field of select does not work properly.
With jquery blockUI version 2.57.0 (17.02.2013) I can make the search field of select2 work as expected by blocking an element in the background application and unblocking it right away:
$("#someDivInTheBg").block();
$("#someDivInTheBg").unblock();

Curiously, that workaround does no longer works with jquery BlockUI version 2.64.0 (18.07.13).
I can't figure what's going on, and I could find how to track the issue except that it's obviously in blockUI/select2 interaction.
Note that sometimes, when I try to use the select2 search field right after he's displayed, the first char I enter is displayed in the search field before it's locked.
Since there's no blockUI loading when I open the qtip, the issue may be triggered by select2 code.
Note also that the problem does not occur with another select2, located in the background application (not inside the blockUI message)
I'll try to report the problem in blockUI and select2 githubs
* EDITED: solution *
Well, the problem is simple in fact.
Select2 is divided in 2 parts:
- select2-container is placed right next to original select (or hidden input when working with dynamically loaded data)
- select2-drop is placed just before  tag (note that this element is unique and is used for each one of your select2 when you open it)
The input field .select2-input, child of select2-drop.
BlockUI, by default, disables key and mouse event for elements not located in its message, just as said by malsup, its creator, in the documentation:

// enable if you want key and mouse events to be disabled for content that is blocked
      bindEvents: true,

So, when you initialize a select2 on a field located inside a blockUI message, everything's alright except that key and mouse events are disabled in the input.select2-input field which is not inside the blockUI message but way outside near the end of your document html...
the solution is as simple as this: init your blockUI with option :
bindEvents: false,

Beware of elements that could keep or take the focus outside of blockUI elements then, because mouse and key events would not be neutralized.
Maybe a little improvement specific to select2 architecture inside blockUI can be found to make it cleaner.


text:
Q: PHP search and count specific words using preg_match_all I would like to ask for help with php regex.
i have this code :
$search = preg_match_all("/$pattern+/", $file, $matches);

for example $pattern will be "car" and string to search for "car acar caracar"
output should be 3 (1 = car,2 = caracar) but my output is 4
i want to not count a word with prefix like "acar" but it will count the pattern with suffix "caracar"
thanks for any ideas
i hope its not hard to understand and sorry for bad english

A: You can use word boundary with preg_quote:
if ( preg_match_all("/\b" . preg_quote($pattern) . "/", $file, $matches) ) {
    print_r($matches); // or echo count($matches);
}


text:
Q: Why my ram specs shows different manufacturer? So I bought these so-called "Kingston" SODIMM rams but when I hit  wmic memorychip list full  it says that the manufacturer code is 802C. That code is for "Micron Technology, Inc.". Is this normal or did the seller just deceive me?

BankLabel=BANK 0
Capacity=4294967296
DataWidth=64
Description=Physical Memory
DeviceLocator=DIMM0
FormFactor=12
HotSwappable=
InstallDate=
InterleaveDataDepth=1
InterleavePosition=1
Manufacturer=802C
MemoryType=0
Model=
Name=Physical Memory
OtherIdentifyingInfo=
PartNumber=16JSF51264HZ-1G4D1
PositionInRow=
PoweredOn=
Removable=
Replaceable=
SerialNumber=32418F63
SKU=
Speed=1067
Status=
Tag=Physical Memory 0
TotalWidth=64
TypeDetail=128
Version=

BankLabel=BANK 2
Capacity=4294967296
DataWidth=64
Description=Physical Memory
DeviceLocator=DIMM2
FormFactor=12
HotSwappable=
InstallDate=
InterleaveDataDepth=1
InterleavePosition=2
Manufacturer=802C
MemoryType=0
Model=
Name=Physical Memory
OtherIdentifyingInfo=
PartNumber=16JSF51264HZ-1G4D1
PositionInRow=
PoweredOn=
Removable=
Replaceable=
SerialNumber=FB4DA8AB
SKU=
Speed=1067
Status=
Tag=Physical Memory 1
TotalWidth=64
TypeDetail=128
Version=

A: You can find the real manufacturer of your RAM by looking at the line:
PartNumber=16JSF51264HZ-1G4D1

If you then search for this Part Number, you will find many references.
For example:

*

*PassMark Micron Technology 16JSF51264HZ-1G4D1 4GB

*Amazon:
Micron 4GB PC3-10600 DDR3-1333MHz Non-ECC Memory Module MT16JSF51264HZ-1G4D1
It is a Micron chip rebranded and sold by Kingston.


text:
Q: How do I hide the panels in fallback mode using the command line? I want to hide the panels via script.
in maverick I used
          gconftool-2 --set "/apps/panel/toplevels/top_panel_screen0/auto_hide" --type bool "true"
now I tried
      gsettings set org.gnome.gnome-panel.layout ...

but there is a problem:
     gsettings list-keys org.gnome.gnome-panel.layout

tells me:
     object-id-list
     toplevel-id-list

but in dconf editor there are 2 subfolder layers called toplevels and then top-panel /bottom-panel
I have no idea how to get there.
it should be
toplevels.top-panel auto_hide true
I tried all different things to get there...no way. does that mean you cannot change these values from commandline any more?

A: As an alternative to gsettings you can use dconf from the command line as well.
For example
dconf write /org/gnome/gnome-panel/layout/toplevels/bottom-panel/auto-hide true

This will write the value TRUE to the auto-hide key.
If you need to see the keys in a path then use the list parameter
For example:
dconf list /org/gnome/gnome-panel/layout/toplevels/top-panel/

Remember to start with a / and end with a / for paths.


text:
Q: django how render 2 classes form forms in template I am trying to render 2 classes in forms and display it in another template, i have no idea on what to do and help would be appreciated so much
here is my code in forms.py
class sample_tableform(ModelForm):
name = forms.CharField( max_length=50, label = ("name"),  help_text = ("Name:"),
    error_messages = {'invalid':"Your name may only contain letters.", 'required':"Enter your name.", 'unique':'Name already exists'}, validators=[RegexValidator( regex='^[a-zA-Z ]*$', message=("Forgotten message."),)])
email = forms.CharField( max_length=50, label = ("email"), help_text = ("Email:"),
    error_messages = {'invalid':"Enter a valid email.", 'required':"Enter your email.", 'unique':'email already exists'}, validators=[RegexValidator( regex='^[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4} *$', message=("Forgotten message."),)])
pnum = forms.CharField( max_length=11, min_length=11, label = ("pnum"), help_text = ("Phone Number:"),
    error_messages = {'invalid':"Enter a valid phone number.", 'required':"Enter your phone number.", 'min_length':"Should contain 11 digits"}, validators=[RegexValidator( regex='^[0-9]*$', message=("Forgotten message."),)])
class Meta:
    model = sample_table
    fields = ('name', 'email', 'pnum',)

class confirm(ModelForm):
pnum = forms.CharField( max_length=11, min_length=11, label = ("pnum"), help_text = ("Phone Number:"),

class Meta:
    model = sample_table
    fields = ('confirm',)`

thank you in advance :*

A: Inside your view, you can pass two forms objects via your context.
I suppose you could do something like this:
context = Context({'form_1': Form_1, 'form_2': Form_2})

Have a look to a similar previous answer on stackoverflow here: https://stackoverflow.com/a/15499249/3967218 :)


text:
Q: Find the values of a and b that make the equation system have infinite solutions I'm given the following system of equations and I need to find the values for a and b so that the system has infinite solutions.
\begin{cases}
&3y &- &2z &= 5 \\
&-2x &+ &az &= -7 \\
&3x &- &2y &= b
\end{cases}
I know that in order for the system to have infinite solutions the rank of the matrix of the coefficents should be the same as the rank of the augmented matrix and lower than the number of equations, but I'm not sure how to find the values of a and b that satisfy such a condition.

A: For infinite solution there are two conditions

*

*$N(A)\neq\{0\}$

*$b\in Col(A)$

A: The augmented matrix $[A\mid b~]$ is$$\begin{vmatrix}0&3&-2&|&5\\-2&0&a&|&-7\\3&-2&0&|&b\end{vmatrix}$$After reducing $A$ to row-echelon form:$$\begin{vmatrix}3&-2&0&|&b\\0&3&-2&|&5\\0&0&a-8/9&|&2b/3-43/9\end{vmatrix}$$Now, $\text{rank}(A)=\text{rank}([A\mid b~])<3\implies a=8/9,b=43/6$.

A: Multiplying 2. with 3 and 3. equation with 2 and add them we get $$3az-4y = -21+2b$$ Multiplying this one with 3 and 1. one with 4 we get: $$-8z+9az=20-63+6b$$
and thus $$ z(9a-8)= 6b-43$$ So if

*

*$ a = {8\over 9}$ and $b={43\over 6}$ we have infinite solutions.

*$ a = {8\over 9}$ and $b\ne {43\over 6}$ we have no solution.

*$ a \ne {8\over 9}$ and $b\in\mathbb{R}$ we have one solution.