text:
Q: How to get a list of all tables in two different databases I'm trying to create a little SQL script (in SQL Server Management Studio) to get a list of all tables in two different databases. The goal is to find out which tables exist in both databases and which ones only exist in one of them.
I have found various scripts on SO to list all the tables of one database, but so far I wasn't able to get a list of tables of multiple databases.
So: is there a way to query SQL Server for all tables in a specific database, e.g. SELECT * FROM ... WHERE databaseName='first_db' so that I can join this with the result for another database?

A: As far as I know, you can only query tables for the active database.  But you could store them in a temporary table, and join the result:
use db1
insert #TableList select (...) from sys.tables
use db2
insert #TableList2 select (...) from sys.tables
select * from #TableList tl1 join Tablelist2 tl2 on ...

A: SELECT * FROM database1.INFORMATION_SCHEMA.TABLES
UNION ALL
SELECT * FROM database2.INFORMATION_SCHEMA.TABLES

UPDATE
In order to compare the two lists, you can use FULL OUTER JOIN, which will show you the tables that are present in both databases as well as those that are only present in one of them:
SELECT *
FROM database1.INFORMATION_SCHEMA.TABLES db1
  FULL JOIN database2.INFORMATION_SCHEMA.TABLES db2
    ON db1.TABLE_NAME = db2.TABLE_NAME
ORDER BY COALESCE(db1.TABLE_NAME, db2.TABLE_NAME)

You can also add WHERE db1.TABLE_NAME IS NULL OR db2.TABLE_NAME IS NULL to see only the differences between the databases.

A: Just for completeness, this is the query I finally used (based on Andriy M's answer):
SELECT * FROM DB1.INFORMATION_SCHEMA.Tables db1
  LEFT OUTER JOIN DB2.INFORMATION_SCHEMA.Tables db2
    ON db1.TABLE_NAME = db2.TABLE_NAME
  ORDER BY db1.TABLE_NAME

To find out which tables exist in db2, but not in db1, replace the LEFT OUTER JOIN with a RIGHT OUTER JOIN.


text:
Q: How can I write the argument name from Python argparse to a file? I want to use argparse to write the argument names & values it receives to a file. I have this so far:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--infile", help = "seed file", default = 'test')
parser.add_argument("--lang", help="wiki language bigram", default = 'en')
parser.add_argument("--request_type", help="request type", default = 'sum')
parser.add_argument("--outfile", help = "path to outfile", default = 'outfile')
parser.add_argument("--summary", help = "true or false", action = "store_true")
parser.add_argument("--pagehits", help = "path to list of page hits", default = 'pagehits')
parser.add_argument("--exemplar_file", help = "file to inspire book")

args = parser.parse_args()

input_file = args.infile
print(args.infile)
print(var(args))

with open('modified-variables', 'w') as outfile:
    outfile.write(args.infile)
    outfile.write('hello world')

with --infile "/path/to/file" --lang "en" output is:
/path/to/file
en

[but nothing written to file]

I want it to loop over all the positional parameters and write all those that are supplied in the command line to modified-variables in the format
infile="/path/to/file"
lang="en"

Googling is not helping me figure out how to print the argnames and there is something simple wrong in the with/write construct.
UPDATE: added print(vars((args)) per answer #1 which yields:
{'lang': 'en', 'exemplar_file': None, 'pagehits': 'pagehits', 'summary': False, 'outfile': '/tmp/pagekicker/123/out_test', 'request_type': 'sum', 'infile': '/home/fred/pagekicker-community/scripts/seeds/revolutionary-figures'}

Now I just want to write
lang="en"
exemplar_file="None"
etc.
to a file.

A: Have you tried
print(args)    # the default Namespace display format

or
print(vars(args))

vars(args) is a dictionary, which you can display in a number of different ways.   You could convert it to a list of tuples (.items()), you could iterate over the keys, etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does "|| [];" mean? What does || [] mean in the code below? Why might this be needed?
getPair: function() {
    return this.props.pair || [];
  },

A: [] is an empty array. ||, in this context, is a guard operator.
The statement says to return this.props.pair, but if this.props.pair is falsy, an empty array will be returned instead.


text:
Q: Finding the area on a graph defined by parametric equations
Find the area enclosed by the graph of the parametric equations:
  \begin{align*}
x & = 6 \cos(t) \sin(t), \\
y & = 6 \cos^2(t).
\end{align*}

Should I multiply the top equation by $-\cos(t)$?  Then I could do like, $y-x = 30 \cos ^2(t) \sin^2(t)$?

A: We have $x^2+(y-3)^2=9$, which gives the answer: $9\pi$.


text:
Q: Angular - force redirect to a certain page In my app there's a certain wizard with several steps the user must finish before using the app. Each step certain data is begin added to an array. How can I use this in order to determine how many steps the user finished before getting to the final page? Can I force redirect him to the step he skipped from? E.g typed the url to the final page.
This is my route config code:
app.config(function ($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "homePage.html",
            controller: "homeController"
        })
         .when("/summary", {
            templateUrl: "summary.html",
            controller: "summaryController"
        })
        .when("/step/:index", {
            templateUrl: "/step/stepPage.html",
            controller: "stepController"
        })
        .otherwise({
            redirectTo: "/"
        })
});

In the summary page I tried something like this to determine how did the user get to this page. If length of array is 5 then he went through all steps, if less, redirect him back to where he left.
if(dataArray.length<5){
    $location.path( "/step/"+dataArray.length );
}

This approach always gets me back to the root URL "/". Why?


text:
Q: How to restrict the answer size in javamail search method? I am using Javamail library to fetch emails from several servers through IMAP.
I only care for the unread messages and I want to download only the 5 last received unread messages.
For filtering the messages in a folder I am using using the Folder.search(FlagTerm ft) method passing the flag SEEN with value false, just as following code shows:
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] messages = folder.search(ft);

I need to diminish bandwidth usage and the above method may return an arbitrarily large number of messages. I am only interested in the last 5 of them, is there a way for the IMAP server return a limited number of messages?

A: You can do the search over a subset of the messages, effectively setting an upper limit on the number of messages returned, but you might have to do multiple searches.  There's no direct way to limit the number of results returned if you're searching all messages.
Note that the search results are relatively compact (effectively only the message number), so unless you're searching a huge number of messages I wouldn't think bandwidth would be an issue relative to fetching the content of the messages.


text:
Q: googlemock : Legacy code classes do not inherit from abstract classes I am looking into different testing frameworks for unmanaged C++ application with VS 8.0
It looks like googlemock requires the original class to inherit from an abstract class. The abstract class is then used as a parent by google mock to generate mocks.
In my legacy code, firstly the original classes in my solution are not derived from abstract classes but non-abstract classes and there are'nt always virtual functions in them. Also, in most cases there is a chain of parents like class D is derived from Class C which is derved from Class B and so on. So to create an interface in this case will be even more involved as in mock objects all the virtual functions need to be implemented.
So I just want to know if my understanding of googlemock and test is correct and if there is a n option to not create abstract classes and simply use the existing classes as is to create mocks.
Thank you

A:
It looks like googlemock requires the original class to inherit from
  an abstract class. The abstract class is then used as a parent by
  google mock to generate mocks.

No, your understanding of the Google C++ Mocking Framework is wrong. Inheriting of mocking class (class which you try to mock) from abstract is design suggestion, but not technical requirement. The technical requirements are:

*

