text:
Q: Using Java to find version and start PostgreSQL Is it possible to find version of PostgreSQL using Java and also to start the PostgreSQL server using Java code?
To find version we have PG_VERSION file which has version under PostgreSQL data directory but we cannot rely on it since this file can be edited.

A: You can also find the version of the server using  DatabaseMetaData. It has helper methods for getting information about the server. getDatabaseProductVersion(),  getDatabaseMajorVersion(), getDatabaseMinorVersion()   will give you the database server version.

A: Quick googling reveals the query:
select version();

Run it through JDBC, you have java anyway.
As for running the the postgres server itself, I think the old way Runtime.exec/ProcessBuilder will do the job. You may want to create some kind of script above it but that the way it should work, I guess, there is no other way.
If you're running on linux machine, maybe you should install the server as a service and run it respectively, but from the point view of Java (if you really want to run it from java) its still an invocation of external process.
Hope this helps

A: If PG_VERSION is edited the server won't start. Don't do that. In general, the PostgreSQL data-dir is off limits for direct editing.
At run-time you can use SELECT version() to get the version of the running server.
The server can be started and stopped with pg_ctl. You can check the version of the server binaries whether or not the server is running postgres --version or pg_ctl --version.
The location of the binaries and datadir is something you can control in terms of how you install the server.

A: Running the query : select version()
would give you the exact version of the posgresql

A: You can also use DatabaseMetaData interface. It's much more general, not only for postgreSQL and gives you much more than just the database version.
Here's an example on how to use it:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

/**
 * @author Binyamin Regev on on 30/11/2016.
 * @version 1.0
 * @since 1.8
 */

public class DatabaseMetaDataHelper {

    static Connection connection = null;
    static DatabaseMetaData metadata = null;

