text:
Q: Having issue in learning CSS Grid and Flex box I am having issues in learning CSS Grid and Flexbox I can not understand the layouts and understand tags. Is there a solution or a way to learn?
Thanks

A: Don't memorize codes, use what you will learn in practices, search about your questions.
you can write a documentation for yourself, draw divs (for example to see whats the difference between "align" and "justify" values).

A: Grid:
Grid Layout

The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning.

For more information try:
https://www.w3schools.com/css/css_grid.asp
Or
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

Flexbox:
CSS Flexbox Layout Module

The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.

For more information try:
https://www.w3schools.com/css/css3_flexbox.asp
Or
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox
Hope these help :)


text:
Q: Put different "schemas" into same MongoDB collection TLDR; Are there drawbacks to putting two different types of documents into the same collection to save a round-trip to the database?
So I have documents with children, and a list of keys in the parent referencing the children, and almost whenever we want a parent, we also want the children to come along. The naive way to do this is to fetch the parent, and then get the children using the list of child keys with $IN (in SQL, we would use a join). However, this means making 2 round trips for a fairly frequent operation. We have a few options to improve this, especially since we can retrieve the child keys at the same time as the parent keys:

*

*Put the children in the parent document
While this would play to mongo's strength, we also want to keep this data normalized

*Pipeline database requests in threads
Which may or may not improve performance once we factor in the connection pool. It also means dealing with threading in a python app, which isn't terrible, but isn't great.

*Keep the parent/child documents in the same collection (not embedded)
This way we can do one query for all the keys at once; this does mean some conceptual overhead in the wrapper for accessing the database, and forcing all indexes to be sparse, but otherwise seems straightforward.
We could profile all these options, but it does feel like someone out there should already have experience with this despite not finding anything online. So, is there something I am missing in my analysis?

A: I'll address the three points separately. You should know that it absolutely depends on the situation on what works best. There is no "theoretically correct" answer as it depends on your data store/access patterns.

*

*It is always a fairly complex decision on how you store your data. I think the main rule should be "How do I query my data?", and not "We want to have all data normalised". Data normalisation is something you do for a relational database, not for MongoDB. If you almost always query the children with the parent, and you don't have an unbound list of children, then that is how you should store them. Just be aware that a document in MongoDB is limited to 16MB (which is a lot more than you think).

*Avoid threading. You will just be better off running two queries in sequence, from two different collections. Less complex is a good thing!

*This works, but it is a fairly ugly way. But then again, ugly isn't always a bad thing if it makes things go a lot faster. I don't quite know how distinct your parent and child documents are of course, so it's a difficult to say whether this is a good solution. A sparse index, which I assume you will do on a specific field depending on whether it is a parent or child, is a good idea. But perhaps you can get away with one index as well. I'd be happy to update your answer after you've shown your suggested schemas.
I would recommend you do some benchmarking, but forget about option 2.

A: If there are more levels in the hierarchy (also works fine for one level) it is a good choice to have an array of ancestors. This is kind of a trick which is not invented by me of course it was explained in the mongodb Developer course : https://education.10gen.com/courses (this is just a link where you can find the curse i cannot link to the tutorial directly). In this case you have an array of ids which contains at least the node itself  and all the ancestors ids. If you query for a sub-tree you just have to search for the root in the ancestors array.
The documents hold an:
{ancestors: [2,7,6]}

You query for subtree under node 6:
find({ancestors:6})

This is nice but in a real world example you usually not query for ids. So you will have two queries one for something meaningful and one for the ids belongs to that.
But if you query for the id at the first step this solution resolves your issue.
I think due to mongodb lots of things depends on the structure of parent-child relation. If there is only one level of lineage there is no really particular reason to store the data separately and in this case the ugly way is the good choice , even more if you likely to have a complex queries (and indexes) over it, use denormalizing.
(You are not really have chance to query for some feature of parents and retrieve children in the same query without denormalizing/embedding) but embed only if you have a really few-few connection and denormalize only if you not duplicate lots of data. Performance with the two queries won't be that bad if you store the children ids in an array (and index it), it is not a really bad idea compare to keep clean the denormalized data or handle the 16MB limit with the embedding.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQLite multiple table INNER JOIN with USING (...) Errors I am trying to run a query on a SQLite database that INNER JOINs two additional tables:
SELECT
    usages.date AS date,
    usages.data AS data,
    stores.number AS store,
    items.name AS item
FROM usages
INNER JOIN stores USING (store_id)
INNER JOIN items USING (item_id)

However, I get the error
SQL error: cannot join using column item_id - column not present in both tables

I know I can use the explicit INNER JOIN stores ON usages.store_id = stores.store_id (and it works), but:
why does the USING query throw an error in SQLite?
It doesn't on MySQL...
I should note:
This isn't a problem for me, as I am using the ON syntax, but I would like to know why this is happening.

A: So you have:
INNER JOIN items USING (item_id)

...and you get an error that says:

SQL error: cannot join using column item_id - column not present in both tables

That's got to be one of the least cryptic error messages I've seen.
What I don't like is that it's not clear to me what table is being compared to ITEMS.item_id - is it STORES or USAGES?  Which is why I refrain from the USING or NATURAL join syntax...


text:
Q: Settings schema 'x.dm.slick-greeter' is not installed I wanted to have a login screen background on Ubuntu 18.04. I followed this: https://askubuntu.com/a/1043034/167612 but it wasn't of much success. Any kind of clue will be helpful.
user:~$ sudo lightdm-settings

(lightdm-settings:6696): GLib-GIO-ERROR **: 14:23:27.908: Settings schema 'x.dm.slick-greeter' is not installed

user:~$

A: lightdm-settings needs slick-greeter (https://github.com/linuxmint/slick-greeter) to be installed, even though it is not listed as a dependency. So just do
sudo apt install slick-greeter


text:
Q: Error occured while running script in QGIS? I am using QGIS version 2.18.9. I first create a graphical modeler and it is working. Then I export it to python script. While I am running the script I got following error massage.

"NoneType' object has no attribute 'getitem See log for more detail".

Can you explain the reason?
My script is shown below:
##Testing=name
##drawingdxf=file
##cleanf=output vector
outputs_GRASS7V_IN_DXF_1=processing.runalg('grass7:v.in.dxf',drawingdxf,'1',True,False,True,False,False,True,['200000.000000,700000.000000,200000.000000,700000.000000'],0,None)
outputs_GRASS7V_CLEAN_1=processing.runalg('grass7:v.clean', outputs_GRASS7V_IN_DXF_1['output'],1,0.1,['200000.000000,700000.000000,200000.000000,700000.000000'],-1.0,0.0001,cleanf,None)

A: You are getting the error because of points in variable name. Variable name doesn't include points. Try to change outputs_GRASS7V.IN.DXF_1 into outputs_GRASS7V_IN_DXF_1 or something else without points.


text:
Q: Dynamic number of stacked LSTM in custom Tensorflow model I'm trying to implement a custom model in tensorflow extending the tf.keras.Model class.
I need a way to add n stacked LSTM layers to the model.
For instance, assuming the following implementation
class CustomizedLSTM(tf.keras.Model):
    def __init__(self, num_hidden_layers, vocab_size):
        super(CustomizedLSTM, self).__init__()
        self.embedding = tf.keras.layers.Embedding(vocab_size,300)
        self.first_lstm = tf.keras.layers.LSTM(256, activation="relu")
        self.first_dense = tf.keras.layers.Dense(64, activation="relu")
        self.classification_layer = tf.keras.layers.Dense(1, activation="sigmoid")

    def call(self, inputs):
        x = self.embedding(inputs)
        x = self.first_lstm(x)
        x = self.first_dense(x)
        return self.classification_layer(x)

I would like to add the possibility to customize the number of hidden LSTM layers.
in other words I would like create a model with num_hidden_layers stacked LSTMs.
Is it possible? Can you please help me?

A: class CustomizedLSTM(tf.keras.Model):
    def __init__(self, num_hidden_layers, dim_per_hidden, vocab_size):
        self.lstms = []
        super(CustomizedLSTM, self).__init__()
        self.embedding = tf.keras.layers.Embedding(vocab_size,300)
        '''
        To stack multiple LSTMs, it is mandatory for all the lower LSTMs to have
        return_sequence=True, as they will be fed as input to the next LSTM.
        '''
        for i in range(num_hidden_layers):
            self.lstms.append(tf.keras.layers.LSTM(dim_per_hidden[i], activation="relu", return_sequences=True))
        '''
        The last lstm with return_sequences=False, you can change it according to
        your needs.
        '''
        self.lstms.append(tf.keras.layers.LSTM(dim_per_hidden[i], activation="relu", return_sequences=False))
        self.first_dense = tf.keras.layers.Dense(64, activation="relu")
        self.classification_layer = tf.keras.layers.Dense(1, activation="sigmoid")

    def call(self, inputs):
        x = self.embedding(inputs)
        for layer in self.lstms:
            x = layer(x)
        x = self.first_dense(x)
        return self.classification_layer(x)

I added another parameter that you can consider - "dim_per_hidden":
This parameter is a list of numbers to decide the number
of neurons of each lstm layer


text:
Q: "NameError: name is not defined" for user input I am new to python and made a short script to try them out, while doing so I came across and error I've never had for the particular situation before, when I try to define uN as a str inputted by the user I get:
Traceback (most recent call last):
  File "/home/pi/Desktop/Scripts/classTest/classTest1.py", line 14, in <module>
uN = input(str("Username"))
  File "<string>", line 1, in <module>
 NameError: name 'ben' is not defined

The code is as follows:
class user:
    def __init__(self, usrName, pWord):
        self.usrName = usrName
        self.pWord = pWord

    def createUsrPw(self):
        f = open("usrName.txt", "a")
        f.write(self.usrName)
        f.write("   ")
        f.write(self.pWord)
        f.write("\n")
        f.close()

uN = input(str("Username"))
pW = input(str("Password"))

usr1 = user(uN, pW)

usr1.createUsrPw()

I have used the x = input(str()) syntax a lot before and never had this error, and the error traces back to line 1, so is uN = input(str("Username")) still being considered a part of the class?
when I simplify the code to this it works perfectly:
class user:
    def __init__(self, usrName, pWord):
        self.usrName = usrName
        self.pWord = pWord

    def createUsrPw(self):
        f = open("usrName.txt", "a")
        f.write(usrName)
        f.write("   ")
        f.write(pWord)
        f.write("\n")
        f.close()

usr1 = user("Ben", "testPw")

usr1.createUsrPw()

with the file usrName.txt being appended to include "Ben   testPw" as intended.

A: You should use raw_input instead of input as you are using Python 2.X. input works in Python 3.
This code would work:
class user:
    def __init__(self, usrName, pWord):
        self.usrName = usrName
        self.pWord = pWord

    def createUsrPw(self):
        f = open("usrName.txt", "a")
        f.write(self.usrName)
        f.write("   ")
        f.write(self.pWord)
        f.write("\n")
        f.close()

uN = raw_input("Username")
pW = raw_input("Password")

usr1 = user(uN, pW)

usr1.createUsrPw()

A: Use raw_input. This looks like a Python 2 error, I don't think you're using Python 3
You also don't need to call str on a string literal. str("asdf") == "asdf"


text:
Q: Adding an onclick event to a new html element only working on the last element The problem is that when I create page number buttons at the bottom of the page the onclick only ever works with the last element created.
Here is what the page buttons look like:

    for(var i = 0; i < numberOfPages; i++) {
        if(Math.floor((((startIndex + 1) / 10) + 1)) == (i + 1)) {
            var newElement = document.createElement("u");
            document.getElementById("imagesNav").appendChild(newElement);
            newElement.id = "imagesNavU";
            var newElement = document.createElement("a");
            document.getElementById("imagesNavU").appendChild(newElement);
            var str = "page" + (i + 1);
            newElement.innerHTML = i + 1;
            newElement.onclick=function(){currentPageNumber(str);};
        } else {
            var newElement = document.createElement("a");
            document.getElementById("imagesNav").appendChild(newElement);
            var str = "page" + (i + 1);
            newElement.innerHTML = i + 1;
            newElement.onclick=function(){currentPageNumber(str);};
        }
        if(i + 1 != numberOfPages) {
            document.getElementById("imagesNav").innerHTML += "  ";
        }
    }
}