*member function which will be invoked must be a virtual (if it isn't you need use static polymorphism instead);

*member function which will be invoked must be a public;

*destructor of mocking class should be a virtual (not obligatory for trivial destructor).

Note: as you can see you don't need to worry about member function which you don't need invoke in through mock-object.

In my legacy code, firstly the original classes in my solution are not
  derived from abstract classes but non-abstract classes and there
  are'nt always virtual functions in them.
  Also, in most cases there is a chain of parents like class D is
  derived from Class C which is derved from Class B and so on.

It is not a problem, while you don't need to invoke non-virtual member functions.

So I just want to know if my understanding of googlemock and test is
  correct and if there is a n option to not create abstract classes and
  simply use the existing classes as is to create mocks.

As I said you don't need to worry about base abstract class, but anyway if your existing code doesn't satisfy the requirements you need modify it. Sometimes for someone it is unacceptable.


text:
Q: How to combine Feign and OAuth 2.0? I'm using Spring Feign and Oauth 2.0
My application has

*

*1 Api gateway with @EnableOAuth2Sso

*2 Services with @EnableResourceServer

When I call an api of an service from the other service, I get this exception.
feign.FeignException: status 401 reading TestFeign#test(); content:
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

How to call an api of an service from the other service?

A: For services you can use these dependency.
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
  <groupId>io.jmnarloch</groupId>
  <artifactId>feign-oauth2-spring-cloud-starter</artifactId>
  <version>1.0.0</version>
</dependency>

This way does not work for api gateway!!!


text:
Q: Is there a way to denote the parent frame in Tkinter? I can't refer to the frame by name due to bad function writing I have a frame with a checkbox and a X button in it. When I hit the X button, I want to delete that frame. Is there a way to denote parent frames? I can't refer to it by its variable name because I made it using a function so all the relevant frames share the same name.
My code:
import tkinter

master = tkinter.Tk()
master.title("test1")
master.geometry("300x300")

checkboxArea = tkinter.Frame(master)

checkboxArea.pack(fill=tkinter.X)

inputStuff = tkinter.Frame(master)

def removeInputStuff():
    inputStuff.pack_forget()
    buttonAdd.pack()
    buttonDone.remove()

buttonDone = tkinter.Button(inputStuff, text = "Close Input", command=removeInputStuff)

def createInputStuff():
    paddingFrame = tkinter.Frame(inputStuff, height=5)
    paddingFrame.pack(fill=tkinter.X)
    buttonDone.pack()
    inputStuff.pack()
    buttonAdd.pack_forget()

buttonAdd = tkinter.Button(master, text="Add Item", command=createInputStuff)
buttonAdd.pack()

topInput = tkinter.Frame(inputStuff)
bottomInput = tkinter.Frame(inputStuff)

topInput.pack()
bottomInput.pack()

def drawCheckboxAndDeleteInputBoxAndPrompt():
    nextToCheckbox = entry.get()
    entry.delete(0,tkinter.END)
    checkboxRow = tkinter.Frame(checkboxArea)
    checkboxRow.pack(fill=tkinter.X)
    checkbox1 = tkinter.Checkbutton(checkboxRow, text = nextToCheckbox)
    checkbox1.pack(side=tkinter.LEFT)
    deleteItem = tkinter.Button(checkboxRow, text = "x", bg="red", fg="white", activebackground="white", activeforeground="red")
    deleteItem.pack(side=tkinter.RIGHT)

prompt = tkinter.Label(topInput, text="What do you want your checkbox to be for?")
prompt.pack()
entry = tkinter.Entry(bottomInput, bd=3)
entry.pack(side=tkinter.LEFT)
buttonConfirm = tkinter.Button(bottomInput, text="Confirm", command=drawCheckboxAndDeleteInputBoxAndPrompt)
buttonConfirm.pack(side=tkinter.LEFT)

master.mainloop()

I would assign a function to delete checkboxRow, but I think that would delete all of my rows.

A: I just added command=checkboxRow.destroy when the deleteItem button is created and it works (it only delete the intended item, not all of them).
So drawCheckboxAndDeleteInputBoxAndPrompt becomes
def drawCheckboxAndDeleteInputBoxAndPrompt():
    nextToCheckbox = entry.get()
    entry.delete(0,tkinter.END)
    checkboxRow = tkinter.Frame(checkboxArea)
    checkboxRow.pack(fill=tkinter.X)
    checkbox1 = tkinter.Checkbutton(checkboxRow, text = nextToCheckbox)
    checkbox1.pack(side=tkinter.LEFT)
    deleteItem = tkinter.Button(checkboxRow, text = "x", bg="red", fg="white",
                                activebackground="white", activeforeground="red",
                                command=checkboxRow.destroy)
    deleteItem.pack(side=tkinter.RIGHT)


text:
Q: Optimizing Listview in C# for large files I have a C# program that is pulling in a .csv file that is approx. 42,000 lines long. All data in the file is stored as follows:
Zipcode,City,State
I am pulling all the information into three different columns in a listview.
Currently this data takes about 30 - 50 seconds to be brought into my program. My question is how can I better optimize my code to get this time down?
The following is a snippet of my code. The commented code is code I previously tried, but had no success in reducing the time, therefore I rewrote it in a way that was easier to read.
 //These are globally declared.
lvZip.Columns.Add("Zipcode", 150, HorizontalAlignment.Left);
lvZip.Columns.Add("City", 150, HorizontalAlignment.Left);
lvZip.Columns.Add("State", 150, HorizontalAlignment.Left);
lvZip.View = View.Details;

lvZip.Items.Clear();

        //string dir = System.IO.Path.GetDirectoryName(
        //  System.Reflection.Assembly.GetExecutingAssembly().Location);

        //string path = dir + @"\zip_code_database_edited.csv";
        //var open = new StreamReader(File.OpenRead(path));

        //foreach (String s in File.ReadAllLines(path))
        //{
        //    Zipinfo = s.Split(',');
        //    Zipinfo[0] = Zipinfo[0].Trim();
        //    Zipinfo[1] = Zipinfo[1].Trim();
        //    Zipinfo[2] = Zipinfo[2].Trim();
        //    lvItem = new ListViewItem(Zipinfo);
        //    lvZip.Items.Add(lvItem);
        //}
        //open.Close();

        StreamReader myreader = File.OpenText(path);
        aLine = myreader.ReadLine();

        while (aLine != null)
        {
            Zipinfo = aLine.Split(',');
            Zipinfo[0] = Zipinfo[0].Trim();
            Zipinfo[1] = Zipinfo[1].Trim();
            Zipinfo[2] = Zipinfo[2].Trim();
            lvItem = new ListViewItem(Zipinfo);
            lvZip.Items.Add(lvItem);
            aLine = myreader.ReadLine();
        }
        myreader.Close();

A: What you should be doing is using the ListView.BeginUpdate() and the ListView.EndUpdate() before and after you add anything into the ListView. The second thing would be to use the ListView.AddRange() instead of ListView.Add(). By using the Add method, you will redraw the ListView every time you use it. However, using ListView.AddRange() you will only redraw it once. That should optimize it a little for you.

A: You can try:
lvZip.BeginUpdate();

before you start adding all the items.
Then:
lvZip.EndUpdate();

when you've finished.
This will prevent the control from drawing each item as you add it, which makes the whole process very slow.

A: Golden Rule: Don't use String.Split() to read CSV data.
The .NET Framework already has a built-in dedicated CSV parser called TextFieldParser.
It's located in the Microsoft.VisualBasic.FileIO namespace.
Not only are there many edge cases that String.Split() is not properly equipped to handle, but it's also much slower to use StreamReader.
One last remark: A tip is to use using statements in order to ensure that your disposable objects get disposed (release unmanaged resources). I see that you are not using them (pun not intended) in the above code.
It's actually not that far outside the scope of this question since efficient memory management can boost the performance of your code.

A: A little more work perhaps but using a DataGridView with the textfile used as a datasource, you can get a load time in under 2 secs., from a 42,000 line .csv.  Here's some code to look at:
    private void button2_Click(object sender, EventArgs e)
    {
        string errorInfo = String.Empty;
        //open text file into Dataset:
        string textFilePath = @"textfile1.csv";

        DataSet dataTextFile = new DataSet("textfile");
        if(!LoadTextFile(textFilePath, dataTextFile, out errorInfo))
        {
            MessageBox.Show("Failed to load text file:\n" + errorInfo,
                "Load Text File");
            return;
        }
        dgTextFile.DataSource = dataTextFile.Tables[0];
        dataTextFile.Dispose();
    }

    private bool LoadTextFile(string textFilePath, DataSet dataToLoad, out string errorInfo)
    {
        errorInfo = String.Empty;

        try
        {
            string textFileFolder = (new System.IO.FileInfo(textFilePath)).DirectoryName;
            string textConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                                            "Data Source=" + textFileFolder + ";" +
                                            "Extended Properties=\"text;\";";
            OleDbConnection textConnection = new OleDbConnection(textConnectionString);

            textConnection.Open();

            textFilePath = (new System.IO.FileInfo(textFilePath)).Name;
            string selectCommand = "select * from " + textFilePath;

            //open command:
            OleDbCommand textOpenCommand = new OleDbCommand(selectCommand);
            textOpenCommand.Connection = textConnection;

            OleDbDataAdapter textDataAdapter = new OleDbDataAdapter(textOpenCommand);

            int rows = textDataAdapter.Fill(dataToLoad);

            textConnection.Close();
            textConnection.Dispose();

            return true;
        }
        catch(Exception ex_load_text_file)
        {
            errorInfo = ex_load_text_file.Message;
            return false;
        }
    }

Some of this code is from an MSDN sample but I can't seem to find the page.


text:
Q: How to track users origin PHP by using example.com/index.php?ref=origin How to track users origin in PHP , i see people using this ref= often i don't have any idea how does this get request works .
My code
 $calling_url = mysql_real_escape_string($_SERVER['HTTP_REFERER']);

A: URL:

http://example.com/index.php?ref=http://externalsite.com/page.html OR
  http://example.com/index.php?ref=http%3A%2F%2Fexternalsite.com%2Fpage.html

PHP:
$ref = mysql_real_escape_string(rawurldecode($_GET["ref"]));
// $ref will be "http://externalsite.com/page.html" in both cases

Resources for URL tracking:

*

*Using Referrer URLs to Better Understand Your Visitors

*Referrers and Search Engines tracking

*Alternative for $_SERVER['HTTP_REFERER'] PHP variable

A: Without knowing more about what you're trying to achieve.
If users are coming from outside your site, the best bet is to use HTTP_REFERER. If someone asks your server for a page, you'll have to take their word for it as far as the referrer is concerned. Whether that's in the URL or in the browser. If they don't want to tell you, you can't make them.
Even though it's not that reliable it's going to be more reliable than depending on someone else's application. Unless there is a transaction involved that would encourage the referrers to format the url correctly.
If users are moving around within your own site. You can use the ref= strategy, or you can use session variables.


text:
Q: Can this model be implemented with lme4? Suppose the data $y_{ijk}$ is structured with three indexes $i,j$ and $k$, and can be decomposed through a linear mixed-effects model:
$y_{ijk}=a + b_i + \xi_j+ \eta_k + \gamma_{jk} + \epsilon_{ijk}$
where $a$ and $b_i$ are fixed effects, $\xi_j$ and $\eta_k$ are two random-effect terms associated with the two grouping factors indexed with $j$ and $k$, respectively, $\gamma_{jk}$ is the interaction effect between the two indexes, and $\epsilon_{ijk}$ is the residual term.
My distribution assumptions are
$\xi_j \sim N(0, \tau^2)$
$\eta_k \sim N(0, \lambda^2)$
$\gamma_{jk} \sim N(0, \theta_k^2)$
$\epsilon_{ijk} \sim N(0, \sigma_k^2)$
Notice that the last two distributions are unique in the sense that they are separately modeled for each $k$. So, is there a way to analyze the data with the R package lme4? Through dummy coding somehow?
If the residuals cannot be partitioned across $k$ with lme4, is it still possible to at least keep $\gamma_{jk} \sim N(0, \theta_k^2)$?


text:
Q: quarkus optaplanner illegal reflective call I have upgraded my JDK to version 17.
Now when I try to run parametized unit tests with optaplanner running on Quarkus I get the following stacktrace:
java.lang.ExceptionInInitializerError
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private transient java.util.NavigableMap java.util.TreeSet.m accessible: module java.base does not "opens java.util" to unnamed module @724b93a8

[ERROR] org.m.s.c.score.constraints.SecConflictTest.secConflictTest(String, int, Agent)[2]  Time elapsed: 0.011 s  <<< ERROR!
java.lang.NoClassDefFoundError: Could not initialize class com.thoughtworks.xstream.converters.collections.TreeSetConverter$Reflections

[ERROR] org.m.s.c.score.constraints.SecConflictTest.secConflictTest(String, int, Agent)[3]  Time elapsed: 0.014 s  <<< ERROR!
java.lang.NoClassDefFoundError: Could not initialize class com.thoughtworks.xstream.converters.collections.TreeSetConverter$Reflections

After reading a bit about this kind of problem I have added
--add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED

to my Maven POM in the following sections: Quarkus-maven-plugin config and maven-surefire-config
        <plugins>
            <plugin>
                <groupId>${quarkus.platform.group-id}</groupId>
                <artifactId>quarkus-maven-plugin</artifactId>
                <version>${quarkus.platform.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <compilerArgs>
                        <arg>--enable-preview --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED</arg>
                    </compilerArgs>
                    <jvmArgs>--enable-preview --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED</jvmArgs>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>build</goal>
                            <goal>generate-code</goal>
                            <goal>generate-code-tests</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${compiler-plugin.version}</version>
                <configuration>
                    <parameters>${maven.compiler.parameters}</parameters>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${surefire-plugin.version}</version>
                <configuration>
                    <argLine>
                        --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED
                    </argLine>
                    <systemPropertyVariables>
                        <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
                        <maven.home>${maven.home}</maven.home>
                    </systemPropertyVariables>
                </configuration>
            </plugin>
        </plugins>

and in maven-failsafe-plugin config for profile native:
<profiles>
        <profile>
            <id>native</id>
            <activation>
                <property>
                    <name>native</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <version>${surefire-plugin.version}</version>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                                <configuration>
                                    <argLine>
                                        --add-opens java.base/java.lang.reflect=ALL-UNNAMED
                                        --add-opens java.base/java.util=ALL-UNNAMED
                                        --add-opens java.base/java.text=ALL-UNNAMED
                                        --add-opens java.desktop/java.awt.font=ALL-UNNAMED
                                    </argLine>
                                    <systemPropertyVariables>
                                        <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
                                        <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
                                        <maven.home>${maven.home}</maven.home>
                                    </systemPropertyVariables>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <properties>
                <quarkus.package.type>native</quarkus.package.type>
            </properties>
        </profile>
    </profiles>

It does work as intended: tests are running fine, but I have "lost" live reload feature of quarkus
If I change anything in my code and call a WS again, here is the error:
Error restarting Quarkus
java.lang.IllegalArgumentException: error: invalid flag: --enable-preview --add-opens
            java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens
            java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED

I'm looking for a configuration allowing Quarkus with Optaplanner to run on Java 17, with ParametizedTests running fine and live reloading still working.
For information, with simple tests (no Parametized), it does work without specific --add-open config.
Here is the post that leads me on the path for my first fix:
https://github.com/quarkusio/quarkus/issues/10303#issuecomment-666492921

A: I actually add the --add-opens... line to the javac parameters
That was breaking the livereload.
By using this add-opens parameters only on JVMArgs on quarkus-maven-plugin, it works as intended. and Live Reload is working also.
Btw I'm still looking for a solution to not have to add any add-opens parameters

A: I see 2 possible causes for this issue (I can't see which one it is):

*

*You're using OptaPlanner 7.
Fix: Upgrade to OptaPlanner 8, which uses JAXB instead of XStream. The Quarkus extension for OptaPlanner 8 is stable and reliable (the one in 7 is not).

*You're loading a dataset with XStream, before calling OptaPlanner, possibly through using optaplanner-persistence-xstream. That's an XStream issue with JDK 17. (See Lukas's comment.) Maybe upgrading to a new version of XStream fixes it, I hope.


text:
Q: Consider or consider as Can I use "consider as' in the meaning "think about options to be/do someone/something?"
For example, "If you have a fashion brand and consider this company as your partner, think about the options for cooperation" (here, I say that this is only one of the options: it may be this company, and may be the other one)

A: "Consider for (some position or role)" is better if you are thinking about whether to hire, engage, or contract with someone. Merriam-Webster has the example "We are considering you for the job."
"Consider as" in contrast is used where someone does not formally hold a status/role/characteristic but is viewed as if they were in that status/role/characteristic: "We consider them as our partner" means they're not actually our partner, but the relationship is so close that it is as good as being partners.
If you just want to express your thoughts more generally, you can use "consider" without a preposition, e.g. you might say "I don't consider him a good employee" or "I consider him my closest friend".
However, these rules are probably not applied 100%, as there is a lot of freedom about English preposition use.


text:
Q: Flutter Firebase apiKey, appId, messagingSenderId and projectId I need to use firebase_messaging to send message from my backend to my flutter apk.
When initialize firebase, these are the 4 keys essential in the FirebaseOptions

apiKey : Is this the Server Key found in FCM?

appId : Where can I find this key?

messagingSenderId : Sender ID FCM

projectId : Where can I find this?

Besides, in order for me to send message to a single user. I need to tell Firebase who am I right? May I know which ID shall I use?
Thx

A: When you register with firebase you obtain the push notification token. This token is used to send a notification to the device the app is installed on.
Assuming you already initialized firebase app in flutter, and you added the google-services.json in your app. You can obtain your push notification token in the following way:
messaging = FirebaseMessaging.instance;
    messaging.getToken().then((value){
        print(value); //this is the push notification token
});

You can also test that you are able to receive the notification on the app from the firebase console. You can send a notification to the app under Compose notification section in the firebase console. It only requires the notification token you obtained from the app.


text:
Q: Multiple and or conditions for flagging in python I have the below data in a pd dataframe :
There are cutoffs for Sliver and OThers(Like all Multi's - Multi_A etc) as below:
d_id    Sliver  Multi_A Multi_B Multi_C Multi_D no_of_prem  Flag_Sliver
5       4.80    53.05   19.07   13.59   0       3           No
18      5.17    27.63   26.83   12.15   0       3           No
25      1.28    0.14    0.12    0       0       2           Yes
32      0.90    0.43    0.94    0       0       2           No
33      3.69    3.24    0.77    1.36    0       3           No
34      0.15    11.62   5.92    1.42    0       3           No
55      0.31    11.29   5.95    1.02    0       3           No
64      0.25    0.82    2.77    0       0       2           No
86      0.02    9.65    1.82    0.10    0       3           No
89      0.13    3.19    1.55    1.77    0       3           No

Sliver  5
Multis  0.15

IF any d_id has value in Sliver which is less than 5 and any two of the multi's(there are 4 Multi's in total) for that d_id has values less than 0.15 then the Flag variable is given a Yes or else a No. IN the above example only 25 satisfies the condition and hence flagged as yes.
Can someone please help me with these conditions?

A: Use numpy.where by condition:
mask = df.filter(like='Multi').lt(.15).all(1) & df['Sliver'].lt(5)
#alternative
#mask = df.drop(['d_id','no_of_prem', 'Sliver'], axis=1).lt(.15).all(1) & df['Sliver'].lt(5)
df['Flag_Sliver'] = np.where(mask, 'Yes' ,'No')
print (df)
   d_id  Sliver  Multi_A  Multi_B  Multi_C  Multi_D  no_of_prem Flag_Sliver
0     5    4.80    53.05    19.07    13.59        0           3          No
1    18    5.17    27.63    26.83    12.15        0           3          No
2    25    1.28     0.14     0.12     0.00        0           2         Yes
3    32    0.90     0.43     0.94     0.00        0           2          No
4    33    3.69     3.24     0.77     1.36        0           3          No
5    34    0.15    11.62     5.92     1.42        0           3          No
6    55    0.31    11.29     5.95     1.02        0           3          No
7    64    0.25     0.82     2.77     0.00        0           2          No
8    86    0.02     9.65     1.82     0.10        0           3          No
9    89    0.13     3.19     1.55     1.77        0           3          No

Explanation:
First select all Multi columns by filter or drop unnecessary columns:
print (df.filter(like='Multi'))
#print (df.drop(['d_id','no_of_prem', 'Sliver'], axis=1))

   Multi_A  Multi_B  Multi_C  Multi_D
0    53.05    19.07    13.59        0
1    27.63    26.83    12.15        0
2     0.14     0.12     0.00        0
3     0.43     0.94     0.00        0
4     3.24     0.77     1.36        0
5    11.62     5.92     1.42        0
6    11.29     5.95     1.02        0
7     0.82     2.77     0.00        0
8     9.65     1.82     0.10        0
9     3.19     1.55     1.77        0

Compare by .15 by lt (<):
print (df.filter(like='Multi').le(.15))
   Multi_A  Multi_B  Multi_C  Multi_D
0    False    False    False     True
1    False    False    False     True
2     True     True     True     True
3    False    False     True     True
4    False    False    False     True
5    False    False    False     True
6    False    False    False     True
7    False    False     True     True
8    False    False     True     True
9    False    False    False     True

Get all only Trues rows by DataFrame.all:
print (df.filter(like='Multi').le(.15).all(1))
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool

Compare also column Sliver:
print (df['Sliver'].lt(5))
0     True
1    False
2     True
3     True
4     True
5     True
6     True
7     True
8     True
9     True
Name: Sliver, dtype: bool

and chain by & (AND):
mask = df.filter(like='Multi').lt(.15).all(1) & df['Sliver'].lt(5)
print (mask)
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool


text:
Q: PKG_CHECK_MODULES breaking in solaris My project requires dependency of libxml2 am using autotools to check the dependencies & install the same. I declare the dependency of using the following macro in configure.ac
echo -n "checking if libxml2 is present... "

PKG_CHECK_MODULES([LIBXML2], [libxml-2.0 >= 2.6.19],
              [echo "yes (features requiring libxml2 enabled)"  AC_DEFINE(HAVE_LIB_XML, 1,     [define if libxml2 is present])],
              [echo "no"] )

The macro works as desired in GNU/Linux.
But somehow it fails in Solaris with the following error
checking if libxml2 is present... ./configure: line 11586: syntax error near unexpected token `LIBXML2,'
./configure: line 11586: `PKG_CHECK_MODULES(LIBXML2, libxml-2.0 >= 2.6.19,'

Googled for a solution, most of them complain of pkg-config not being installed. But in my test machine its actually installed, checked it by executing the following command.
bash-3.00# pkg-config libxml-2.0 --modversion
2.6.23

Some suggestions would be welcomed.

A: The PKG_CHECK_MODULES macro doesn't seem to be expanded properly. When you installed pkg-config, did it install pkg.m4 (in somewhere like /usr/share/aclocal)? If so, try running aclocal again (maybe with -I m4, if you've got custom m4 code in the m4 subdirectory) and then run autoconf.
If that doesn't work and pkg.m4 was installed, try running autoreconf -f (and maybe autoreconf -i -f).
If that doesn't work, you'll need to copy pkg.m4 to a directory for your package. Usually this is the m4 subdirectory. Set ACLOCAL_AMFLAGS = -I m4 (or ACLOCAL_AMFLAGS = -I m4 --install) in Makefile.am (if you're using automake), and AC_CONFIG_MACRO_DIR([m4]) in configure.ac. Then run aclocal -I m4 and autoconf and ./configure.


text:
Q: Http request from node server to Strapi throws error "econnrefused" I'm trying to access a strapi api in my local dev environement. Wheras I have no issues to access the api under the same url with postman, trying to access it from my node server i run into this error:
connect ECONNREFUSED ::1:1337
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 1337

This is the part of my server where I make the request:
const request = require('request');
        request({
      url: 'http://localhost:1337/api/homepage?populate=*',
      headers: {
         'Authorization': 'Bearer 123455347'  },
      rejectUnauthorized: false
    }, function(err, res) {
          if(err) {
            console.error(err);
          } else {
            console.log(res.body);
          }

    });
    }

Why refuses strapi the connection? I'm helpless.. Ist there something I missed while configuring it?

A: I had the exact same issue and I have found a work around inspired by a discussion on GitHub (https://github.com/axios/axios/issues/3821).
The problem seems to be that Strapi does not support IPv6 properly with all Node-Versions (https://github.com/strapi/strapi/issues/12285).
When I try to access my Strapi-API with the address http://localhost:1337 my computer resolves the IPv6 address ::1: and this causes the beforehand mentioned error.
connect ECONNREFUSED ::1:1337

Therefore instead of trying to connect to http://localhost:1337 try to use the IPv4 address of your computer. In my case this meant to connect to http://192.168.0.12:1137.


text:
Q: How does react know where to put the cursor while typing inside an input element? If I write this in a component:
const [value, setValue] = useState("");
....
return <input onChange={(e) => setValue(e.target.value)} value={value} />

Then react somehow knows how to preserve the cursor position. I'm wondering - how does react do this exactly? All react knows is that I'm resetting the value of the input. Is there some sort of algorithm to find the added letter and add the cursor in at the right place?

A: Nothing special needs to be done.
The target value has been reassigned by the user by the time the React change callback runs; that's why the setValue(e.target.value) sets the new value in state, rather than the old value.
When the value is assigned to an input, if the new value is the same as the old value, the browser will not change the cursor position. Demo:

const input = document.querySelector('input');
input.addEventListener('input', (e) => {
  console.log('change seen');
  input.value = input.value;
});
<input>


text:
Q: groff ms column break macro I have seen here how to perform a page break:
groff ms page break macro
I have been trying to find the equivalent but for columns in a .2C two columns formatted document. Sometimes the header of a section appears at the end of the left column isolated and I would like to manually force to appear at the beginning of the right column in those cases.
Is there any equivalent to .bp but for columns?

A: You can use the basic troff need command. It takes the number of lines of space you need for the following input.  Typically, a header macro would include such a command to avoid the widow that you are seeing. So if you would like at least 2 lines of text plus a header you might use, say
.ne 5


text:
Q: How to italicize enumeration in task environment Consider the following MWE:
\documentclass{article}
\usepackage{tasks}

\begin{document}
\begin{tasks}[label-format=\itshape](4)
    \task Ex. 1
    \task Ex. 2
    \task Ex. 3
    \task Ex. 4
\end{tasks}
\end{document}

I would like to not italicize the parentheses:

Is it possible to achieve it in an easy way?
Thanks!

A: One should use \textup{)}, so the italic correction would be automatically added; unfortunately, this crashes because of the nature of \textup that doesn't really like to be used in that place. However, there's an easy fix.
Note that \upshape doesn't take an argument.
\documentclass{article}
\usepackage{tasks}
\usepackage{etoolbox}
\robustify{\textup}

\begin{document}

\begin{tasks}[label-format=\itshape,counter-format=tsk[a]\upshape{)}](4)
    \task Ex. 1
    \task Ex. 2
    \task Ex. 3
    \task Ex. 4
\end{tasks}

\begin{tasks}[label-format=\itshape,counter-format=tsk[a]\/\upshape)](4)
    \task Ex. 1
    \task Ex. 2
    \task Ex. 3
    \task Ex. 4
\end{tasks}

\begin{tasks}[label-format=\itshape,counter-format=tsk[a]\textup{)}](4)
    \task Ex. 1
    \task Ex. 2
    \task Ex. 3
    \task Ex. 4
\end{tasks}

\end{document}

You can see that the second and third examples print the same. In the second example, the italic correction \/ is explicitly added.

A: Thanks to @AlanMunn for the hint.
I added the \upshape command only for the parentheses and used tsk[a] for a, b, c, ... style numbers, all inside counter-format command.
\documentclass{article}
\usepackage{tasks}

\begin{document}
\begin{tasks}[label-format=\itshape,counter-format=tsk[a]\upshape{)}](4)
    \task Ex. 1
    \task Ex. 2
    \task Ex. 3
    \task Ex. 4
\end{tasks}
\end{document}


text:
Q: Unable to get nativeElement of ion-textarea in Ionic 4 to set height I have a custom directive to adjust the ion-textarea height to autosize the height as text is entered rather than setting a fixed row height or having ugly scroll bars as the textarea fills up.
In Ionic-4 I am unable to get the nativeElement of the html textarea of the ion-textarea. Any help would be great
It's running on Angular 6 and Ionic 4 but when I try and get this.element.nativeElement.getElementsByTagName('textarea')[0] it is always undefined so I can't set the height programatically.
import { ElementRef, HostListener, Directive, OnInit } from '@angular/core';

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class AutosizeDirective implements OnInit {
  @HostListener('input', ['$event.target'])
  onInput(textArea:HTMLTextAreaElement):void {
    this.adjust();
  }

  constructor(public element:ElementRef) {
  }

  ngOnInit():void {
    setTimeout(() => this.adjust(), 0);
  }

  adjust():void {
    const textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = textArea.scrollHeight + 'px';
  }
}

As the const textArea always comes back undefined I can't set the height to follow the scroll height to prevent the scroll bars.
Anyone been able to do this in Ionic-4? seen working examples in Ionic-3 as per the above code.
Thank you
Rowie

A: Below code would help your problem.
import { ElementRef, HostListener, Directive, AfterViewInit } from '@angular/core';

@Directive({
  selector: 'ion-textarea[autosize]'
})

export class AutoSizeDirective implements AfterViewInit {
  readonly defaultHeight = 64;

  @HostListener('input', ['$event.target'])
  onInput(textArea: HTMLTextAreaElement) {
    this.adjust(textArea);
  }

  constructor(private element: ElementRef) {}

  ngAfterViewInit() {
    this.adjust();
  }

  adjust(textArea?: HTMLTextAreaElement) {
    textArea = textArea || this.element.nativeElement.querySelector('textarea');

    if (!textArea) {
      return;
    }

    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.style.height = (textArea.value ? textArea.scrollHeight : defaultHeight) + 'px';
  }
}

Usage: <ion-textarea autosize></ion-textarea>

I have confirmed it on Ionic 4.0.2/Angular 7.2.6.
Regards.

A: this package does all the autosizing of my ion-textareas for me https://github.com/chrum/ngx-autosize
just follow the guide and get it working, if it doesn't work importing it into the app.module.ts then try importing it into the page's module, I personally needed that dunno if you will, but package is a life saver


text:
Q: Disable Application Cache in Chrome and Safari I'm using the AppCache in order to enable offline access for a web app. The issue is that for development every time I make a change to my JavaScript I also need to make a change to the manifest (in order to trigger a re-download of the cached field). Now I know that in FireFox you can disable the AppCache (in fact you are prompted when you first visit the page whether to grant permission to web site to store data locally) which makes it a lot more convenient for development.
My question is there a similar option for chrome and safari?
I know that I can view/Edit the AppCache in chrome via chrome://appcache-internals/, what I'm looking for is a way to disable it.
Thanks

A: In Chrome, use Incognito Mode. Okay, it's probably not what it was originally intended for, but it does the job. Nothing gets cached, and now developers everywhere have a handy excuse for why they might be using Incognito Mode.
I assume there's similar 'Private Browsing' functionality available in Safari.
EDIT: I see from your comment that you want to disable Cache Manifest functionality only. Try starting Chrome from a Command Line with the --disable-application-cache switch.


text:
Q: Fody.Propertychanged preventing Edit and Continue when used with MVVMLight I understand that using AOP tooling could/should interfere with edit and continue for a class that is weaved.  But I have a case where simply using MVVMLight and Fody.PropertyChanged in the same project prevents edit and continue anywhere if there is a class inheriting from ObservableObject in the project.
To reproduce, I simply create a WPF 4.6.2 project in VS 2017 Update 3 (happens in all the updates), add nuget references to MVVMLight & Fody.PropertyChanged, and then I can't edit and continue even simple code like this:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    int i = 0;
    i++;
    i++;
}

