text:
Q: Pagination in SQL Server I have a very large database, roughly 100 GB. I'm executing query:
select * from <table_name>;

and I want to show only the 100th to 200th rows.
I want to understand how this happens internally. Does the database fetch all of the records from disk into memory and sends back 100th to 400th rows to the querying client? Or does there exist any mechanism, so that only those records (100th -200th) are fetched from database - by using indexing mechanism like B-trees etc.?
I found that this is related to pagination concept, but I could not exactly find how it happens internally at the database level.

A: In the query you posted:
select * from <table_name>;

There's no such thing as the 100th-200th rows, because you don't specify an ORDER BY. Order isn't guaranteed unless you include the ORDER BY for a whole lot of interesting reasons, but that's not really the point here.
So to illustrate your point, let's use a table - I'm going to use the Users table from the Stack Overflow data dump, and run this query:
SELECT * FROM dbo.Users ORDER BY DisplayName;

By default, there's no index on the DisplayName field, so SQL Server has to scan the entire table, then sort it by DisplayName. Here's the execution plan:

It's not pretty - that's a lot of work, with an estimated subtree cost of around 30k. (You can see it by hovering your mouse over the select operator over at PasteThePlan.) So what happens if we only want rows 100-200? We can use this syntax in SQL Server 2012+:
SELECT * FROM dbo.Users ORDER BY DisplayName OFFSET 100 ROWS FETCH NEXT 100 ROWS ONLY;

The execution plan on that is pretty ugly too:

SQL Server's still scanning the whole table to build the sorted list just to give you your rows 100-200, and the cost is still around 30k. Even worse, this whole list will be rebuilt every time your query runs (because after all, someone might have changed their DisplayName.)
To make it go faster, we can create an nonclustered index on DisplayName, which is a copy of our table, sorted by that specific field:
CREATE INDEX IX_DisplayName ON dbo.Users(DisplayName);

With that index, our query's execution plan now does an index seek:

The query finishes instantly and has an estimated subtree cost of just 0.66 (as opposed to 30k).
In summary, if you organize the data in a way that supports the queries you frequently run, then yes, SQL Server can take shortcuts to make your queries go faster. If, on the other hand, all you have is heaps or clustered indexes, you're screwed.

A: It really depends on how you implement the pagination within your query, the nature of the data and the way that your system is configured. It's pretty safe to say that SQL Server will attempt to return your data using what it feels is the least amount of effort possible. If you have no explicit sort order, filtering, grouping or any windowing then SQL Server could possibly optimize the query plan such that it could return just the pages from the disk that contained the data required by your query - or even better, directly from the buffer pool. As soon as you start changing the query to include sorting, grouping, windowing and filtering then it starts to get complicated.
There is a very good article on SQL Performance here that goes into some detail of the various methods of pagination and how they affect the query plan. I would highly recommend reading it and then trying out some of the various methods they point out and see what query plan is chosen on your own system.

A: Just as an addition to Brent's answer when using a non covering index to avoid a sort there is a potential issue with later page numbers that can be seen from running the below
SELECT *
FROM dbo.Users
ORDER BY DisplayName
OFFSET 100000 ROWS
FETCH NEXT 100 ROWS ONLY;

The execution plan shows that the lookup was executed 100,100 times even though all but 100 rows are then filtered out by the TOP operator.

This can be mitgated by using the pattern below
WITH T
     AS (SELECT Id,
                DisplayName
         FROM   dbo.Users
         ORDER  BY DisplayName
        OFFSET 100000 ROWS
        FETCH NEXT 100 ROWS ONLY
        )
SELECT U.*
FROM   dbo.Users U
       JOIN T
         ON U.Id = T.Id
ORDER  BY T.DisplayName

This filters out all except the final 100 rows before doing the lookups which can have a significant impact on speed for large offset values.


text:
Q: URL loading issue in WKWebView I'm getting a URL from API, I'm passing that URL to my webview and trying to load that, but it isn't loading. I don't know why but it isn't working. Even it's not showing any error or crashes. It's so weird but I don't know what I'm missing in that all the code is written fine. This is my code:
self.loadWeb(webURL: newsUrl!)
func loadWeb(webURL: String) {
    let url = URL(string: webURL)
    MBProgressHUD.hide(for: self.view, animated: true)
    webView.navigationDelegate = self
    webView.uiDelegate = self
    webView.load(URLRequest(url: url!))
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.frame.size.height = 1
    webView.scrollView.isScrollEnabled = false
    webView.frame.size = webView.scrollView.contentSize
    self.bgViewHeight.constant = webView.frame.size.height
}

private func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    print(error.localizedDescription)
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Start to load")
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    print("finish to load")
}