The first if statement just puts underline tags on if that element is the current page.
Edit:  The problem has been solved.  Thank you to everyone for their help!

A: The problem is with this part of the loop:
    if(i + 1 != numberOfPages) {
        document.getElementById("imagesNav").innerHTML += "  ";
    }

This is re-parsing all the HTML in the imagesNav element. This creates new <a> elements, which don't have the onclick bindings that the previous ones had.
Instead, you can append a <span> element containing the spaces.

var numberOfPages = 3;
var startIndex = 0;

for (var i = 0; i < numberOfPages; i++) {
  if (Math.floor((((startIndex + 1) / 10) + 1)) == (i + 1)) {
    var newElement = document.createElement("u");
    document.getElementById("imagesNav").appendChild(newElement);
    newElement.id = "imagesNavU";
    var newElement = document.createElement("a");
    document.getElementById("imagesNavU").appendChild(newElement);
    var str = "page" + (i + 1);
    newElement.innerHTML = i + 1;
    newElement.onclick = function() {
      currentPageNumber(str);
    };
  } else {
    var newElement = document.createElement("a");
    document.getElementById("imagesNav").appendChild(newElement);
    var str = "page" + (i + 1);
    newElement.innerHTML = i + 1;
    newElement.onclick = function() {
      currentPageNumber(str);
    };
  }
  if (i + 1 != numberOfPages) {
    var span = document.createElement('span');
    span.innerHTML = '  ';
    document.getElementById("imagesNav").appendChild(span);
  }
}

function currentPageNumber(str) {
  alert(str);
}
<div id="imagesNav">

</div>

Another way to do it is with insertAdjacentHTML, which adds HTML to an element without re-parsing what's already in it.
    document.getElementById("imagesNav").insertAdjacentHTML('beforeend', '  ');

You should also see JavaScript closure inside loops – simple practical example because the way you're using the str variable, all the click handlers will use the value from the last iteration of the loop.


text:
Q: What does it mean by approach, method, principle, technique in ELT? According to Longman Dictionary of Language Teaching and Applied Linguistics:
.

approach n
  in language teaching, the theory, philosophy and principles underlying a particular set of teaching practices.
Language teaching is sometimes discussed in terms of three related aspects:
  approach, method, and technique.
Different theories about the nature of language and how languages are learned
  (the approach) imply different ways of teaching language (the method), and different methods make use of different kinds of classroom activity (the
  technique).
Examples of different approaches are the aural–oral approach (see audiolingual method), the cognitive code approach, the communicative approach, etc. Examples of different methods which are based on a particular approach are the audiolingual method, the direct method, etc.
Examples of techniques used in particular methods are drills, dialogues,
  role-plays, sentence completion, etc.

.

method n
  (in language teaching) a way of teaching a language which is
  based on systematic principles and procedures, i.e. which is an
  application of views on how a language is best taught and learned and
  a particular theory of language and of language learning.
Different methods of language teaching such as the direct method, the
  audiolingual method, total physical response result from different
  views of: a the nature of language b the nature of second language
  learning c goals and objectives in teaching d the type of syllabus to
  use e the role of teachers, learners, and instructional materials f
  the activities, techniques and procedures to use.

.

principles1 n
  in teaching, beliefs and theories that teachers hold
  concerning effective approaches to teaching and learning and which
  serve as the basis for some of their decision-making.
For example,
Make the lesson learner-centered.
Every learner is a genius.
Provide opportunities for active learner participation.
Teachers' principles are an important aspect of their belief systems and may be
  a result of teaching experience, training, or their own experiences as
  learners.

.

technique n
  in teaching, a specific procedure for carrying out a teaching activity, such as
  the ways a teacher corrects students' errors or sets up group activities.
  see approach

I haven't understood these definitions.
They seemed to be recursive. For instance, APPROACH makes use of "principle" to define itself, on the other hand, PRINCIPLE makes use of "approach" to define itself.
Where can I find better definitions?

A: I suspect you are studying that dictionary with a lot more precision than its authors expected! And I don't think those particular definition were written with enough rigour to withstand the kind of (admirable) scrutiny you are giving them. Also, the concepts being discussed are simply not sufficiently clear to allow precise definitions to be constructed.
As a result, the bottom line is that I doubt you're going to find anything else that is very much better than what you already have. So I'd suggest that rather than go on a hunt for better definitions, you just gather a few from some reasonable sources and then compare them. In doing that, if you retain what is common to all of them, and discard or at least pay less attention to the rest, you can converge on what the various authors are talking about.
I did a little bit of that, and from my quick survey I think it's safe to say that of the four words you are mulling over —- principles, approaches, methods, and techniques —- only the first is problematic from a self-reference point of view (although the way the definition of approaches includes mini definitions of all three core terms is also confusing). By contrast, the other three seem to be the key concepts at play. They appear to be a classic "chunking", each concept being a more abstract context or "container" for the one following it.
So: approaches are the highest, most abstract level. Any given approach then provides a context within which reside any number of methods. Finally, each method will be implemented in practice using one or more techniques.
If you really want to fit the less formal notion of principles into that pyramid, then I'd say it is a layer on top — i.e. it is the context for approaches. The fact that their definitions of approach and principle appear to refer to each other is, I'd guess, simple carelessness on their part. You are quite correct to notice the issue. However, as I said, I don't think they'll have been expecting such a precise reader.


text: Q: Buck converter vs LDO I have a simple STM32 MCU board design that will be sleeping most of the time, waking every 30 minutes to take some measurements (which take about 20 seconds max), and then going back to sleep. It must run without intervention for 4 years (in the ground). Our sleep current usage is in the nAmps. I'm curious whether I am better off with a buck converter going from 6V -> 3.3V or use an LDO.  I realize the LDO is not as efficient and every mA counts so I am leaning toward a buck converter but wonder what others think.


text:
Q: Autostarting .desktop application at startup not working I have read that adding a .desktop file to /etc/xdg/autostart can start an application at startup. I did the same to execute my application. But nothing happens on startup. Following is the content of my .desktop file:
[Desktop Entry]
Type=Application
Encoding=UTF-8
Version=1.0
Name=screenshot
Exec=/home/anaswara/eclipse_agent/bin/Screenshot
X-GNOME-Autostart-enabled=true
X-KDE-autostart-after=panel

Can anybody tell what is going wrong(Ubunu 14.04)

A: My standard debugging flow for desktop entry file (.desktop application):

*

*file format - check if the desktop entry follow the spec of freedesktop.

*executable command - if the previous check looks good, try your command of Exec in a terminal directly.

*executable as expected - if the previous check looks good, then double click the .desktop with your mouse.

*executing environment - if the previous check looks good, it means your execution command and .desktop should at least run in your desktop environment. Put it under ${HOME}/.config/autostart will definitely work.

[Additional Information]

*

*What if it does still not work with all check passed and .desktop has been in ${HOME}/.config/autostart?

*

*You may consider to redirect logs from your Exec in .desktop to see what special application behavior raised by your executable.

*Why does ${HOME}/.config/autostart work but not /etc/xdg/autostart?

*

*There are possible root causes. The most common case is that your executable needs to read or manipulate user-specific files/directories/config/cache/environment. For example, an autostart applet wants to write something in $HOME/.cache. Trigger .desktop in $HOME/.config/ will make sure the executable is triggered with a known $HOME.

A: Copy and Paste the .desktop file to /home/'user'/.config/autostart/, e.g. /home/rumi/.config/autostart/app.desktop where rumi is the user and app.desktop is the .desktop file.
Should work fine.


text:
Q: How to include movie showtimes in Google Movies? I am making the website of a movie theater, and I want Google Movies to index the showtimes I publish on the website.
Does anyone know if there's a way to do this? Maybe using Microformats? Or exposing this information using RSS or something similar?

A: I don't believe that Google harvest the show times from the theater web site, they probably buy/tap into a reliable source for that.
At most you need to make sure that the theater is listed under Google Local.

A: This depends on the region.  Google anoints specific companies that scrape or attach to Cinema APIs for sharing session data.  This is a common feature of cinema-specific point-of-sale solutions.
Whoever is the anointed company in your region that google uses, contact them and tell them how to get to an exposed endpoint for your session data.
Otherwise, they try to scrape it, usually with many errors.
Personally, I find Google is acting very poorly here and building silos of data mining companies that can abuse this data (Manipulate it).  This should be an open public API that a cinema can simply make available on their website and Google can attach to automatically based on creating a company in the google business application and like defining the opening hours, if the business is a Cinema, define the session times data endpoint.