Error is:
CS7038  Failed to emit module 'WithFodyPropertyChangedAndMvvmLight'.
If I remove the PropertyChanged tag from the FodyWeavers.xml file, the problem goes away.  If I don't use MVVMLight and instead just:
class Class : INotifyPropertyChanged
{
    public int Test { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
}

it works fine.  So it looks MVVMLight specific.
Anyone seen this?  Thanks!


text:
Q: 2 classes with same methods and properties (ambiguous references) C# I have 2 XSD'd that I turned into classes. Company and Person class. The XSD's have several included tags that referenced the same data. Example:
    <xs:include schemaLocation="ControlAreaType.xsd"/>

When I place both of these classes (Person and Company) into my project and compile. I get "ambiguous references" The classes are okay because they are partial, but the properties both inside the nested classes and outside are what is causing the issues. I have tried to place them in their own namespace but I get errors stating that you cannot put properties outside of classes within a namespace. Each class is about 5000 lines of code (no joke).
The solution that I have come up with is to place 1 of the classes (Person) into it's own project, and the other class into it's own project (Company) within the same solution. I have referenced the "PERSON" project within the "COMPANY" project where most of the code resides. I think it's kinda clunky, but it seems to compile and I've written code off of it.
Do any of you have a better solution? I cannot alter the classes since they are auto generated by the .NET XSD command.
Here is a link to the code. DL it and compile it, you'll see the error.
TestCode


text:
Q: Sinatra: before filter ordering I want to define a global before filter that will run before every request that will set up some instance variables for all the methods.
I have set up the filter and have also set up some route specific before filters. It appears that my route specific filters are being executed prior to my global one and therefore crashing because expected instance variables are not set yet.
Is there a way to specify the order in which before filters are processed?

A: This works for me, on Sinatra 1.3.2.
before do
  @filter = [] << 'everything'
end
before '/filter' do
  @filter << 'specific'
end
get '/filter' do
  @filter.inspect
end

This gives me ["everything", "specific"] which is what I would expect. Is it possible you do not have the catch-all filter before all the rest?
In Sinatra, routes are evaluated in order from the top, not by how well they match. Therefore, if you have the specific filters before the catch-all filter, it will evaluate those first, as seen here:
before '/filter' do
  @filter = [] << 'specific'
end
before do
  @filter << 'everything'
end
get '/filter' do
  @filter.inspect
end    # => ["specific", "everything"]


text:
Q: what aspects should i keep in mind while developing a Java based API I am experiencing the pain of developing an API based on (Selenium2) Webdriver and here is my dilemma.
I have basically 4 packages:
com.example.qa.pageobject
com.exmaple.qa.setup
com.example.qa.test
com.example.qa.utils

In com.example.qa.test, i have test classes that "USE" classes from other packages.
I am ending up in the following test method.
@Test
    public void testScenario16786() {
        Login login = new Login();
        login.setUp();
        AddSingleDomain asd = new AddSingleDomain();
        asd.addSingleDomain();
        AddARecord ar = new AddARecord();
        ar.AddARecordTest();

    }

Now, this seems to be a very bad example of developing in Java, which almost seems procedural. Is there any other way of doing it ? Are there some RULES that i need to be aware of while designing an API, which will be used by others ? i am sure that this is somewhat of a classical problem and has been solved before, i just want to know what are the many ways of resolving this, like:
One resolution, could be to use Factory Pattern, and based on a key, a specific class is instantiated, which is good but is there a more elegant way ?

A: Your test class is necessarily procedural - a repeatable set of steps, that's fine.
The commonly recommended approach is to use the Page Object pattern and selenium also provides a PageFactory object to help you (see end of the page):
page objects

A: You might find the presentation "How to Design a Good API & Why it Matters" by Joshua Bloch to be helpful.


text:
Q: Display a local image in WPF I have a problem displaying an image in WPF. The problem is that I add the image into the Grid and I can not actually see the image. I can see the place where the image is, but not the image itself (check the image below):

Here is my code:
View:
<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True" Visibility="Visible">
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <Image Height="25" Width="50" Source="{Binding Path=ImageArticle}" />
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Here I take the path and add it:
ContinueArticle ca = new ContinueArticle();
string ImagePath = Environment.CurrentDirectory + @"C:\iClipIT\Thumbs\" + ClipID;
ca.ImageArticle = ImagePath;
atlist.Add(ca);

And here I create the object and the getters and setters:
public static readonly DependencyProperty ArticleImageProperty
    = DependencyProperty.Register("ArticleImage", typeof(string), typeof(ContinueArticle));

public string ImageArticle
{
    get
    {
        return (string)GetValue(ArticleImageProperty);
    }
    set
    {
        SetValue(ArticleImageProperty, value);
    }
}

Any clue what I'm doing wrong? I read a lot about this and I can't find the problem.


text:
Q: entity framework code first select multiple levels into a viewmodel Good day,
I am using ASP. NET MVC with C# and entity framework. I have three tables in my codefirst model.
public class Project
{
    public Guid Id { get; set; }
    public guid ProjectTypeId{ get; set; }
    public string projectType{ get; set; }
    [Required]
    public DateTime CreationDate{ get; set; }
    //more properties here
    //...
    public bool Activated{ get; set; }
    public IList<ProjectDetail> ProjectDetails{ get; set; }
}

As you can see a project has many details.
public class ProjectDetail
{
    [Required]
    public Guid Id { get; set; }
    public Project Project{ get; set; }
    [Required]
    public Guid ProjectId{ get; set; }
    public string DetailDescription{ get; set; }
    public IList<ProjectDetailsAnswer> ProjectDetailsAnswers{ get; set; }
}

And a projectDetail has many answers:
public class ProjectDetailsAnswer
{
    [Required]
    public Guid Id { get; set; }
    [Required]
    public Guid ProjectDetailId{ get; set; }
    public ProjectDetail ProjectDetail{ get; set; }
    public string OtherField{ get; set; }
    [Required]
    [MaxLength(512)]
    public string AnswerDescription{ get; set; }
}

What I would like to do is to use entity framework with lambda expresions to load a viewmodel
public class MyViewModel
{
    public Guid projectTypeId{ get; set; }
    public string projectType { get; set; }
    public string DetailDescription { get; set; }
    public IEnumerable<string> AnswerDescription{ get; set; }//this propertie comes from ProjectDetailsAnswer.AnswerDescription
}

What I have so far is this code:
var y = _dbContext.Project
    .Include(a => a.ProjectDetail.Select(p => p.ProjectDetailsAnswer))
    .Select(n =>new MyViewModel{projectTypeId=n.projectTypeId,projectType =n.Project.projectType,DetailDescription =n.AnswerDescription.Select(b =>b.AnswerDescription).ToList()})
    .ToList();

I receive this error: > cannot convert string to List in this code  . n.AnswerDescription.Select(b =>b.AnswerDescription).ToList()
What am I doing wrong? Can you, if possible, provide me some code that works for the purpose of loading my viewmodel with data?
, the problem comes
Thanks

A: if DetailDescription is just a string in your viewmodel, but not a IList, so I guess it's a ProjectDetailViewModel, so your linq should be:
        var result = _dbContext.ProjectDetails //<==search from details
            .Select(x => new ProjectDetailViewModel
            {
                projectTypeId = x.Project.ProjectTypeId,
                projectType = x.Project.projectType,
                DetailDescription = x.DetailDescription,
                AnswerDescription = x.ProjectDetailsAnswers.Select(a => a.AnswerDescription)
            }).ToList();

but if you insist on query from projects:
        var result = _dbContext.Projects.SelectMany(x=>x.ProjectDetails) //<==use SelectMany
            .Select(x => new ProjectDetailViewModel
            {
                projectTypeId = x.Project.ProjectTypeId,
                projectType = x.Project.projectType,
                DetailDescription = x.DetailDescription,
                AnswerDescription = x.ProjectDetailsAnswers.Select(a => a.AnswerDescription)
            }).ToList();


text:
Q: Endless horizontally scrolling view to draw content dynamically I want to create the following view / set of views which behave following way:

*

*I have huge set of points which have been stored to DB in web server.

*My client application downloads those and should draw curved lines about the data.

*What components should I use here to get this "infinite" scrolling view to draw content dynamically.

*No snapping wanted, so it should be smooth and can stop to every X position.

Should I proceed with this by using HorizontalScrollView with horizontal LinearLayout and remove/add views based on scrolling, then translate the scrolling position and provide fling that the scrolling doesn't stop suddenly.
Or is just one canvas possible to use and draw the content to simulate the scrolling?
Maybe a horizontally scrolling ListView component?
The solution should be efficient and use minimum of memory.
Which solution do you recommend, or do you have some new ideas other than above?
All suggestions are highly appreciated. Thanks.

A: There is several possibilities:
Create custom View class and implement GestureDetector there. You can get movement of finger, calculate currently visible area and draw only visible part of content.
May be this solution is not the easiest to implement, but it will be fast and does not require   any resources.


text:
Q: When to use homeAsUpIndicator in a toolbar? I see that in a Toolbar e.g.
<androidx.appcompat.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:navigationIcon="?attr/homeAsUpIndicator">

Either I add app:navigationIcon="?attr/homeAsUpIndicator" or if that is missing i.e.
<androidx.appcompat.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary">

the back arrow is displayed. I was wondering, is there a reason to add ?attr/homeAsUpIndicator anyway?

A: ?attr/homeAsUpIndicator
Specifies a drawable to use for the 'home as up' indicator which is used to navigate back to former page or activity
It can also be added programmatically
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true)