    public DatabaseMetaDataHelper() throws SQLException{

        boolean success = initJDBCDriver();
        if (!success) { throw new SQLException("INIT JDBC DRIVER FAILED!"); }

        success = connectToDatabase();
        if (!success) { throw new SQLException("Connect to database FAILED"); }

        connection = databaseConnection.getConnection();

        try {
            metadata = databaseConnection.getConnection().getMetaData();
        } catch (SQLException e) {
            System.err.println("There was an error getting the metadata: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public boolean initJDBCDriver() {
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("Where is your PostgreSQL JDBC Driver? Include in your library path!");
            e.printStackTrace();
            return false;
        }

        System.out.println("PostgreSQL JDBC Driver Registered!");
        return true;
    }

    public boolean connectToDatabase() {
        try {
            connection = DriverManager.getConnection(
                    "jdbc:postgresql://127.0.0.1:5432/postgres",
                    "postgres",
                    "admin");

        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return false;
        }

        if (connection == null) {
            System.out.println("Failed to make connection!");
            return false;
        }

        System.out.println("You made it, take control your database now!");
        return true;
    }

    public static Connection getConnection() {
        return connection;
    }

    public static String getDatabaseProductName() {
        try {
            return metadata.getDatabaseProductName();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDriverName() {
        try {
            return metadata.getDriverName();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getUserName() {
        try {
            return metadata.getUserName();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDatabaseProductVersion() {
        try {
            return metadata.getUserName();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDriverVersion() {
        try {
            return metadata.getDriverVersion();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getURL() {
        try {
            return metadata.getURL();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getDriverMinorVersion() {
        return metadata.getDriverMinorVersion();
    }

    public static int getDriverMajorVersion() {
        return metadata.getDriverMajorVersion();
    }

    public static int getDatabaseMinorVersion() {
        try {
            return metadata.getDatabaseMinorVersion();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static int getDatabaseMajorVersion() {
        try {
            return metadata.getDatabaseMajorVersion();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static int getJDBCMajorVersion() {
        try {
            return metadata.getJDBCMajorVersion();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static int getJDBCMinorVersion() {
        try {
            return metadata.getJDBCMinorVersion();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static void main(String[] args) {
        try {
            DatabaseMetaDataHelper helper = new DatabaseMetaDataHelper();
            int result = helper.connectToDatabase();

            System.out.println("Database product name = " + getDatabaseProductName());
            System.out.println("Database product version = " + getDatabaseProductVersion());
            System.out.println("Database User name = " + getUserName());
            System.out.println("Driver name = " + getDriverName());
            System.out.println("Driver version = " + getDriverVersion());
            System.out.println("URL = " + getURL());
            System.out.println("Driver major version = " + getDriverMajorVersion());
            System.out.println("Driver minor version = " + getDriverMinorVersion());
            System.out.println("Databse major version = " + getDatabaseMajorVersion());
            System.out.println("Databse minor version = " + getDatabaseMinorVersion());
            System.out.println("JDBC major version = " + getJDBCMajorVersion());
            System.out.println("JDBC minor version = " + getJDBCMinorVersion());

            /*
             * Print all the tables of the database scheme,
             * with their names and structure
             */
            getColumnsMetadata(getTablesMetadata());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.err.println("There was an error retrieving the metadata properties: "+ e.getMessage());
        }
    }
}


text:
Q: What languages have higher levels of abstraction and require less manual memory management than C++? I have been learning C++ for a while now, I find it very powerful. But, the problem is the the level of abstraction is not much and I have to do memory management myself.
What are the languages that I can use which uses a higher level of abstraction.

A: Trying something really foreign like Haskell will allow you to think in different ways. It also helps you to think recursively. C++ has recursion but it infiltrates many more parts of functional languages.

A: Java, C#, Ruby, Python and JavaScript are probably the big choices before you.
Java and C# are not hugely different languages. This big difference you'll find from C++ is memory management (i.e. objects are automatically freed when they are no longer referenced). You would chose these if you were interested in desktop style applications, or keen on static typing (and you'd probably choose between them based on how you feel towards Microsoft and the Windows platform). In both cases you'll find much richer standard libraries than you'll be used to from C++.
Python and Ruby take a step away from static typing, into a world where you can call and method on any object (and fail at runtime if it's not there). That is both a blessing (a lot less boilerplate code) and a curse (the compiler can't catch those errors for you anymore). Once again, you'll find they have richer standard libraries, and are higer level again than Java / C#. Performance is the main downfall, with Python being somewhat faster than Ruby as I understand it. To choose between them, you'd probably choose Ruby if you're interesting in web development for the Ruby on Rails framework community, and otherwise go with Python.
JavaScript is even more different from C++ in that it does away with classes entirely. Objects are simply cloned from other objects and can have methods and properties added to them at runtime. Very flexible, but also very easy to make into a total mess. JavaScript is the only real choice if you're interested in running applications in a browser, which is really coming into its own as a platform. You'll find the standard libraries available rather limited if you're not doing a lot with the browser, but there are quite a few good frameworks which fill in some of the gaps.
Some other interesting, though more niche choices are

*

*Smalltalk - More or less in the Ruby and Python camp, and significantly faster as I understand it. Be careful though _ I've seen lots of good engineers learn Smalltalk and never come back ;)

*Objective-C - When C went object oriented, C++ went one way (static typing), and Objective-C went the other (dynamic typing). It's quite Smalltalk inspired, and has a good standard library if you're in Mac / iPhone land. In terms of memory management, unlike everything else I've listed, it's not garbage collected (though that's now an option on Mac OS X 10.5), but it does have a reference counting scheme which makes life significantly simpler than managing memory by hand.

*Lisp - I've never learnt it myself beyond what I needed for minor Emacs hacking. As I understand it, the libraries were nice in their day, but though the language remains supremely elegant, they've fallen a little behind the times.

*Haskel - If you wanted a complete break from objects and classes, Haskel and it's functional approach is an interesting way to go (or Lisp as above, or F# if you are in .Net land). Basically, you're giving up loops and variables in favour of doing everything recursively. Takes some time to wrap your mind around, and probably isn't practical for most real world applications, but it's a good one to learn.

*Eiffel - I love it - Very clean syntax, and designed for serious engineering type systems. Statically types like C# and Java, and with a weaker standard library, but it will make you really think about language and class library design.

*ActionScript and Flex - The programming interface to Flash, which is based on what seems to be a statically typed version of JavaScript. I've played with it a bit, and it's quite slick if you're interested in developing media based applications. You can also push beyond the browser with Flex and into the Air platform to build real desktop apps.

A: ditto Lisp,.. or scheme
Even if you don't ever use it, it's handy. I only really got template programming after learning it.
Another one is prolog. it puts you in a non sequential mindset.

A: If you're comfortable with C++ syntax and style, you might find D to be an interesting language. Or if you want to branch out, any of Python, C#, Java, Ruby would be excellent choices.

A: C# if you're in the Microsoft ecosystem.
Python and Ruby seem to have the most traction in the Linux/Unix/etc space.
ObjectiveC is dominant on the Macintosh and iPhone. The most recent MacOS implements garbage collection for a subset of the frameworks, but to use the rest you'd have to do resource management yourself.
You could learn Java, as it does garbage collection as well, but the number of frameworks you'd need to become familiar with to be a productive Java developer is daunting.

A: I would say that from your question you probably haven't finished learning about C++. If you're still doing your own memory managment then you still have a long way to go my friend!
Check out the auto_ptr and shared_ptr - check out the Boost libraries.
Similarly with abstraction - what are you specifically complaining about? AFAIK there's not much you can't do with C++ that is present in other strongly-typed languages.
I know this doesn't answer your question - you want to move forwards, but C++ is one of those things where you never really stop learning. If you get bored, take a brief foray into templates and template meta-programming...

A: Well if you're looking for a very high level of abstraction and memory management then I'd say lisp would be an ideal candidate.  I'm learning it now, slowly, and it's the most fun I've had with a new language.
Having said that Python or Ruby may be a better compromise between expressiveness and popularity.  Python's Django framework is one of the better RAD frameworks if you're looking for web application stuff.

A: I'd say it depends on the kind of programming you want to try. If you want to stay on the OOP side, learn Python or Ruby, both languages provide an easy way to create bindings to use your C++ code from a script (for efficiency reasons).
If you need another approach to programming, learn a "functional" language like Lisp or Haskell.
And if you need to include a fast and small scripting language inside your C++ application, try Lua.
Last but not least, if you know Java and hate it, you can try Scala, a language where you can mix your Java classes with your Scala code, very interesting.

A: Scheme.
The Little Schemer and Structure and Interpretation of Computer Program will stretch your mind in strange and wonderful ways.
DrScheme is a good IDE for beginners. The Scheme Programming Language makes a good, free reference.

A: I see a lot of excellent suggestions so far. However, I think there's something missing, assembler.
Why learn assembly language?

*

*It's not as difficult as you may think. Assembly language is a lot smaller in scope than many modern languages, there are a few tricks you need to understand for it to make sense, but it's not that complicated.

*It broadens your knowledge base. Knowing the fundamentals is almost always beneficial, even when working at a high level.

*It can be extremely useful when debugging. Especially debugging native code without the source, the knowledge you gain from learning assembler enhances your ability to debug in these situations by leaps and bounds.

*It gives you more options. When the rare circumstance comes up where assembly code is needed you won't be helpless.

*It's good for your resume. It shows that you learn beyond just the bare minimum needed to keep your current job, it shows a curiosity about fundamentals, and it puts you in a different class of programmers, and that class tends to be more experienced and more capable.

*It's just plain cool.
Some assembly language resources:

*

*Sandpile.org (assembly language / processor architecture reference)

*Gavin's Guide to 80x86 Assembly (a decent online tutorial)

*Assembly Language for Intel-Based Computers (5e) (a decent textbook for x86 assembly)

A: try c# much :)

A: if you want to abstract memory management, Java comes to my mind instantly.

A: I suggest learning database design and a query language such as SQL.
You can start with a desktop tool like Microsoft Access or use the free SQL Server Express or Postgre or MySQL.

A: Well I think there is no predefined route in learning programming languages. You may learn your next lang based on your job needs, academic research, just for fun, etc. There are many options.
In you feel comfortable in C++, you can go down and learn some assembly. It's a dark art but you'll be glad when you encounter some hard debugging session.
In terms of more abstraction, Smalltalk is extremely fun, OOP-pure and 100% dynamic (debugging is a pleasant thing to do, which is not in static-typed languages). Dolphin Smalltalk is a good implementation for Windows, even the free community edition gives enough to play with. In multiplatform Smalltalk VMs, go for Visualworks or Squeak. Visualworks is extremely stable and comes with a lot of documentation.
Python is used today in many, many fields. I don't know anything about Python excepting the basic syntax and semantics, but it's required today for many jobs.
Java it's, well Java. It's interesting that Java never catch on me. You may get interested on Java, altough. Ask here for advantages of using it over C++ or other OOP languages.
For Web development go for Javascript, specially considering the AJAX wave. It's getting interesting those days. We've talked about Smalltalk, all right, Seaside is an amazing  framework for web development. It works (at least I tried on) Squeak /Visualworks... it's beatiful.
Well, there are a lot of more to get your hands on: Scheme, LISP,  Ruby, Lua, Bash (!), Perl (ugh), Haskell... Try them all and have fun!

A: Qt

A: Why not learn Qt? Its a great application development framework available on all platforms and even mobile devices!

A: Clojure is well worth exploring as it meets both of your criteria:

*

*It has a strong emphasis on programming with higher level abstractions. see e.g. this video: Clojure: The Art of Abstraction

*It has automatic memory management / garbage collection (via the JVM, which has some of the world's best GC implementations)

I'll give some examples using just one abstraction: in Clojure you can manipulate pretty much any data structure via the sequence abstraction.
;; treat a vector as a sequence and reverse it
(reverse [1 2 3 4 5])
=> (5 4 3 2 1)

;; Take 10 items from a infinite sequence
(take 10 (range))
=> (0 1 2 3 4 5 6 7 8 9)

;; Treat a String as a sequence of characters, calculate the frequencies
(frequencies "abracadabra")
=> {\a 5, \b 2, \r 2, \c 1, \d 1}

;; Define an infinite lazy sequence of fibonacci numbers, take the first 10
(def fibs (concat [0 1] (lazy-seq (map + fibs (rest fibs)))))
(take 10 fibs)
=> (0 1 1 2 3 5 8 13 21 34)

A: Since you are already into C++, next step would be to learn .Net through managed C++ or managed extensions for C++..this will get you a step in the big world of .Net framework..Once you understand the framework, makes it more comfortable to learn other .Net languages like C#, VB.Net etc.
One of the areas that MC++ excels in, and is in fact unique in amongst the .NET languages, is the ability to take an existing unmanaged (C++) application, recompile it with the /clr switch, have it generate MSIL and then run under the CLR. This extraordinary feat is aptly termed "It Just Works (IJW)!" There are some limitations, but for the most part, the application will just run. The C++ code can consist of old-fashioned printf statements, MFC, ATL, or even templates!

A: I recommend python as it's not only a sexy language, but also very widely used and easy to integrate with C++ through Boost.Python.
But as Thomi said, there's lot to explore in C++ and with the help of Boost libraries it's becoming really easy to develop in.

A: Rather than suggest a specific language, I would recommend you pick any language or languages that offer the following 4 features:

*

*Automatic Memory Management

*Reflection/Introspection

*Declarative/Functional constructs(e.g. lambda functions)

*Duck Typing

The idea here is to expand your programming perspective to include concepts that the C++ language does not offer you out of the box.

A: It depends on what you want to do.  If you have some specific tasks that you are interested in accomplishing then look at languages that are best for those types of tasks. The best way to learn a language is to actually use it.

A: I'd say get started with Python. It has a higher level of abstraction and it teaches you the importance of indenting and making "pretty" code. Not that "pretty" is very important, but it will make the future maintainer of your code a lot happier :)
There's a lot of example code out there, and if you are into Linux there are various distributions out there who have all (or most) of their tools based on the language. If you like digging into how managing an operating systems works (something most programmers do) it's a good start. Before I get the flames I said managing, not the actual kernel stuff for that you mostly need C and you should have that covered.
On the other hand it might be nice to dive into the C side of things, ignore the OO stuff and learn functional programming. If you head down that road I also suggest to start with basic assembly language like one of the upper posts suggested. Maybe HLA (High-Level Assembly by Randall Hyde, he wrote a great book called  Art of Assembly Language Programming) is a good start. You'll either learn to love memory management or hate it for the rest of your live. Good to know in case you want to start a career in programming :)
However if you're looking to make a job out of programming, Java and J2EE is an easy money maker if you know what you're doing. IMHO it gets boring really quick though.

A: Personally, I have been programming in Java, Python, C/++ and my favorite has to be python. Although C++ can do everything Python can do and more, I wrote a Python program with about 10 lines that would take about 50 in C++. So, moral of the story, use python.

A: If you haven't already, try out a scripting language. It should change the way you work & think. Hopefully, in a good way :)

A: I've got to put up a separate answer for Perl. While Python is roughly equivalent in functionality and considered more clean and modern, Perl has an elegance all of its own - the elegance of pure pragmatism. It also boasts a truly great library support. Take a look at Perl to expand your brain in the direction opposite to Haskel :) (although Perl aficionados claim that it can be used for functional programming).

A: Rust

*

*Syntactically similar to C++

*Designed for performance and safety, especially safe concurrency

redpajama_set_name: RedPajamaStackExchange


text:
Q: jenkins slave agent on ubuntu core My Jenkins Master is hosted on a non windows machine and I want to run my Jenkins slave/agent on Ubuntu core 16, but to run a slave/agent on Ubuntu core we need java to be installed in ubuntu core.
What is the right way to install java on ubuntu core because apt-get doesn't work on ubuntu core, neither could I find the java in snapcraft store

A: Ubuntu Core 16 and Ubuntu 16.04 are both LTS releases and thus fully supported until april 2021 (5y) with the option to buy "extended security maintenance" (ESM) for another 5 years ...
there is a java runtime environment https://snapcraft.io/java-jre-ondra that you should be able to use on armhf core installations.


text:
Q: Exception is java.lang.NoClassDefFoundError: org/bouncycastle/jce/spec/ECPublicKeySpec <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com" />

        <property name="username" value="abc@gmail.com" />
        <property name="password" value="asasas" />

        <property name="javaMailProperties">
            <props>
                <!-- <prop key="mail.smtp.auth">true</prop> -->
                <prop key="mail.smtps.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.debug">false</prop>
                <prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop>

            </props>
        </property>
    </bean>

</beans>

above code is working fine on localhost but when we are deploying on server it gives an Exception is java.lang.NoClassDefFoundError: org/bouncycastle/jce/spec/ECPublicKeySpec

A: Seems like BouncyCastle Jar is not found in class path , if it is working fine at local host then you must have used Add External jarOption of Eclipse which finds out the jar from your local file System ,
but when you deploy in Server you need to keep jar in WebContent/WEB-INF/lib directory


text:
Q: Understand following cases... when fstream opens file and when it doesn't Here is my piece of code:
fstream f;
f.open("memory.txt", ios::out|ios::in);//'memory.txt' already exists - I open it

//...(here are some operations performed on file f)...

f.close();
remove("memory.txt");

//             *** Next, I create a file with the same name ***

fstream f1("memory.txt");
f1.open("memory.txt", ios::in |ios::out |ios::trunc);//#

//...(some operations performed on file f1)...

f1.close();

My questions are:

*

*If I replace # - line with f1.open("memory.txt", ios::in |ios::out );
the file f1 won't open. Why ?

*If I replace # - line with f1.open("memory.txt", ios::in |ios::trunc );
the file f1 won't open. Why ?

*If I replace # - line with f1.open("memory.txt", ios::out |ios::trunc ); the file will open! Why ?

A: *

*You don't check if the file has been successfully deleted, it'll fail if the file doesn't exists.

*ios::out has to be set ref.

*ios::trunc flag deletes all content if the file does exist, so it'll open whether the file exists or not.


text:
Q: Number sequence as geometric sequence In a number sequence, I've figured the $n^{th}$ element can be written as $10^{2-n}$.
I'm now trying to come up with a formula that describes the sum of this sequence for a given $n$. I've been looking at the geometric sequence, but I'm not sure how connect it.

A: Hint: We have $10^{2-n}=10^2\cdot 10^{-n}=10^2\cdot(10^{-1})^n$ and $$\sum_{k=0}^n x^k=\frac{1-x^{n+1}}{1-x}.$$

A: If it is $10^{2-n}$ then, the initial term is $10$ and common ratio is $\frac 1{10}$, Now, can you get it?


text:
Q: Android: Create a Quick Action Menu I need to create some type of quick action menu that appears to the right side of the clicked item (button) whenever the user clicks the button.
Here's an example of what I'm trying to achieve:

When the user clicks button1 I want the "sub quick action menu" to appear like it's shown in the image above.
Is there anyway to do this 'natively' in android?
I have found this plugin but it only allows you to show the menu from the top or bottom of the button.
https://github.com/lorensiuswlt/NewQuickAction3D

A: As tyczj said, you could achieve that with a PopupMenu. The idea is that the popup menu will inflate a custom view with all the elements, having as background a 9 patch image.
Here's a blog post that shows how to do that. Hope it will help you.

A: You can do the same using Quick Action Menu, for more details you can follow the
"http://www.codeproject.com/Articles/521455/Quick-action-pattern-in-Android-and-simple-impleme"
    Link.
In example Items are presented in horizontal manner, whereas you can manage them, like listview as per your requirement.

A: there is a PopupMenu but there is no arrow or anything pointing to where it came from. Its basically the same thing that comes up when clicking the Overflow actionbar item

A: Maybe this link can help you ;) But instead of sliding use press button.
Making a slide menu


text:
Q: IndexOutOfRange error when accessing OleDbDataReader items I have some sql that works fine in access 2010 and returns the correct values. However, in VB.NET, when I run it causes the above error in the while loop. dr.HasRows is returning 'TRUE' but the var 'itm' shows nothing in auto window. Can someone please explain why this is happening and how I can correct it. Thanks
Dim cmd As OleDbCommand = New OleDbCommand("SELECT Max(Requests.[Request no]) AS [MaxOfRequest no], Requests.Customer, " &
                    "Max([Request Boxes].[Request no]) AS [MaxOfRequest no1], [Request Boxes].Customer " &
                    "FROM Requests, [Request Boxes] " &
                    "GROUP BY Requests.Customer, [Request Boxes].Customer " &
                    "HAVING (((Requests.Customer)='" & cmbCustomer.Text & "') AND (([Request Boxes].Customer)='" & cmbCustomer.Text & "')) " &
                    "ORDER BY Requests.Customer, [Request Boxes].Customer", oledbCnn)

            dr = cmd.ExecuteReader()

            If dr.HasRows Then <--- this returns true

                While dr.Read

                    itm = CStr(dr.Item("[MaxOfRequest no]")) <--- ERROR HERE
                    itm2 = CStr(dr.Item("[MaxOfRequest no1]"))

                End While

            End If

A: You don't need the square brackets here:
itm = CStr(dr.Item("[MaxOfRequest no]"))

The square brackets are just delimiters in the SQL statement; they are not part of the column name itself. Try this instead:
itm = CStr(dr.Item("MaxOfRequest no"))


text:
Q: Keep getter function in sync with an object's current state in React/TypeScript WHAT I HAVE
I have a Parent class and a Child class.
export class Parent {
    properties: { x: number};
    child: Child;
    constructor() {
        this.properties = {
            x: 1
        }
        this.child = new Child(this.getX);
    }
    getX = () => {
        return this.properties.x;
    }
}

class Child {
    parent_getX:()=>string
    constructor(parent_getX:()=>string){
        this.parent_getX = parent_getX;
    }
}

The Parent class has:

*

*a field called properties which stores an number value called x.

*a function called getX() which simply pulls the value of x from within the properties object.

*a field called child which holds a reference to a Child object.

The Child class only receives a reference to the Parent's getX() function.
WHAT I WANT
My goal is to be able to update the value of x and that everytime I call child.parent_getX() or parent.getX() I get the latest value of x.
WHAT I'M SEEING
I have a React component called Example that takes a Parent object with a an x value of 1 as initial state.
Whenever I increment this value using setState(...) the value of x is incremented but for some reason, parent.getX() and parent.child.parent_getX() always keeps returning the initial value of x. What can I do to keep the function in sync with the parent object?
export const Example = () => {

    const [parent, setParent] = useState(new Parent());

    const incrementX = ()=>{
        let newParent = { ...parent, properties: { ...parent.properties, x: parent.properties.x + 1 } }
        setParent(newParent);
    }

    return (<>

            Parent.properties.x = {parent.properties.x}

            Parent.getX() = {parent.getX()}

            Parent.child.parent_getX() = {parent.child.parent_getX()}

        <button onClick={incrementX}>
            Increment
        </button>
    </>);
}

A: The reason that you are seeing the old values is that in incrementX() you create a copy of the existing Parent instead of instantiating a new one with new (). Therefore, the existing instance of Child (which references the old parent's getX() function) is copied over, as opposed to being instantiated in Parent's constructor. Similarly, the getX() method itself is copied over with it's this referencing the old parent (because it is a fat arrow function, the this reference does not change).
The most straightforward way to fix this is to add a copy constructor to Parent and use that instead of the spread syntax:
export class Parent {
    properties: { x: string};
    child: Child;
    constructor(source?: Parent) {
        this.properties = {
            x: '1'
        }

        this.child = new Child(() => this.getX());

        if (source) {
            this.properties = {...source.properties};
            // any additional copy logic goes here
        }
    }

    getX() {
        return this.properties.x;
    }
}

Then use that copy constructor in your component:
    const incrementX = () => {
        let newParent = new Parent(parent);
        newParent.properties.x = newParent.properties.x + 1;
        setParent(newParent);
    }

Note that an even easier solution would be to not copy the original Parent at all, and just increment its properties.x, but I'm assuming you need a new instance for the state change to be detected.


text:
Q: GET request for redirect initiated by browser but not successful While trying to redirect user to a URL, it works with GET requests but not with postback requests.
Through firebug's Network window, I can see the redirect response received by browser after the postback request (that should cause redirect) completes. The browser seemingly initiates a GET request for the redirect URL but doesn't actually successfully redirect. It remains there on the same page.
 I use JSF server side. The initiated GET request is not received at all by the server. However initiated by the browser on server's demand. I guess problem is somewhere client side only
Can anyone please explain how to make redirect work successfully ? Let me know incase I should provide any more information.
Edit:
Request header for redirect:
GET /Px10Application/welcome.xhtml HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: application/xml, text/xml, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://localhost:8080/Px10Application/channelPages.xhtml?channelId=-3412&type=Group
X-Requested-With: XMLHttpRequest
Faces-Request: partial/ajax
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: hb8=wq::db6a8873-f1dc-4dcc-a784-4514ee9ef83b; JSESSIONID=d40337b14ad665f4ec02f102bb41; oam.Flash.RENDERMAP.TOKEN=-1258fu7hp9
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Response header for redirect:
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1 Java/Sun Microsystems Inc./1.6)
Server: GlassFish Server Open Source Edition 3.1
Set-Cookie: oam.Flash.RENDERMAP.TOKEN=-1258fu7hp8; Path=/Px10Application
Pragma: no-cache
Cache-Control: no-cache
Expires: -1
Content-Type: text/xml;charset=UTF-8
Content-Length: 262
Date: Wed, 22 May 2013 17:18:56 GMT

A: X-Requested-With: XMLHttpRequest
Faces-Request: partial/ajax

You're thus attempting to send a redirect on a JSF ajax request using "plain vanilla" Servlet API's HttpServletResponse#sendRedirect(). This is not right. The XMLHttpRequest does not treat a 302 response as a new window.location, but just as a new ajax request. However as you're returning a complete plain vanilla HTML page as ajax response instead of a predefined XML document with instructions which HTML parts to update, the JSF ajax engine has no clues what to do with the response of the redirected ajax request. You end up with a JS error (didn't you see it in the JS console?) and no form of visual feedback if you don't have the jsf.ajax.onError() handler configured.
In order to instruct the JSF ajax engine to change the window.location, you need to return a special XML response. If you have used ExternalContext#redirect() instead, then it would have taken place fully transparently.
externalContext.redirect(redirectURL);

However, if you're not inside JSF context, e.g. in a servlet filter or so, and thus don't have the FacesContext at hands, then you should be manually creating and returning the special XML response.
if ("partial/ajax".equals(request.getHeader("Faces-Request"))) {
    response.setContentType("text/xml");
    response.getWriter()
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
        .printf("<partial-response><redirect url=\"%s\"></redirect></partial-response>", redirectURL);
} else {
    response.sendRedirect(redirectURL);
}

If you happen to use JSF utility library OmniFaces, then you can also use Servlets#facesRedirect() for the job:
Servlets.facesRedirect(request, response, redirectURL);

See also:

*

*Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same

*JSF Filter not redirecting After Initial Redirect


text:
Q: Is it correct that $f \in R[X]$ is a unit, iff $a_0$ is a unit. Let $R$ be ring and $R[X]$ its polynomial ring in one indeterminate $X$. Then
$$
 f \in R[X] \mbox{ is a unit } \Leftrightarrow a_0 \mbox{ is a unit }
$$
for $f = a_0 + a_1 X + \ldots + a_n X^n$.
If $f \cdot g  = 1$ with $g = b_0 + b_1 X + \ldots b_n X^n$, then $a_0 b_0 = 1$, hence $a_0$ is a unit. Conversely, suppose $a_0$ is a unit, and choose $b_0$ such that $a_0 b_0 = 1$ and define
\begin{align*}
 b_1 & := b_0(-a_1 b_0) \\
 b_2 & := b_0(-a_2 b_0 - a_1 b_1 ) \\
 b_3 & := b_0(-a_3 b_0 - a_2 b_1 - a_1 b_2 ) \\
 \vdots \\
 b_n & := b_0(-a_n b_0 - a_{n-1} b_1 - \ldots - a_1 b_{n-1} ).
\end{align*}
Then every sum of the form
$$
 \sum_{i + j = k} a_i b_j
$$
for $k > 0$ vanishes, hence the polynomial $g = b_0 + b_1 X + \ldots + b_n X^n$ is an inverse for $f$.
I am just asking if this is correct, or if I have overlooked something. I am asking because I nowhere find this  characterisation stated for general rings (just find a variant for fields), and for rings I just find the result:
$$
 f \in R[X] \mbox{ is a unit } \Leftrightarrow
 a_0 \mbox{ is a unit and } a_1, \ldots, a_n \mbox{ are nilpotent }
$$
which proofs could be found on this page, for example here, here or here. But nowhere do I find it that the condition of nilpotency could be dropped in the implication from right to left.

A: I just considered the coefficients in the result $f\cdot g$ that have a term of the form $a_0 b_j$ $j=1,\ldots,n$ in them, and those will vanish. But I totally forgot about the other coefficients like $a_1 b_n + \ldots + a_n b_1$ and so on up $i + j = n + n$ with $g = b_0 + b_1 X + \ldots b_n X$, $f = a_0 + a_1 X + \ldots a_n X$.
Thanks to @charmichael561 and @DanielFischer for their comments!
But if we contine this process indefinitely, we can build a series $g \in R[[x]]$ and for this $f\cdot g = 1$ if I interpret @LordSharkTheUnknown's comment correctly. But we can find no polynom.


text:
Q: DBT (Data Build Tools) - Create CI/CD pipeline in Azure DevOps I am working on a project that uses DBT by Fishtown Analytics for ELT processing. I am trying to create a CI/CD pipeline in Azure DevOps to automate the build release process, but I am unable to find a suitable documentation around it. The code has been integrated in DevOps Repos, now I need a reference to start with building the CI/CD pipelines.

A: Our team uses ADO Pipelines, here's our doc on how we do it!
To make this example work, you will need 3+ files:
1. profiles.yml.
If you look at this file, you'll see usage of dbt-jinja's env_var macro. This lets you make ADO Pipeline secret variables for your database credentials, and make them available to dbt.
2. step_template.yml
This file is a recipe of deployment steps that are used when deploying to different environments. The beauty of the dbt CLI is that the same steps are used when:

*

*doing our integration tests (gatekeeper), and

*deploying to our production and staging/UAT environments.
So this step_template.yml lets each pipeline re-use the same steps. It's worth noting here that because we are using the AzureCLI@2 task because it will auto-authenticate to Azure for us. If you're not using Azure, you'll need to:

*add Pipeline secrets for username and password to the db, and

*use the Bash@3 task

3. gatekeeper.yml and prod.yml
These are the actual pipelines. If you look, they are identical except for:

*

*the variables they deploy to different databases), and

*the trigger changes to which branch will trigger this pipeline?

*the schedule should this run even if there are no new commits to the branch? Yes, if production because we want the data to stay up-to-date for our users.


text:
Q: Cannot start Eclipse Juno I am getting very frustrated with this problem with Eclipse.  I have had it many times, and quite frankly I think Eclipse is garbage.  But since I do all of my Android development there, there are no other alternative IDE's.  Here is my problem: I cannot start Eclipse.  I changed absolutely nothing, and all of a sudden the .log file in .metadata throws the following stack trace error:
!ENTRY org.eclipse.osgi 4 0 2012-11-16 15:07:22.032
!MESSAGE Application error
!STACK 1
java.lang.NullPointerException
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.processHierarchy(E4Workbench.java:172)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.init(E4Workbench.java:118)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.<init>(E4Workbench.java:69)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.createE4Workbench(E4Application.java:302)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:557)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)

I don't know what to do!  I have no .snap file anywhere.  What else can I try???
Thank you all for your help,
Igor

A: I occasionally have this issue as well, and it is indeed frustrating. What fixes it for me is to go into my eclipse workspace: <workspace>/.metadata/.plugins and start deleting stuff. Most of the things in here are auto-generated; settings etc. I think you can keep org.eclipse.core.resources (that's where a lot of your own user settings area).
Unfortunately, this makes the workspace forget what projects you were working on, so you have to re-add them, but for me this isn't a big deal because I store them elsewhere on my filesystem.
Hopefully this helps!


text:
Q: Stimulated emission direction Place a sub-micron clump of crystal violet molecules in front of a multipixel detector. Raise the molecules to an electronically excited state with a beam of 590 nm light, illuminating from the side so you don't hit the detector with this beam.
Next, fire a collimated beam of 660 nm light at the molecules, which goes on to hit the detector at normal incidence. Qualitatively, how does the intensity pattern on the detector change due to the presence of the clump of electronically excited molecules? How will this pattern change as we vary the distance between the clump and the detector?
Background details:
Assume that the the illumination beam and the detector pixels are as ideal as possible; the detector pixels are as small as we care to make them and have negligible read noise, and the intensity of the beam is as uniform and stable as the shot-noise limit allows.
Crystal violet is an interesting chromophore. 590 nm light raises it to an electronically excited state which can fluoresce, but it can also relax to the electronic ground state via a nonradiative transition. Since the nonradiative relaxation is much faster than spontaneous emission, fluorescence from crystal violet molecules is nearly undetectable.
Min et. al showed that if you shoot crystal violet hard enough with 660 nm light, stimulated emission outcompetes nonradiative relaxation, and you can detect the stimulated emission as a small increase in the brightness of the stimulating beam.
I'm considering crystal violet molecules to eliminate the complication of spontaneous emission; they won't radiate on their own, the only light they'll emit is stimulated emission.
I'm considering a sub-micron clump of molecules to eliminate the complication of nonresonant scattering. Nonresonant scattering drops off extremely quickly with the radius of a spherical scatterer.
I'm considering a clump of molecules rather than a single molecule to ground the question in semiclassical mechanics (meaning QM for the molecules, but Maxwell's equations for the light). It's possible one cannot answer this question without reference to the photon model of light (meaning second quantization and Fock states, etc), but I'd be surprised if this is truly a quantum-optics phenomenon. I suspect the photon model of light and the quark model of the nucleus are equally (ir)relevant to the answer to this question.

A: This is a kind of optical amplifier -- see 1, 2.
Probably the main effect of the molecules on the beam will be scattering / refraction, just like if you put anything into of a beam of light. But a secondary effect, especially if the beam is much much larger than the clump of molecules, is that the profile of the beam will change a bit. The part of the beam that passes through the clump will become relatively brighter, while the rest of the beam won't change, loosely speaking.
To be more precise you need to look up gain guiding and play around with the equations. Sorry I cannot give a better description, I'm not sufficiently familiar with it myself.
But once again, I suspect that the gain guiding effect will be pretty hard to see compared to plain old scattering / refraction.


text:
Q: Why does my ajax call fail when an almost identical one succeeds? I have this HTML
Rejoin
Remove

and I am binding the links to a function using unobstrusive javascript like so:
$(function SetUp()
    {
    var el = document.getElementById('rejoinGroups');
    el.onclick = rejoinGroups;
    var removeElements = document.getElementsByClassName('removeGroup');
    for (var i = 0; i < removeElements.length; i++) {
        removeElements[i].onclick = function() {
            removeGroup(this.id);
        }
    }
  });

There may be many 'Remove' link generated hence why I am binding it differently, (but currently I have only one), and am passing the id as the function parameter.
These are the functions I am biding to.  I have deliberately made them identical for testing as the first one (with the groupName parameter) doesn't work, but the second one does and I don't understand why. Once this issue is fixed I'll actually use the groupName parameter.  The second returns a 200 code and the first immediately gives an 'Error0' message, then goes to the /noJavascript page.  I can only assume it's something to do with the parameter, but it seems to be set correctly, so I'm not sure what it is.  What am I missing?
function removeGroup(groupName){
    $.ajax({
            url: '/tasks/aTask',
            type: 'POST',
            data: {userId:38},
            success: function(data, textStatus, jqXHR)
            {
               alert(jqXHR.status);
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
               alert("Error" + jqXHR.status);
            }
        });
        return false;
}

function rejoinGroups(){
   $.ajax({
            url: '/tasks/aTask',
            type: 'POST',
            data: {userId:38},
            success: function(data, textStatus, jqXHR)
            {
               alert(jqXHR.status);
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
               alert("Error" + jqXHR.status);
            }
        });
        return false;
}

this is what I get in the chrome dev window for the second function:
Request URL:http://localhost:8888/tasks/aTask
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:9
Content-Type:application/x-www-form-urlencoded
Cookie:dev_appserver_login=test@example.com:true:18580476422013912411; JSESSIONID=10yktze1j72fa
Host:localhost:8888
Origin:http://localhost:8888
Referer:http://localhost:8888/users/38
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
userId:38
Response Headersview source
Content-Length:0
Server:Jetty(6.1.x)

and this is what I get for the first (failing) one:
Request URL:http://localhost:8888/tasks/aTask
Request Headersview source
Accept:*/*
Content-Type:application/x-www-form-urlencoded
Origin:http://localhost:8888
Referer:http://localhost:8888/users/38
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
userId:38

A: I'm not very sure, but I think it might be because your anonymous function is not returning the result of the function. Try changing:
removeGroup(this.id);

to
return removeGroup(this.id);


text:
Q: Class not changing state of pyserial connection when unplug device I am trying to do simple serial link program for school project and I have small problem. I created class to maintain serial communication, but when I unplug and plug back serial port, it doesnt change state of serial connection (self.ser have still same object like when it was initalized). I want it to recconnect and continue to work. Can you please help me and tell mi what I am doing wrong? I am new to python. Thank you very much!
import serial
import uuid

class SerialWrapper:

    def __init__(self):
        self.ser = serial.Serial("COM3", 9600)

    def handleconnect(self):
        try:
            if self.ser is None:
                self.ser = serial.Serial("COM3", 9600)
                self.ser.close()
                self.ser.open()
                print("Reconnecting...")

        except:
            if not (self.ser is None):
                self.ser.close()
                self.ser = None
                print("Disconnecting")
            else:
                print("No Connection")

    def serialwrite(self, data):
        self.handleconnect()

        try:
            datalength = self.ser.write(data.encode())
            print("Writing data...")
            return datalength

        except:
            print("Error in writing data")

    def serialread(self, datalength):
        self.handleconnect()

        try:
            data = self.ser.read(datalength).decode()
            print("Reading data...")
            return data

        except:
            print("Error in reading data")

def main():
    ser = SerialWrapper()
    while 1:
        value = uuid.uuid4().hex
        length = ser.serialwrite(value)
        print(ser.serialread(length))

main()

A: So I found that on every end of cycle must be port closed with self.ser.close() and then at the start of new cycle openened again with self.ser.open()


text:
Q: errors when putting a function inside setInterval() I have written this code in nodeJs:
function ricarica() {

   request.get(url, function (error, response, body) {
       if (!error && response.statusCode == 200) {
           var json = JSON.parse(body);
           //console.log(json[11].nome_abbr);
           //console.log(json[11].valore);

            app.use(function(req, res, next) {
                res.header("Access-Control-Allow-Origin", "*");
                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                next();
            });

            app.get('/valore', function(req, res){
            res.json({ livello: json[11].valore });
            });
        }
   });
}

I want to run that function every 10 minutes, i have looked at setInterval but when i replace this:
ricarica();

with this:
 setInterval(function() {
     ricarica();
 }, 600000);

When I ask for the data from my website, with the first I can see the data but It is not updated, with the second one I have the message"Cannot GET /valore";
How can i fetch data and update every 10 minutes?

A: Try this :
function updateData() {
   ricarica();
}

function ricarica() {

   request.get(url, function (error, response, body) {
       if (!error && response.statusCode == 200) {
           var json = JSON.parse(body);
           //console.log(json[11].nome_abbr);
           //console.log(json[11].valore);

            app.use(function(req, res, next) {
                res.header("Access-Control-Allow-Origin", "*");
                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                next();
            });

            app.get('/valore', function(req, res){
            res.json({ livello: json[11].valore });
            });
        }
   });
}

setInterval ( updateData, 600000 );

A: I have resolved in this mode:
async function ricarica() {
while(true){
    await sleep(120000);
    request.get(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var json = JSON.parse(body);
            var i;
            for(i = 0; i< json.length && json[i].nome_abbr != "PS_Giud" ; i++);
            console.log(json[i].nome_abbr);
            //console.log(json[i].valore);

            app.use(function(req, res, next) {
                res.header("Access-Control-Allow-Origin", "*");
                res.header("Access-Control-Allow-Headers", "Accept, Content-Type, If-None-Match, X-If-None-Match");
                res.header("Access-Control-Expose-Headers", "Location, Warning, Etag");
                res.header("Access-Control-Allow-Headers", "Content-Type, If-None-Match, X-If-None-Match, Authorization");
                res.header("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS");

                next();
            });

            app.get('/valore', function(req, res, next){
              res.json({ livello: json[i].valore });
            });
        }
    });
}

}
and i have to call it only once


text:
Q: have the date validation errors with datepicker I am working on MVC and Jquery, and I had a form to create a new event for the website. On the date part, I use datepicker to show the calendar and lets user the select a date. my format is:
 format: 'dd/mm/yyyy',

but when I submit the form, it always failed and told me invalid format. I found the problem was when I selected the date March 24, 2016, it set month was 24, and date was 3(means March).
what's going on here, can anyone help me? Thank you very much.
error messages
how the dates are formatted
Model:
 public SeminarListViewModel()
    {
        Documents = new List<DocumentDisplayViewModel>();
    }

    public string EventID {get;set;}
    public string Name { get; set; }
    public short Capacity { get; set; }

    [DataType(DataType.Date)]
    public DateTime StartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime EndDate { get; set; }

    public List<DocumentDisplayViewModel> Documents { get; set; }
}

A: In your class, over top of the start date and end date properties add this:
using System.ComponentModel.DataAnnotations; /*put above namespace*/

[Display(Name = "Start Date:")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime StartDate { get; set; }

[Display(Name = "End Date:")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime EndDate { get; set; }


text:
Q: Memory Optimization With UIView I have a custom subclass of UIView who has been allocated. Every time I invoke the class, i need to realloc it's subviews like this:
- (void)invoke{
    [[self subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for(NSDictionary *dict in self.list){
        MySubview *subView = [[MySubview alloc] initWithFrame:self.view.frame];
        [self addSubview:subView];
    }
}

So the result is that every time I invoke it, the memory increases by around 4MB.
Then how can I fix it and optimize my memory?

A: [someView removeFromSuperView] is not the same as someView = nil;
you'll have to ensure that each view you are attempting to eradicate is set to nil. Otherwise they will hang around until ARC thinks it's time to expunge them (probably when the superview is destroyed) or you call release on them (for non ARC)


text:
Q: How to put linebreak after text with docxtemplater I'm using the docxtemplater module to fill template on a MS Word document. I've used this, but it just add space to the template:
var EOL = "\n";
var willBeTemplated = "Something" + EOL;

How can I put a line break after this text?

A: I'm the creator of docxtemplater.
You can use the following code :
const doc = new Docxtemplater(zip, {linebreaks: true});

By default, docxtemplater does'nt take into account linebreaks, but with this option it will add them.
https://docxtemplater.readthedocs.io/en/latest/faq.html#inserting-new-lines


text:
Q: Why is my queue sorting input strings differently than a first in-first out basis? I'm trying to utilize a queue but the queue is reorganizing itself and I have no idea why
Everyone else who uses queues seems to have theirs working fine, and no one seems to be encountering this problem
public static void main(String[] args){
    PriorityQueue<String> cue = new PriorityQueue<String>();
    cue.offer("this");
    cue.offer("that");
    cue.offer("then");
    System.out.printf("%s \n", cue);
    System.out.printf("%s \n", cue.peek());
    cue.poll();
    System.out.printf("%s \n", cue);
}

I expect it to print:
[this, that, then]
this
[that, then]

But instead it prints:
[that, this, then]
that
[then, this]

I just have no idea why

A: From the java doc of PriorityQueue:

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering

So this is by-design.
You can use a java.util.LinkedList (which implements the Queue interface and will act like a first in first out queue), and will give you the expected ordering

A: PriorityQueue does not override toString() from AbstractCollection.
From the Javadoc of AbstractCollection.toString():

The string representation consists of a list of the collection's elements in the order they are returned by its iterator

PriorityQueue.iterator() says:

The iterator does not return the elements in any particular order.

So there is no guarantee that it would print the lowest element first either.

A: The constructor new PriorityQueue<String>()'s documentation states that it

Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.

However, this should result in the output

[that, then, this] that [then, this]

I assume the output you posted was manually typed, with a mistake - "then" should be before "this".
EDIT:
It seems like the output and the actual order in the queue are not the same.
That's misleading but explains it.

A: EDIT: You're using a PriorityQueue, but expecting it to work like a regular Queue. A regular queue works FIFO (the way you are expecting - you put this in first, and this will be the first element). A PriorityQueue will assign a priority to it's elements and order them accordingly. By default it uses the standard compare() method of its elements, which in the case of Strings will sort them alphabetically. After that, see the explanation below for why the contents aren't sorted alphabetically.
As far as I can tell (but I can't find any documentation explicitly confirming this), PriorityQueue only makes sure the first element is the 'lowest' according to natural ordering. When .poll()ing the queue or offering a new element that turns out to be the 'lowest', the whole contents are re-ordered to put the new 'lowest' in front. If the element in front remains the 'lowest' when changing the contents of the queue, the new element is just enqueued at the back - even if it is lower than other elements already in the queue.


text:
Q: How old is Finn? How old is Finn in Adventure Time? Because it never says, yet he always looks the same from time to time when surely they can't have trouble every day.

A: 17 years old, at time of posting this answer
In the Season 6 finale "The Comet", Finn states that he is 16:

FINN: Besides, it was like 40 years ago. I'm 16! I don't have a star to revolve around to track time.

Since time in Adventure Time elapses at the same rate as in the real world, and since we are currently near the end of Season 7, this would make Finn 17 years old.


text:
Q: Aligning icon in toolbar How do I align my icon in the toolbar to the middle? I already removed the label with getSupportActionBar().setDisplayShowTitleEnabled(false);
Is the best idea to create an xml file for my toolbar?

A: Yes in toolbar create some layout and in layout you can have other controls(views).
Toolbar is like other layouts and you can nested them.
<android.support.v7.widget.Toolbar
      android:id="@+id/toolbar_actionbar"
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      app:layout_scrollFlags="scroll|enterAlways">
      <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize">
           <TextView
                 android:id="@+id/title"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_alignParentLeft="true"
                 android:layout_alignParentStart="true"
                 android:layout_centerVertical="true"
                 android:text="@string/news"/>
      </RelativeLayout>
  </Toolbar>

A: programatically you can do it as follows:
mToolbar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            ImageView imageView = (ImageView)mToolbar.findViewById(R.id.logo);
            if( mToolbar == null ){
                return;
            }
            int toolbarWidth = mToolbar.getWidth();
            int imageWidth = imageView.getWidth();
            imageView.setX((toolbarWidth-imageWidth)/2);
        }
    });

customise your layout_toolbar.xml:
<android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        style="@style/Toolbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_height"
        android:background="@drawable/toolbar_background"
        android:focusable="false"
        app:titleTextAppearance="@style/AppTheme.Toolbar.Title">
        <ImageView
            android:id="@+id/logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/toolbar_logo"/>

</android.support.v7.widget.Toolbar>


text: Q: how to enable Microsoft docs popup in visual studio 2019 like java docs in NetBeans I was wondering if there is a way to enable Microsoft docs as popup in visual studio 2019 when I type code like java docs in NetBeans?


text:
Q: How to convert the elements of a python list of lists? I have a python list (vals) containing lists of strings like this:
[['540.0 ', '0.0 ', '0.0 ', '162.0 ', '2.5 ', '1040.0 ', '676.0 ', '28 ', '79.99 \r'],

['540.0 ', '0.0 ', '0.0 ', '162.0 ', '2.5 ', '1055.0 ', '676.0 ', '28 ', '61.89 \r'], ...]

When I want to convert its elements with the code below, I get the following error:
ValueError: could not convert string to float
vals = [[float(item) for item in rec] for rec in vals]

How can I solve this problem?

A: Palliative solution :
Not really optimized
It keep only dot and numeric
vals = [[float("".join(_ for _ in item if _.isdigit() or _ == ".")) for item in rec] for rec in vals]

A: Casting to float from str allows white spaces but not alphabetical characters. A rough solution is str.strip to remove the undesired characters, either at the start or at the end of the string.
l = [['540.0 ', '\r0.0 ', '0.0 ', '\r162.0 \r', '2.5 ', '1040.0 ', '676.0 ', '28 ', '79.99 \r'], ['555']]

new_l = [[float(s.strip('\r')) for s in lst] for lst in l]
print(new_l)
# [[540.0, 0.0, 0.0, 162.0, 2.5, 1040.0, 676.0, 28.0, 79.99], [555.0]]


text:
Q: Unable to plot line in the animation I have created an animated line in Matplotlib which moves from left to right of the curve using my script below:
from __future__ import division
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation

X =  #Time scale in milliseconds, converted to seconds

# Data to plot the curves
Y1 = data_orig[410:524,4]
Y2 = data_orig[410:524,3]
Y3 = data_orig[410:524,2]

plt.plot(X, Y1, 'r--', X, Y2, 'b--', X, Y3, 'g--')
plt.grid(True)

plt.xlabel('Time [s]')
plt.ylabel('Force [N]')

X_MIN = 0.0  //0
X_MAX = 0.6  //600
Y_MIN = -300
Y_MAX = 1500
X_VALS = np.arange(X_MIN, X_MAX+1);

def update_line(num, line):
    i = X_VALS[num]
    line.set_data( [i, i], [Y_MIN, Y_MAX])
    return line,

#l , v = plt.plot(0, -200, 600, 1500, linewidth=2, color= 'gold')
l , v = plt.plot(0.0, -200, 0.6, 1500, linewidth=2, color= 'gold')

anim = animation.FuncAnimation(fig, update_line, len(X_VALS), fargs=(l, ), interval=15, blit=False, repeat=False)

plt.show()

Problem: The line works if the values in X_MIN and X_MAX is set to 0 and 600 respectively. But when I divide this by 1000(to convert to seconds, the line disappears. There is no error which pops as well.
Before (with 0 and 600)

After (with 0.0 and 0.6)

What I am doing wrong? How could I solve this?

A: Possible problem lies in the following line:
X_VALS = np.arange(X_MIN, X_MAX+1);

You did not specify some step size, therefore when X_MIN and X_MAX is 0 and 0.6, X_VALS only is an array with two entries, [0, 1]
So, a possible minimal version works pretty well:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

def update_line(num, line):
    i = X_VALS[num]
    line.set_data([i, i], [Y_MIN, Y_MAX])
    return line,

X_MIN = 0.0
X_MAX = 0.6
Y_MIN = -300
Y_MAX = 1500
step_size = 0.01

fig = plt.figure()
plt.plot([X_MIN, X_MAX], [Y_MIN, Y_MAX], 'r--',)
plt.grid(True)

plt.xlabel('Time [s]')
plt.ylabel('Force [N]')

X_VALS = np.arange(X_MIN, X_MAX + step_size, step_size)

l, v = plt.plot(0.0, -200, 0.6, 1500, linewidth=2, color= 'gold')

anim = animation.FuncAnimation(fig, update_line, len(X_VALS), fargs=(l, ), interval=15, blit=False, repeat=False)

plt.show()


text:
Q: Creating new variable based on specific rows of other two variables in a long formatted dataset I have a long dataset of emotional responses and I need to create a variable based on specific rows of two other variables, within subjects.
The following data frame includes data for two participants ("person") presented with 2 pictures (P1, P2, P3), each with 3 repetitions (R1, R2, R3) which is the "phase" variable. The variable response includes two things the rating for each presentation ( scale -30 to 30) and the emotion experienced per picture.
person <- c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2)
block <- c(4, 4, 4, 5, 5, 5, 8, 8, 4, 4, 4, 5, 5, 5, 8, 8)
phase <- c("P1R1", "P1R2", "P1R3", "P2R1","P2R2","P2R3", "Post1", "Post2","P1R1",
    "P1R2", "P1R3", "P2R1","P2R2","P2R3", "Post1", "Post2")
response <- c(30, 30, 30, -30, -30, -30, "Happy", "Sad", 28, 27, 25, -23, -24,
    -22, "Excited", "Scared")
df <- data.frame(person, block, phase, emotion, response)

I need to create a new column that will be based on the block number and give me the emotion per picture.
I would like the new column to be called "postsurvey" and expect it to be as following:
postsurvey <-c ("Happy", "Happy", "Happy","Sad","Sad", "Sad", NA, NA,
    "Excited", "Excited", "Excited", "Scared", "Scared", "Scared", NA, NA)
df <- data.frame(person, block, phase, emotion, response, postsurvey)

The code that I used is:
df<-df  %>% group_by(person, block) %>%
mutate(postsurvey=if(block==4){response[phase=="Post1"]}
      else if (block==5){response[phase=="Post2"]}
   else {print("NA")})

I expect for each subject to receive for each block number the same response, but what I get is that the response is not grouped by the subjects, and is not repeated within the subject by a block number, as if there is a vector of emotions and a person gets emotions that are not his.
*In my original data I have 4 pictures per subject with 10 repetitions, so the "else if" code repeated with more then two conditions.


text:
Q: Why doesn't the setInterval function stop? I'm trying to clear the time interval which runs every 15 seconds.
Here is the ajax request:
function extras()
{
    $x = {
        action:'extras'
    };
    var r;
    $.ajax({
        type:'POST',
        url:'services.php',
        data:$x,
        beforeSend:function() {
            $('input[name="stop_"]').trigger("click");
        },
        success:function(response) {
            r = response;
            //console.log(response)
        },
        complete:function() {
            console.log(r);
            $('input[name="re_start"]').trigger("click");
        }
    });
}

So, in my buttons re_start and stop_ i have:
$('input[name="re_start"]').click(function (event) {
    event.preventDefault();
    clearInterval(check);
    var check = setInterval(function() {
        extras();
    },15000);
    console.log('Starting again...');
});

$('input[name="stop_"]').click(function (event) {
    event.preventDefault();
    clearInterval(check);
    console.log('Stop');
});

In my DOM in jQuery I initialize the function extras() and keep it in a variable called "check" where I initialize the time interval as follows:
<input type="button" style="display:none;" name="re_start">
<input type="button" style="display:none;" name="stop_">

<script type="text/javascript">
    (function() {
        extras();
        var check = setInterval(function() {
            extras();
        },15000);
    })();
    function extras()
    {
        $x = {
            action:'extras'
        };
        var r;
        $.ajax({
            type:'POST',
            url:'services.php',
            data:$x,
            beforeSend:function() {
                $('input[name="stop_"]').trigger("click");
            },
            success:function(response) {
                r = response;
                //console.log(response)
            },
            complete:function() {
                console.log(r);
                //message_smart(r);
                $('input[name="re_start"]').trigger("click");
            }
        });
    }
</script>

Then I can not understand how it is possible that the first 30 seconds work and when they pass 60 seconds seem to start doing things twice at once, then three and so on! It seems like if I change the interval every second and will run faster and faster. What is the problem?

A: The problem is here:
(function() {
    extras();
    var check = setInterval(function() {
        extras();
    },15000);
})();

You are creating a variable check in a new function scope that is inaccessible outside of that scope. Microsoft has a good example of scope in javascript. Additionally you can see this question.
Now to solve your problem you need to put the check variable in the global scope so remove the function wrapper.
extras();
var check = setInterval(function() {
    extras();
},15000);

You also need to change the restart handler to reassign the variable, like so:
$('input[name="re_start"]').click(function (event) {
    event.preventDefault();
    clearInterval(check);
    check = setInterval(function() {
        extras();
    },15000);
    console.log('Starting again...');
});

Now they should all be using the same check variable and work as expected when clearing the timeout.


text:
Q: Analytic formulas for special values of $L$-functions In The Princeton Companion to Mathematics, IV.1, "Algebraic Numbers", the conditionally convergent series
\begin{equation}
(1)\qquad\frac{\log(\sqrt{2}+1)}{\sqrt{2}}=1-\frac{1}{3}-\frac{1}{5}+\frac{1}{7}+\frac{1}{9}+\cdots\pm\frac{1}{n}+\cdots\quad(2\not\mid n), \\
(2)\qquad\frac{2\log(\frac{1}{2}(1+\sqrt{5}))}{\sqrt{5}}=1-\frac{1}{2}-\frac{1}{3}+\frac{1}{4}+\frac{1}{6}+\cdots\pm\frac{1}{n}+\cdots\quad(5\not\mid n),
\end{equation}
where the sign is minus in (1) iff $n$ mod $8\neq\pm1$ (i.e., $n$ is a quadratic nonresidue mod $2$) and in $(2)$ iff $n$ mod $5\neq\pm1$, are given. There is a hint at a connection between these two formulas (via $\sqrt{2}$ for $(1)$ and $\phi$ for $(2)$), but I am wondering how exactly these formulas generalize.

A: These are instances of Dirichlet's class number formula.
Let $K/\mathbb{Q}$ be a quadratic extension with discriminant $d$. Let $\chi(n) = \left( \frac{d}{n}\right)$ be the Jacobi symbol.
If $K$ is real, then
$$ L(\chi,1) = \frac{h\log(\epsilon) }{\sqrt{d}},$$
where $\epsilon$ is a fundamental unit of $K$, and $h$ is the class number.
If $K$ is imaginary
$$ L(\chi,1) = \frac{2\pi h}{w\sqrt{|d|}},$$
where $w$ is the number of roots of unity in $K$ and $h$ is again the class number.
Your examples correspond to real quadratic fields $\mathbb{Q}(\sqrt{2})$ and $\mathbb{Q}(\sqrt{5})$.
For a more explicit expression, see Proposition 13.3 in these notes.


text:
Q: Using initialized String in asynchronous anonymous function in another page how can you use String theFlag anywhere else outside of this anonymous function
I had to make it an anonymous function as I failed to point a separate  asynchronous function into onPressed in a RaisedButton as it only worked with onChanged now i just need to pass String theFlag to another widget in another screen
please help and mind the beginner question
  onPressed:() async {
       Locale _temp = await setLocale(LanguageClass.languageList()[index].langCode);
       BldrsApp.setLocale(context, _temp);

       String theFlag = LanguageClass.languageList()[index].langFlag ; //I need to use this elsewhere
            print(theFlag);
   },

A: You can do it like this,
String iCanBeAcessed; //make this variable somewhere else, so that you can use it anywhere.
//Inside your anonymous function
 iCanBeAcessed=theFlag;

How can i use that?
You can declare it outside a class, and can use it anywhere in your project.
Example,
//imports

String iCanBeAcessed;

class yourClassName{
//All your other functions and build method

Now, import the dart file( where you have declared the iCanBeAcessed ) in the following manner.
import dartFile.dart as flagString;

//Now, you can use this variable anywhere!

Text(flagString.iCanBeAcessed),


text:
Q: springframework multiple form in one view page I want to have two page views and two controllers.
profile/update.jsp
form:form id="updateform" commandName="profile" method="post" action="/profile/update/${id}"

account/update.jsp
form:form id="updateform" commandName="account" method="post" action="/account/update/${id}"

Now I want to merge them into one page view.
I should add profile and account in profile/update.jsp, and then submit them with one button.
How can I do that?
Please let me know.
Thanks

A: One form can handle only one set of data. The best solution is to create a complex bean with two entites:
public class FormData {
    private Account account;
    private Profile profile;

    ....
}

have a form:
<spring:url value="/handler" var="handler" />
<spring:form commandName="formData" action="${handler}" method="POST">
    <form:input path="account.id" />
    <form:input path="profile.name" />

    ...
</spring:form>

and a controller method:
@RequestMapping("handler")
public update(@ModelAttribute("formData") FormData formData){
    ...
}


text:
Q: .NET/MVC4/Jquery Mobile/Knockout/Chrome/iPhone extra # character in URL Okay, if I could offer a bounty for this I would - I offer virtual karma.
As mentioned in the title I have an .NET/MVC4/Jquery Mobile/Knockout website.  On the index page there is a button
<button data-bind="click: getResults" data-theme="f">Search</button>

which calls a javascript function
$.mobile.navigate("/results?option1=a&option2=b", { transition: amw.transitions.slide });

This works great on all browsers and devices except Chrome/iPhone.  As far as I can tell the version of Chrome or iOS does not matter. The resulting URL in the address bar is
iPhone/Chrome: http://www.mywebsite.com/#/results?option1=a&option2=b
Other Devices: http://www.mywebsite.com/results?option1=a&option2=b
I have put alerts throughout jQuery mobile to try and figure out what is going on (if someone knows a way to debug chrome on iOS let me know) and I cannot see where the extra # is being added.
This may not seem like a big deal but the url ends up being passed on to a downstream service that really does not like the extra #.
I can put in a hack at the call to the service to strip out the # but I would really like to figure out what is happening.
The only suspect line I can find in jQuery mobile (1.3.0) is line #2298
// if the hash is included in the data make sure the shape
// is consistent for comparison
if( data.hash && data.hash.indexOf( "#" ) === -1) {
    data.hash = "#" + data.hash;
}

But I am not sure what this does or why it would occour only on Chrome/iPhone.
so StackOverflow people - what is going on?
Thanks.


text:
Q: Unable to step through program in gdb after SIGTRAP Using mingw gdb, when I to break the program as it's running (using the method from In GDB on MinGW, how do I make Ctrl-C stop the program?), gdb fails to pick up from there.
The only backtrace information I can get is
#0  0x00007fffbfccd881 in ntdll!DbgBreakPoint () from /c/WINDOWS/SYSTEM32/ntdll.dll
#1  0x00007fffbfcf99fb in ntdll!DbgUiRemoteBreakin () from /c/WINDOWS/SYSTEM32/ntdll.dll
#2  0x00007fffbd473034 in KERNEL32!BaseThreadInitThunk ()
   from /c/WINDOWS/System32/KERNEL32.DLL
#3  0x00007fffbfca1431 in ntdll!RtlUserThreadStart () from /c/WINDOWS/SYSTEM32/ntdll.dll
#4  0x0000000000000000 in ?? ()

and if I try to step through the program I get
Single stepping until exit from function ntdll!DbgUiRemoteBreakin,
which has no line number information.

and the program runs to completion. I am able to step through normally (after a breakpoint) but I can't seem to get the debugger to recover from a SIGTRAP

A: DebugBreakProcess creates a new thread in the target process, which is then signalling the debugger via a breakpoint exception to pause the execution.
You can list all available threads with info threads, and then switch to another thread via thread YOUR_THREAD_NUMBER.


text:
Q: How to schedule the execution of a PHP script on the server side? I need a PHP script to be automatically executed at a particular time. How would I achieve this aim?

A: I'm assuming you're creating some kind of webapp and you need part of the system to run something periodically, so it can't be run through a browser.  It's a little tricky to do this if you're loading lots of 3rd party libs or using a lot of server functionality, but if it's straight PHP, you can do it very easily.  Create a scheduled job of some sort (cron job on Linux, Scheduled Task on Windows, etc) that runs the command php -f filename.php.  That will execute your PHP script of choice through the CLI PHP interpreter, which is very similar (perhaps identical to) the way the PHP script would be executed through CGI, but minus some of the server-specific environment variables.

A: If you're running a flavor of Linux/Unix (including Mac OSX), create a cron job.
If you're running Windows, create a scheduled task.
Note: both of the above links relate specifically to a PHP audience.

A: How to Create a Cron Job (Scheduled Task) for Your Website or Blog if you are on linux.

A: If you edit the crontab manually with crontab -e or go to list it with crontab -l, a useful comment to put at the top of the crontab is below.
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  *  command to be executed

  30 3  *  *  *  php /home/scripts/do_something.php

A: If you're not using Linux/Unix, ask your host whether they would be able to set up a Windows scheduled job for you.  Depending whether you can get through the thicket of some hosts' support departments, they should be happy to as it doesn't necessarily pose a security risk


text:
Q: Bootstrap 3.3.1 modal popup close from inside iframe I have an iframe through jQuery and bootstrap, and I need to add a Close button inside the iframe page itself, not from the popup window that opens.
I tried adding <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> in the html popup page, but it does nothing.
Here is the current code with the outer close button, and an example page link of bbc.com:

<link href="https://bootstrapdocs.com/v3.3.1/docs/dist/css/bootstrap.min.css" rel="stylesheet"/>
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">Popup page</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

I found this post but not sure how to implement it in the current case.

A: you can just add button like this
and provide some id 'blackout' to iframe.
<button type="button" class="btn btn-default" onclick="window.jQuery('#blackout').toggle('slow');">Open/Close</button>


text:
Q: Getting ExecuteExcel4Macro to Recognise Empty Cells When I use the ExecuteExcel4Macro function in a VBA script like so:
Public Function GetNamedData(Path, File, Address)
  Dim Data As String
  Data = "'" & Path & File & "'!" & Address
  GetNamedData = ExecuteExcel4Macro(Data)
End Function

Where Address is a named range in my case, if the cell in the closed workbook is empty, this function returns 0. But some cells contain (deliberately) 0.
How do I differentiate between empty cells and cells containing 0?
To explain further, I am using this function to get data from a closed workbook. This has proven very fast at collecting lots of data from closed workbooks.
I understand there are differences between '0' and empty, but I am not sure how to work it into this function.

A: Try this one:
GetNamedData = ExecuteExcel4Macro("IF(COUNTA(" & Data & ")," & Data & ",""X"")")

Then GetNamedData = "X" in case the cell in closed workbook is empty.

A: The below function adds a "" (Null) the the value and so the GetValue2 function returns a null if empty or a zero if it is a zero.
Function GetValue2(strPath As String, strFilename As String, strTabName As String, intColumnNumber As Integer, intRowNumber As Integer) As String
  Dim varCellValue As Variant
  Dim strContents As String

  On Error GoTo ErrHandler

  varCellValue = ExecuteExcel4Macro("'" & strPath & "[" & strFilename & "]" & strTabName & "'!R" & intRowNumber & "C" & intColumnNumber & " & """"")
  strContents = CStr(varCellValue)
  GoTo NiceExit
ErrHandler:
  Call MsgBox("strPathFilename : " & strPath & strFilename & Chr(13) & _
           "strTabName      : " & strTabName & Chr(13) & _
           "intColumnNumber : " & intColumnNumber & Chr(13) & _
    "") ' & Error.msg, vbOKOnly)
NiceExit:
  GetValue2 = strContents
End Function


text:
Q: When are python objects candidates for garbage collection? I am trying to figure out when exactly a python object is a candidate for garbage collection. I have read through a few documents/posts and have been unable to find a definite answer.
Take for example the following line. This is the last reference to foo. When is the object pointed to by foo available for garbage collection?
ret = func(['xyz: ' + foo.name])

Breaking it down to the (possible) individual steps:

*

*temporary reference to name is created.

*'xyz: ' is concatenated with name and value is returned.

*list is created with the new string.

*function is called with new array.

*function returns.

*result is assigned to ret.

*next instruction...

Between which two steps is the object first eligible to be collected? When is the reference count to the object decremented?
If the list of steps is incomplete/incorrect please let me know as well. I only attempted to enumerate them to give a common starting place for the potential answers to reference.

A: As in other garbage collected languages, the rule of thumb is: When it's unreachable. That means, is must not be gc'd as long as the program (any part of it) could still access it. After that, it's fair game. When (even whether) it is actually reclaimed is completely up to the implementation.
In your example, the name foo keeps the object alive, as the program could still use it in later statements. (Theoretically, an implementation may detect if a variable is no longer used, and remove that reference - possibly making the object unreachable sooner. Practically, this is impossible in Python, except perhaps in some traces compiled by a JIT compiler.) The list, in contrast, may become unreachable after the execution of func, or even during it, if func does not store references to it in some reachable locations (e.g. attributes of a reachable object, or a global variable).
Note that you mix up foo and the object it refers to, which is deadly when reasoning about garbage collection. There's no object foo, there's just an object which foo refers to at a given point in time (and thereby, a set of objects it refers to at distinct points in time). This matters:

*

*foo may be changed to refer to another object and the object it originally referred to may become unreachable. You can't talk about such situations unless you differentiate between the two.

*There may be many other references to the object foo points to (actually rather likely). There may keep the object alive long after foo went out of scope, was fed to del, or changed to refer to another object.

A: The variable will be eligible for garbage collection as soon as all references to it go out of scope or are manually deleted (del x).
In your example, foo must exist before this line (otherwise it's a NameError), and therefore will never be garbage collected in your example block of code, as the reference will still exist after this. Even if one were to call del foo after this, we would have to presume there were no references to the object anywhere else for it to be garbage collected.


text:
Q: How do I find the "elliptical confidence region" from columns of a matrix that follows the Wishart distribution? The subject is about the sample mean and the sample covariance estimators and their respective confidence regions for the estimated parameters.
Suppose that $n$ samples are taken from a $p$-variate normal distribution $\mathcal{N}_p(\boldsymbol{\mu},\boldsymbol{\Sigma})$. As far as I know the sample mean estimator has a $p$-variate normal distribution $\mathcal{N}_p(\hat{\boldsymbol{\mu}},\hat{\boldsymbol{\Sigma}}\cdot\frac{1}{n})$ and the sample unbiased covariance estimator has a Wishart distribution $W_p(n-1,\hat{\boldsymbol{\Sigma}}\cdot\frac{1}{n-1})$ with $n-1$ degrees of freedom. The Wishart distribution is a generalization to multiple dimensions of the chi-squared distribution.
The $(1-\alpha)\%$ confidence region for the estimated mean could be obtained as an ellipsoidal inequation:
$\begin{equation}(x-\hat{\boldsymbol{\mu}})^\intercal\left(\displaystyle\frac{\hat{\boldsymbol{\Sigma}}}{n}\right)^{-1}(x-\hat{\boldsymbol{\mu}})\leq \gamma^2\end{equation}$
Where $\gamma^2$ is the value of the Chi-squared CDF for the probability $(1-\alpha)$ and $p$ degrees of freedom. For example, for a confidence region of $95\%$ the value of $\gamma$ is approximately $\sqrt{\chi^2_{_\text{CDF}}(1-\alpha,p)}=\sqrt{5.9915}\approx 2.4477$.
I suppose, based on simulations, that the vectors of the estimated covariance matrix has also an elliptical confidence region. Considering that $\hat{\boldsymbol{\Sigma}}$ is composed by $p$ vectors $[\boldsymbol{w}_1 \boldsymbol{w}_2 \cdots \boldsymbol{w}_p]$ then the confidence region for each vector should be somenting like:
$\begin{equation}(y-\boldsymbol{w}_i)^\intercal \boldsymbol{D}_i^{-1}(y-\boldsymbol{w}_i)\leq \delta_i^2\end{equation}$
The questions that I have are the following:
(1) How do I find the matrices $\boldsymbol{D}_i$ and the parameters $\delta_i$?
(2) The matrix $\boldsymbol{D}_i$ and the parameter $\delta_i$ are the same for all the $\boldsymbol{w}_i$ vectors?


text:
Q: Simple way to make animation character by character ( Kotlin ) Show letter by letter in an easy way with kotlin Class
Like :
A
An
And
Andr
Andro
Androi
Android

A: Try this:
val textView = TextView(this)
val resultText = "Android"
Thread {
    for (i in 0..resultText.length) {
        runOnUiThread { textView.text = resultText.substring(0, i) }
        Thread.sleep(500)
    }
}.start()

You'll have to add textView to some parent, like your contentView.

A: I like Cactusroot's answer better but here's another way to do it with a Timer
private fun animateCharacters(activity: Activity, str: String, animationIntervalMs: Long) {
    val chars = str.toCharArray().toMutableList()
    var cStr = ""

    val timer = Timer()
    val task = object: TimerTask() {
        override fun run() {
            activity.runOnUiThread {
                val char = chars.removeFirstOrNull()
                if (char == null) {
                    cancel()
                    return@runOnUiThread
                }

                cStr += char
                Log.i("Animated String", cStr)
                // update UI with new text
            }
        }
    }
    timer.schedule(task, 0, animationIntervalMs)
}

A: There are a couple of issues with the other answers (as of this writing):

*

*It will leak the Activity for the duration of the animation. Suppose the user rotates the screen a few times quickly. There will be many outdated copies of the Activity in memory, still running useless animations.

*They assume that all code points fit within a single code unit (Kotlin char). When there are longer code points you will get some weird behavior when you try to set text with the in-between state.
If you do this with a coroutine, it automatically will cancel itself when the activity is destroyed so the activity won't be leaked. This is much simpler than trying to manage threads or timers externally and cancelling them in onDestroy().
To animate text correctly, you should add one code point at a time, not one code unit (Kotlin Char) at a time. This is still assuming there are no emoji in the String. To support emoji is very complicated and you would probably want to use an external library to handle it.
fun typeWrite(textView: TextView, text: String, intervalMs: Long) = lifecycleScope.launch {
    val numCodePoints = text.codePointCount(0, text.length)
    for (i in 0..numCodePoints) {
        textView.text = text.take(text.offsetByCodePoints(0, i))
        delay(intervalMs)
    }
}


text:
Q: force an opportunity to always have the same contract Currently our salesforce users are changing the contracts of the opportunities. We automatically create a contract and do some maintenance on the contracts so we do not want anyone to replace the contracts.
My approach is to create a new field called ContractId__c, I will use this new field along with a trigger to make sure that any update in the contract field must have the same contract id.
Is there any other easy and better way to accomplish this?

A: You don't need to write a trigger for this use.
You should write a validation rule like this to check the prior value and current value:
NOT($Permission.Change_Contract_Permission)
&& NOT(ISBLANK(Contract_Id__c))
&& NOT(ISBLANK(PRIORVALUE(Contract_Id__c)))
&& ISChanged(Contract_Id__c)
&& PRIORVALUE(Contract_Id__c) != Contract_Id__c

then throw an error message
You can also create  Custom Permission and assign this to users who wants to change the contract. In the above example Change_Contract_Permission is the custom permission.