text:
Q: "Uncaught SyntaxError: Unexpected token {" when loading module i wanted to move part of my code into JS module, but when I did that i get:
Uncaught SyntaxError: Unexpected token { on line 3 of script.js
The script.js starts like this:
'use strict'

import {MyClass} from "./module.js";

The module.js starts like this:
'use strict';

export class MyClass {

Both files are imported in index.html at the end of body:
<script src="js/module.js" type="module"></script>
<script src="js/script.js"></script>

When I change reference to script.js to type="module", the error is not thrown anymore, but I cannot use any of script.js's functions in onload etc.

A: Some browsers support ES6 modules as long as you use type="module" in your imports. So you need to make it like this:
<script src="js/script.js" type="module"></script>

Now you said that you cannot use functions from script.js when you do this. could you be more specific ? (by sharing code and error may be)


text:
Q: SSH via /sbin/ssh cannot read RSA-Key-File (running from console works) I am trying to connect to a server via SSH from my C++ application (and send a shut-down command). I have informed the server about my SSH-key (updated authorized_keys on my FreeBSD-based Freenas server).
The following console command works instantly (Manjaro Linux console):
ssh -i /home/[uname]/.ssh/amd_freenas root@freenas.local poweroff

I'm trying to use the following command from my C++ code to do exactly the same:
execl("/sbin/ssh", "ssh", "-i /home/[uname]/.ssh/amd_freenas", "root@192.168.178.48", "poweroff", (char*)NULL);

When called from my program, the console output consistently says, that my SSH-file does not exist, which is not true, since the direct console command has no issues either (picture shows comparison, upper command was from code, bottom one was in the console directly).
The error output is:
Warning: Identity file  /home/al/.ssh/amd_freenas not accessible: No such file or directory.

I have tried to change permissions on the file (chmod 600), I tried to move it elsewhere and read it from there. I have no clue why this does not work. The file is my private key, so that should be correct. Can somebody help?
enter image description here

A: execl("/sbin/ssh", "ssh", "-i /home/[uname]/.ssh/amd_freenas", ...

Warning: Identity file  /home/al/.ssh/amd_freenas not accessible
                      ^^

ssh is interpreting the space following the -i as part of the filename. You can see that there's an extra space before the name of the key file in the error message, because ssh thinks the name has a leading space.
You should specify the parameter in one of these ways:
execl("/sbin/ssh", "ssh", "-i", "/home/[uname]/.ssh/amd_freenas", ...

or
execl("/sbin/ssh", "ssh", "-i/home/[uname]/.ssh/amd_freenas", ...


text:
Q: Waf Application already defines some members (initializecomponent, main, _contentLoaded) I'm using the WAF-Framework for building a MVVM-Application. I got my own App-Class (App.xaml and App.xaml.cs).
Everytime I try to compile my application I get 3 different error messages:

*

*The type MyApplication.Presentation.App already defines a member
InitializeComponent with same types of parameters

*The type MyApplication.Presentation.App already defines a member Main with same types of parameters

*The type MyApplication.Presentation.App already contains a definition for _contentLoaded
When I click on the error-message I get redirected to a file called App.g.cs. If I then remove everything within this file, my application will be build and everthings works as wished. But after another change the file is back and I would have to delete it again.
I checked all my files and I can't find another definition of these 3 members. I don't have another Main-Method anywhere. I also tried to rename my Application but this didn't solve the problem.
Any suggestions what I could do to solve this annoying problem?

A: I had something very similar recently, and it turned out that when importing existing code files I had imported the obj directory itself!

This directory contained, for example, the auto-generated (and automatically imported) MainWindow.g.i.cs file. So I was effectively including the same partial class definition twice, hence the "already defined" errors.
Excluding this folder from the project and rebuilding the solution works to resolve the errors.

A: In case someone else had similar problem - this was my solution:
The problem occured after I've copied and pasted one of my Views (.xaml and .cs files). I changed the file's name, BUT NOT A CLASS NAME, so I had two classes with same name.
Then after other changes in code I forgot about it.
This was giving same error as in question.
So like in previous answer the compiler while auto-generating g.cs and g.i.cs files was giving an error - because there was this class name used already. A class was partial (as xaml views are), so duplicated classname was not a problem, but duplicated constructors and everything else - was.


text:
Q: Redirect to Index page after session timeout not working in .war We are using Struts2 & GWT-EXT.
We have crated a LoginInterceptor which will be called before performing certain restricted tasks.
Here is the method of LoginInterceptor
public String intercept(ActionInvocation arg0) throws Exception {

        try
        {
            System.err.println("inside the login interceptor");
            Map session = arg0.getInvocationContext().getSession();
            User loggedInUser = (User)session.get("loggedInUser");

            if(loggedInUser != null)
            {

                return arg0.invoke();
            }else {

                throw new AuthorizationException("unAuthorized");
            }

        }catch (Exception e) {
            throw e;
        }
    }

After session timout.. If a user clicks on any button. Before proceeding LoginInterceptor gets called and checks whethere user is logged in or not.
In the code
We have a method  public void onFailure(Throwable caught) {
where i check that
if (caught instanceof InvocationException) {
        if (caught instanceof StatusCodeException
                && caught.getMessage().contains(
                    "<title>Error 500 unAuthorized</title>")) {
            MessageBox.alert("Session Expired", "Session has been expired. Press Ok to redirect to Login page.", new AlertCallback(){
                    public void execute(){
                        History.newItem(HistoryToken.INDEX_PAGE.toString());
                    }
                });

        } else if (caught.getMessage().contains("LoginInterceptor")) {
            History.newItem(HistoryToken.INDEX_PAGE.toString(), true);
        }

Then, I redirect it to Index Page.
This works in Eclipse fine in Hosted Mode but when I create .war and run it in JBoss. It does not comes into onFailure method and gets redirected directly to Index Page.

A: Hiii...
try this code just before the invocation exception code. before if (caught instanceof InvocationException) {
 condition....
if(caught.getMessage().contains("unAuthorized") )
    {
        MessageBox.alert("Session Expired", "Session has been expired. Press Ok to redirect to Login page.", new AlertCallback(){
            public void execute(){
                History.newItem(HistoryToken.INDEX_PAGE.toString());
            }
        });

    }


text:
Q: How to sort orders by timestamps? I want my recent order at the top
I am trying
Order.find({ userID: req.params.id })
.sort({'timestamps': -1})

but it dosen't work.

A: I have added sample code for you which I have done on mongo shell. You can do it same way.
Following is the sample data document with collection name people in the database:
{ "_id" : ObjectId("60540411ad84317971f11dc3"), "name" : "john", "age" : 24, "gender" : "female" }
{ "_id" : ObjectId("60540457ad84317971f11dc4"), "name" : "sarah", "age" : 15, "gender" : "male" }
{ "_id" : ObjectId("60540536ad84317971f11dc5"), "name" : "jimmy", "age" : 19, "gender" : "male" }
{ "_id" : ObjectId("60540583ad84317971f11dc6"), "name" : "sashi", "age" : 20, "gender" : "male" }
{ "_id" : ObjectId("6054074fad84317971f11dc7"), "name" : "kevin", "age" : 39, "gender" : "male" }
{ "_id" : ObjectId("60540760ad84317971f11dc8"), "name" : "daisy", "age" : 5, "city" : "WA", "gender" : "female" }
{ "_id" : ObjectId("60540786ad84317971f11dc9"), "name" : "kevin vien", "age" : 25, "gender" : "female" }
{ "_id" : ObjectId("60540791ad84317971f11dca"), "name" : "sara", "age" : 24, "gender" : "male" }
{ "_id" : ObjectId("605554facebf6a49ed5b6e97"), "name" : "chloe", "city" : "LA", "age" : 56, "mothertoungue" : "english", "gender" : "female" }
{ "_id" : ObjectId("60593aec8658728413dd21bf"), "name" : "brett", "age" : 28, "gender" : "female" }
{ "_id" : ObjectId("60593afb8658728413dd21c0"), "name" : "matt", "age" : 28, "gender" : "female" }
{ "_id" : ObjectId("60593b0c8658728413dd21c1"), "name" : "george", "age" : 29, "gender" : "female" }
{ "_id" : ObjectId("60593b1d8658728413dd21c2"), "name" : "cassindra", "age" : 22, "gender" : "male" }
{ "_id" : ObjectId("60593b2a8658728413dd21c3"), "name" : "daisy pies", "age" : 49, "gender" : "male" }
{ "_id" : ObjectId("60593b3e8658728413dd21c4"), "name" : "john dion", "age" : 47, "gender" : "male" }
{ "_id" : ObjectId("605a914f5cc4ed47147fa728"), "name" : "dweyn", "city" : "tokyo", "gender" : "female", "age" : 23 }

So, if you sort for the above then the code would be as below:
db.people.find({'gender':'female'},{name:1,age:1,_id:0,gender:1}).sort({age:-1})

This perfectly work fine for me. It should for you as well.


text:
Q: Forms are broken in CodeIgniter I am trying to rewrite my urls to go from /controller/method to index.php?/controller/method, and that is mostly working, except that forms won't submit correctly. I have some routing set up, but the forms are also breaking on non re-routed urls. Here's a little context.
I have moved my index.php out into a separate web folder that is the web root, so there is no chance of exposing application files. I'm not sure whether this would potentially cause this problem, but it's something slightly unusual about my installation. My directory structure looks like:
+ codeigniter/
  + application/
    - models, views, etc
  + system/
  + web/
    - .htaccess
    - index.php
    - css, javascript, images, etc

My .htaccess is pretty simple:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

It seems to work fine on XAMPP for Windows, but it is broken on a basic Ubuntu LAMP stack. When I submit a form, nothing happens. The page that the form directs to loads, but as if the form hadn't been submitted.
Sorry, one more important piece of information: If I leave the index.php in there, so the urls look like /index.php/contacts/edit/1, it works.
Let me know if I can provide any more information. Thanks!

A: Turns out a part of the .htaccess that I didn't include was causing the error to be difficult to find.
<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

I had assumed that this would show a CodeIgniter error page if it reached that block, but it turns out (I assume) that CodeIgniter was valiantly trying to salvage the situation by looking at the path in $_SERVER, from which it was able to get the page it was supposed to display. However, since the path didn't exist, none of the $_POST data made it through. In the error log I was seeing this line:
[error] File does not exist: /path/to/web/contacts/edit/1

Enabling mod_rewrite solved the problem.


text:
Q: how to pass output of grep to "lsof -p" I want to know the path of currently running ./a.out
There are several MPI process, but I only need one of the PID of several ./a.out. So I first use below code to grep it
ps aux|grep -P "Rl.*a\.out"|grep -oP "\d+"|head -n 1

which gives one pid, for example 12345
Now I want to use
lsof -p12345

to know the file path of PID 12345
How to combine the two step into one command line?

A: This is the command that you need:
ps aux|grep -P "Rl.*a\.out"|grep -oP "\d+"|head -n 1 | xargs lsof -p

The key here is xargs.
Commands such as grep and awk can accept the standard input (STDIN) as a parameter, or argument by using a pipe. However, others such as cp, echo and lsof disregard the standard input stream and rely solely on the arguments found after the command.
Using the command xargs you can build and execute command lines from standard input.

A: I would recommend using xargs when a command returns multiple lines (or records). In this case, the command returns a single PID and a shell feature known as command substitution would be an appropriate solution.
This allows the output of one command to be used by another and is accomplished by wrapping the command that provides the input in $( and ). In the past, backticks (`) were used but these are no longer recommended.
lsof -p $(ps aux|grep -P "Rl.*a\.out"|grep -oP "\d+"|head -n 1)

A: Your 1st complex command to find the PID based on name can be replaced by pgrep, e.g.
$ pgrep -nf a.out
70512

Then to get the path from lsof, you can use conditional print in awk.
So the command could be:
$ lsof -p $(pgrep -nf a.out) | awk '$4 == "cwd" {print $9}'

Above is based on the following lsof output:
$ lsof -p $(pgrep -nf a.out)
COMMAND   PID   USER   FD   TYPE DEVICE  SIZE/OFF      NODE NAME
gsleep  70513 kenorb  cwd    DIR    1,4      1938 121793972 /my/path


text:
Q: Visual Basic. Method cannot be reflected I have a problem using soap client in vb.net with Visual Studio 2015 Community. I want to use to soap client library, but I can't find it.
So, I found the wsdl.exe command in Visual Studio 2015 Community. I tried wsdl.exe. It generated the code in the following link:
https://github.com/yahoojp-marketing/sponsored-search-api-documents/blob/master/wsdl/LocationService.wsdl
C:\Program Files\Microsoft Visual Studio 14.0>wsdl /l:VB https://ss.yahooapis.jp/services/V6.0/LocationService?wsdl /out:C:\Users\user_name\Desktop\

I added the Project and successfully compiled it. However, an exception occurs when instantiate the object in this line.
Dim LocationServiceWsdl As New LocationService()

Below is the error message.

Message: LocationService.get cannot to be reflected
  InnnerException: An error occurred while reflecting the SoapHeader.
  at:
  System.Web.Services.Protocols.SoapReflector.ReflectMethod(LogicalMethodInfo methodInfo, Boolean client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, String defaultNs)
  System.Web.Services.Protocols.SoapClientType.GenerateXmlMappings(Type type, ArrayList soapMethodList, String serviceNamespace, Boolean serviceDefaultIsEncoded, ArrayList mappings)
  System.Web.Services.Protocols.SoapClientType..ctor(Type type)
  System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()

LocationService.vb
<System.Web.Services.Protocols.SoapHeaderAttribute("RequestHeader"),
 System.Web.Services.Protocols.SoapHeaderAttribute("ResponseHeader", Direction:=System.Web.Services.Protocols.SoapHeaderDirection.Out),
 System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace:="http://ss.yahooapis.jp/V6", ResponseNamespace:="http://ss.yahooapis.jp/V6", Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)>
Public Function [get](ByVal accountId As Long, <System.Xml.Serialization.XmlElementAttribute("error")> ByRef [error]() As [Error]) As <System.Xml.Serialization.XmlElementAttribute("rval")> LocationReturnValue
    Dim results() As Object = Me.Invoke("get", New Object() {accountId}) ' <- maybe error occurs here.
    [error] = CType(results(1), [Error]())
    Return CType(results(0), LocationReturnValue)
End Function

How can I resolve the error?

A: If you inspect the innerexception you can see the actual error is related to the SoapHeader class generated by wsdl.exe.
Types 'System.Web.Services.Protocols.SoapHeader' and 'FullNamespaceToYourClass.SoapHeader' both use the XML type name, 'SoapHeader', from namespace 'http://ss.yahooapis.jp/V6'. Use XML attributes to specify a unique XML name and/or namespace for the type.

You could either rename the SoapHeader class within the LocationService.vb file to something else or alternately add the full namespace to your class within the XmlTypeAttribute:
'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0"),
System.SerializableAttribute(),
System.Diagnostics.DebuggerStepThroughAttribute(),
System.ComponentModel.DesignerCategoryAttribute("code"),
    System.Xml.Serialization.XmlTypeAttribute(TypeName:="FullNamespaceToYourClass.SoapHeader", [Namespace]:="http://ss.yahooapis.jp/V6"),
System.Xml.Serialization.XmlRootAttribute("RequestHeader", [Namespace]:="http://ss.yahooapis.jp/V6", IsNullable:=False)>

Partial Public Class SoapHeader
    Inherits System.Web.Services.Protocols.SoapHeader


text:
Q: Explode a string I have a string as follows :
      $str = "am_customers.customer_key,am_customers.add_dt,CONCAT(am_customers.first_name,'',am_customers.last_name) as
             name,am_customers.cell_phone,am_customers.crm_phase_key,  am_customers.source,am_customers.location_key,am_customers.hub_key,
             am_customers.crm_priority,am_customers.update_dt";

I want to explod a string by comma. But the problem is with open and close brackets , When I try to expload a string by comma, I will get the result like as follows
          Array
         (
           [0] => am_customers.customer_key
           [1] => am_customers.add_dt
           [2] => CONCAT(am_customers.first_name
           [3] => ''
           [4] => am_customers.last_name) as name
           [5] => am_customers.cell_phone
           [6] => am_customers.crm_phase_key
           [7] => am_customers.source
           [8] => am_customers.location_key
           [9] => am_customers.hub_key
           [10] => am_customers.crm_priority
           [11] => am_customers.update_dt
         )

But I want the result like as follows :
       Array
     (
       [0] => am_customers.customer_key
       [1] => am_customers.add_dt
       [2] => CONCAT(am_customers.first_name,'',am_customers.last_name) as name
       [3] => am_customers.last_name) as name
       [4] => am_customers.cell_phone
       [5] => am_customers.crm_phase_key
       [6] => am_customers.source
       [7] => am_customers.location_key
       [8] => am_customers.hub_key
       [9] => am_customers.crm_priority
       [10] => am_customers.update_dt
     )

Is there any way to do this like i want above ?
Thank You.

A: Inspired by the comment by @Devon you can achieve this with preg_match_all:
preg_match_all( '/[^C\(,]*(?:(?:Cf\.|C(?!f)|\([^)]*\))[^C\(,]*)*/', $str, $matches );
Regex Source: http://www.perlmonks.org/?node_id=907316
I just tested this code and it seems to do what you are asking for:
$str = "am_customers.customer_key,am_customers.add_dt,CONCAT(am_customers.first_name,'',am_customers.last_name) as
             name,am_customers.cell_phone,am_customers.crm_phase_key,  am_customers.source,am_customers.location_key,am_customers.hub_key,
             am_customers.crm_priority,am_customers.update_dt";

$matches = [];
preg_match_all( '/[^C\(,]*(?:(?:Cf\.|C(?!f)|\([^)]*\))[^C\(,]*)*/', $str, $matches );

/*
* Trims each match, removes empty string matches, and resets array keys.
*
* Source: http://php.net/manual/en/function.array-filter.php#111091
*/
$clean = array_map( 'trim', $matches[0] );
$clean = array_filter( $clean, 'strlen' );
$clean = array_values( $clean );

var_dump( $clean );

Documentation
array_filter: http://php.net/array_filter
array_map: http://php.net/array_map
array_values: http://php.net/array_values
preg_match_all: http://php.net/preg_match_all


text:
Q: JQuery select2 set default value from an option in list? I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

A: One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :
Markup
<select class="select2">
   <option id="foo">Some Text</option>
   <option id="bar" selected="selected">Other Text</option>
</select>

JavaScript
$('select').select2(); //oh yes just this!

See fiddle : http://jsfiddle.net/6hZFU/
Edit: (Thanks, Jay Haase!)
If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:
$('select').select2("val", null); //a lil' bit more :)

After this, it is simple enough to set val to "Whatever You Want".

A: Came from the future? Looking for the ajax source default value ?
// Set up the Select2 control
$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});

You're welcome.
Reference:
https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

A: Step 1: You need to append one blank option with a blank value in your select tag.
Step 2: Add data-placeholder attribute in select tag with a placeholder value
HTML
<select class="select2" data-placeholder='--Select--'>
  <option value=''>--Select--</option>
  <option value='1'>Option 1</option>
  <option value='2'>Option 2</option>
  <option value='3'>Option 3</option>
</select>

jQuery
$('.select2').select2({
    placeholder: $(this).data('placeholder')
});

OR
$('.select2').select2({
    placeholder: 'Custom placeholder text'
});

A: The above solutions did not work for me, but this code from Select2's own website did:
$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed

Webpage found here
Hope this helps for anyone who is struggling, like I was.

A: $("#id").select2("val", null); //this will not work..you can try

You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');

A: One way to accomplish this is...
$('select').select2().select2('val', $('.select2 option:eq(1)').val());

So basically you first initalize the plugin then specify the default value using the 'val' parameter.  The actual value is taken from the specified option, in this case #1.  So the selected value from this example would be "bar".
<select class=".select2">
  <option id="foo">Some Text</option>
  <option id="bar">Other Text</option>
</select>

Hope this is useful to someone else.

A: e.g.
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');

you can see it here https://select2.org/programmatic-control/add-select-clear-items

A: For 4.x version
$('#select2Id').val(__INDEX__).trigger('change');

to select value with INDEX
$('#select2Id').val('').trigger('change');

to select nothing (show placeholder if it is)

A: Don't know others issue, Only this code worked for me.
$('select').val('').select2();

A: Normally we usually use active but in select2, changes to selected="selected"
Example using Python/Flask
HTML:
<select id="role" name="role[]" multiple="multiple" class="js-example-basic-multiple form-control">
  {% for x in list%}
  <option selected="selected" value="{{x[0]}}">{{x[1]}}</option>
  {% endfor %}
</select>

JQuery:
$(document).ready(function() {
        $('.js-example-basic-multiple').select2();
    });

    $(".js-example-theme-multiple").select2({
        theme: "classic",
        placeholder: 'Select your option...'
    });

A: It's easy. For example I want to select option with value 2 in default:
HTML:
<select class="select2" id="selectBox">
   <option value="1">Some Text</option>
   <option value="2">Other Text</option>
</select>

Javascript:
$("#selectBox").val('2').trigger('change')

A: For ajax select2 multiple select dropdown i did like this;
  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

A:     $('select').select2("val",null);

A: If you are using an array data source you can do something like below -
$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.


text:
Q: Get jars from mvnrepository.com directly from Eclipse (java project)? Is there an en easy way to set up an existing java project in Eclipse to get the required jar-files from mvnrepository? Instead of going to mvnrepository.com and download them manually and later "add jar-file" in Eclipse?
I accidently tried Configure -> Convert to Maven project, hoping it would work. It converted the whole project into something that wouldn't even run. "Main class missing" and so on. It took just about the whole day restoring back the normal Java project.
Can this be done with Ivy?


text:
Q: You have requested a non-existent service "security.context" i create service but it doesn't work
services:
    redirectionListener:
          class: Front\EcommerceBundle\Listener\RedirectionListener
          arguments: ["@service_container","@session"]
          tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

and this my class

namespace Front\EcommerceBundle\Listener;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class RedirectionListener
{
    public function __construct(ContainerBuilder $container, Session $session)
    {
        $this->session = $session;
        $this->router = $container->get('router');
        $this->securityContext = $container->get('security.context');
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $route = $event->getRequest()->attributes->get('_route');

        if ($route == 'livraison' || $route == 'validation') {
            if ($this->session->has('panier')) {
                if (count($this->session->get('panier')) == 0)
                    $event->setResponse(new RedirectResponse($this->router->generate('panier')));
            }

            if (!is_object($this->securityContext->getToken()->getUser())) {
                $this->session->getFlashBag()->add('notification','Vous devez vous identifier');
                $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
            }
        }
    }
}

ServiceNotFoundException in Container.php line 268: You have requested
  a non-existent service "security.context".

A: The security.context service was deprecated in the 2.6 and split into two new services: security.authorization_checker and security.token_storage.
Some different usage from the prior version of the framework:
// Symfony 2.5
$user = $this->get('security.context')->getToken()->getUser();
// Symfony 2.6
$user = $this->get('security.token_storage')->getToken()->getUser();

// Symfony 2.5
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) { ... }
// Symfony 2.6
if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { ... }

More info in this announcement
Hope this help

A: Following example will work:
/*Symfony 4.1.3*/

$user = $this->get('security.token_storage')->getToken()->getUser();

echo $user->getId(); // USER ID SESSION


text:
Q: Composite Keys and Zero padding in EF6 database first project I have three tables in a SQL Server 2016 db, Events, Races, Seasons. The Races table is a composite primary key of the PK for Events table and PK for Seasons table. I want to zero pad the primary key for the Events table primary key so that it is 3 digits. The desired Composite key for races would be in a format like 2018001 where 2018 is the seasonId and 001 is the eventId.
I am also using EF6 and database first approach for this. Is this a reasonably plan in first place and if so how do I set up the Events table to auto-increment with the proper zero padding?

A: When non database first approach is used, it is why sql guys are needed ;).
Zero padding seems like an arbitrary requirement and while it looks cool, functionally it will cause problems. Look up zip code issues via google to learn more about similar challenges.
I would suggest tableid int identity(1,1) not null for a surrogate key. Padding is done after the fact in the usp_ that you return the results with.

A: I would suggest three columns, eventid, seasonID and DisplayId. That way you can join correctly on the int fields for queries and use a calculated field to pad the numbers for the DisplayID. Note this will slightly slow inserts and updates but given the nature of the table it will probably not be noticable. It is better to do the padding once in the database on insert that to have to waste time do in the calculation every time you call up the data, so no this does not belong in the presentation layer.
The way you pad in SQl server is to use right and replicate together similar to this
right(replicate ('0',4)+ cast(event_id as Varchar(20)), 10)

Make sure to pad enough spaces to cover the maximum number of events you can conceive that database having in one year.
Then to combine with the seasonid:
Cast(seasonId as varchar(4)) + right(replicate ('0',4)+ cast(event_id as Varchar(20)), 10)

Do this as part of creating the calculated field (and persist the calculated field, so it doesn't have to keep recreating.
See this question for how to create a calculated field:
How can I set up a simple calculated field in SQL Server?


text:
Q: Search engine error? Image of code and phpmyadmin: http://www.dodaj.rs/f/Z/d0/2BO43myA/dwm-2015-04-08-19-27-19-.png
I thing the error is in $query = $db->query...
I have two errors:
Notice: Trying to get property of non-object in C:\xampp32\htdocs\Ceragem\search.php on line 78

Notice: Trying to get property of non-object in C:\xampp32\htdocs\Ceragem\search.php on line 82

PHP Code
    <?php
        require_once 'connect.php';

        if(isset($_GET['qsearch'])){
            $search = $db->escape_string($_GET['qsearch']);

            $query = $db->query("
                SELECT ime, prezime
                FROM data_users
                WHERE body LIKE'%{$search}%'
                OR ime LIKE '%{$search}%'
            ");
            ?>

                Nadjeno je <?php echo $query->num_rows;?> // Line 78

            <?php

            if($query->num_rows){ // Line 82
                while($r = $query->fetch_object()){
                ?>

                        <?php echo $r->ime;?>

                <?php
                }
            }
        }
    ?>

A: Your Query is wrong.
Your table has no body attribute
 WHERE body LIKE'%{$search}%'

Also it shoud be LIKE '%$search%' without {}
Take a look at this document.


text:
Q: Graphics glitches in Visual Studio 2010 I'm having graphics issues with Visual Studio 2010. When I open a solution only part of the UI renders. Entire sections like the solution explorer will be missing.
This only happens after I've had Visual Studio running for a while and have opened/closed a variety of solutions.
It "feels" like some sort of a GDI handle leak because the problem goes away once I reboot.
I'm running Windows 7 Ultimate - 64 bit. I've updated my graphics drivers, installed the latest patches, etc. I can't find any postings about this on stackoverflow or doing a variety of Google searches.
Any ideas?

A: It's a known issue, seems like no fix is coming in SP1, see https://connect.microsoft.com/VisualStudio/feedback/details/575376/visual-studio-2010-code-editor-problems?wa=wsignin1.0 & the workaround described at http://support.microsoft.com/kb/2023207 (disabling HW-Acceleration & Visual Experience adjustment did the trick for me).
Try also to update the graphic driver to their latest version.

A: The Visual Studio 2010 UI has been rewritten from the ground up in WPF.  Myself and a couple of other devs in our team are experiencing the same issues (various hardware and software but my software is the same as yours).  In our case closing and reopening VS solves it with no reboot required.
It's a cracking product but roll on SP1.

A: Running Visual Studio under Administrator (Run as Administrator) fixes the problem for me.


text:
Q: iis 6: Unable to assign IP address to new website I am trying to create a new website in IIS 6. I follow the wizard and choose an IP address after pinging it and ensuring it does not return a reply. After adding the site with the new IP address and pinging it the ip still returns nothing. The website also does not load using this IP in a browser. What am I missing?

A: The IP address has to be one of the addresses physically assigned to the server IIS is running on in the TCP/IP settings.  You can't just arbitrarily pick an IP address that nothing is using.

A: Where to start:
Is the ip address bound to the NIC?
Is the NIC plugged in to the network?
Is the web site bound to the ip address?
Is the web site running?

A: It sounds like you just 'picked' an IP address out of thin air and pinged it and assumed it gets assigned to IIS.
Why not use a virtual host approach (you assign it a dns like mydomain.com).
Your server will stay on 1 single IP (which is what it most likely has, as I would find it odd to get an IP per website for IIS).
This is the proper way to get it done when adding new sites to IIS (unless you really do have IP's lying around pointed to the server -- properly!).


text:
Q: Javascript Function Accepting PHP Variables I'm drawing a complete blank why this isn't working. I can do it with one variable passing through, but not two. When I use actually numbers like getnt(1,2) it works. It's just not working with two PHP variables.

  <?php
    echo "VIEW";
  ?>

I can make the code work with echo "VIEW";, but that's no good if I want to add in alerts and javascript commands.

A: You could always try:

    <a href="#" onclick="getnt(<?php echo $nid; ?>,<?php echo $pnid; ?>)">VIEW

A: If the ID and pnID are strings, enclose them with brackets like this.

  <?php
    echo "VIEW";
  ?>

If still not working, You can debug your code

*

*View the source code in browser,
make sure it generates correctly.

*Put some alert messages in the
javascript function. Install Firebug
if you have Firefox or see

*Javaascript console if you get any   javascript errors.

A: Your question is probably best answered by looking at the rendered HTML source.
In any case, here's how I'd do it using graceful degradation

<a href="nt.php?nid=<?php echo $nid ?>&pnid=<?php echo $pnid ?>"
      data-nid="<?php echo $nid ?>"
      data-pnid="<?php echo $pnid ?>"
      onclick="return getnt(this)">VIEW


text:
Q: does there always exist a vector v such that, the partial derivative of a function $f:\mathbb{R}^n \to \mathbb{R}$ in the direction of v is zero? Does there always exist a vector v such that, the partial derivative of a function $f:\mathbb{R}^n \to \mathbb{R}$ in the direction of v is zero?
My approach would be saying that the directional derivative of f equals:
$\frac{\partial f}{\partial x} + \frac{\partial f}{\partial y} + \frac{\partial f}{\partial z}.... $
and then we consider it in the direction v with:
$$\frac{\partial f}{\partial x} v_x + \frac{\partial f}{\partial y} v_y + \frac{\partial f}{\partial z} v_z = 0$$
and since the derivative is a constant just solve for $v_x, v_y, v_z,...,v_n$ and call it proven, stating that there always exist a direction v in which the slope would be zero.
Is this approach rigorous/correct?

A: The directional derivative in the direction of a unit vector $\vec u$ can be calculated most easily by taking the dot product of the gradient vector $\nabla f$ with $\vec u$:
$$D_{\vec u}f = \nabla f \cdot \vec u$$
If $\nabla f \ne \vec 0$ at a particular point, then at that point any vector $\vec u$ perpendicular to $\nabla f$ will be a direction in which the directional derivative is zero.  In general, if we are in $\mathbb R^n$ (with $n \ge 2$), this will be an $(n-1)$-dimensional subspace.  On the other hand, if $\nabla f = \vec 0$ at a particular point, then at that point the directional derivative is zero in every direction.


text:
Q: How to associate Buttons with the parent view and announce to the user with TalkBack? I'm trying to make TalkBack work for my Android app, in my app layout I have a list of CardViews inside a RecyclerView, each CardView contains several TextViews and several Buttons: App layout image
When I turn on Android TalkBack, and tap on a CardView, TalkBack announces all the TextViews, but doesn't announce any Button. If I continue swiping right, the buttons will gain focus one by one. Not sure if my understanding is correct, but seems like TalkBack treats TextViews and Buttons differently because the buttons are focusable.
Is there a way to make TalkBack announce all content on the CardView (TextViews and Buttons) and keep the Buttons focusable (so I'll still be able to set focus on Buttons by swiping)?
PS:
One solution that worked is to directly set a content description on the CardView, and make the content description contain all content of TextViews and Buttons, but that's kind of hacky, so I'm trying to find a better solution here.
Any help is appreciated. Thanks!

A: The behaviour you've described is expected and your solution is the correct one.
For ViewGroups with no explicit content description, TalkBack will attempt to infer one from the children, by concatenating the content description (or text value if view extends from TextView) of all the children.
Since the buttons themselves are actionable (focusable/clickable), they are not included in the inferred content description.
Setting an explicit content description on the card is the correct approach to take - your goal should be to describe the information that the card represents. IMO, it should not contain the description for the buttons since they will be separately focusable and will be read aloud when the user focuses on them.

The best approach IMO is to hide the buttons if TalkBack is enabled, and to present the cards as entities that contain a single action and a single, explicitly-set content description.
It's important not to reduce functionality for TalkBack users - all the user goals that were achievable should still be achievable; there is no requirement that the goals must be achieved in the same way by all users. So in this case, you could make the card's primary action as the click action, and offer the actions from the buttons in another place in the app.
One pattern which works well is to display a dialog on click, and this contains all the actions. This has a couple of benefits:

*

*the card is single action so navigating between cards is single-swipe only

*the default dialog is accessible by default - no extra work needed

I wrote a blog post explaining how you can do it with (and without) a library I helped write. The section under "actions dialog" is the relevant bit.

A: A button is actionable. If you want your users to be able to do the actions of each button, they need to be separately focusable. If they aren't actionable, they shouldn't be buttons.


text:
Q: C Program that determines whether a number is prime or not using a recursive function The program I am trying to create should print whether a number scanned from the keyboard is prime or not. The program should use a recursive function for determining whether the number is prime or not. The program I have created has no compiling issues. However, when the main() function calls the function for determining if the number is prime or not (I called this function isprime), it seems to return that the integer scanned from the keyboard is always prime. This is the case for both prime and non prime numbers. The program I created looks like this:
#include <stdio.h>
//function for determining whether a number is prime or not
int isprime(int i, int n){
    i = 2;
    if(n > 1){
        /* i = 2, i is the divisor that checks whether n (the number
        being checked for being prime) is in fact prime */
        if(n % i == 0){
            return 1;
        }
        /* recursive step that returns function with increased value
        of i */
        isprime(i + 1, n);
    }
    else {
        return 0;
    }
    return -1;
}

int main(){
    int x;
    //scans integer from the keyboard
    scanf("%d", &x);
    //calls recursive function
    if(isprime(2, x) == 1){
        printf("%d is prime\n", x);
    }
    if(isprime(2, x) == 0){
        printf("%d is not prime\n", x);
    }
    return 0;
}

One last question: is calling a recursive function like in my program:
 isprime(2, x)

the right syntax to use? Is it correct to insert the number 2 directly into the argument of the function?
Any help is appreciated!:)

A: The following proposed code:

*

*cleanly compiles

*performs the desired functionality

*checks for and handles I/O errors

*incorporates the comments to the OPs question

*reversed the meaning of a returned value of 0 or 1 for ease of calculation

*properly implements a recursive algorithm, including edge cases and stop condition

*could greatly limit the recursion depth by utilizing the sqrt of 'n' as a limiting factor for the parameter 'i'

*uses 'unsigned' values to avoid the complications of negative numbers

and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>

int isprime( unsigned i, unsigned n )
{
    if( n < 2 )
    { // cannot be prime
        return 1;
    }

    if( i >= n )
        return 0;

    if(n % i == 0)
    {  // then, not prime
        return 1;
    }

    return isprime(i + 1, n );
}

int main( void )
{
    unsigned x;
    if( scanf("%u", &x) != 1 )
    {
        fprintf( stderr, "scanf failed\n" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    if( !isprime(2, x ) )
    {
        printf("%d is prime\n", x);
    }
    else
    {
        printf("%d is not prime\n", x);
    }
    return 0;
}

A: An example program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int is_prime(int n, int div)
{
    if (n <= 1)
        return 0;
    else if (div <= 1)
        return 1;
    else if (n % div == 0)
        return 0;
    return is_prime(n, --div);
}

int main()
{
    for (int i = 0; i < 100; i++)
    {
        printf("%d is %s\n", i, is_prime(i, (int)(sqrt(i)))? "prime":"not prime");
    }

    return 0;
}

The two arguments which you need to pass is the number to be checked, and its square root. You do not need to check numbers greater than this because if you think about it, there is really no need to.
For example if your number is 16 you will only need to check numbers from 1 to 4. Kind of hard to explain so here is a table:
1*16
2*8
4*4
8*2 <----- We already checked this!!
...

Hope this will help!

A: I recommend you deal with argument testing (negative input) and special cases (even numbers other than 2) in a general is_prime() function but once your data is clean, turn the calculation over to a focused is_prime_recursive() function, avoiding redundant tests:
#include <stdio.h>
#include <stdbool.h>

bool is_prime_recursive(unsigned number, unsigned odd_divisor)
{
    if (odd_divisor * odd_divisor > number) {
        return true;
    }

    if (number % odd_divisor == 0) {
        return false;
    }

    return is_prime_recursive(number, odd_divisor + 2);
}

bool is_prime(int number)
{
    if (number <= 1) {
        return false;
    }

    if (number % 2 == 0) {
        return (2 == number);
    }

    return is_prime_recursive(number, 3);
}

int main()
{
    for (int i = 0; i <= 100; i++)
    {
        printf("%d is %sprime\n", i, is_prime(i) ? "" : "not ");
    }

    return 0;
}

A: Here is a program I created that prints out whether a number is prime or not using a recursive function for determining so! The comments in the program explain each part! Hopefully this helps anyone trying to create a similar program!
#include <stdio.h>
// i = divisor
// n = number being checked for being prime
int isprime(int i, int n){
    //base case one: 1 is not prime
    if (n == 1){
        return 0;
    }
    //base case two: 2 is prime
    if (n == 2){
        return 1;
    }
    //if i is a divisor then n not prime
    if (n % i == 0){
        return 0;
    }
    /* if root of n is reached while trying
    to find a divisor but no divisor found, so
    no previous return, then we have a prime number */
    if (i * i > n){
        return 1;
    }
    //recursive step, trying next value as divisor
    return isprime(i + 1, n);
}

int main(){
    int x;
    scanf("%d", &x);
    if(isprime(2, x) == 1){
        printf("%d is prime\n", x);
    }
    if(isprime(2, x) == 0){
        printf("%d is not prime\n", x);
    }
    return 0;
}

The input for this program looks like this:
3

The output of this program looks like this:
3 is prime


text:
Q: Email cache database design Can you advice how to store email MessagePart hierarchy into database (SQLite)?
Parts can be of different MIME type (text, image, etc). Also they can be multipart.
The only way I see is to store all parts in single MessageParts table with content_bytes field and mime_type field + parent_id for multipart
Is it ok? Is there some better way?
Thanks!

A: Look up "generalization specialization relational modeling" and you will find some excellent articles on the web.  This is well understood, but often overlooked.


text:
Q: Render Google Charts on server In our web application we are using Google Charts. Now we have to create monthly reports as pdf, which should contain same (or very similar) Charts.
Is there a way to render Google Charts on the server side in .Net?
Edit:
What I basically need are line-charts with multiple lines and pie charts so nothing extraordinary. I am using C# and for pdf creating MigraDoc/PdfSharp, but we really don't like the look of the MigraDoc charts.


text:
Q: How to Create own admin module in Joomla 3.x. I have created a new folder in joomla/ and than paste all the files and folders of administrator folder within this.
Then i got an error message:
Error displaying the error page: Application Instantiation Error: JLIB_APPLICATION_ERROR_APPLICATION_LOAD
How to i procees further...

A: You should create a folder joomla, paste all the extracted files of joomla zip into that folder and then try installing joomla using url.

A: It's look like you only copy/paste administrator files, is it true? (if I understand your question well) if so then you should copy all the files, not only administrator files. Then make changes in configuration.php for database name and host detail etc... then you will able to use joomla normally.
Note: if there is installation folder then you will prompt for installation of joomla else you will use it normally.
Also make sure your directory has read and execute permissions.

A: If you copy the administrator application to a folder and try to run it you need to understand that the administrator application bootstrap is assuming that the application is one level down, in the /administrator folder.  So all the includes that call the libraries and all the path constants are looking one level up and in many cases will have the folder name hard coded as administrator.  So you would need to go look at the defines.php and probably everything in the the includes folder and check for hard coding.   It should not be hard since it is just a couple of changes to put all of your files above the web root.
That said if I were making my own standalone application for administering I would not start by copying the core. I would start from scratch so you can not include all the unnecessary parts plus use the more modern parts of the framework unlike the legacy parts currently used.


text:
Q: Switching from WDS to MDT I am in the process of moving from WDS to MDT. I will be installing MDT alongside WDS on the same box. The concept I am not grasping is at what point in this process will clients pxe boot to the MDT service instead of the already established WDS instance?
Thanks in advance!

A: MDT uses WDS for pre-boot. Within MDT, you will generate a boot image. Within WDS, you will import this boot image and make it available to PXE clients to choose during PXE Boot.
From MDT Workbench:

*

*Configure all the properties of your environment by right-clicking the MDT Deployment share, and selecting properties.

*Most of the boot image settings are under the 'Windows PE' tab and the 'Bootstrap.ini'

*When your settings are ready, or anytime you need to refresh your boot images, right-click the MDT Deployment share and select 'Update Deployment Share.'

*New boot images are generated in your deployment share location under <DeploymentSharePath>\Boot. They are named LiteTouchPE_<bitness>.wim.

On the WDS console:

*

*Right-Click 'Boot Images' and 'Add boot image.'

*Navigate to the where the boot image is saved and select it.

*Provide a name and description.

*Complete adding the image to WDS.

In the future, you can update the existing boot image in WDS, when a new one is generated in MDT.
Change the properties of the WDS server and choose default boot images if you want one image to boot by default, over another, or change how PXE devices are presented boot images, and selections.
When clients boot the LiteTouch image, the MDT deployment will begin however you have it configured.
You'll need to generate a new boot image whenever you update your bootstrap.ini or Windows PE properties, or if you upgrade MDT or your Windows ADK environment. You do not need to update the boot image, if all you do is change other MDT features like the Task Sequence or Drivers (unless, ofcourse, you are changing drivers in the Windows PE environment). You are basically deploying a pre-configured WinPE environment, with necessary drivers, and settings that tells the client where to connect to get further instructions from MDT.

A: Pretty much this, i would just add one thing: Make sure you add your Network Drivers in both, the MDT (under "Out-oBox-Drivers") and the WDS (Plus injecting it in your MDT Boot Image inside the WDS)
Because of how the Installation works, without having it in both "Places", either the PreInstallation-Environment or the installed Client would not have a driver to use otherwise.
If the PE-Drivers are missing, the MDT Wizard will basically outright fail with the appropriate error. If the OS Driver is missing, the Installation will go through until the OS starts and then the Client will be effectively offline, failing any further operation from the Task Sequence that would depend on network


text:
Q: Java: alternative to LinkedList or int pointer data structure Since LinkedList is a nightmare in terms of memory overhead and also slower when iterating elements, I would like to have something like int poiter data structure.
So I have a list of ints and I form it by inserting elements at the beginning-middle. When the list is ready, I iterate it in a one-by-one fashion from the left. That is my problem constraint.

A: I would profile and try different data structures.
That being said, why not try to use ArrayList; it's fast to iterate and even insert, while in O(n), is fast because moving consecutive data in a cache is lightning fast. (If you also reverse the list while inserting it will be even faster!)

Update, since my fellow programmers doesn't understands why I recommend ArrayList for this perticular problem:
The problem isn't inserting elements. In that case the linked list wins direcly (O(1) against the O(n) for the array list). The problem is to find the place to insert them. In this case the LinkedList is really slow. There is a huge overhead to find the place to insert since it doesn't allocate the memory in a "good matter". Lots of cache misses!
OP hasn't posted any code so we only know what OP wants but here is an algorithm analysis for the two cases (where C* are constants):
LinkedList, for each element to insert:

*

*Iterating O(C1 * n)

*Inserting O(1)
ArrayList, for each element to insert:

*

*Iterating O(C2 * n)

*Inserting O(C3 * n)
So, both algorithms are in O(n) but looking closely at the constants: C1 is really big (explained above). C2 and C3 on the other hand are small because iterating and moving within the cache is fast.
So, if you have enough memory try an ArrayList!

A: LinkedList has indeed terible performance if you constantly do list.get(index);
Use the ListIterator instead so that each time you don't traverse the list over and over.
And if you need to add elements in the middle of the list it will have much better performance than an ArrayList O(1) (since you don't need to move elements)
Update:
The proper way to iterate over a list is using iterators (implicit or explicit). Example of using implicit iterators:
for(E e:list){
}

Never do:
for(int i = 0; list.size(); i++{
    E e = list.get(i);
}

If the list is a LinkedList this operation is O(N^2) as list.get(i) is traversing the list from the beginning in each iteration of the loop.
Using the first form with an iterator is only O(N) same almost as an ArrayList due to the fact that the iterator "remembers" the last element accessed and starts from there

A: Try Gaplist, it offers ArrayList-like performance and memory footprint for many use cases. If insertion is mostly sequential (at any index), inserts are close to O(1).

A: 1st step: insert the elements in LinkedList
2nd step: copy elements to ArrayList to iterate.
btw, "nightmare" is a little bit exaggerating to LinkedList:)


text:
Q: How to train and deploy model in script mode on Sagemaker without using jupyter notebook instance (serverless)? I have been using a jupyter notebook instance to spin up a training job (on separate instance) and deploy the endpoint (on another instance). I am using sagemaker tensorflow APIs for this as shown below:
# create Tensorflow object and provide and entry point script
tf_estimator = TensorFlow(entry_point='tf-train.py', role='SageMakerRole',
                      train_instance_count=1, train_instance_type='ml.p2.xlarge',
                      framework_version='1.12', py_version='py3')

# train model on data on s3 and save model artifacts to s3
tf_estimator.fit('s3://bucket/path/to/training/data')

# deploy model on another instance using checkpoints saved on S3
predictor = estimator.deploy(initial_instance_count=1,
                         instance_type='ml.c5.xlarge',
                         endpoint_type='tensorflow-serving')

I have been doing all of these steps through a jupyter notebook instance. What AWS services I can use to get rid off the dependency of jupyter notebook instance and automate these tasks of training and deploying the model in serverless fashion?

A: I recommend AWS Step Functions.  Been using it to schedule SageMaker Batch Transform and preprocessing jobs since it integrates with CloudWatch event rules.  It can also train models, perform hpo tuning, and integrates with lambda.  There is a SageMaker/Step Functions SDK as well as you can use Step Functions directly by creating state machines. Some examples and documentation:
https://aws.amazon.com/about-aws/whats-new/2019/11/introducing-aws-step-functions-data-science-sdk-amazon-sagemaker/
https://docs.aws.amazon.com/step-functions/latest/dg/connect-sagemaker.html


text:
Q: how to retrieve list of objects from dao via LiveData<> in View Model when there is no change to trigger onChange method in View Model in android I am using android studios to build a dictionary app.  Everything has went fairly well with help from the SO community and now I have another question.
I have setup several custom dictionaries so that the user can store and view words in different dictionaries. (e.g. literature, programming, general, etc.)
These will be a FK id in the word entity and filled when the user adds new words.
In the MainActivity, I have an Options menu item for 'Change Dictionary'.  This brings up an AlertDialog where the user can change the dictionary and theoretically see a new set of words.
Here is the problem.  No changes to the database are happening when the user selects a particular dictionary so the onChange attached to the WordViewModel's getWordsByDictionaryId() method does not trigger. Hence, the LiveData> will not refill.
Code in onCreate() method:
    // get all words from WordDao
    mWordViewModel = ViewModelProviders.of(MainActivity.this).get(WordViewModel.class);
    mWordViewModel.getWordByDictionaryId(dictionaryId).observe(MainActivity.this, new Observer<List<Word>>() {
        @Override
        public void onChanged(@Nullable List<Word> words) {
            mainAdapter.setWords(words);
            mAllWords = words;
            mainAdapter.notifyDataSetChanged();
        }
    });

Code in OnOptionsItemSelected() method:
        AlertDialog.Builder changeDictionaryDialog = new AlertDialog.Builder(MainActivity.this);
        changeDictionaryDialog.setTitle("Select Dictionary:");
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.alert_dialog_spinner_view, null);

        mDictionaryStringList = new ArrayList<>();
        mDictionaryStringList = convertToList(mDictionaryList);

        final Spinner dictionarySpinner = (Spinner) view.findViewById(R.id.alert_dialog_spinner);

        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, mDictionaryStringList);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dictionarySpinner.setAdapter(spinnerAdapter);

        dictionarySpinner.setSelection(0);

        changeDictionaryDialog.setView(view);
        changeDictionaryDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String dictionaryValue = dictionarySpinner.getSelectedItem().toString();

                for (Dictionary dictionary : mDictionaryList) {
                    if (dictionary.getDictionaryName().trim().equals(dictionaryValue)) {
                        dictionaryId = dictionary.getDid();
                       LiveData<List<Word>> myNewList = mWordViewModel.getWordByDictionaryId(dictionaryId);
                        List<Word> testList = myNewList.
                    }
                }
            }
        });

        changeDictionaryDialog.setNegativeButton("Cancel", null);
        changeDictionaryDialog.create();
        changeDictionaryDialog.show();

Code in the WordViewModel:
public LiveData<List<Word>> getWordByDictionaryId(long dictionaryId) {
    return mWordRepository.getWordByDictionaryId(dictionaryId);
}

Code in WordDao:
@Query("SELECT * FROM word_table WHERE dictionary_id =:dictionaryId")
public LiveData<List<Word>> getWordsByDictionaryID(long dictionaryId);

Finally, the Word entity:
@Entity(tableName = "word_table",
indices = { @Index(value = "word", unique = true),
@Index("dictionary_id") })
public class Word {
@PrimaryKey(autoGenerate = true)
private long id;
private String word;
@ColumnInfo(name = "dictionary_id")
private long dictionaryId;

@Ignore
public Word(String word, long dictionaryId) {
    this.word = word;
    this.dictionaryId = dictionaryId;
}

public Word(long id, String word, long dictionaryId) {
    this.id = id;
    this.word = word;
    this.dictionaryId = dictionaryId;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getWord() {
    return word;
}

public void setWord(String word) {
    this.word = word;
}

public long getDictionaryId() {
    return dictionaryId;
}

public void setDictionaryId(long dictionaryId) {
    this.dictionaryId = dictionaryId;
}
}

I have tried to setup a background thread (AsyncTask), but the one time that I did, the results came after I needed them so the return value was null. Some SO developers have said don't use Asynctask, but I think the issue would still be timing...
I have also read a little about generating a callback.  Would that actually work in this situation?  It seems to me like it might put me in the same boat as the background thread.
I have been really struggling trying to learn how to get data out of this "wonderfully simple way to create databases" when it comes to getting data out of the SQLite database via Room persistence via View Model via LiveData via ???whatever comes next???. Is there a "Google" way to do this?  Or is this where the RxJava and other libraries come into play?
So my question is just this "exactly how can I get a List of entity objects out of the database if there is no onChange event through live data?"  Is there a best practices or right way to call the query without the LiveData wrapper?  or a way to access the query directly within the LiveData wrapper without needing the data to change to get things done?

A: LiveData solution
@Zohaib Amir's comment is correct. You can call LiveData#observe() on anywhere you want as long as you remember to clear the observers. One drawback with this approach is that you have to keep the reference to these observers and LiveData already has Transformations.switchMap() so that you can avoid that.
ViewModel
// Instance variable that stores the current dictionaryId that user wants to see.
private final MutableLiveData<Long> currentDictionaryId = new MutableLiveData<>();

// Instance variable that stores the current list of words. This will automatically change when currentDictionaryId value changes.
private final LiveData<List<Word>> words = Transformations.switchMap(currentDictionaryId, dictionaryId ->
    mWordRepository.getWordByDictionaryId(dictionaryId));

// Set new dictionaryId
public void setDictionaryId(long dictionaryId) {
    currentDictionaryId.postValue(dictionaryId);
}

// Get LiveData to listen to
public LiveData<List<Word>> getWords() {
    return words;
}

Activity
// onCreate()
    // get all words from WordDao
    mWordViewModel = ViewModelProviders.of(MainActivity.this).get(WordViewModel.class);
    mWordViewModel.setDictionaryId(dictionaryId);
    mWordViewModel.getWords().observe(MainActivity.this, new Observer<List<Word>>() {
        @Override
        public void onChanged(@Nullable List<Word> words) {
            mainAdapter.setWords(words);
            mAllWords = words;
            mainAdapter.notifyDataSetChanged();
        }
    });

    // note that the order of calling setDictionaryId and getWords doesn't matter. setDictionaryId is supposed to call at anytime.

// OnOptionsItemSelected
    ...
    changeDictionaryDialog.setView(view);
        changeDictionaryDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String dictionaryValue = dictionarySpinner.getSelectedItem().toString();

                for (Dictionary dictionary : mDictionaryList) {
                    if (dictionary.getDictionaryName().trim().equals(dictionaryValue)) {
                        dictionaryId = dictionary.getDid();
                        mWordViewModel.setDictionaryId(dictionaryId);
                        break;
                    }
                }
            }
        });
    ...

This time I prepared other solutions so that you can compare. Other solutions (almost) do the exact same thing.

Non-reactive solution
You can implement above feature based on callbacks, and this means that you have to manually handle lifecycle changes, notifications, and threading. Also, there is a functional difference that LiveData will automatically notify the observer when there is a change in the db, while this callback design is just one-time look up only.
In this example, we will use Executor to execute tasks in the background thread.
WordDao
@Query("SELECT * FROM word_table WHERE dictionary_id =:dictionaryId")
public List<Word> getWordsByDictionaryID(long dictionaryId); // notice that livedata is gone.

WordRepository
Database access must be done in a background thread. So when we access db, we need to switch to a background thread at some point. In this example, we will switch to the background
thread in this layer.
// This executor is needed to run Runnables on a background thread. In real application, you may
// create this executor outside of this repository and later inject it to this repository.
private final Executor ioExecutor = Executors.newSingleThreadExecutor();

private void getWordByDictionaryId(long dictionaryId, Consumer<List<Word>> callback) {
    ioExecutor.execute(() -> {
        List<Word> wordList = wordDao.getWordsByDictionaryId(dictionaryId);
        callback.accept(wordList);
    });
}

WordViewModel
There isn't much ViewModel does in this example. Just pass the parameters to the repository.
public void getWordByDictionaryId(long dictionaryId, Consumer<List<Word>> callback) {
    mWordRepository.getWordByDictionaryId(dictionaryId, callback);
}

Activity
Note that Consumer#accept will run on a background thread. Therefore before you do anything with the ui, you need to switch back to the ui thread.
// onCreate
mWordViewModel = ViewModelProviders.of(MainActivity.this).get(WordViewModel.class);
mWordViewModel.getWordByDictionaryId(dictionaryId, words -> {
    runOnUiThread(() -> {
        if (isFinishing() || isDestroyed()) return; // if the activity is finishing, don't do anything.

        mainAdapter.setWords(words);
        mAllWords = words;
        mainAdapter.notifyDataSetChanged();
    });
});

// onOptionsItemSelected
changeDictionaryDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        final String dictionaryValue = dictionarySpinner.getSelectedItem().toString();

        for (Dictionary dictionary : mDictionaryList) {
            if (dictionary.getDictionaryName().trim().equals(dictionaryValue)) {
                dictionaryId = dictionary.getDid();
                mWordViewModel.getWordByDictionaryId(dictionaryId, words -> {
                    runOnUiThread(() -> {
                        if (isFinishing() || isDestroyed()) return; // if the activity is finishing, don't do anything.

                        mainAdapter.setWords(words);
                        mAllWords = words;
                        mainAdapter.notifyDataSetChanged();
                    });
                });
                break;
            }
        }
    }
});

RxJava
RxJava solution will look much like the LiveData solution. It has many advantages over LiveData: it has lots of observables and operators to work with. These advantages are more apparent in more complex applications, where you need to do conditional or delayed async tasks, periodic tasks, multiple requests chained one after the other, error handlings, etc.
WordDao
@Query("SELECT * FROM word_table WHERE dictionary_id =:dictionaryId")
public Flowable<List<Word>> getWordsByDictionaryID(long dictionaryId);

ViewModel
private final BehaviorProcessor<Long> currentDictionaryId = BehaviorProcessor.create();

// Set new dictionaryId
public void setDictionaryId(long dictionaryId) {
    currentDictionaryId.onNext(dictionaryId);
}

// Get Flowable to listen to
public Flowable<List<Word>> getWords() {
    return currentDictionaryId.switchMap(dictionaryId -> mWordRepository
        .getWordByDictionaryId(dictionaryId)
        // add ".take(1)" if you need one-time look up.
        .subscribeOn(Schedulers.io()));
}

Activity
private fianl CompositeDisposable disposables = new CompositeDisposable();

// onCreate()
mWordViewModel = ViewModelProviders.of(MainActivity.this).get(WordViewModel.class);
mWordViewModel.setDictionaryId(dictionaryId);
disposables.add(mWordViewModel.getWords()
    .observeOn(AndroidSchedulers.mainThread()))
    .subscribe(words -> {
        mainAdapter.setWords(words);
        mAllWords = words;
        mainAdapter.notifyDataSetChanged();
    });

// onOptionsItemSelected()
 changeDictionaryDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        final String dictionaryValue = dictionarySpinner.getSelectedItem().toString();

        for (Dictionary dictionary : mDictionaryList) {
            if (dictionary.getDictionaryName().trim().equals(dictionaryValue)) {
                dictionaryId = dictionary.getDid();
                mWordViewModel.setDictionaryId(dictionaryId);
                break;
            }
        }
    }
});

// onDestroy()
disposables.clear();


text:
Q: vfsstream paths and realpath I'm experimenting with vfsStream for unit testing filesystem interactions and have very quickly run into a major hurdle.  One of the validation checks the code under test does is execute realpath() on a supplied input path to test that it's an actual path and not nonsense.  However, realpath always fails on a vfsstream path.
The following code demonstrates the problem outside of any particular class.
$content    = "It rubs the lotion on its skin or else it gets the hose again";
$url        = vfsStream::url ('test/text.txt');
file_put_contents ($url, $content);
var_dump ($url);
var_dump (realpath ($url));
var_dump (file_get_contents ($url));

The output is as follows:
string(27) "vfs://FileClassMap/text.txt"
bool(false)
string(61) "It rubs the lotion on its skin or else it gets the hose again"

Obviously the vfsStream created the file and wrote the given content to it, but I can't verify that the path to it is correct with realpath.  As realpath is being used inside the actual code I need a way of working about this.
I really don't think removing realpath is a sensible approach because it performs an important function inside the code, and eliminating an important check just to make the code testable seems a pretty poor solution.  I could also put an if around the test to make it possible to disable it for testing purposes, but again I don't think that's a good idea either.  Also I'd hate to have to do that at every point in the code where I might make a call to realpath ().  The third option would be to set up a RAM disk for filesystem unit tests, but that's not ideal either.  You have to clean up after yourself (which is what vfsstream is supposed to help you avoid the need for) and how to actually do it will differ from OS to OS, so the unit tests would cease to be OS agnostic.
So is there a way to get a vfsstream path in a format that actually works with realpath?
For completeness, the following is the code fragment from the class I'm trying to actually test.
if (($fullPath = realpath ($unvalidatedPath))
&& (is_file ($fullPath))
&& (is_writable ($fullPath))) {

A refactoring to the following (as per potential solution 2) allows me to test with vfsStream, but I think it could be problematic in production:
// If we can get a canonical path then do so (realpath can fail on URLs, stream wrappers, etc)
$fullPath   = realpath ($unvalidatedPath);
if (false === $fullPath) {
    $fullPath   = $unvalidatedPath;
}

if ((is_file ($fullPath))
&& (is_writable ($fullPath))) {

A: If you use namespaces you can override the realpath function only in the test class. I always use canonical paths in my vfsStream testcases, beause i don't want to test the realpath() function itself.
namespace my\namespace;

/**
 * Override realpath() in current namespace for testing
 *
 * @param string $path     the file path
 *
 * @return string
 */
function realpath($path)
{
    return $path;
}

Good described here: http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/

A: I opened a bug with an implementation of Sebkrueger's method on vfsStream: https://github.com/bovigo/vfsStream/issues/207
Waiting for their feedback, here is my working realpath():
/**
 * This function overrides the native realpath($url) function, removing
 * all the "..", ".", "///" of an url. Contrary to the native one,
 *
 * @param string $url
 * @param string|bool The cleaned url or false if it doesn't exist
 */
function realpath(string $url)
{
    preg_match("|^(\w+://)?(/)?(.*)$|", $url, $matches);
    $protocol = $matches[1];
    $root     = $matches[2];
    $rest     = $matches[3];

    $split = preg_split("|/|", $rest);

    $cleaned = [];
    foreach ($split as $item) {
        if ($item === '.' || $item === '') {
            // If it's a ./ then it's nothing (just that dir) so don't add/delete anything
        } elseif ($item === '..') {
            // Remove the last item added since .. negates it.
            $removed = array_pop($cleaned);
        } else {
            $cleaned[] = $item;
        }
    }

    $cleaned = $protocol.$root.implode('/', $cleaned);
    return file_exists($cleaned) ? $cleaned : false;
}