Visit https://developer.android.com/reference/android/R.attr.html#homeAsUpIndicator to
know about it...
I hope this helps...


text:
Q: Let $A$ is doubly stochastic , Can we say that ${\sigma _1}(A) = 1$? Let $A\in M_n$ be doubly stochastic and let ${\sigma _1}(A)$ be its largest singular value.
Can we say that  ${\sigma _1}(A) = 1$?

A: Yes.
Hint: $\sigma_1(A)^2 = \lambda_{\max}(A^TA)$. However, if $A$ is doubly stochastic, so is $A^TA$.


text:
Q: Fetch only the ids from a hasMany in Grails? I know I can do Parent.childId in Grails, but is there anything similar I can do to only load ids (proxies) for every children in a hasMany? I.e., something similar to Parent.childrenIds?
In my case, the hasMany is mapped by a joinTable.

A: You can do this with a projection. e.g.
def result = Child.createCriteria().list {
    projections {
        property('id')
    }
    eq ('parent', parent)
}

This will return just the ids of the child objects.

A: With a joinTable in mind:
def getChildIds(parentId) {
    Child.withSession { session ->
        def sql = new Sql(session.connection())
        sql.rows(
            'select pc.child_id from parent_child pc where pc.parent_id = :parentId',
             [parentId: parentId]
        ).collect{ it.child_id }
    }
}