How i can load this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java substring() not working as expected Consider the following code in Java:
String str = "a";
System.out.println("Length is :")+str.length(); //Prints "Length is :1"
System.out.println("Substring is :"+str.substring(1); //Prints "Substring is :"
System.out.println("Char at :")+str.charAt(1); //Throws IndexOutofbounds exception as expected

I was under the impression that substring() starts from the index specified till the end of the string. Following this rule, shouldn't the substring() function above throw an arrayindexoutofbounds exception? Why does it print an empty string? The charAt() function works as expected i.e it throws an exception.

A: It is actually correct. According to the String API:

IndexOutOfBoundsException - if beginIndex is negative or larger than
  the length of this String object.

If you make it substring(2), you will see the exception.

A: everything is fine, you didn't read the javaDoc carefully.
you have only one char string, so index is only 0, length is 1. In javaDoc,
subString() will throw IndexOutOfBoundsException if:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

so your subString() call won't throw exception because the length is 1, but return empty str.
charAt():  while the charAt() call, will throw ex if:
IndexOutOfBoundsException  if the {@code index}
                  argument is negative or ***not less than*** the length of this
                  string.

that's why you got the ex.


text:
Q: Infinitely many exceptional curves on ruled surfaces
Take an algebraically closed field $k$. Let $C$ be a smooth projective variety of dimension $1$ over $k$(a curve). Consider a geometrically ruled surface $S :=C\times\mathbb{P}^1$. Does there exists a blow-up, say $\widehat{S}$ of $S$ at distinct points $p_1,\ldots,p_n$ on $S$, which has infinitely many exceptional curves?

This is in spirit of the analogous result for $C=\mathbb P^1$, where the answer is affirmative. The pith of the proof relies on the fact that blowing-up $\mathbb P^2$ at $k$ points in the general position might introduce large number of exceptional curve even for very small $k$. But for curves of higher genus it seems not to be the case. Is this observation correct?
Also could we say something for higher Kodaira dimension surfaces?

A: Let me write a short answer summarizing the comments above, so that the question will not appear unanswered anymore.

Proposition. The following holds.
(1) If $C$, $D$ are smooth curves and  $g(C) \geq 1$, then any blow-up of $C \times D$ contains at most finitely many $(-1)$-curves.
(2) If $S$ is any smooth, complex, projective surface with non-negative Kodaira dimension, then $S$ contains at most finitely many $(-1)$-curves.
Thus, surfaces containing infinitely many $(-1)$-curves are necessarily rational.

Proof. (1) Let $\pi \colon S \to C \times D$ be a blow-up in a finite number of points, and $p \colon S \to C$ the composition of $\pi$ with the projection onto $C$. Since $g(C) \geq 1$, no rational curve in $S$ can dominate $C$. It follows in particular that the $(-1)$-curves of $S$ are contained in reducible fibres of $p$, so there are finitely many of them.
(2) If $E \subset S$ is a $(-1)$-curve, then by adjunction $K_XE = -1$.
If we take a positive integer $m$ such that $mK_X$ is effective, it follows that $E$ is necessarily one of the finitely many components of the base locus of the complete linear system $|mK_X|$.


text:
Q: How to group database records by field using another field for calculating aggregate values in Laravel? I have a table with fields 'name', 'type' and 'amount', for example
|------------|-------|----------|
| name       | type  | amount   |
|------------|-------|----------|
| Name_1     | 1     | 100      |
|------------|-------|----------|
| Name_1     | 2     | 200      |
|------------|-------|----------|
| Name_2     | 1     | 300      |
|------------|-------|----------|
| Name_1     | 1     | 400      |
|------------|-------|----------|

And I need to receive a result
|------------|---------------------------|--------------------------|
| name       | sum(amount) of type 1     | sum(amount) of type 2    |
|------------|---------------------------|--------------------------|
| Name_1     | 500 (as 100 + 400)        | 200                      |
|------------|---------------------------|--------------------------|
| Name_2     | 300                       | 0                        |
|------------|---------------------------|--------------------------|

How can I do it with Laravel? Or with MySQL?
PS. As @Barmar say, the decision of
a question is already found (need to return two sets of data with two different where clauses). But this is fully MySQL approach, also interest Laravel Eloquent decision.


text:
Q: SQL - Shorter way to query user and usermeta data I'm looking to query a bunch of user and usermeta data into a single table.  I'm able to do so by creating multiple temporary tables and a pivot:
    create temporary table meta

    select u.ID, u.user_login, meta_key, meta_value from wp_users u
    inner join wp_usermeta m on m.user_id = u.ID;

    create temporary table users

    select ID, user_login,
        MAX(CASE WHEN meta_key = 'first_name' THEN meta_value END) as first_name,
        MAX(CASE WHEN meta_key = 'middle_name' THEN meta_value END) as middle_name,
        MAX(CASE WHEN meta_key = 'last_name' THEN meta_value END) as last_name,
        MAX(CASE WHEN meta_key = 'university_program' THEN meta_value END) as university_program,
        MAX(CASE WHEN meta_key = 'wp_capabilities' THEN meta_value END) as wp_capabilities
    from meta
    group by ID, user_login;

    drop temporary table meta;

    select * from users
    where wp_capabilities like '%um_student%';

    drop temporary table users;

However, is there a better and shorter way to run this query without the need to create temporary tables or the pivot?

A: I was just trying out the wp_get_users() function and I think that's a much cleaner way to get the user data in a table.  I can simply do something like this:
$users = get_users('role=um_student');

        foreach ( $users as $user )
        {
            echo "
";
                echo "$user->ID	";
                echo "$user->user_login	";
                echo "$user->first_name	";
                echo "$user->middle_name	";
                echo "$user->last_name	";
                echo "$user->university_program	";
                echo "
";
        }


text:
Q: MeijerG gives the wrong result? (V10.2) alpha = 6.39;
beta = 3.69;
a1 = (1 - alpha)/2;
a2 = (2 - alpha)/2;
a3 = (1 - beta)/2;
a4 = (2 - beta)/2;
a5 = 1;
b1 = 0;
b2 = 1/2;
SNR = 0;
SNR0 = 10^(SNR/10);
z = 2*(SNR0/(alpha*beta))^2;
p1 = 2^(alpha + beta - 3)/(Pi*Sqrt[Pi]*Gamma[alpha]*Gamma[beta]);
p2 = MeijerG[{{a1, a2, a3, a4}, {a5}}, {{b1, b2}, {}}, z, 1]

108.522

This was done in V10.2.
The result of p2 is expected to be 12.83559958, doubled checked in Maple and Matlab and confirmed from other research papers.
Syntax is expected to be correct too.
What is going on here?
Screenshot from Maple:

A: As Daniel Lichtblau showed in his comment, use exact numbers (or Rationalize) for input values
alpha = 639/100;
beta = 369/100;
a1 = (1 - alpha)/2;
a2 = (2 - alpha)/2;
a3 = (1 - beta)/2;
a4 = (2 - beta)/2;
a5 = 1;
b1 = 0;
b2 = 1/2;
SNR = 0;
SNR0 = 10^(SNR/10);
z = 2*(SNR0/(alpha*beta))^2;
p1 = 2^(alpha + beta - 3)/(Pi*Sqrt[Pi]*Gamma[alpha]*Gamma[beta]);

Then use arbitrary-precision of at least 10 digits rather than machine precision
{#, N[MeijerG[{{a1, a2, a3, a4}, {a5}}, {{b1, b2}, {}}, z], #]} & /@
  Range[3, 20] // Grid


text:
Q: Reading JSON data in PHP I have a JSON object like below, which is stored in a variable called $product.
{"id":30}

When I try to access the stored value though, I get the following error:

Trying to get property of non-object

Here is what I am doing:
echo $product->id;

Alright folks, sorry for the wild goose chase. Apparently $products was an array and not a JSON data, which is really odd because print_r($products) and echo $products gave different results.
The results can be viewed here:

I am using Laravel, and usually laravel returns a nice JSON object from an SQL query, I must have changed something somewhere, which is why this happened. Thanks.

A: Try following json_decode function
$product = '{"id":30}';
$t = json_decode($product);
echo $t->id;exit;

A: You could use json_decode to your object.

Takes a JSON encoded string and converts it into a PHP variable.

usage:
print_r(json_decode($obj, true));
var_dump(json_decode($obj));

A: Trying below sample :
<?php
$product = '{"id": 30}';

$obj = json_decode(json_encode($product));  // or json_decode(json_encode($product), true);
echo $obj->{'id'};  // or echo $obj->id
?>

A: The first examples are working for me, make sure you PHP is supporting the json_decode() function.
Or you could try this:
$product = '{"id":30}';
$t = json_decode($product, true);
echo $t["id"];

Passing the true value converts it to an array instead.


text:
Q: Adding or removing upstream layers in a keras model I would like to modify or append keras input layer to a pretrained inception model. I know that there is a way to pop and append downstream layers. How about upstream layers?
For example, I would like to add a layer which will take my input image and branch it in 3 channels (I know there are other solutions, but let's try it):
from keras.applications.inception_v3 import InceptionV3
from keras.models import Model
from keras.layers import Dense,

base_model = InceptionV3(weights='imagenet', include_top=False)

img = Input(( None, None, 1))
d0 = Dense(3,kernel_initializer='Ones', use_bias=False)
img3 = d0(img)

It turns I cannot set the input attribute easily like base_model.input = img3 -- it raises an exception.

Update:
I actually need to modify both upstream and downstream layers. Currently I am cropping downstream layers in my network in following way:
n_classes = 1
final_activation = 'sigmoid'
ndense=64
dropout=0.5
base_trainable=False

base_model = InceptionV3(weights='imagenet', include_top=False)
img = Input(( None, None, 1))
d0 = Conv2D(3, (1,1), kernel_initializer='Ones', use_bias=False)
img3 = d0(img)
base_model(img3)

# get third Concatenation layer and crop the network on it:
cc=0
poptherest = False
for nn, la in enumerate(base_model.layers):
    if type(la) is keras.layers.Concatenate:
        if cc==3:
            x = la.output
            break
        cc+=1
base_model.layers = base_model.layers[:nn+1]

#x = [la.output for la in base_model.layers if type(la) is keras.layers.Concatenate][3]
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dropout(dropout)(x)

x = Dense(ndense, activation='relu')(x)
# and a logistic layer -- let's say we have 200 classes
predictions = Dense(n_classes, activation=final_activation)(x)

# this is the model we will train
model = Model(inputs=img, outputs=predictions)

How do I add the above mentioned modification to my code?

A: For complex models, and necessarily for models with branches, the idea of popping/adding layers doesn't apply, because it's for sequential models.
The good news is that using the Functional API Model you can do almost anything.
You're almost correct on your model, but you can't set "model.input". But you can pass the input to the model as if the model were a layer:
output = base_model(img3) #if an exception appears here, it's probably a shape problem
myModel = Model(img,output)

Now, there is a problem with your input. You cannot use "None". None is reserved for Keras to separate the variable batch size. You must define exactly the size of your image, which should be:
img = Input((horizPixels,vertPixels,channels))

Please notice that your img3 tensor must have a shape compatible with the inception expected input. If inception is expecting three channel images, make sure your img3 is shaped like (x,y,channels) or (None,x,y,channels).

I'm not sure I understood what you want to achieve, but if your input image has only one channel and you want to create a 3 channel image from it, I suggest you use a convolutional layer with 3 filters:
d0 = Conv2D(filter=3, kernel_size=(3,3), .....)

But if you want a layer that doesn't learn anything and already knows what to do, maybe it's better to just separate the image yourself in your training data instead of leaving the task to the model.


text:
Q: Command output retention while counting lines I was reading Count number of lines of output from previous program
and found it helpful. However, while
$ grep -i [pattern, file] | tee >(wc -l)

gives me a nice output of the grep lines and the number of matches, I want to ask if anyone knows how to save the number of matches to a variable in my script. I want to output it within a string with more readable formatting.

A: somevar=$(wc -l <(grep -i [pattern, file]) | awk '{print $1}')

Then later on
echo "This was the numbers reported: $somevar"

If you want to keep the output of grep in a file and still do the count:
$ wc -l <(grep -i [pattern, file] | tee somefile) | awk '{print $1}'

$ wc -l somefile
 364 somefile


text:
Q: Error when running any kivy code: Kivy 2.0.0 , python 3.9 error: [CRITICAL] [Window ] Unable to find any valuable Window provider I've been having this same error running any kivy code I type into IntelliJ. I'm using kivy 2.0.0 and Python 3.9.
Here's my code:
from kivy.app import App
from kivy.lang import Builder

kv = """
Screen:
    FloatLayout:
        Button:
            text: "It works!"
            pos_hint: {"x": 0.1, "y": 0.7}
            text_size: self.size
        """

class MyApp(App):
    def build(self):
        self.screen = Builder.load_string(kv)
        return self.screen

if __name__ == "__main__":
    MyApp().run()

I've tried many solutions including reinstalling kivy, adding to path, and I've installed all the dependencies.
Here's the error message:
[INFO   ] [Logger      ] Record log in C:\Users\James\.kivy\logs\kivy_21-10-25_21.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.3.2
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO   ] [Kivy        ] v2.0.0
[INFO   ] [Kivy        ] Installed at "C:\Users\james\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Users\james\IdeaProjects\HelloWorld\venv\Scripts\python.exe"
[INFO   ] [Logger      ] Purge log fired. Analysing...
[INFO   ] [Logger      ] Purge 9 log files
[INFO   ] [Logger      ] Purge finished!
[INFO   ] [Factory     ] 186 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_pil (img_sdl2, img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: pil(['text_sdl2'] ignored)
2.0.0
[CRITICAL] [Window      ] Unable to find any valuable Window provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
sdl2 - ImportError: DLL load failed while importing _window_sdl2: The specified module could not be found.
  File "C:\Users\james\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\core\__init__.py", line 58, in core_select_lib
    mod = __import__(name='{2}.{0}.{1}'.format(
  File "C:\Users\james\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\core\window\window_sdl2.py", line 27, in <module>
    from kivy.core.window._window_sdl2 import _WindowSDL2Storage

[CRITICAL] [App         ] Unable to get a Window, abort.

Process finished with exit code 1

EDIT
So thanks to Weebify I got through. Just Follow all the download instructions from the kivy docs exactly. I posted the full method I used as an answer (not marked as best answer).

A: The solution for this problem is to uninstall kivy and reinstall the cutting-edge version from master:
python3 -m pip uninstall kivy
python3 -m pip install "kivy[base] @ https://github.com/kivy/kivy/archive/master.zip"

A: Ok, so many thanks to Weebify for help here. Here are the full download instructions for Windows for anyone who is having problems:

NOTE: Kivy does not yet support Python 3.10 but you can get through fine with Python 3.9

Setup terminal and pip
Before Kivy can be installed, Python and pip need to be pre-installed. Then, start a new terminal that has Python available. In the terminal, update pip and other installation dependencies so you have the latest version as follows, (for linux users you may have to substitute python3 instead of python and also add a --user flag in the subsequent commands outside the virtual environment):
python -m pip install --upgrade pip setuptools virtualenv

Create virtual environment

*

*Create a new virtual environment for your Kivy project. A virtual
environment will prevent possible installation conflicts with other
Python versions and packages. It's optional but strongly
recommended:

Create the virtual environment named kivy_venv in your current directory:
python -m virtualenv kivy_venv

*Activate the virtual environment. You will have to do this step from
the current directory every time you start a new terminal. This sets
up the environment so the new kivy_venv Python is used.

For Windows default CMD, in the command line do:
kivy_venv\Scripts\activate

If you are in a bash terminal on Windows, instead do:
source kivy_venv/Scripts/activate

If you are in Linux, instead do:
source kivy_venv/bin/activate

Your terminal should now preface the path with something like (kivy_venv), indicating that the kivy_venv environment is active. If it doesn't say that, the virtual environment is not active and the following won't work.

Install Kivy
Finally, install Kivy using the latest cutting-edge Kivy from master:
python -m pip install "kivy[base] @ https://github.com/kivy/kivy/archive/master.zip"

More info on the Kivy installation page.


text:
Q: Modifying bibliography with biblatex/biber (apa-style) location+publisher+doi Concerning the citation and bibliography of my thesis, some issues I could solve myself, with others I got help. But here is where I'm stuck:
If there is a book or bookchapter that's got a doi, location+publisher won't show up (for example check Backhaus et al.; Castells; Revelle/Condon), but without doi, location+publisher show up (for example check Foucault. Is there a possibility to change that? It should look like: »location: publisher. doi:12345« (for example »Oxford: Wiley-Blackwell. doi:10.1002/9781444319514«).
Maybe you also notice, that in the case of Castells the volume number is not shown, too, whereas for Revelle/Condon without doi it is shown, but in the arabic number, not the roman number (even if that's the information of the bibentry). In the case of Foucault the volume number is not shown although there's no doi. Could that be fixed, too?
Maybe this has got to do with changes to an APA feature? Or does it have to do with the zotero-import of my bibentries? See, before this problem happened, all books would be imported as »@book« (Backhaus et al.), whereas now it's »@mvbook« (Foucault).
I'm using APA-Style with biber as backend for biblatex. All help is much appreciated.
MWE:
\documentclass[11pt,a4paper,toc=listof]{scrartcl}
\usepackage[left=3cm, right=2cm, bottom=3cm, top=2cm]{geometry}
\usepackage[english,ngerman]{babel} % Sprachpakete
\usepackage[utf8]{inputenc}         % Direkte Eingabe von Umlauten
\usepackage[T1]{fontenc}            % Worttrennung bei Umlauten
\usepackage{microtype}              % Verbesserter Randausgleich
% Anführungszeichen
\usepackage[
 babel,
 german=quotes,
 german=guillemets
 ]{csquotes}

% ––––––––––––––––––––––––––––––––––––––––––––––––––
% Bibliographie
% ––––––––––––––––––––––––––––––––––––––––––––––––––

\usepackage[
    style           = apa,
    citestyle       = authoryear,
    citetracker     = false,    % immer Kurzform (= ab 3 Autoren et al.)
    uniquelist      = false,    % immer nur 1. Autor + et al.
    sorting         = nyt,
    sortcites       = true,
    autocite        = inline,
    maxbibnames     = 99,
    maxcitenames    = 2,
    backend         = biber,
    bibliography    = totoc,
    isbn            = false,
    doi             = true,
    urldate         = short
    ]{biblatex}
\DeclareLanguageMapping{german}{german-apa}
\DeclareFieldFormat{apacase}{#1}
\DefineBibliographyStrings{ngerman}{%
   andothers = {{et\,al\adddot}},
}

% increase vertical space between bibliography items.
\setlength\bibitemsep{1.3ex}
\setlength\bibnamesep{1.0ex}

% ––––––––––––––––––––––––––––––––––––––––––––––––––
% Zitation
% ––––––––––––––––––––––––––––––––––––––––––––––––––

% remove comma in (Beadle and Tautum, 1941) This applies to citation only
\renewcommand*{\nameyeardelim}{\addspace}

% change delimiters
% since the delimiters use several contexts, some format clearing needs to happen
\DeclareDelimFormat*{multinamedelim}{\,/\,}
\DeclareDelimFormat*{finalnamedelim}{}
\DeclareDelimAlias{finalnamedelim}{multinamedelim}
\DeclareDelimFormat*{finalnamedelim:apa:family-given}{}
\DeclareDelimAlias{finalnamedelim:apa:family-given}{multinamedelim}

% Umbrüche in URL und DOI bei Zahlen zulassen
\setcounter{biburlnumpenalty}{100}  % allow breaks at numbers

% Reihen in Bibliographie
\DeclareFieldFormat{number}{\bibstring{number}~#1}

% name sort always last, first
\DeclareNameAlias{editor}{family-given}

% Anpassungen um Schriftenreihe mit Nummer vor Ort und Verlag zu platzieren
\renewbibmacro*{addinfo}{%
  \ifthenelse{\iffieldundef{edition}\AND%
              \iffieldundef{chapter}\AND%
              \iffieldundef{volumes}\AND%
              \iffieldundef{pages}\AND%
              \(\iffieldundef{volume}\OR\boolean{bbx:volseen}\)}
  {}
  {\printtext{\bibopenparen}%
   \printfield{edition}%
   \setunit*{\addcomma\addspace}%
   \printfield{chapter}%
   \setunit*{\addcomma\addspace}%
   \notbool{bbx:volseen}%
     {\iffieldundef{volume}{}{\global\booltrue{bbx:volseen}}%
      \printfield{volume}%
      \iffieldundef{part}{}{\printfield{part}}}{}%
   \setunit*{\addcomma\addspace}%
   \printfield{volumes}%
   \setunit*{\addcomma\addspace}%
   \printfield{pages}%
   \setunit{}%
   \printtext{\bibcloseparen}%
   \newunit}}

\renewbibmacro*{maintitle+title}{%
  \iffieldsequal{maintitle}{title}
    {\clearfield{maintitle}%
     \clearfield{mainsubtitle}%
     \clearfield{maintitleaddon}}
    {\iffieldundef{maintitle}
      {}
      {\usebibmacro{maintitle}%
       \newunit\newblock
           \iffieldundef{volume}
         {}
         {\setunit{\global\booltrue{bbx:volseen}}%
          \printfield{volume}%
          \printfield{part}%
          \setunit{\adddot\space}}}}%
  \usebibmacro{title}%
  \newunit}

\renewbibmacro*{maintitle+booktitle}{%
  \ifthenelse{\iffieldundef{maintitle}\AND\iffieldundef{booktitle}}
    {}
    {\usebibmacro{in}%
     \iffieldundef{maintitle}
      {}
      {\usebibmacro{maintitle}%
   \newunit\newblock
   \iffieldundef{volume}
     {}
     {\setunit{\addspace\global\booltrue{bbx:volseen}}%
      \printfield{volume}%
      \printfield{part}%
      \setunit{\adddot\addspace}}}%
\usebibmacro{booktitle}}}

\renewbibmacro*{series+number}{%
  \printfield{series}%
  \setunit{\addcomma\space}%
  \printfield{number}%
  \newunit}

\usepackage{xpatch}

\xpatchbibdriver{book}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}
\xpatchbibdriver{inbook}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}
\xpatchbibdriver{incollection}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}

\xpatchbibdriver{collection}
  {\printfield{number}}
  {}
  {}{}
\xpatchbibdriver{collection}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}
% * * *

% Eintragsart Bericht (report) Anpassung
\DeclareFieldFormat[report]{number}    {\bibcpstring{number}~\apanum{#1}}
\renewbibmacro*{apa:reportnum}{%
  \newunit\newblock
  \printfield{type}%
  \setunit*{\addcomma\space}%
  \printfield{number}}

\xpatchbibdriver{report}
  {\printlist{institution}}
  {}
  {}{}
\newbibmacro*{location+institution}{%
  \printlist[default][1-1]{location}%
  \setunit*{\addcolon\space}%
  \printlist{institution}%
  \newunit}
\xpatchbibdriver{report}
  {\usebibmacro{location+publisher}}
  {\usebibmacro{location+institution}}
  {}{}

% bei allen Eintragsarten andere Editortypen missachten
\AtEveryBibitem{
  \iffieldequalstr{editortype}{redactor}
    {\global\clearname{editor}\typeout{delete editor (type: redactor) in \thefield{citekey}}}{}%
  \iffieldequalstr{editoratype}{redactor}
    {\global\clearname{editora}\typeout{delete editora (type: redactor) in \thefield{citekey}}}{}%
  \iffieldequalstr{editorbtype}{redactor}
    {\global\clearname{editorb}\typeout{delete editorb (type: redactor) in \thefield{citekey}}}{}%
  \iffieldequalstr{editorctype}{redactor}
    {\global\clearname{editorc}\typeout{delete editorc (type: redactor) in \thefield{citekey}}}{}%
}

% Angabe "S." vor Seitenzahlen bei Journals
\DeclareFieldFormat*{pages}{\mkpageprefix[bookpagination]{#1}}

% Subtitel nach Titel mit "––"
%\renewcommand*{\subtitlepunct}{\addspace\textemdash\space}

% ––––––––––––––––––––––––––––––––––––––––––––––––––
% Quellen
% ––––––––––––––––––––––––––––––––––––––––––––––––––

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@book{Backhaus.etal_2016,
  langid    = {ngerman},
  location  = {Berlin},
  title     = {Multivariate Analysemethoden \textemdash{} Eine anwendungsorientierte Einf{\"u}hrung},
  edition   = {14., {\"u}berarb. u. akt. Aufl.},
  isbn      = {978-3-662-46075-7},
  publisher = {Springer Gabler},
  date      = {2016},
  author    = {Backhaus, Klaus and Erichson, Bernd and Plinke, Wulff and Weiber, Rolf},
  doi       = {10.1007/978-3-662-46076-4}
}
@report{Revelle_2017b,
  langid      = {english},
  location    = {Evanston, IL},
  title       = {How To: {Use} the psych package for Factor Analysis and data reduction},
  url         = {http://personality-project.org/r/psych/HowTo/factor.pdf},
  institution = {Department of Psychology, Northwestern University},
  urldate     = {2018-07-01},
  date        = {2017},
  author      = {Revelle, William}
}
@incollection{Revelle.Condon_2018,
  langid       = {english},
  location     = {Chichester},
  title        = {Reliability},
  volume       = {II},
  isbn         = {978-1-118-48977-2},
  booktitle    = {The Wiley Handbook of Psychometric Testing \textemdash{} A Multidisciplinary Reference on Survey, Scale and Test     Development},
  publisher    = {J.~Wiley \& Sons},
  date         = {2018},
  pages        = {709-749},
  author       = {Revelle, William and Condon, David M.},
  editor       = {Irwing, Paul and Booth, Tom and Hughes, David J.},
  doi          = {10.1002/9781118489772.ch23}
}
@article{Wright.Herrington_2011,
  langid       = {english},
  title        = {Problematic Standard Errors and Confidence Intervals for Skewness and Kurtosis},
  volume       = {43},
  issn         = {1554-3528},
  doi          = {10.3758/s13428-010-0044-x},
  number       = {1},
  journaltitle = {Behavior Research Methods},
  date         = {2011},
  pages        = {8-17},
  author       = {Wright, Daniel B. and Herrington, Joshua A.}
}
@mvbook{Castells_2010,
  langid = {english},
  location = {{Oxford}},
  title = {The Information Age \textemdash{} Economy, Society, and Culture, Vol. 1: The Rise of the Network Society},
  edition = {2. Aufl.},
  volume = {I},
  isbn = {978-1-4443-1951-4},
  volumes = {III},
  publisher = {{Wiley-Blackwell}},
  date = {2010},
  author = {Castells, Manuel},
  doi = {10.1002/9781444319514}
}
@mvbook{Foucault_2004,
  langid = {ngerman},
  location = {{Frankfurt am Main}},
  title = {Geschichte der Gouvernmentalit{\"a}t, Bd. 2: Die Geburt der Biopolitik \textemdash{} Vorlesung am Coll{\`e}ge de France 1978\textendash{}1979},
  volume = {II},
  isbn = {978-3-518-58393-7},
  shorttitle = {Die Geburt der Biopolitik},
  volumes = {II},
  pagetotal = {517},
  series = {Taschenbuch Wissenschaft},
  publisher = {{Suhrkamp}},
  date = {2004},
  author = {Foucault, Michel},
  editor = {Sennelart, Michel},
  translator = {Brede-Konersmann, Claudia and Schr{\"o}der, J{\"u}rgen}
}
\end{filecontents}
\addbibresource{\jobname.bib}
% ******************* T E X T *******************%
\begin{document}
\noindent Source 1: \cite[8]{Wright.Herrington_2011}\\
Source 2: \cite{Revelle_2017b}\\
Source 3: \cite{Backhaus.etal_2016}\\
Source 4: \cite{Castells_2010}\\
Source 5: \cite{Revelle.Condon_2018}\\
Source 6: \cite{Foucault_2004}

\printbibliography[title=Literaturverzeichnis]
\end{document}

Result:

A: I have said this before, but for the benefit of other readers: It is usually a bad idea to try to modify specialised styles like biblatex-apa and biblatex-chicago so heavily. These styles were specifically written to conform to very strict (and sometimes complicated and slightly inconsistent) rules of an authoritative style guide. That means that the code is much more complicated than the standard styles, which were meant to be modified as needed. For future project I strongly advise to build your customised style upon one of the standard styles (probably authoryear in this case) \begin{advertising} or upon one of the style of my biblatex-ext family \end{advertising}
It is a feature of APA style that location and publisher are dropped if the DOI is present for chapters like @incollection or @inbook. That can be turned off by redefining the macro location+publisher.
The volume field in Castells_2010 and Foucault_2004 is not shown because the entries lack a maintitle field. Usually the maintitle+volume are used together like
@book{Castells_2010,
  langid       = {english},
  location     = {Oxford},
  maintitle    = {The Information Age},
  mainsubtitle = {Economy, Society, and Culture},
  title        = {The Rise of the Network Society},
  volume       = {I},
  edition      = {2. Aufl.},
  isbn         = {978-1-4443-1951-4},
  volumes      = {III},
  publisher    = {Wiley-Blackwell},
  date         = {2010},
  author       = {Castells, Manuel},
  doi          = {10.1002/9781444319514}
}
@book{Foucault_2004,
  langid     = {ngerman},
  location   = {Frankfurt am Main},
  maintitle  = {Geschichte der Gouvernmentalit{\"a}t},
  volume     = {II},
  title      = {Die Geburt der Biopolitik},
  subtitle   = {Vorlesung am Coll{\`e}ge de France 1978\textendash{}1979},
  isbn       = {978-3-518-58393-7},
  shorttitle = {Die Geburt der Biopolitik},
  volumes    = {II},
  pagetotal  = {517},
  series     = {Taschenbuch Wissenschaft},
  publisher  = {Suhrkamp},
  date       = {2004},
  author     = {Foucault, Michel},
  editor     = {Sennelart, Michel},
  translator = {Brede-Konersmann, Claudia and Schr{\"o}der, J{\"u}rgen}
}

(note that I also split up fields into ...title and ...subtitle where appropriate).
Since both entries refer only to one (pyhsical) book of a a multi-volume project, @book is the appropriate entry type. I would use @mvbook only if I wanted to refer to the entire multi-volume work at once for example
@mvbook{knuth:ct,
  author       = {Knuth, Donald E.},
  title        = {Computers \& Typesetting},
  date         = {1984/1986},
  volumes      = 5,
  publisher    = {Addison-Wesley},
  location     = {Reading, Mass.},
}

Similarly volumes (in plural) only makes sense if a work consists of several volumes, and that will always be a @mvbook/@mvcollection. Your entries, however, refer to just one book and so volumes is not really needed (except as an volume 2 of 3 sort of thing, which I don't think any style does).
The two code-level changes have been marked with today's date 2018-09-24 so they are easier to spot.
\documentclass[11pt,a4paper,toc=listof]{scrartcl}
\usepackage[left=3cm, right=2cm, bottom=3cm, top=2cm]{geometry}
\usepackage[english,ngerman]{babel} % Sprachpakete
\usepackage[utf8]{inputenc}         % Direkte Eingabe von Umlauten
\usepackage[T1]{fontenc}            % Worttrennung bei Umlauten
\usepackage{microtype}              % Verbesserter Randausgleich
% Anführungszeichen
\usepackage[
 babel,
 german=quotes,
 german=guillemets
 ]{csquotes}

% ––––––––––––––––––––––––––––––––––––––––––––––––––
% Bibliographie
% ––––––––––––––––––––––––––––––––––––––––––––––––––

\usepackage[
    style           = apa,
    citestyle       = authoryear,
    citetracker     = false,    % immer Kurzform (= ab 3 Autoren et al.)
    uniquelist      = false,    % immer nur 1. Autor + et al.
    sorting         = nyt,
    sortcites       = true,
    autocite        = inline,
    maxbibnames     = 99,
    maxcitenames    = 2,
    backend         = biber,
    bibliography    = totoc,
    isbn            = false,
    doi             = true,
    urldate         = short
    ]{biblatex}
\DeclareLanguageMapping{german}{german-apa}
\DeclareFieldFormat{apacase}{#1}
\DefineBibliographyStrings{ngerman}{%
   andothers = {{et\,al\adddot}},
}

% increase vertical space between bibliography items.
\setlength\bibitemsep{1.3ex}
\setlength\bibnamesep{1.0ex}

% ––––––––––––––––––––––––––––––––––––––––––––––––––
% Zitation
% ––––––––––––––––––––––––––––––––––––––––––––––––––

% remove comma in (Beadle and Tautum, 1941) This applies to citation only
\renewcommand*{\nameyeardelim}{\addspace}

% change delimiters
% since the delimiters use several contexts, some format clearing needs to happen
\DeclareDelimFormat*{multinamedelim}{\,/\,}
\DeclareDelimFormat*{finalnamedelim}{}
\DeclareDelimAlias{finalnamedelim}{multinamedelim}
\DeclareDelimFormat*{finalnamedelim:apa:family-given}{}
\DeclareDelimAlias{finalnamedelim:apa:family-given}{multinamedelim}

% Umbrüche in URL und DOI bei Zahlen zulassen
\setcounter{biburlnumpenalty}{100}  % allow breaks at numbers

% Reihen in Bibliographie
\DeclareFieldFormat{number}{\bibstring{number}~#1}

% name sort always last, first
\DeclareNameAlias{editor}{family-given}

% Anpassungen um Schriftenreihe mit Nummer vor Ort und Verlag zu platzieren
\renewbibmacro*{addinfo}{%
  \ifthenelse{\iffieldundef{edition}\AND%
              \iffieldundef{chapter}\AND%
              \iffieldundef{volumes}\AND%
              \iffieldundef{pages}\AND%
              \(\iffieldundef{volume}\OR\boolean{bbx:volseen}\)}
  {}
  {\printtext{\bibopenparen}%
   \printfield{edition}%
   \setunit*{\addcomma\addspace}%
   \printfield{chapter}%
   \setunit*{\addcomma\addspace}%
   \notbool{bbx:volseen}%
     {\iffieldundef{volume}{}{\global\booltrue{bbx:volseen}}%
      \printfield{volume}%
      \iffieldundef{part}{}{\printfield{part}}}{}%
   \setunit*{\addcomma\addspace}%
   \printfield{volumes}%
   \setunit*{\addcomma\addspace}%
   \printfield{pages}%
   \setunit{}%
   \printtext{\bibcloseparen}%
   \newunit}}

\renewbibmacro*{maintitle+title}{%
  \iffieldsequal{maintitle}{title}
    {\clearfield{maintitle}%
     \clearfield{mainsubtitle}%
     \clearfield{maintitleaddon}}
    {\iffieldundef{maintitle}
      {}
      {\usebibmacro{maintitle}%
       \newunit\newblock
           \iffieldundef{volume}
         {}
         {\setunit{\global\booltrue{bbx:volseen}}%
          \printfield{volume}%
          \printfield{part}%
          \setunit{\adddot\space}}}}%
  \usebibmacro{title}%
  \newunit}

\renewbibmacro*{maintitle+booktitle}{%
  \ifthenelse{\iffieldundef{maintitle}\AND\iffieldundef{booktitle}}
    {}
    {\usebibmacro{in}%
     \iffieldundef{maintitle}
      {}
      {\usebibmacro{maintitle}%
   \newunit\newblock
   \iffieldundef{volume}
     {}
     {\setunit{\addspace\global\booltrue{bbx:volseen}}%
      \printfield{volume}%
      \printfield{part}%
      \setunit{\adddot\addspace}}}%
\usebibmacro{booktitle}}}

\renewbibmacro*{series+number}{%
  \printfield{series}%
  \setunit{\addcomma\space}%
  \printfield{number}%
  \newunit}

\usepackage{xpatch}

\xpatchbibdriver{book}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}
\xpatchbibdriver{inbook}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}
\xpatchbibdriver{incollection}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}

\xpatchbibdriver{collection}
  {\printfield{number}}
  {}
  {}{}
\xpatchbibdriver{collection}
  {\printfield{series}}
  {\usebibmacro{series+number}}
  {}{}
% * * *

% 2018-09-24:1
\renewbibmacro*{location+publisher}{%
  \printlist[default][1-1]{location}%
  \setunit*{\addcolon\space}%
  \printlist{publisher}%
  \newunit}

% Eintragsart Bericht (report) Anpassung
\DeclareFieldFormat[report]{number}    {\bibcpstring{number}~\apanum{#1}}
\renewbibmacro*{apa:reportnum}{%
  \newunit\newblock
  \printfield{type}%
  \setunit*{\addcomma\space}%
  \printfield{number}}

\xpatchbibdriver{report}
  {\printlist{institution}}
  {}
  {}{}
\newbibmacro*{location+institution}{%
  \printlist[default][1-1]{location}%
  \setunit*{\addcolon\space}%
  \printlist{institution}%
  \newunit}
\xpatchbibdriver{report}
  {\usebibmacro{location+publisher}}
  {\usebibmacro{location+institution}}
  {}{}

% bei allen Eintragsarten andere Editortypen missachten
\AtEveryBibitem{
  \iffieldequalstr{editortype}{redactor}
    {\global\clearname{editor}\typeout{delete editor (type: redactor) in \thefield{citekey}}}{}%
  \iffieldequalstr{editoratype}{redactor}
    {\global\clearname{editora}\typeout{delete editora (type: redactor) in \thefield{citekey}}}{}%
  \iffieldequalstr{editorbtype}{redactor}
    {\global\clearname{editorb}\typeout{delete editorb (type: redactor) in \thefield{citekey}}}{}%
  \iffieldequalstr{editorctype}{redactor}
    {\global\clearname{editorc}\typeout{delete editorc (type: redactor) in \thefield{citekey}}}{}%
}

% Angabe "S." vor Seitenzahlen bei Journals
\DeclareFieldFormat*{pages}{\mkpageprefix[bookpagination]{#1}}

% 2018-09-24:2
% Subtitel nach Titel mit "––"
\renewcommand*{\subtitlepunct}{\addspace\textemdash\space}
\DeclareFieldFormat{volumes}{#1 \bibstring{volumes}}
\renewbibmacro*{maintitle}{%
  \ifthenelse{\iffieldundef{maintitle}\AND\iffieldundef{mainsubtitle}}
    {}
    {\printtext[maintitle]{%
       \printfield[apacase]{maintitle}%
       \setunit{\subtitlepunct}%
       \printfield[apacase]{mainsubtitle}}%
    \setunit{\addspace}}
  \printfield{maintitleaddon}%
  \addcolon\space}

% ––––––––––––––––––––––––––––––––––––––––––––––––––
% Quellen
% ––––––––––––––––––––––––––––––––––––––––––––––––––

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@book{Backhaus.etal_2016,
  langid    = {ngerman},
  location  = {Berlin},
  title     = {Multivariate Analysemethoden},
  subtitle  = {Eine anwendungsorientierte Einf{\"u}hrung},
  edition   = {14., {\"u}berarb. u. akt. Aufl.},
  isbn      = {978-3-662-46075-7},
  publisher = {Springer Gabler},
  date      = {2016},
  author    = {Backhaus, Klaus and Erichson, Bernd and Plinke, Wulff and Weiber, Rolf},
  doi       = {10.1007/978-3-662-46076-4}
}
@report{Revelle_2017b,
  langid      = {english},
  location    = {Evanston, IL},
  title       = {How To: {Use} the psych package for Factor Analysis and data reduction},
  url         = {http://personality-project.org/r/psych/HowTo/factor.pdf},
  institution = {Department of Psychology, Northwestern University},
  urldate     = {2018-07-01},
  date        = {2017},
  author      = {Revelle, William}
}
@incollection{Revelle.Condon_2018,
  langid       = {english},
  location     = {Chichester},
  title        = {Reliability},
  volume       = {II},
  isbn         = {978-1-118-48977-2},
  booktitle    = {The Wiley Handbook of Psychometric Testing},
  booksubtitle = {A Multidisciplinary Reference on Survey, Scale and Test Development},
  publisher    = {J.~Wiley \& Sons},
  date         = {2018},
  pages        = {709-749},
  author       = {Revelle, William and Condon, David M.},
  editor       = {Irwing, Paul and Booth, Tom and Hughes, David J.},
  doi          = {10.1002/9781118489772.ch23}
}
@article{Wright.Herrington_2011,
  langid       = {english},
  title        = {Problematic Standard Errors and Confidence Intervals for Skewness and Kurtosis},
  volume       = {43},
  issn         = {1554-3528},
  doi          = {10.3758/s13428-010-0044-x},
  number       = {1},
  journaltitle = {Behavior Research Methods},
  date         = {2011},
  pages        = {8-17},
  author       = {Wright, Daniel B. and Herrington, Joshua A.}
}
@book{Castells_2010,
  langid       = {english},
  location     = {Oxford},
  maintitle    = {The Information Age},
  mainsubtitle = {Economy, Society, and Culture},
  title        = {The Rise of the Network Society},
  volume       = {I},
  edition      = {2},
  isbn         = {978-1-4443-1951-4},
  publisher    = {Wiley-Blackwell},
  date         = {2010},
  author       = {Castells, Manuel},
  doi          = {10.1002/9781444319514}
}
@book{Foucault_2004,
  langid     = {ngerman},
  location   = {Frankfurt am Main},
  maintitle  = {Geschichte der Gouvernmentalit{\"a}t},
  volume     = {II},
  title      = {Die Geburt der Biopolitik},
  subtitle   = {Vorlesung am Coll{\`e}ge de France 1978\textendash{}1979},
  isbn       = {978-3-518-58393-7},
  shorttitle = {Die Geburt der Biopolitik},
  pagetotal  = {517},
  series     = {Taschenbuch Wissenschaft},
  publisher  = {Suhrkamp},
  date       = {2004},
  author     = {Foucault, Michel},
  editor     = {Sennelart, Michel},
  translator = {Brede-Konersmann, Claudia and Schr{\"o}der, J{\"u}rgen}
}
\end{filecontents}
\addbibresource{\jobname.bib}
% ******************* T E X T *******************%
\begin{document}
Source 1: \cite[8]{Wright.Herrington_2011}\par
Source 2: \cite{Revelle_2017b}\par
Source 3: \cite{Backhaus.etal_2016}\par
Source 4: \cite{Castells_2010}\par
Source 5: \cite{Revelle.Condon_2018}\par
Source 6: \cite{Foucault_2004}

\printbibliography[title=Literaturverzeichnis]
\end{document}


text:
Q: How to create a vector of class objects in C++? I am trying to create a simple stack using vector in C++.
Here is the code:
#include <vector>

class Site
{
    public:
        int i; // site position i (x-axis)
        int s; // site state
        vector<Site> neighbors;
        Site(void);
        Site(int ii, int ss);
        void AddNeighbor(Site &site);
};
Site::Site()
{
    i = -1;
    s = -1;
    vector<Site> neighbors;
}
Site::Site(int ii, int ss)
{
    i = ii;
    s = ss;
}
void Site::AddNeighbor(Site &site)
{
    neighbors.push_back(site);
}

void testStack()
{
    int tot = 600;
    vector<Site> myStack();
    int i = 0;
    while (i < tot)
    {
        Site site(i, 1);
        myStack.push_back(site);
        i++;
    }

    i = 0;
    while (i < tot)
    {
        Site *site = myStack.back();
        myStack.pop_back();
        cout << site->i << site->s << endl;
        i++;
    }
}

Compiler errors:

ising_wolff.cpp: In function 'void testStack()':
  ising_wolff.cpp:373:17: error: request for member 'push_back' in
  'myStack', which is of non-class type 'std::vector()'
           myStack.push_back(site);
                   ^ ising_wolff.cpp:380:30: error: request for member 'back' in 'myStack', which is of non-class type 'std::vector()'
           Site *site = myStack.back();
                                ^ ising_wolff.cpp:381:17: error: request for member 'pop_back' in 'myStack', which is of non-class type
  'std::vector()'
           myStack.pop_back();

What do these errors mean?
Here are some sites I have looked at:
1) Creating objects while adding them into vectors
2) push_back causing errors in C
3) how to create vectors of class object

A: vector<Site> myStack();

This is wrong. Lose the ().
You're declaring a function, not a vector.
Just write:
vector<Site> myStack;

A: How to create a vector of class objects in C++?
Start with something simpler so you can get the hang of it.
First, create a vector of primitive ints:
#include <vector>
#include <iostream>
using namespace std;
int main(){
  vector<int> sites(5);
  sites.push_back(5);
  for(int x = 0; x < sites.size(); x++){
    cout << sites[x];
  }
  cout << endl;
  return 0;
}

Compiling it:
g++ -o test test.cpp

Running it:
./test
000005

Create a vector of class objects in a similar way as above:
#include <iostream>
#include <vector>
using namespace std;

class Site {
public:
    int i;
};

int main() {
    vector<Site> listofsites;
    Site *s1 = new Site;
    s1->i = 7;
    Site *s2 = new Site;
    s2->i = 9;
    listofsites.push_back(*s1);
    listofsites.push_back(*s2);
    vector<Site>::iterator it;
    for (it = listofsites.begin(); it != listofsites.end(); ++it) {
        cout << it->i;
    }
    return 0;
}

Which should print:
79

A: You could use:
vector<Site> myStack;
myStack.resize(100); //will create 100 <Site> objects

A: vector<Site> myStack();

This is actually a function declaration. The function is called myStack and it returns a vector<Site>. What you actually want is:
vector<Site> myStack;

The type of neighbours at the moment will store copies of the objects, not references. If you really want to store references, I recommend using a std::reference_wrapper (rather than using pointers):
vector<reference_wrapper<Site>> neighbors;


text:
Q: Box styled with Tailwind has unwanted margin on top of it I'm trying to create a Hamburger menu button. But the button element has an unwanted margin on top of it.

    <button class="bg-blue-400 w-full h-full relative focus:outline-none">
        Open main menu

    </button>

This code is not complete yet. I need to first this issue.
What is wrong here?
Update:
This code also has the same problem.

  <button class="w-full h-full">

  </button>
</div

A: There were pretty much issues with that code.

*

*Absolute and relative can't be used parallel.

*You are making spans and making them block, why not use div.

*Also flex needs to be directed as columns (flex-col).

    <button class="bg-blue-400 w-full h-full relative focus:outline-none">
        Open main menu

    </button>

A: Can't get the code snippet that you provided to produce anything noteworthy or descriptive, may be work uploading an image example but just from a glance. you are using both absolute and relative classes when you should only be using one here:

change to


text:
Q: check box not working properly at page load I have got problem with check-box to enable corresponding control next to it. My Requirement is at the page load we want to disable the all textboxes and dropdownlists by using checkbox
if the check-box is checked the control next to that check-box will be enabled for that i have done like this....
at page load
i have written like this
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ChckOrdType.Checked = false;
            ChkPlntPric.Checked = false;
            ChkExcluBro.Checked = false;
            ......
            .....
        }

and then in checkbox check changed event i have written like this
    protected void ChckOrdType_CheckChanged(object sender, EventArgs e)
    {
        if (ChckOrdType.Checked)
            ddlOrdType.Enabled = true;
        else
            ddlOrdType.Enabled = false;
    }

    protected void chkPlntPric_CheckChanged(object sender, EventArgs e)
    {
        if (ChkPlntPric.Checked)
            ddlPlntPric.Enabled = true;
        else
            ddlPlntPric.Enabled = false;
    }

    protected void chkExcluBro_CheckChanged(object sender, EventArgs e)
    {
        if (ChkExcluBro.Checked)
            ddlExcluBroker.Enabled = true;
        else
            ddlExcluBroker.Enabled = false;
    }

but results is like this ...
I am getting checkbox not checked and control next to it is enabled...But this not what i want
My results is if the check-box is not checked the control next to it is disabled
would any one pls help on this....
Thanks In advance......

A: This is because you have just wrote ONLY to uncheck the checkboxes in the pageload and not to disable the controls  behind the checkbox; If thats needed, then your snippet in the pageload should be:
if (!Page.IsPostBack)
{
  ChckOrdType.Checked = false;
  ChkPlntPric.Checked = false;
  ChkExcluBro.Checked = false;
  ......
  .....
  ddlOrdType.Enabled = false;
  ddlPlntPric.Enabled = false;
  ddlExcluBroker.Enabled = false;
  .........
}

or
if (!Page.IsPostBack)
{
  ChckOrdType.Checked = false;
  ChkPlntPric.Checked = false;
  ChkExcluBro.Checked = false;
  ......
  .....

  ChckOrdType_CheckChanged(sender,e);
  chkPlntPric_CheckChanged(sender,e);
  chkExcluBro_CheckChanged(sender,e);
  ...
}

A: Disable text boxes in page load like below.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ChckOrdType.Checked = false;
            ChkPlntPric.Checked = false;
            ChkExcluBro.Checked = false;

            DisableFirstTime();
            ......
            .....
        }

private void DisableFirstTime()
{
  ddlOrdType.Enabled = false;
  ddlPlntPric.Enabled = false;
  ddlExcluBroker.Enabled = false;
}


text:
Q: Angular: how to share data from custom-component with app-component (app-root) App-Component-Html: (which is in Index.Html as <app-root></app-root> )
<h2> {{currentOrNextWeek}} week from {{dateMonday}} to {{dateFriday}} </h2>
<div class="container"> <router-outlet></router-outlet> </div>

Custom-Component-TS: Is defined in routes -> router.module.ts and besides many other custom-components it has a table showing information realized by data from a service which sends get-requests to an API. Like this:
this.configService.getData.subscribe(data => organizeData(data))

The data itself has information like "Week = Current", "DateOfMonday=01.01.2021" (everything is a string)
How can I pass the data from custom.component to the app.component? I tried EventEmitter but I use <router-outlet>. As I understand correctly the sequence begins with app-component but the first GetData call is in custom-component, but the title is in the app-component-html

A: Your question seems to be how to exchange property between two component that are dynamic and does not need to be parent child.
In that case communication through Service seems to be the best way to go.
You can create a service called AppCommunication with property tittle = new subject() that can have observable which is subscribed at app component and can be injected to you custom component so you can trigger the value from 'next'.
This can be used where ever you want to set it from.

A: you cant send this data using RXJS, behaviourSubject?
on some service:
varbSubject$ = new BehaviorSubject(<string>);

on your app component:
bSubject$ = yourservice.varbSubject$
bSubject$.next("b");

on custom unknow element =>
bSubject$ = yourservice.varbSubject$
bSubject$.subscribe(value => {
  console.log("Subscription got", value);
});

A: Have a look at @ThiagoNascimento post right underneath, it solved my problem!
Link: https://stackoverflow.com/a/70028739/17449921


text:
Q: Where does problems analytically arise in logistic regression on singular data matrix? If you do linear regression without regularization on close-to-singular data matrix $X$ (or it does not have enough data), the problem arises even in closed-form solution $w = (X^TX)^{-1}X^Ty$ when you do $(X^TX)^{-1}$.
If you do logistic regression, your gradient would look like:
$\frac{\partial L(w)}{\partial w} = X(y-\text{logit}(w^TX))$ and I don't see any particular reason why it should diverge if $X$ has not enough data or data is perfectly separable. I would expect gradient to skyrocket when problem is ill-posed, but that is not obviously follows from gradient.
How one can see from analytical derivations that logistic regression would experience serious troubles if we don't have enough data? (same way as be observe inverse of singular matrix in linear regression)


text:
Q: prevent custom iterator from getting nullptr I wrote a PriorityQueue class and an iterator class for it. But I don't understand why these
line compile?
PriorityQueue<int,int> pq;
   auto z =pq.begin();
   z=nullptr;

I mean, The iterator isn't a pointer(It has a pointer in it,but there is no conversion between them).How can I prevent this from hapenning?
EDIT: The begin decleration:
const iterator begin() const;

A: Your single argument constructor
iterator::iterator(Node<Priority,T>* node) : node(node) {}

establishes a user-defined conversion from a pointer type Node<Priority,T>* to iterator.  Since nullptr_t implicitly converts to any pointer type, that gives you a conversion from nullptr to your iterator type.  The line z = nullptr; in your example then implicitly converts nullptr to the iterator type, before calling the automatically-generated move- or copy-assignment operator.
Fix: Add the explicit keyword to your constructor.
explicit iterator(Node<Priority,T>* node) : node(node) {}

Rule from the Standard, section 12.3.1:

A constructor declared without the function-specifier explicit specifies a conversion from the types of its parameters to the type of its class.  Such a constructor is called a converting constructor.
An  explicit  constructor  constructs  objects  just  like  non-explicit  constructors,  but  does  so  only  where  the direct-initialization  syntax  (8.5)  or  where  casts  (5.2.9,  5.4)  are  explicitly  used.  A default  constructor may be an explicit constructor;  such a constructor will be used to perform default-initialization or value-initialization (8.5).


text:
Q: Drbd issue - is it by design? On fresh drbd setup (no filesystem on drbd0, just synced) I have invalidated "node2" state and full sync started:
root@node1:~# drbdadm invalidate-remote drbd0
root@node1:~# drbd-overview
 0:drbd0/0  SyncSource Secondary/Secondary UpToDate/Inconsistent
        [>....................] sync'ed:  0.2% (153188/153464)Mfinish: 1:04:59 speed: 40,180 (40,180) K/sec

and having drbd0 sync from node1 to node2 in progress I have set it primary on node1 for a moment, created ext4, and set it back to standby and then I went to node2 (inconsitent) and made it as primary without any warnings (sic!)
root@node2:~# drbd-overview
 0:drbd0/0  SyncTarget Secondary/Secondary Inconsistent/UpToDate
        [====>...............] sync'ed: 26.7% (112500/153464)Mfinish: 0:47:58 speed: 40,000 (40,296) want: 74,040 K/sec
root@node2:~# drbdadm primary drbd0
root@node2:~# drbd-overview
 0:drbd0/0  SyncTarget Primary/Secondary Inconsistent/UpToDate
        [====>...............] sync'ed: 27.1% (111912/153464)Mfinish: 0:50:37 speed: 37,724 (40,252) want: 75,600 K/sec
root@node2:~#

next, I mounted the ext4 from inconsistent device filesystem without any problems:
root@node2:~# mount /dev/drbd0 /mnt
then in that /mnt I created a few thousands of rsa key pairs (all the time on inconsistend drbd0 on node2 and sync from node1 in progres)
then I unmounted /mnt on node2 and mounted it on node1 and I see there all the files (sync node1->node2 still in progress) which I have created on the inconsistent state drbd0 on node2.
next I created another thousands of files on node1 and remounted /mnt to node2 and I see all the files which were created on node1 and node2 (during full sync on drbd0 on node2 in porgress = inconsistent state of it)
I have checked all files checksums in each step and all were ok.
How it works?? Is that by design? Why there was no split-brain state when I activated drbd0 on inconsistent device? What is the real state of drbd0 device on inconsistent node that is can be used as a primary for read/write?
Was the resync done in both ways: from node1-node2 full sync (as node2 was invalidated in first step) and from inconsistent node node2 -> node1 the changes/files I created when I mounted it there?
After sync completed, final status is ok but I am still confused...
root@node2~# drbd-overview
 0:drbd0/0  Connected Primary/Secondary UpToDate/UpToDate /mnt ext4 148G 1.7G 145G 2%

thank you in advance for any explaination,
best regards,

A: Completely by design. When you made the node with the Inconsistent disk primary it then is essentially reading and writing across the network to the peer with the UpToDate disk.
If you were to break the network connection while the Inconsistent disk was primary, things would have gone south real quick. ;-)
The same also applies if the disk fails on the primary node. DRBD will switch to diskless and then push all reads and writes to the peer node (assuming the peer has a disk which is UpToDate. This can help avoid a service outage due to local disk failure.


text:
Q: Add Rupee symbol in the text box How can i add Indian Rupee Symbol inside a text box field and do not use Rs.
Amount: <input name="amount" type="text" size="20" value="Rs. 1.00">
In this i need to show "Rs." in terms of a symbol, as how we use "$".

A: According to me you shouldn't do this, whether you are saving the value in the database, or you are using to calculate something or anything else, simply store the integer, and than concatenate the Rs. or the rupee sign with the integer. This way it won't trouble you while calculating or storing values.
As far as the rupee symbol goes, you can use ₹
Demo
Demo 2 (Recommended)

Even Better Solution
I've made a demo from scratch which uses background-image, this way, your text field will indicate that the value is a rupee, also, it will be cross browser.
Demo
Demo 2 (Using background-size to make image tiny)
input[type=text].rupee {
    background-image: url(http://i.imgur.com/Fd7NROx.png);
    border: 1px solid #aaa;
    padding: 5px;
    padding-left: 20px; /* Indent the text values inside textbox */
    background-size: 20px 25px; /* Change symbol size */
    background-repeat: no-repeat; /* So that rupee image doesn't repeat */
}

A: use #8360;
<input name="amount" type="text" size="20" value="₨ 1.00">

A: Just include the following javascript and it will update all the " Rs " to " Rupee Symbol " for you
<script src="http://webrupee.anmoul.com/js" type="text/javascript"></script>
or Simply Use rupee symbol Unicode character code &#x20B9

A: Try this snippet
css

 .customTextfield input{
 border:unset;

}
.customTextfield input:focus{
  outline:unset;
}
.customTextfield{
  border:1px solid #000;
  padding:2px;
}
<span class="customTextfield">
  ₹ <input name="amount" type="text">
</span>


text:
Q: Ways to create a Minesweeper table in Java GUI I'm trying to create a Minesweeper game in Java but there is a question: Why is the first attempt not working (lines 3-7)? I mean, supposed to add the buttons on the screen but it doesn't appear.
Probably the problem is in the GameButton constructor but IDK.
for(int i=0;i<size;i++) {
    for(int k=0; k<size; k++) {
        /* this one don't work
        butt[i][k] = new GameButton(i,k);
        contentPane1.add(butt[i][k]);
        */

        // this one works well
        Button button_1 = new Button("?");
        contentPane1.add(button_1);
    }
}

class GameButton extends JButton {
    int row, col;
    public GameButton(int row, int col){
        this.row = row;
        this.row = col;
    }
}

Full code
package gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
//import mapa.*;
//import jogo.*;

public class Gameplay extends JFrame {

    GameButton[][] butt;
    private int size;
    private JPanel contentPane1;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                Gameplay frame2 = new Gameplay("MEDIO");
                frame2.setVisible(true);
            }
        });
    }

    public Gameplay(String dificuldade) {
        this.setTitle("Minesweeper");
        setBounds(100, 100, 450, 300);
        contentPane1 = new JPanel();
        this.setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane1.setBackground(Color.WHITE);
        contentPane1.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane1);
        setLocationRelativeTo(null);

        if (dificuldade.contentEquals("MEDIO")) {
            size = 16;
        }

        contentPane1.setLayout(new java.awt.GridLayout(size, size));

        for (int i = 0; i < size; i++) {
            for (int k = 0; k < size; k++) {
                /* this one don't work
                 butt[i][k] = new GameButton(i,k);
                 contentPane1.add(butt[i][k]);
                 */

                // this one works well
                Button button_1 = new Button("?");
                contentPane1.add(button_1);

            }
        }
    }

    class GameButton extends JButton {

        int row, col;

        public GameButton(int row, int col) {
            this.row = row;
            this.row = col;
        }
    }
}

A: The problem is that the GameButton array is null. It is necessary to initialize it before use.
So this:
GameButton[][] butt;

Should be more like this:
GameButton[][] butt = new GameButton[1][1];

(But change the number from '1')

Edit
I realized the situation was a little more complex than in the first part of the answer. The grid of places in the minefield is set by the size. But the size is not set until the constructor is invoked.
So the approach then would be to initialize the GameButton array after the size has been determined.
Like this. Also look carefully at the code comments.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class Gameplay extends JFrame {

    private int size;
    GameButton[][] butt;
    private JPanel contentPane1;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                Gameplay frame2 = new Gameplay("MEDIO");
                frame2.setVisible(true);
            }
        });
    }

    public Gameplay(String dificuldade) {
        this.setTitle("Minesweeper");
        // instead of doing this, which is no more than a guess,
        // add the components then pack() the frame.
        //setBounds(100, 100, 450, 300);
        contentPane1 = new JPanel();
        this.setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane1.setBackground(Color.WHITE);
        contentPane1.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane1);
        setLocationRelativeTo(null);

        if (dificuldade.contentEquals("MEDIO")) {
            size = 16;
        }
        butt = new GameButton[size][size];

        contentPane1.setLayout(new java.awt.GridLayout(size, size));

        for (int i = 0; i < size; i++) {
            for (int k = 0; k < size; k++) {
                butt[i][k] = new GameButton(i, k);
                contentPane1.add(butt[i][k]);
            }
        }
        this.pack();
    }

    class GameButton extends JButton {

        int row, col;

        public GameButton(int row, int col) {
            this.row = row;
            this.row = col;
        }
    }
}


text:
Q: looping a command without waiting for the first run I want a better way to do this, mostly for command line use:
while sleep 60; do
  mysql -e 'show processlist';
done

This is better than:
while mysql -e 'show processlist'; do
  sleep 60;
done

... because if I type a ctrl-c, it stops.  However, the first version waits for a minute before first output.
I know about watch.  Often good, but not for all circumstances.  I'm looking for a simple output to stdout, not curses.  It'd be nice if watch had a --stdout option.
Simplicity is key here.  I don't care about handling errors in the mysql statement.  It can report its own errors to stdout.

A: This one might work for you:
trap "pkill -TERM -P $$" SIGINT

while [ 1 ]; do
   mysql -e 'show processlist'
   sleep 60
done

A: Ctrl+C does kill the whole loop under normal circumstances. The signal is sent to the whole foreground process group.
You may be looking for
while mysql -e 'show processlist' && sleep 60; do :; done

which exits as soon as either mysql or sleep fails.

A: Well, for your example...
n=; while sleep "$((n&(n=60)))"
do   mysql...
done

...will do it. On the first go it will sleep 0 and all of the rest will sleep 60. Still, I think probably there is a better way to reach your end goal than this.
If you did use something like this you'd probably want to do it in a function:
every_minute() ( n=
    while sleep "$((n&(n=60)))"
    do "$@"; done)

...or in a single line...
every_minute() (n=; while sleep "$((n&(n=60)))"; do "$@"; done)

If you put something like that in your shell's rc file you could just do...
every_minute mysql "$whatever" "$args" "$you" "$use"

...or you could just type out the single-line version at any prompt and continue to use it until you close the shell.


text:
Q: Reset Keychain in swift and IOS 10 crash The problem happen on only in Xcode 8 and IOS 10.
If I use XCode 8 and IOS 9 it is working perfectly.
func resetKeychain() {

    if !self.keychainItemData.isEmpty {
        let tempDict = self.dictToSecItemData(self.keychainItemData)
        var junk = noErr
        junk = SecItemDelete(tempDict as CFDictionary)

        assert(junk == noErr || junk == errSecItemNotFound, "Failed to delete current dict")
    }

    self.keychainItemData[kSecAttrAccount] = ""
    self.keychainItemData[kSecAttrLabel] = ""
    self.keychainItemData[kSecAttrDescription] = ""

    self.keychainItemData[kSecValueData] = ""
}

The assert is always happening in IOS 10 and the app crash
Any Ideas?

A: In your Xcode Project, go to the app target and then to Capabilities. Turn on Keychain Sharing. That should do the trick!


text:
Q: AppleScript to identify the current status of Network Connection? What is the AppleScript to identify the current status of MacBook Pro's network connection (Yosemite 10.10.3)

*

*Connected via Iphone USB on/off (Hotspotting to Iphone)

*Connected via WIFI ON on/off

*Connected via Ethernet on/off

*No Connection
I want to add this condition check into my Automator Workflow, so workflows run similar to many of the IOS Apps that have the setting "do not send files / do not download unless connected to WIFI"

A: If you have Network menu bar item/icon in top right menu bar. You can do:
tell application "System Events" to tell process "SystemUIServer"
    value of attribute "AXDescription" of menu bar items of menu bar 1
end tell

To get connection status. For example:
{"Wi-Fi, four of four bars, with WiFiNetworkName.", "Battery: Charged ", "Clock"}

Then you can parse the string/list to check if a certain word is present.


text:
Q: Read a string file as ints into an array? I need to write a program that takes an input file with the name, age, and score information of a Golfer (practice.txt). The file then should compare the scores with the par scores for the specific age group. For example: Manny is 14, so he follows the par scores for the 12-15 age group. Manny shot a 5 on hole one, so he made par. I'm having trouble understanding how to compare between the file and the array? Any code or ideas to get me on my way would be great.
Input File practice.txt:
Jay 57 4 3 2 3 5 3 2 3 4
Gloria 39 4 4 3 4 3 4 3 3 5
Manny 14 5 6 4 6 5 6 4 4 6
Joe 3 9 8 8 7 6 6 7 5 7
Par Scores Chart:
                           HOLES
AGE             1   2   3   4   5   6   7   8   9

4 and under     8   8   9   7   5   7   8   5   8
5 – 7           7   7   8   6   5   6   7   5   6
8 – 11          6   5   6   5   4   5   5   4   5
12 – 15         5   4   4   4   3   4   3   3   4
16 and over     4   3   3   3   2   3   2   3   3

What I have:
import java.io.File;
import java.util.Scanner;
import java.util.List;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class imTryingHere {
 public static void main (String[] args) throws FileNotFoundException
  {

     int [][] ageGroups =
    {
       {4},
       {7},
       {11},
       {15},
       {100},
    };

    int[][] holePars=
    {
      {8,8,9,7,5,7,8,5,8},
      {7,7,8,6,5,6,7,5,6},
      {6,5,6,5,4,5,5,4,5},
      {5,4,4,4,3,4,3,3,4},
      {4,3,3,3,2,3,2,3,3},
   };

  }
}

A: Try this.
// Put age and par scores into Map
static Map<Integer, List<Integer>> ageParsList = new LinkedHashMap<Integer, List<Integer>>() {
    {put(4,  new LinkedList<Integer>(Arrays.asList(8, 8, 9, 7, 5, 7, 8, 5, 8)));}
    {put(7,  new LinkedList<Integer>(Arrays.asList(7, 7, 8, 6, 5, 6, 7, 5, 6)));}
    {put(11, new LinkedList<Integer>(Arrays.asList(6, 5, 6, 5, 4, 5, 5, 4, 5)));}
    {put(15, new LinkedList<Integer>(Arrays.asList(5, 4, 4, 4, 3, 4, 3, 3, 4)));}
    {put(-1, new LinkedList<Integer>(Arrays.asList(4, 3, 3, 3, 2, 3, 2, 3, 3)));}
};

public static List<Integer> getParScoresList(int age) {

    int targetAge = -1;
    for (Integer key : ageParsList.keySet()) {
        if (age <= key) {
            targetAge = key;
            break;
        }
    }

    return ageParsList.get(targetAge);
}

public static class Player {
    String name;
    int age;
    List<Integer> scoreList;

    public Player(String name, int age, List<Integer> scoreList) {
        this.name = name;
        this.age  = age;
        this.scoreList = scoreList;
    }
}

private static List<Player> getPlayerScore() {
    Scanner scan = null;
    try{
          File file = new File(_path_to_file_);
          scan = new Scanner(file);

          List<Player> playerList = new ArrayList<Player>();

          while (scan.hasNext()) {
              String name = scan.next();
              int age = scan.nextInt();
              List<Integer> scoreList = new LinkedList<Integer>();
              for (int i = 0; i < 9; i++) {
                  scoreList.add(scan.nextInt());
              }
              scan.nextLine(); // last line must have newline character.

              Player player = new Player(name, age, scoreList);
              playerList.add(player);
          }

          return playerList;
    } catch(FileNotFoundException e){
        System.out.println(e);
        return null;
    } finally {
        if (scan != null) {
            scan.close();
        }
    }
}

public static void main (String[] args) {
    List<Player> playerList = getPlayerScore();

    for (Player player : playerList) {
        List<Integer> parScoresList = getParScoresList(player.age);

        for (int i = 0; i < 9; i++) {
            int score = player.scoreList.get(i);
            int par   = parScores.get(i);

            // Compare player's score and par score here.
        }
    }
}

A: NIO's Files.newBufferedReader() is very good
So it will probably look something like this:
Path practiceFile = Paths.get("/tmp/practice.txt");
try (BufferedReader reader = Files.newBufferedReader(practiceFile, StandardCharsets.UTF_8))
{
    Pattern scorePattern = Pattern.compile("^(\\w+)([\\d\\s]+)");
    String line;
    while ((line = reader.readLine()) != null) {
        Matcher m = scorePattern.matcher(line.trim());
        if (m.matches())
        {
          String name = m.group(1);
          String[] scores = m.group(2).trim().split(" ");
          //do more stuff
        }
    }
}
catch (Exception e) {
    e.printStackTrace();
}


text:
Q: Using ViewSwitcher in childs of ExpandableListView I can't alternate correctly 2 views (from my ViewSwitcher)  in any child of my ExpandableListView. The child that alternate the layout is always the first showed at screen (can be the first child of first group, or third child of 2nd group.. if this child is at first in screen)
This is my code:
 protected override void OnCreate(Bundle bundle)
 {
      base.OnCreate(bundle);

      this.SetContentView(Resource.Layout.main);

      ExpandableListView elv = (ExpandableListView)FindViewById(Resource.Id.ExpandableListView01);

      loadData();

      MyExpandableAdapter adapter = new MyExpandableAdapter(this, groups, childs);
      elv.SetAdapter(adapter);

      elv.ChildClick += (object sender, Android.Widget.ExpandableListView.ChildClickEventArgs e) =>
      {
           ViewSwitcher vs = FindViewById<ViewSwitcher>(Resource.Id.details2);
           vs.InAnimation = AnimationUtils.LoadAnimation(this, Resource.Animation.fade);
           vs.ShowNext();

      };
}

Moreover, if I change the ChildClick event to next code, the 'fade' animation will be used on the correct child but I will not be using the layout with the ViewSwitcher, so, how can I do it?
 elv.ChildClick += (object sender, Android.Widget.ExpandableListView.ChildClickEventArgs e) =>
          {
               Animation animation = AnimationUtils.LoadAnimation(this, Resource.Animation.fade);

               e.V.StartAnimation(animation)  ;

          };
    }

A: I answer myself.
elv.ChildClick += (object sender, Android.Widget.ExpandableListView.ChildClickEventArgs e) =>
{

     ViewSwitcher vs = (ViewSwitcher)e.V;
     vs.InAnimation = AnimationUtils.LoadAnimation(this, Resource.Animation.fade);

     vs.ShowNext();

};


text:
Q: Add custom confirm message to standard joomla 3.0 admin toolbar button Add custom confirm message to standard joomla 3.0 admin toolbar button.
I can get alert messages on delete when I don't selected any check boxes on detailed list.
I can get same on any button by set last parameter true in
JToolBarHelper::custom('userdetails.sendMail', 'mail.png', 'mail_f2.png', 'Send Mail', false);

I want to add a confirm message on the click event of this Button?

A: On view file (tpl/view file name).
<script type="text/javascript">
    Joomla.submitbutton = function(task)
    {
        if (task == 'userdetails.sendMail')
        {
            if (confirm(Joomla.JText._('Do you really want to send mails to selected users?'))) {
                Joomla.submitform(task);
            } else {
                return false;
            }
        }
    }
</script>

A: Just as an addition to Suman Singh's answer, you may want to include the script in the document header, and also be able to translate the confirmation text. So, in your layout file, you can write:
$document = JFactory::getDocument();
$document->addScriptDeclaration('
  Joomla.submitbutton = function(task) {
    if (task == "userdetails.sendMail") {
      if (confirm(Joomla.JText._("COM_YOURCOMPONENT_USERDETAILS_SENDMAIL_CONFIRMATION_TEXT"))) {
        Joomla.submitform(task);
      } else {
        return false;
      }
    }
  }
');
JText::script('COM_YOURCOMPONENT_USERDETAILS_SENDMAIL_CONFIRMATION_TEXT');

And of course in the language/en-GB/en-GB.com_yourcomponent.ini file:
COM_YOURCOMPONENT_USERDETAILS_SENDMAIL_CONFIRMATION_TEXT="Are you sure you want to send mails to the selected users?"


text:
Q: Read exact moisture values from soil moisture sensor using raspberry Pi I am new to IoT and I am trying to read the soil moisture sensor readings using Raspberry Pi. I need the EXACT moisture values and NOT just the boolean values as in the water is present or not.
I have tried reading the exact values using Arduino-UNO but not sure on how to do it with Raspberry Pi in python.
I have this code that I found on Intructables.
https://www.instructables.com/id/Soil-Moisture-Sensor-Raspberry-Pi/
#!/usr/bin/python
import RPi.GPIO as GPIO
import time

#GPIO SETUP
channel = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)

def callback(channel):
        if GPIO.input(channel):
                print "no Water Detected!"
        else:
                print "Water Detected!"

GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)  # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback)  # assign function to GPIO PIN, Run function on change

# infinite loop
while True:
        time.sleep(1)

This code just tells if the water is detected or not but I need the actual values of moisture.

A: It is based on the type of output your sensor can provide as well the configuration of the controller I/O channel.
A digital sensor and IO pin can only give 0 or 1 input which is 0V or 3/5V which you are presently using.
 For the requirement you specified, the sensor and IO must be of analog type which gives varying 0-3/5V based on the moisture level. Go through the sensor spec and find out whether analog output it can give then program for the same.
From the link you shared it seems the sensor output is digital(DO) which is not suitable for your requirement. Find a sensor from market which can give AO(analog output).


text:
Q: ARM assembly: bad instruction 'ldrbcc' I am writing an ARM assembly code. In it there is a snippet:
cmp r3, r2
ldrbcc r6, [r3], #1

I want to express if r3 is less than r2, then load [r3] to register r6. But when I compile it with linaro toolchain(version 13.04):
arm-linux-gnueabihf-as -march=armv7-a -mcpu=cortex-a9 test.s -o test

The compiler outputs:
Error: bad instruction `ldrbcc r6,[r3],#1'

I can't figure it out. Anyone can help me? Thanks.

A: LDRBCC is the modern "Unified Assembly Language"; your assembler is defaulting to the older pre-UAL syntax and expects LDRCCB.  You could change your code to use the pre-UAL syntax, but a much better solution is to tell the assembler that you are using the UAL style by adding a ".syntax unified" directive before your code.

A: use ldrccb instead of ldrbcc...

A: Try to run qmake with these arguments:
~/raspi/qt5/bin/qmake -r WEBENGINE_CONFIG+=use_proprietary_codecs QMAKE_CFLAGS+=-mthumb

Then try make


text:
Q: MVC Default binder not binding a nested class I'm having trouble getting the MVC default binder to serialize a nested object.
I've done quite a bit of research to try and figure out what I'm doing wrong, but I'm not seeing it.
The model comes in with all nested objects created (courtesy of the constructors, without them nothing is created) but no data is serialized.
I've overridden the DefaultBinder and added breakpoints to figure out what is failing. It seems to recognize Start and End as DateTimePart, but doesn't do anything with them.
I spent a lot of time trying to read and understand the logic of the DefaultBinder and everything I've read seems to indicate this should work, yet it doesn't. Any help or wild guesses would be appreciated as this is driving me nuts.
Also, to make it clear, I realize I can use a custom binder to overcome this, but before I do I want to understand why this doesn't work with the default binder.
Here's the controller:
public class TestController : Controller
{
    // GET: Test
    public ActionResult Index()
    {
        StartEndTime se = new StartEndTime();
        se.Start = new DateTimeParts();
        se.End = new DateTimeParts();
        se.Start.Date = new DateTime(2015, 2, 22, 13, 12, 0);
        se.End.Date = new DateTime(2015, 3, 1, 10, 43, 0);
        return View(se);
    }

    [HttpPost]
    public ActionResult Index(StartEndTime se)
    {
        return RedirectToAction("Index");
    }
}

Here's the view (example only, replicates the issue, but the real one treats time and date differently)
@model Models.StartEndTime

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    @Html.EditorFor(model => model.Start.DatePart)
    @Html.EditorFor(model => model.Start.TimePart)

    @Html.EditorFor(model => model.End.DatePart)
    @Html.EditorFor(model => model.End.TimePart)

    @Html.SButtonSave()
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Relevant part of generated HTML:
<input name="Start_DatePart" id="Start_DatePart" class="text-box single-line form-control datepicker" type="text" value="2015-02-22">
<input name="Start_TimePart" id="Start_TimePart" class="text-box single-line form-control datepicker" type="text" value="0001-01-01">
<input name="End_DatePart" id="End_DatePart" class="text-box single-line form-control datepicker" type="text" value="2015-03-01">
<input name="End_TimePart" id="End_TimePart" class="text-box single-line form-control datepicker" type="text" value="0001-01-01">

And finally the model. I've included everything since I'm not sure what is causing the issue:
public class DateTimeParts
{
    public DateTime? Date { get; set; }

    public DateTime? DatePart
    {
        get
        {
            if (Date.HasValue)
                return Date.Value.Date;
            else
                return null;
        }
        set
        {
            if (value.HasValue)
            {
                if (Date.HasValue)
                    Date = value.Value.Date.Date + Date.Value.TimeOfDay;
                else
                    Date = value.Value.Date.Date;
            }
            else
            {
                Date = null;
            }
        }
    }

    public DateTime? TimePart
    {
        get
        {
            if (Date.HasValue)
                return new DateTime() + Date.Value.TimeOfDay;
            else
                return null;
        }
        set
        {
            if (value.HasValue)
            {
                if (Date.HasValue)
                    Date = Date.Value.Date + value.Value.TimeOfDay;
                else
                    Date = new DateTime() + value.Value.TimeOfDay;
            }
            else
            {
                Date = new DateTime();
            }
        }
    }
}

public class StartEndTime
{
    public DateTimeParts Start { get; set; }

    public DateTimeParts End { get; set; }

    public int Minutes
    {
        get
        {
            if (!Start.Date.HasValue || !End.Date.HasValue)
                return 0;
            else
                return (int)(End.Date.Value - Start.Date.Value).TotalMinutes;
        }
        set
        {
            if (!Start.Date.HasValue)
                return;
            End.Date = Start.Date.Value + new TimeSpan(0, value, 0);
        }
    }
}

A: I bet it's the way C# handles DateTime. For example, 0001-01-01 doesn't look like a valid date, and it's missing the time stamp.
You should make it set the value to something like:
string dateString = "5/1/2008 8:30:52 AM";

I think the default binder will pick it up then. Use @Html.HiddenFor to test it out.


text:
Q: Action-dependant Javascript/Jquery - how to activate a command only AFTER another script has finished? I'm working on my website and I decided it would be to my advantage to use 'designed' scroll bars instead of the ones browsers come with. I was lucky enough to come across this script http://www.hesido.com/web.php?page=customscrollbar which basically does exactly what I need.
The only problem I've got is that I am trying to apply the custom scrollbars to some divs which are initially hidden and then toggle via a link div between hide/show.
As the programming page (http://www.hesido.com/flexcroll/flexcroll-programming.htm) explains, sometimes the scrollbar needs to be updated and/or manually applied, because being in hidden divs they do not load when the page opens.
I've checked my CSS and my HTML and the code works fine if the div is not hidden, so I am 100% that this has to do with the way I am hiding my divs.
The basic format for that is
$(document).ready(function() {
      $('#iddiv').hide();});
$(document).ready(function() {
 $('#id').click(function() {
      $('#iddiv').animate({
           height: 'toggle'
           }, 2000
      );
 });});

So I hide it initially, and then toggle it via a button.
Now, in this logic - the manual application of fleXenv.fleXcrollMain("your-div-id"); should be somewhere above the last line of script (the one containing }); ).
This, however, either makes the div unscrollable or messes up the rest of my Javascript (scrollTo functions stop working, etc...)
My question is, as a bit of a noobie JS user - WHERE do I need to place that piece of code that manually activates the custom scrollbar in my code  AFTER the toggle is activate and WHAT is the structure?
By which I mean, does fleXenv.fleXcrollMain("your-div-id"); stand on its own, does it need its own separate function, does it get a $ before it?
Loads of thanks to anyone who can help me with this! Final bit stopping me from launching my website.
UPDATE!
HERE is the CSS/HTML and code for an example of what I am trying to achieve; because one of the files in the script needs to be downloaded to work, I think the only way is to copy and paste all the bits in a new HTML document.

A: The jQuery .animate() function accepts more arguments. One of them is a function that gets called when the animation completes.
function activateScrollbar () {
    fleXenv.fleXcrollMain('iddiv');
}

$('#iddiv').animate({
        height: 'toggle'
    },
    2000,
    activateScrollbar
);

You can also use an anonymous function, like this:
$('#iddiv').animate({
        height: 'toggle'
    },
    2000,
    function () {
        fleXenv.fleXcrollMain('iddiv');
    }
);

Most functions in jQuery that include an animation, (like .hide() or .fadeOut()), allow you to pass a function that gets called when the animation completes. Most of these jQuery functions allow you to pass these extra arguments in a configuration object which can be more readable:
$('#iddiv').animate({
        height: 'toggle'
    },
    {
        duration: 2000,
        complete: function () {
            fleXenv.fleXcrollMain('iddiv');
        }
    }
);

See the .animate() documentation for more details.
Here's a full example with the click behavior included:
$('#myButton').click(function () {

    $('#iddiv').animate({
            height: 'toggle'
        },
        {
            duration: 2000,
            complete: function () {
                fleXenv.fleXcrollMain('iddiv');
            }
        }
    );

});

A: Try this:
$(document).ready(function() {
 $('#id').click(function() {
      $('#iddiv').animate({
           height: 'toggle'
           }, 2000,
           function(){
               fleXenv.fleXcrollMain( $(this).attr('id') );
           }
      );
 });

That function is callback executed after animate function is complete.


text:
Q: Using parts of the primary key to improve searching in KUDU I have a primary key composed of three columns (id_grandparent, id_parent, id_row) which is residing in KUDU.
I want my lookups to be fast (hbase-like) when looking by id_grandparent. I'm using Impala and Spark to do lookups, let's assume both of them do the predicate pushdown on equality.
I have some questions which I can't tell 100% sure by reading the docs
SELECT * FROM my_table where id_grandparent = 55

Will this query be able to use the index-order even If i'm not providing the whole primary key? (aka return mega-fast). I'm assuming yes because I guess primary key is sorted by the first column and it's some kind of prefix-scan
SELECT * FROM my_table where id_parent = 55

Will this query be able to use any kind of optimization? Or any non-first column (if first-column not provided) will force a full scan on all the tablets.
I've read about this here: https://kudu.apache.org/2018/09/26/index-skip-scan-optimization-in-kudu.html but I'm not sure if that has been released or not
Thanks beforehand!

A: According to the this JIRA ticket it is still pending.
According to this documentation (latest at the time of this answer)

Scans on multilevel partitioned tables can take advantage of partition pruning on any of the levels independently.

However I doubt is index skip scan is implemented yet, considering the blog post was written only a few months ago.
Update According to reply from dev@kudu.apache.org

Unfortunately the original author's internship ended last summer and nobody has taken the time to complete the work. It would definitely speed up certain types of queries. There are some concerns that in its current state it could cause a performance regression for some queries though. It could probably benefit from improvements to the heuristics it uses to decide when to enable the skip scan optimization.


text:
Q: Can't get ubuntu to recognize my network adaptor on ASUS TP300l and I couldn't find a driver for it on the internet I'm trying ubuntu on my TP300l ASUS laptop but it is not recognizing the network driver, so I can't even find drivers for other devices and I searched on the Internet but couldn't find any drivers for linux.
What can I do to solve that problem?


text:
Q: Haskell fmt library not found When I import the Haskell Fmt module, I get the information
"Could not find module 'Fmt'.
It is not a module in the current program, or in any known package".
GHCi, version 9.2.1: https://www.haskell.org/ghc/  :? for help
ghci> :set -XOverloadedStrings
ghci> import Fmt

<no location info>: error:
Could not find module `Fmt'
It is not a module in the current program, or in any known package.
ghci>

A: Nowadays one uses cabal repl rather than ghci:
cabal repl --build-depends fmt
...
Prelude> :set -XOverloadedStrings
Prelude> import Fmt
Prelude Fmt> let (a, b, n) = ("foo", "bar", 25)
Prelude Fmt> ("Here are some words: "+|a|+", "+|b|+"\nAlso a number: "+|n|+"") :: String
"Here are some words: foo, bar\nAlso a number: 25"


text:
Q: TFLite cross-compiling arm64 build error? As I am currently trying to Tensorflow lite for ARM64 architecture, I just try to follow the instructions from below:
https://www.tensorflow.org/lite/guide/build_arm64#cross-compile_for_arm64
But I simply get a compilation error:
tensorflow/lite/tools/make/downloads/ruy/ruy/cpuinfo.cc:9:21: fatal error: cpuinfo.h: No such file or directory
I am surprised this starting build not working out of the box.
Btw, I am trying to do the above in Ubuntu 16.04 VM.
Anybody had the same issues?

A: Solved now. You need to explicity install Bazel for this.
The tensorflow-lite dependencies script does not do this. Not sure why, should have been part of this.


text:
Q: how to import a .csv or excel file contents into a table in ORACLE 11G i have excel file with me.and i want to create a table with the structure in the excel file in ORACLE 11G. please help me which command is used to do this possible?
Except SQL Developer Option.

A: Suppose your test.csv is as follows
1   ahmad   20000
2   ahmad   20000
3   ahmad   20000
4   ahmad   20000
5   ahmad   20000
6   basit   20000
7   basit   20000
8   basit   20000
Create a cotrolfile.txt in any oracle directory and put parameters you want to have as follows in controlfile
load Data
CHARACTERSET UTF8
infile 'path_of_csv_file\test.csv'
Truncate
into table csvload_table
fields terminated by "," optionally enclosed by '"'
(Coloumn1,Coloumn2,Coloumn3)
Finally invoke sqlldr from cmd with parameters as follows

sqlldr username/password control=path_of_controlfile.txt log=path_of_log_file bad=path_of_bad_records discard=path_of_discarded_records_file


text:
Q: select time and add to getdate using SQL Server i have a column TYPE_TOURNE type datetime that contain '1900-01-01 05:15:00.000'
i want to select just hour and minute and add to getdate().
example : now is 25/02/2013 then the result is  = 2013-02-25 05:15:00.000
select DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))+DATEPART(hh, TYPE_TOURNE) FROM TOURNE

but unfortunately the result is wrong

A: If you want to add time from TYPE_TOURNE to current date and return as datetime then;
Select convert(datetime,
               convert(varchar, getdate(),112) + ' ' +
               convert(varchar, TYPE_TOURNE, 114)
              ) newDate
From TOURNE

OR if you need yyyy-mm-dd hh:mm:ss.mmm format then convert to varchar with 121 format
Select convert(varchar,
               convert(datetime,
                 convert(varchar, getdate(),112) + ' ' +
                 convert(varchar, TYPE_TOURNE, 114)
              ), 121) newDate
From TOURNE

OR if you need just hour & minutes from TYPE_TOURNE then
Select convert(varchar,
               convert(datetime,
                 convert(varchar, getdate(),112) + ' ' +
                 left(convert(varchar, TYPE_TOURNE, 108),6) + '00'
              ), 121) newDate
From TOURNE

A: Either:
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), TYPE_TOURNE)
FROM TOURNE

or, return the TYPE_TOURNE and handle the formatting in the presentation layer.

A: select DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))+DATEADD(hh,0, TYPE_TOURNE) FROM TOURNE

A: Try this:
DECLARE @TimeHolder DATETIME = '1900-01-01 05:15:00.000'

SELECT DATEADD(MINUTE, DATEPART(MINUTE, @TimeHolder),
                   DATEADD(HOUR, DATEPART(HOUR, @TimeHolder),
                        DATEADD(DAY, 0, DATEDIFF(DAY, 0, GETDATE()))))

A: SELECT CAST(CONVERT(DATE, GETDATE()) AS DATETIME) +
CAST(CONVERT(TIME, TYPE_TOURNE) AS DATETIME)
FROM   TOURNE