This works for a joinTable mapped as such:
class Parent {

    static mapping = {
        childs joinTable: [name: 'parent_child', column: 'child_id', key: 'parent_id']
    }
    ...

It's not pretty but I believe it's the best way considering the situation and requirement.


text:
Q: How to Create of list containing links using javascript Am pretty new to JavaScript and trying to create a list containing links. so how do we achieve it using JavaScript? Assuming the contents that are part of the list are available as an array.
What needs to be acheived is
LinkList

*

*Link1

*Link2

Link1 and Link2 are links.
Statically in HTML page, it can be acheived as given below

LinkList

Link1

Link2

if we get Link1 and Link2 as an array, how can the dynamic creation of list containing links be achieved using Javascript?

A: What you posted in your comment above is a good start. Rather than adding the link name as text, you need to create an anchor element and append it to your li element.
Try something like the following. It's more complicated than it has to be, but it also is probably more readable than some other solutions.
var Link = function(href, name) {
    this.href = href;
    this.name = name;
    this.generateAnchor = function() {
        return $("" + this.name + "");
    };
};

var links = [new Link("http://www.google.com", "Google"),
             new Link("http://www.yahoo.com", "Yahoo")];

for (var i = 0; i<links.length; i++) {
    var listElement = $("

").append(links[i].generateAnchor());
    $("ul.linkList").append(listElement);
}

Working example in this jsFiddle.
If you have any questions, let me know.  For next time, please remember that StackOverflow is intended to help refine existing code and answer questions that are the fruit of research.  The more of your work and research you show, the more helpful we can be.


text:
Q: Cheese will not start in 12.04 I start Cheese on my 12.04 installation. I have used it before in my previous installations but since I upgraded to 12.04, no joy!  I have a GeForce GT-520 video card with the "recommended" additional proprietary drivers installed and activated.
I tried to run Cheese from the terminal and got the following errors:
dozens of these errors:
(cheese:5467): Gtk-WARNING **: Theme parsing error: gnome-applications-light.css:42:23: Not using units is deprecated. Assuming 'px'.

about a dozen of these errors:
(cheese:5467): Gtk-WARNING **: Attempting to add a widget with type GtkImage to a
GtkToggleButton, but as a GtkBin subclass a GtkToggleButton can only contain one widget
at a time; it already contains a widget of type GtkLabel

only one of these errors:
(cheese:5467): CRITICAL **: cheese_camera_device_get_uuid: assertion
CHEESE_IS_CAMERA_DEVICE (device)' failed
Segmentation fault (core dumped)

A: Probe with this
Alt + F2 >> gstreamer properties >> section video and probe your dispositive (check correct device, is possible have 2 or + in your /dev/video)... if you webcam working, is problem identifier device for cheese, change en dconf apps >> cheese >> camera -- for /dev/video #Number for you webcam.


text:
Q: Is there a matplotlib contourf equivalent for bokeh? I need to perform something in bokeh which I am successfully doing in matplotlib.
I plot contour plots using matplotlib along with a colorbar on the side using contourf function.
I do not use the meshgrid fuction because I already have X, Y and Z data in (78, 60001) shape arrays each.
So this is what works:
array1[0].shape
(78, 60001)
array1[1].shape
(78, 60001)
array1[2].shape
(78, 60001)

CS = plt.contourf(array1[0], array1[1], array1[2], 25, cmap = plt.cm.jet)

Which gives the following results:

How do I do the same thing in bokeh? Most of the examples on the internet and manual are using meshgrid.
===
Update #1:
Example:
https://docs.bokeh.org/en/latest/docs/gallery/image.html
I tried the above bokeh code as follows:
p.image(array1[2], array1[0], array1[1], dw=10, dh=10, palette="Spectral11")

Which gives the following error:
 RuntimeError: Columns need to be 1D (x is not)

===
Update #2:
p.image(array1[2].ravel(), array1[0].ravel(), array1[1].ravel(), dw=10, dh=None, palette="Spectral11")

Above line of code creates the HTML file but no plot is displayed.

A:
RuntimeError: Columns need to be 1D (x is not)

The reason for this is that you are attempting to pass coordinates for every pixel of the image, but that is not what Bokeh expects. For each 2D image data (either RGBA array, or scalar data to be color mapped in the client), Bokeh only expects to receive a single value for each of: x, y, dw, and dh. The x and y coordinates are the coordinates of the lower left of the image. The dw and dh are the width and height of the the image in data space coordinates.
It is possible to pass multiple images to a single call to image_rgba or image. In this case x, y, dw, and dh would have a single value for each image. I.e., x would be a 1d array of numbers (one for each image).

A: I think the hvplot library would answer your question.
See a the reproducible example on an Xarray dataset below:
import xarray as xr
import hvplot.xarray  # noqa

import holoviews as hv
from holoviews import opts
hv.extension('bokeh')

air_ds = xr.tutorial.open_dataset('air_temperature').load()
meanairbyyear = air_ds.air.groupby('time.year').mean()
stdairbyyear = air_ds.air.groupby('time.year').std()

meanair2d = xr.Dataset(
    {
        "y2013": (["lat", "lon"], meanairbyyear[0,:,:]),
        "y2014": (["lat", "lon"], meanairbyyear[1,:,:]),
    },
    coords={
        "lon": ("lon", meanairbyyear.lon),
        "lat": ("lat", meanairbyyear.lat),
    },
)

meanair2d

pl=meanair2d.hvplot.contourf(z='y2013',width=400)

from bokeh.models import HoverTool
MyHover = HoverTool(
    tooltips=[
        ( 'x', '$x'),
        ( 'y', '$y'),
        ( 'Year 2013', '@y2013{%3.0f} degC'),
   ],
    formatters={
        '$x' : 'numeral',
        '$y' : 'numeral',
        '@y2013' : 'printf',
    },
    point_policy="follow_mouse"
)

pl.opts(tools = [MyHover])


text:
Q: Refresh Fargment from adapter I know this question has been around, but trying solutions proposed in SO threads weren't helpful!
I Have an activity (Favorites) with 3 fragment (represent categories, Video/figures/other) ..in each fragment there is a list of favorites following the category ..
my problem is ..when i delete an item from list of favorite ..it get deleted from database but the listview don't get refresh instantely! ..i have to move between fragments for that to happen ..
i tried:
1. notifyDataSetChanged(); //do nothing
2. `refreshEvents(listfavorite);` // after the delete button onclick with refresh events=:
         public void refreshEvents(final List<Data> events)
            {
                this.listfavorite.clear();
        this.listfavorite.addAll(events);
        notifyDataSetChanged();
The result of 2nd method: the list is cleared instantely but don't get repopulated again!

    3.
    //after on delete on click
     Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //listfavorite.addAll(events);
                    notifyDataSetChanged();            }
            }, 1000);

This is my Fragment Adapter
public class FragmentAdapter  extends BaseAdapter {
    private List<Data> listfavorite;
    Context context;
    String name, packagename, id, section;
    Long _id;
    private DBManager dbManager;
    boolean isFavourite;
    private LayoutInflater mInflater;

    public FragmentAdapter(Context FragmentOther,List<Data> resultsFavorite){
        this.listfavorite = resultsFavorite;
        this.context=FragmentOther;
        mInflater = LayoutInflater.from(FragmentOther);

    }

    public void removeItemAtPosition(int position) {
        if (listfavorite != null) {
            listfavorite.remove(position);
            notifyDataSetChanged();
        }
    }

    public void clearAll() {
        if (listfavorite != null) {
            listfavorite.clear();
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return listfavorite.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return listfavorite.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    public View getView(int position, View rowView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder holder;
        if(rowView == null){
            rowView = mInflater.inflate(R.layout.activity_view_record, null);
            holder = new ViewHolder();

            //define those textsview that corresponds to the row views so later we'll retrieve the data from them
            holder.idTextView = (TextView) rowView.findViewById(R.id.id);
            holder.nameTextView = (TextView) rowView.findViewById(R.id.name);
            holder.sectionTextView = (TextView) rowView.findViewById(R.id.section);
            holder.packageTextView = (TextView) rowView.findViewById(R.id.packagename);

            //retrieve to this strings
            id = listfavorite.get(position).getIdFav();
            name = listfavorite.get(position).getNameAct();
            section = listfavorite.get(position).getSectionName();
            packagename = listfavorite.get(position).getPackageAct();

            //This will be used for deleting data, because delete data we'll need to pass a long type variable
            _id = Long.parseLong(id);

            // define the button/textview because the popmenu needs a header!
            holder.viewoption=(TextView) rowView.findViewById(R.id.textViewOptions);
            holder.viewoption.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // so we can use a custom pop menu we'll use this code, first define the contextwrapper
                    // and define the style of popmenu as second argument! , the style should have as parent
                    // Widget.AppCompat.PopupMenu ! then
                    //pass it in popmenu as firstargument
                    // the gravity.right serve to create margin from right side of the screen
                    Context wrapper = new ContextThemeWrapper(context, R.style.YOURSTYLE);
                    //creating a popup menu
                    PopupMenu popup = new PopupMenu(wrapper, holder.viewoption, Gravity.RIGHT);
                    //inflating menu from xml resource
                    popup.inflate(R.menu.options_menu);
                    // this is really important! to show icon you should use this function, because the icons in normal
                    // cases don't show up! (we pass the name of the popupmenu inside
                    setForceShowIcon(popup);
                    //adding click listener
                    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            switch (item.getItemId()) {
                                case R.id.delete:
                                    //delete from database
                                    //Open the database
                                    dbManager = new DBManager(context);
                                    dbManager.open();
                                    dbManager.delete(_id);

                                    //change value of isfav
                                    isFavourite = false;

                                    //save it to sharedprefrenece, the state will be read in other activities and
                                    //show the correspondante state False or true
                                    saveState(isFavourite);
                                    refreshEvents(listfavorite);
                                    notifyDataSetChanged();
                                    //update activity so it'll delete it
                                    // onResume();
                                    break;
                                case R.id.gotoact:
                                    Intent access_activity = new Intent();

                                    //we use this type of intent because it allow us to use strins for intent
                                    //after retrieving data from row, we'll pass it as second argument
                                    access_activity.setClassName(context,packagename);
                                    context.startActivity(access_activity);
                                    break;

                            }
                            return false;
                        }
                    });

                    //displaying the popup
                    popup.show();

                }
            });
            rowView.setTag(holder);
        } else {
            holder = (ViewHolder) rowView.getTag();
        }

        holder.nameTextView.setText(Html.fromHtml(listfavorite.get(position).getNameAct()));
        holder.sectionTextView.setText(listfavorite.get(position).getSectionName());

        return rowView;
    }

    public void refreshEvents(final List<Data> events)
    {

            this.listfavorite.clear();
    this.listfavorite.addAll(events);
    notifyDataSetChanged();

    }

my fragment.java
public class FragmentVideosFav extends Fragment {

    private static final String ARG_TITLE = "title";
    private String mTitle;
    //------Define Database
    private DBManager dbManager;
    //
    List<Data> listContact;

    //ListView
    private ListView listView;

    // Adapter
    private FragmentAdapter adapter;

    public FragmentVideosFav (){}

    public static FragmentVideosFav getInstance(String title) {
        FragmentVideosFav fra = new FragmentVideosFav();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_TITLE, title);
        fra.setArguments(bundle);
        return fra;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        mTitle = bundle.getString(ARG_TITLE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_other, container, false);
        listContact = Getlistfavorite();
        //define the list
        listView = (ListView) v.findViewById(R.id.list_view);
        //if the list is empty! set the correspondante layout!
        listView.setEmptyView(v.findViewById(R.id.empty));
        // set list to the adapter
        adapter= new FragmentAdapter(getActivity(),listContact);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        return v;
    }

    //refresh fragment when switch to ..
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(
                isVisibleToUser);

        if (getFragmentManager() != null) {

            getFragmentManager()
                    .beginTransaction()
                    .detach(this)
                    .attach(this)
                    .commit();
        }
    }

    // init Data of fragment
    private List<Data> Getlistfavorite(){
        List<Data> favoritelist = new ArrayList<Data>();
        dbManager = new DBManager(getActivity());
        dbManager.open();
        Cursor c = dbManager.fetchvideo();
        //startManagingCursor(c);
        int ititle = c.getColumnIndex(_ID);
        int idesc = c.getColumnIndex(ACTIVITY_NAME);
        int isection = c.getColumnIndex(SECTION_NAME);
        int ipath = c.getColumnIndex(PACKAGE_NAME);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            String title = c.getString(ititle);
            String desc = c.getString(idesc);
            String section = c.getString(isection);
            String path = c.getString(ipath);
            favoritelist.add(new Data(title, desc , section , path));}

        return favoritelist;
    }

}

A: Try this:
View getView(int position, View rowView, ViewGroup parent) {
    Data favorite = listfavorite.get(position);
    // Etc
    case R.id.delete:
        dbManager = new DBManager(context);
        dbManager.open();
        dbManager.delete(_id);

         //change value of isfav
         isFavourite = false;

         //save it to sharedprefrenece, the state will be read in other activities and
        //show the correspondante state False or true
        saveState(isFavourite);

        listfavorite.remove(favorite);
        notifyDataSetChanged();


text:
Q: Ensuring unique elements in a nested ruby array I have an array which can have N nested array where N can contain M arrays where both N and M are >= 1. Some examples include the following:
[[[1,2,3],[3,4,5]],[[2,1,1]]]

or
[[[1,2,3]],[]]]

and finally
[[[1,2,3],[3,4,5]],[[2,1,1]], [[1,1,1],[2,2,2]]]

I need something that returns a boolean true or false if there is a duplicate value for the 0th element in a nested array, the issue is the composite array is not the unique identifier. Only the 0th element in each value array such as [1,2,3] or [3,4,5], in this case the integers 1 and 3, are what I need a unique against. so in the case of the last array, [1,1,1] and [1,2,3] would clash as the 1 is repeated.
What's the best way to iterate through this type of nesting and signal true or false on whether there are duplicates?

A: def uniq_prime_elements?(arr)
  prime_elements = arr.map(&:first).map(&:first).compact
  prime_elements.length == prime_elements.uniq.length
end


text:
Q: Saving RGB matrix as text I tried to save an RGB matrix in text format but without success. The resolution of the image is 640 x 480. I'm looking for matrix with 640 columns and 480 rows and for every element the corresponding RGB value. For example:
(230, 200, 20) (130, 11, 13) ... # and the others 658 columns
(200, 230, 20) (11, 130, 13) ...
... # and the others 478 rows

A: If that's the exact output you want, then I think this does the job. You can use str.format() to get whatever you need.
# Read the image file.
from scipy import misc
data = misc.imread('image.jpg')

# Make a string with the format you want.
text = ''
for row in data:
    for e in row:
        text += '({}, {}, {}) '.format(e[0], e[1], e[2])
    text += '\n'

# Write the string to a file.
with open('image.txt', 'w') as f:
    f.write(text)

Note that some image types (e.g. PNG) commonly contain four values per pixel, because they can have an 'alpha' (opacity) channel.

A: You could try using scipy and numpy, and do something like this (untested)
from scipy import misc
import numpy
data = misc.imread('img1.png')
numpy.savetxt('out.txt', data)


text:
Q: JavaFX: Only update binding after all dependencies are updated? private final Property<BigDecimal> a = new SimpleObjectProperty<BigDecimal>();
private final Property<BigDecimal> b = new SimpleObjectProperty<BigDecimal>();

private ObjectBinding<BigDecimal> c = new ObjectBinding<BigDecimal>() {
    {
        super.bind(a, b);
    }

    @Override
    protected BigDecimal computeValue() {
        return a.getValue().add(b.getValue());
    }
};
public BigDecimal getC() { return c.getValue(); }

I have two properties and a value that is bound to the sum of those properties. I have one thread viewing c and calling getC() when it is changed, and another thread that is supposed to update a & b. I would like the update to a & b to be atomic; I do not want the value of c to be observed when a has been updated but b has not.
The solution I came up with is to have a third property that c's binding uses as a flag to signal update completion, something like
update(a, 1);
update(b, 2);
update(updateComplete, true); // C is only computed at this point

private final Property<BigDecimal> a = new SimpleObjectProperty<BigDecimal>();
private final Property<BigDecimal> b = new SimpleObjectProperty<BigDecimal>();
private final IntegerProperty updateComplete = new SimpleIntegerProperty(0);

private ObjectBinding<BigDecimal> c = new ObjectBinding<BigDecimal>() {
    {
        super.bind(updateComplete);
    }

    @Override
    protected BigDecimal computeValue() {
        return a.getValue().add(b.getValue());
    }
};
public BigDecimal getC() { return c.getValue(); }

Is there a more idiomatic solution to this problem?

A: A possible solution, though I would not call it idiomatic ;), is to provide 2 different bindings to c. Both bindings would have the same computeValue method, but one of those binds to only a (or b, depending on your needs).
The thread viewing c would then get access to the binding, that updates only when one value changes.
private final ObjectBinding<BigDecimal> c              = new ObjectBinding<BigDecimal>()
                                                     {
                                                       {
                                                         super.bind( a, b );
                                                       }

                                                       @Override
                                                       protected BigDecimal computeValue()
                                                       {
                                                         return a.getValue().add( b.getValue() );
                                                       }
                                                     };

private final ObjectBinding<BigDecimal> cOnlyOnBChange = new ObjectBinding<BigDecimal>()
                                                     {
                                                       {
                                                         super.bind( b );
                                                       }

                                                       @Override
                                                       protected BigDecimal computeValue()
                                                       {
                                                         return a.getValue().add( b.getValue() );
                                                       }
                                                     };

See full example.


text:
Q: A quadratic function bounded from below
Let $A\in\mathbb{R}^{n\times n}$ be a symmetric matrix such that the quadratic function
  $$f(x)=x^\top Ax-2(x_1+\ldots+x_n)$$
  is uniformly bounded from below by a constant. Does it imply that $A$ is positive definite?

By using the eigenvalue decompostion of $A$ and making orthogonal transformations for $x$, we can easily show that $A$ must be positive semidefinite. Is it necessary that $A$ is positive definite in this case?

A: No, $A$ does not need to be positive definite. Consider the matrix $$A=\begin{bmatrix} 1 & 1 \\ 1 & 1\end{bmatrix}$$
This matrix is symmetric with $$f(x,y)=x(x+y)+y(x+y)-2(x+y)=(x+y-2)(x+y)$$
This functions is bounded below. Letting $c=x+y$, then this reads $f(x,y)=c^2-2c$, which attains a minimum of $-1$ when $c=1$, so $f$ is bounded below. However, $A$ is not positive definite, since one of its eigenvalues is $0$. In particular, for $x=\begin{bmatrix} 1 \\ -1\end{bmatrix}$ satisfies $x^TAx=0$.

A: The function $g_{A,b}(x):=x^tAx+b^tx$ (with $A$ symmetric) is bounded below if and only if $A$ is positive semidefinite and $\ker A\subseteq b^{\perp}$. In fact, let $x\in(\ker A)\setminus b^{\perp}$ (positive semidefiniteness is clearly necessary). Then, $b^tx\ne 0$, $x^tAx=0$, and $\lim\limits_{\lambda\to-\infty} g(\lambda (b^tx)x)=-\infty$. On the other hand, if $\ker A\subseteq b^{\perp}$, then consider a subspace $W$ such that $W\oplus \ker A=\Bbb R^n$. Then, $$\inf_{x\in\Bbb R^n}g_{A,b}(x)\stackrel{\text{since }\forall x\in\ker A,\ b^tx=0}=\inf_{x\in W}g_{A,b}(x)=\\=\inf_{x\in W} x^tAx+b^tx=\inf_{x\in W\\ \lVert x\rVert=1\\ \lambda\ge0} \lambda^2x^tAx+\lambda b^tx\ge\\\ge\inf_{\lambda\ge 0}\left(\lambda^2\left(\min_{x\in W\\ \lVert x\rVert=1}x^tAx\right)+\lambda\left(\min_{x\in W\\ \lVert x\rVert=1} b^tx\right)\right)$$
Since $W\cap \ker A=\{0\}$ and $A$ is positive semidefinite, the quantity $\alpha:=\min_{x\in W\\ \lVert x\rVert=1}x^tAx$ is strictly positive. If $\beta:=\min_{x\in W\\ \lVert x\rVert=1} b^tx$, we have bounded below $g_{A,b}(x)$ by the quantity $\min\limits_{\lambda\in\Bbb R}\alpha\lambda^2+\beta\lambda=-\frac{\beta^2}{4\alpha}$.


text:
Q: Break a foreach loop I am working on a windows phone project in c#. In the game you need to get the red point inside your "Player"/ellipse. You can control the player with the accelerometer sensor.
When the red dot is inside you, a counter begins to count. This works only for the first ellipse. This ellipse is also declared as the first ellipse in the XAML file.
When the first red dot is inside the player, the if statement is called. But when the player is on the second red dot, the loop is jumping between the if and the else statement but I don't know why he is doing this...
edit:
the problem is that when I have a intersection with one dot I will start to count, but because of it's inside a foreach loop it will loop trough it 5 times
so
dot1 no intersection so goes to else and reset the counter to 0
dot2 no intersection so goes to else and reset the counter to 0
dot3 no intersection so goes to else and reset the counter to 0
dot4 no intersection so goes to else and reset the counter to 0
dot5 has a intersection so it starts to count.
but it loops again because it is in a timer so it automatically sets counter to 0
anybody know why this is happening?
foreach (Ellipse mellipse in mCanvas.Children.OfType<Ellipse>())
{
    if (mellipse.Name != "my_ellipse")
    {
        int ellipse_top = (int)my_ellipse.Margin.Top;
        int ellipse_left = (int)my_ellipse.Margin.Left;

        if (Canvas.GetLeft(mellipse) >= ellipse_left && Canvas.GetLeft(mellipse) + mellipse.Width <= ellipse_left + my_ellipse.Width && Canvas.GetTop(mellipse) >= ellipse_top && Canvas.GetTop(mellipse) + mellipse.Height <= ellipse_top + my_ellipse.Height)
        {
            my_ellipse.Fill = new SolidColorBrush(Colors.LightGreen);
            count++;
            System.Diagnostics.Debug.WriteLine(mellipse.Name);
            //if (count == 100)
            //{
            //    mellipse.Fill = new SolidColorBrush(Colors.Green);
            //    break;
            //}
            break;
        }
        else
        {
            my_ellipse.Fill = new SolidColorBrush(Colors.White);
            count = 0;
            System.Diagnostics.Debug.WriteLine("else");
        }
    }
}

[code]
<Canvas Name="mCanvas">
        <Ellipse Name="my_ellipse" Fill="#FFF4F4F5" Height="100" Stroke="White" Width="100"/>

        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="140,106,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
        <TextBlock x:Name="textBlock1" Canvas.Left="44" TextWrapping="Wrap" Text="0" Canvas.Top="44" Foreground="#FF232020" FontSize="18.667"/>
        <Ellipse Name="_1" Fill="Red" Height="39" Canvas.Left="248" Stroke="Indigo" Canvas.Top="187" Width="39"/>
        <Ellipse Name="_2" Fill="Red" Height="39" Canvas.Left="185" Stroke="Indigo" Canvas.Top="390" Width="39"/>
        <Ellipse Name="_3" Fill="Red" Height="39" Canvas.Left="146" Stroke="Indigo" Canvas.Top="614" Width="39"/>
        <Ellipse Name="_4" Fill="Red" Height="39" Canvas.Left="316" Stroke="Indigo" Canvas.Top="509" Width="39"/>
    </Canvas>

[/code]
Game_image
XAML layout


text:
Q: Buffer is allocated from a shared heap for the process that is 64 KB in size? Would anyone be kind enough to translate this sentence for someone blissfully ignorant of unmanaged code and intricacies of memory management?

The storage for this buffer is
  allocated from a shared heap for the process that is 64 KB in size.
  The maximum size of the buffer will depend on heap usage.

It's present on few dozen MSDN pages, e.g. WriteConsole, but I can't find any API that would calculate the maximum size such array is allowed to be before blowing up, empirically I can tell it's somewhere between 61 and 62.5 KB (by calling 64, 63, 62 etc until it stops setting DllImport's SetLastError). Is there anything like GetTotalHeapSize (if it's not a const 64KB independent of Windows version, platform architecture, defaults, etc) and something like GetCurrentHeapInUse available? How would one get the max bytes I can pass to that and other P/Invoked methods?

A: This is not how heaps work.  They don't keep track of the largest allocation you can make.  It is unpredictable because a heap can get fragmented.  Free blocks may be interleaved with allocated ones.  Releasing a single small allocation may suddenly double the available space for example.   Unmanaged heaps don't have the luxury of a managed heap, they cannot get compacted.  Albeit that the .NET Large Object Heap has this problem too.  There is no function to measure the largest available space, it is impossible to make that thread-safe.
Nothing you can do but try to allocate and deal with the consequences if you can't.


text:
Q: request().body().asJson() as null Why do I always get request().body().asJson() value as null.
I am sending the form data as
clientId    test123
clientScopes    local
clientSecret    AfrTest123
clientSecretOnly    true
clientServices[]    test
clientVersions  []
module  clientConfig
save    Save

On the API side I am doing something like this.
    TestConfiguration config = Json.fromJson(request().body().asJson(), TestConfiguration.class);


text:
Q: Using arr.push() to add an object to an array replacing existing value instead of adding new one Currently trying to render a list of components that expands/shrinks as values are added/removed from an array of a custom object type. However, whenever I make the called to push a value into a new array and then pass that into a hook, the array simply replaces the previous value rather than making the list of objects longer. Any help appreciated.
// My interface
interface IAddedSkill {
    id: string,
    level: Level,
    name: string,
}

const [potentialSkills, setPotentialSkills] = useState<IAddedSkill[]>([]);
let addedSkills: IAddedSkill[] = [];

function handleAddedSkills(addedSkill: IAddedSkill) {
        addedSkills.push(addedSkill);
        setPotentialSkills(addedSkills);
    }
    ...some code in between
    // Rendering the react component using this hook
    {potentialSkills.map(skill => (
          <Chip label={skill.name} onDelete={() => handleDelete(skill)} />
          ))}

Can anyone see something I'm doing wrong that would cause this behaviour?
Edit:
Thanks for all the answers, the implementation I used that resolved the issue was changing the handleAddSkills function to:
function handleAddedSkills(addedSkill: IAddedSkill) {
    setPotentialSkills([...potentialSkills, addedSkill]);
}

I also completely removed any reference to the addedSkills list and removed the declaration.

A: Your code is redeclaring the variable addedSkills every render with an empty array, so you are setPotentialSkills with addedSkills which's length always equals 1.
You can just remove addedSkills, and invoke setPotentialSkills like:
setPotentialSkills((previousSkills) => [...previousSkills, addedSkill]);

A: You also need to make addedSkills a state variable otherwise it will get overwritten every time your component renders.
let [addedSkills, setAddedSkills] = useState([])

A: Remove the addedSkills array and update the potentialSkills state directly:
const [potentialSkills, setPotentialSkills] = useState<IAddedSkill[]>([]);

function handleAddedSkills(addedSkill: IAddedSkill) {
    setPotentialSkills((oldSkills) => [...oldSkills, addedSkills]);
}


text:
Q: Error: Failed to serialize user into session I am using mysql with nodejs. I am getting "Error: failed to serialize user into session". When I console.log user in serializeuser function it prints "serialize [object Object]" and in "local-login" strategy it prints RowDataPacket as shown below.
RowDataPacket {
  Patient_id: 2,
  fname: 'xxx',
  mname: 'yyy',
  lname: 'zzz',
  Email: 'xxx@yyy.com',
  pass: '$2b$10$ycZI4SLTJEihxKDHpCXwcOhkmBiOKzmMqFyuEOgXa0KuXYupgaMeG',
  Contact: '090078601',
  Gender: 'Male',
  dateofbirth: 1111-01-13T19:31:48.000Z,
  Blood_group: null
}

// used to serialize the user for the session
passport.serializeUser(function(user, done) {
    console.log(`serialize ${user}`)
    done(null, user.patient_id)
})

// used to deserialize the user
passport.deserializeUser(function(id, done) {
    // connection.connect()
    connection.query("SELECT * FROM PATIENT WHERE PATIENT_ID = ? ",[id], function(err, rows){
        done(err, rows[0])
    })
    // connection.end()
})

passport.use('local-login', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
    // connection.connect()
    connection.query("SELECT * FROM PATIENT WHERE EMAIL = ?",[email],function(err,rows){
            if (err)
                return done(err)
            if (!rows.length) {
                return done(null, false, req.flash('error', 'No user found.')) // req.flash is the way to set flashdata using connect-flash
            }

            bcrypt.compare(password, rows[0].pass, function(err, result) {
                if(!result)
                {
                    return done(null, false, req.flash('error', 'Oops! Wrong password.'))
                }
                // console.log(rows[0])
            });
            return done(null, rows[0])
        })
    // connection.end()
    }
))

my post login look like this
router.post('/patient/login',  ensureGuest, passport.authenticate('local-login', {
        successRedirect : '/home', // redirect to the secure profile section
        failureRedirect : 'login', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    })
);

don't suggest to use session:false while authenticating in post method

A: The type of object being returned by the sql query was causing the problem, serialize and deserialize accepts json object so I just added stringifyObjects option in my connection configs so that sql query returns json objects and not the default type of object which it usually returns.
module.exports = {
    'connection': {
        'host': 'localhost',
        'user': 'root',
        'password': 'fast',
        'database': 'hms',
        'stringifyObjects': 'Stringify'
    }
};


text:
Q: 1px gap between table cells This bug is really making my head hurt. For some reason my table has a 1px gap on the left and right side of the middle cell. I have no idea what is causing this. You can see an example here: http://jsfiddle.net/JdayW/1/
What I need to have is an image in the middle cell that acts as a "mask" so you can see the background image behind it. There needs to be a solid color to the left and right of the image that stretches to the edges of the browser window. I figured a table was the best way to achieve this.. but I could be wrong. The gaps go away when I put a background color on the middle cell or the entire table, but obviously that is not going to work for me because I cannot have a background color behind the image.
In the site I'm building this "mask" image with transparency will scroll over the the fixed background behind it. So I cannot just make the png a jpg with the background on it.
Is this happening because I have the table set to width:100% and the middle cell set to a fixed 300px width?

A: For some reason, your td tags were causing the margins. Setting them to 0 and giving the left and right td tags a width of 50% seemed to fix the problem:
table {width:100%; height:300px; border-collapse: collapse; border-spacing: 0;}

td.left, td.right {background-color:green; margin:0; padding:0; width:50%;}

td.middle {width:300px; margin:0; padding:0;}

Working jsfiddle: http://jsfiddle.net/JdayW/34/

A: have you tried setting a padding of 0px only on the center td ? http://jsfiddle.net/JdayW/45/
td.middle {width:300px;padding: 0px}

the left and right tds also have a 1px gap on every side, but since background colors includes the padding you don't see that, if you put a white space on each td you can set all tds to padding:0px http://jsfiddle.net/JdayW/44/