text:
Q: Getting a ear to function after adding arquillian testing I have a perfectly functionning application that I then package to an ear to run on a jboss application server. This working I started to implement testing.
Now my tests work with the profile however my ear now refuses to deploy with a strange error coming in.
Here is my pom.xml with the different profiles:
<?xml version="1.0" encoding="UTF-8"?>
<!-- JBoss, Home of Professional Open Source Copyright 2013, Red Hat, Inc.
    and/or its affiliates, and individual contributors by the @authors tag. See
    the copyright.txt in the distribution for a full listing of individual contributors.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not
    use this file except in compliance with the License. You may obtain a copy
    of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
    by applicable law or agreed to in writing, software distributed under the
    License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
    OF ANY KIND, either express or implied. See the License for the specific
    language governing permissions and limitations under the License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>ithink</artifactId>
        <groupId>com.fluxon.iflux</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>ithink-ejb</artifactId>
    <packaging>ejb</packaging>

    <name>ithink: EJB Module</name>

    <url>http://wildfly.org</url>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>1.0.0.Final</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>

        <!-- Declare the APIs we depend on and need for compilation. All of them
            are provided by JBoss WildFly -->

        <!-- Import the EJB API, we use provided scope as the API is included in
            JBoss WildFly -->
        <dependency>
            <groupId>org.jboss.spec.javax.ejb</groupId>
            <artifactId>jboss-ejb-api_3.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the CDI API, we use provided scope as the API is included in
            JBoss WildFly -->
        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the JPA API, we use provided scope as the API is included in
            JBoss WildFly -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- JSR-303 (Bean Validation) Implementation -->
        <!-- Provides portable constraints such as @Email -->
        <!-- Hibernate Validator is shipped in JBoss WildFly -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>javax.ejb</groupId>
            <artifactId>ejb-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.2</version>
        </dependency>

        <!-- To initialize collections -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <!-- To deal with tests -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.17</version>
            </plugin>
            <plugin>
                <artifactId>maven-ejb-plugin</artifactId>
                <version>${version.ejb.plugin}</version>
                <configuration>
                    <!-- Tell Maven we are using EJB 3.1 -->
                    <ejbVersion>3.1</ejbVersion>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <!-- The default profile skips all tests, though you can tune it to run
                just unit tests based on a custom pattern -->
            <!-- Seperate profiles are provided for running all tests, including Arquillian
                tests that execute in the specified container -->
            <id>default</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>${version.surefire.plugin}</version>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>arquillian-jbossas-managed</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.jboss.as</groupId>
                    <artifactId>jboss-as-arquillian-container-managed</artifactId>
                    <version>7.1.1.Final</version>
                    <scope>test</scope>
                </dependency>
                <dependency>
                    <groupId>org.jboss.spec</groupId>
                    <artifactId>jboss-javaee-web-6.0</artifactId>
                    <version>3.0.0.Final</version>
                    <type>pom</type>
                    <scope>provided</scope>
                    <exclusions>
                        <exclusion>
                            <groupId>xalan</groupId>
                            <artifactId>xalan</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
            </dependencies>
            <build>
                <testResources>
                    <testResource>
                        <directory>src/test/resources</directory>
                    </testResource>
                    <testResource>
                        <directory>src/test/resources-jbossas-managed</directory>
                    </testResource>
                </testResources>
            </build>
        </profile>
        <profile>
            <id>arquillian-glassfish-embedded</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.jboss.arquillian.container</groupId>
                    <artifactId>arquillian-glassfish-embedded-3.1</artifactId>
                    <version>1.0.0.CR3</version>
                </dependency>
                <dependency>
                    <groupId>org.glassfish.main.extras</groupId>
                    <artifactId>glassfish-embedded-web</artifactId>
                    <version>3.1.2</version>
                </dependency>
            </dependencies>
            <build>
                <testResources>
                    <testResource>
                        <directory>src/test/resources</directory>
                    </testResource>
                    <testResource>
                        <directory>src/test/resources-glassfish-embedded</directory>
                    </testResource>
                </testResources>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.12</version>
                        <configuration>
                            <systemPropertyVariables>
                                <java.util.logging.config.file>
                                    ${project.build.testOutputDirectory}/logging.properties
                                </java.util.logging.config.file>
                                <derby.stream.error.file>
                                    ${project.build.directory}/derby.log
                                </derby.stream.error.file>
                            </systemPropertyVariables>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

    </profiles>

</project>

and here is my error stack when I launch my local server:
23:33:05,203 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "ithink-ear.ear")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"ithink-ear.ear\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"ithink-ear.ear\".WeldStartService: Failed to start service
    Caused by: org.jboss.weld.exceptions.DefinitionException: Exception List with 1 exceptions:
Exception 0 :
java.lang.RuntimeException: javax.naming.NamingException: Unable to acquire SerialContextProvider for SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.ldap.version=3, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is java.lang.RuntimeException: Orb initialization erorr]
    at com.sun.jersey.server.impl.cdi.CDIExtension.initialize(CDIExtension.java:196)
    at com.sun.jersey.server.impl.cdi.CDIExtension.beforeBeanDiscovery(CDIExtension.java:297)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
    at org.jboss.weld.injection.MethodInvocationStrategy$SpecialParamPlusBeanManagerStrategy.invoke(MethodInvocationStrategy.java:144)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:306)
    at org.jboss.weld.event.ExtensionObserverMethodImpl.sendEvent(ExtensionObserverMethodImpl.java:121)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:284)
    at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:262)
    at org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:271)
    at org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:260)
    at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:154)
    at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:148)
    at org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:54)
    at org.jboss.weld.bootstrap.events.AbstractDefinitionContainerEvent.fire(AbstractDefinitionContainerEvent.java:42)
    at org.jboss.weld.bootstrap.events.BeforeBeanDiscoveryImpl.fire(BeforeBeanDiscoveryImpl.java:45)
    at org.jboss.weld.bootstrap.WeldStartup.startInitialization(WeldStartup.java:368)
    at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:76)
    at org.jboss.as.weld.WeldStartService.start(WeldStartService.java:92)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.naming.NamingException: Unable to acquire SerialContextProvider for SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.ldap.version=3, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is java.lang.RuntimeException: Orb initialization erorr]
    at com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:351)
    at com.sun.enterprise.naming.impl.SerialContext.createSubcontext(SerialContext.java:937)
    at javax.naming.InitialContext.createSubcontext(InitialContext.java:489)
    at javax.naming.InitialContext.createSubcontext(InitialContext.java:489)
    at javax.naming.InitialContext.createSubcontext(InitialContext.java:489)
    at com.sun.jersey.server.impl.cdi.CDIExtension$1.stepInto(CDIExtension.java:280)
    at com.sun.jersey.server.impl.cdi.CDIExtension.diveIntoJNDIContext(CDIExtension.java:267)
    at com.sun.jersey.server.impl.cdi.CDIExtension.createJerseyConfigJNDIContext(CDIExtension.java:273)
    at com.sun.jersey.server.impl.cdi.CDIExtension.initialize(CDIExtension.java:192)
    ... 26 more
Caused by: java.lang.RuntimeException: Orb initialization erorr
    at org.glassfish.enterprise.iiop.api.GlassFishORBHelper.getORB(GlassFishORBHelper.java:180)
    at com.sun.enterprise.naming.impl.SerialContext.getORB(SerialContext.java:364)
    at com.sun.enterprise.naming.impl.SerialContext.getProviderCacheKey(SerialContext.java:371)
    at com.sun.enterprise.naming.impl.SerialContext.getRemoteProvider(SerialContext.java:401)
    at com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:346)
    ... 34 more
Caused by: java.lang.NullPointerException
    at org.glassfish.enterprise.iiop.api.GlassFishORBHelper.getORB(GlassFishORBHelper.java:152)
    ... 38 more
"}}

I have tried activating and deactivating the profile but as soon as I add the testing profile I fall back to this state.
Thank you a lot for any help,
My arquillian.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://jboss.org/schema/arquillian
    http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<container qualifier="glassfish-embedded" default="true">
    <configuration>
        <property name="resourcesXml">
            src/test/resources-glassfish-embedded/glassfish-resources.xml
        </property>
    </configuration>
</container>


text:
Q: Openshift 3 - Installing dependency from s2i/bin/assemble I have the following file in the directory for my Openshift project which uses s2i to create a build image. This script attempts to install the cairo package.
.s2i/bin/assemble
#!/bin/bash
echo "Before assembling"

sudo yum install cairo

/usr/libexec/s2i/assemble
rc=$?

if [ $rc -eq 0 ]; then
    echo "After successful assembling"
else
    echo "After failed assembling"
fi

exit $rc

However, it fails with a "sudo": command not found.
This isn't a package that can be added in the requirements.txt file, and I need it for use with the WeasyPrint package. I've tried several different approaches, and this is the closest I've been able to get. (and this approach successfully builds despite the error)

A: Unfortunately you can't use root on open shift by default. You need to add your dependencies to DockerFile

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to open local file with its default launching application in silverlight 5? I'm using in-browser application with elevated trust. I have local file path (say files in my documents) & I want to launch that file in its default application. how to get this working?

A: dynamic dynamic_obj = AutomationFactory.CreateObject("WScript.Shell");
dynamic_obj.Run(FilePath);

This worked perfectly fine.
Note: It needs to add reference to Microsoft.CSharp.dll


text:
Q: How do I check types within a template class in c++? I have a Button class that can either display an image or a line of text, which I am trying to use a template implement.
If it's text, then the template type is: const char*
If its an image, then the template type is: const wchar_t*
Here is the method that needs to differentiate between the two types:
template <typename T>
void Button<T>::draw(EasyGraphics* canvas)
{
    canvas->setBackColour(colour);

    if (mouseOver)
    {
        canvas->setPenColour(EasyGraphics::BLACK, 4);
    }
    else
    {
        canvas->setPenColour(EasyGraphics::BLACK, 2);
    }

    canvas->drawRectangle(Entity::GetX(), Entity::GetY(), Entity::getWidth(), Entity::getHeight(), true);
    canvas->setFont(20, L"");
    canvas->setTextColour(textColour);

    switch (typeid(T))
    {
        // Button has display text
        case typeid(const char*):
        {
            canvas->drawText(displayData, Entity::GetX() + textXOfset, Entity::GetY() + (Entity::getHeight() / 4) - 3);
            break;
        }
        // Button has display image
        case typeid(const wchar_t*):
        {
            canvas->drawBitmap(displayData, Entity::GetX() + textXOfset, Entity::GetY() + (Entity::getHeight() / 4) - 3, 60, 60, 0x0000FF00);
            break;
        }
    }
}

I cannot seem to get the switch at the bottom to function correctly. I am not sure if a switch is the best way to go about it. Any advice would be appreciated, cheers.

A: Use type traits (and if constexpr) instead of typeid. For example:
void g_char(const char*);
void g_wchar_t(const wchar_t*);

template <typename T>
void f(T)
{
    if constexpr (std::is_same_v<T, const char*>)
    {
        g_char(T());
    }
    else if constexpr (std::is_same_v<T, const wchar_t*>)
    {
        g_wchar_t(T());
    }
}

http://coliru.stacked-crooked.com/a/08e9e66ed5c776a4
The reason a switch doesn't work here is that the condition must be implicitly convertible to an integral type, and std::type_info (what typeid returns) isn't.
But then if you try keeping the typeid expressions, you have the problem of compile-time type checking when you try calling drawText or drawBitmap. Both calls must be valid unless you use constexpr branches (if constexpr). However, the conditions must then be compile-time constants, where typeid cannot be used. So instead, you can use type traits, and in particular, std::is_same.

A: Do a template specialization:
template <typename T>
void DoDraw(EasyGraphics* canvas);

template<>
void DoDraw<char>(EasyGraphics* canvas)
{
  canvas->drawText(displayData, Entity::GetX() + textXOfset, Entity::GetY() + (Entity::getHeight() / 4) - 3);
}

template<>
void DoDraw<wchar_t>(EasyGraphics* canvas)
{
  canvas->drawBitmap(displayData, Entity::GetX() + textXOfset, Entity::GetY() + (Entity::getHeight() / 4) - 3, 60, 60, 0x0000FF00);
}

template <typename T>
void Button<T>::draw(EasyGraphics* canvas)
{
  ...
  DoDraw(canvas);
}

*check the template argument, it's pretty weird to have const char* and not just char.

A: You can go for typeid with a caution that it is not suitable for run time polymorphism. For example below.
#include <iostream>

template<class T>
void getType(T A) {
    std::cout<<typeid(A).name()<<"\n";
}

class Base {
};

class Derived : public Base {
};

int main(){
    getType(Base());
    getType(Derived());
    Derived *d = new Derived();
    getType(d);
    Base *b = d;
    getType(b);
    return 0;
}

Output:
4Base
7Derived
P7Derived
P4Base


text:
Q: Is MySQL release_lock() Blocking? I'm running MySQL:
~/g/profile> mysql --version
mysql  Ver 14.14 Distrib 5.7.28, for osx10.13 (x86_64) using  EditLine wrapper

My Go application is performing some schema migrations, which starts with SELECT GET_LOCK() and then executes a bunch of DDL and other statements, followed by SELECT RELEASE_LOCK().  All of these queries are executed on the same connection.
I'm experiencing a scenario where the migration driver returns a success (lock has now been released) and yet immediately subsequent SQL calls see a picture of the database which is only partly migrated.  Calls a few ms later see the fully migrated schema.
I have read through the documentation on these MySQL functions.  I understand that these create/destroy an "advisory lock" which has no power to prevent concurrent access to data except when two applications use the same name for the lock.
My question is, is it possible for RELEASE_LOCK() to return before other statement(s) executed with the same connection, or before such statements completely take effect?

A: If you mean that you run:
GET_LOCK()
...some DDL statements...
RELEASE_LOCK()

And these are run serially on a single thread, then no, it's not possible for RELEASE_LOCK() to run before the DDL statements are finished.
In fact, the DDL statements themselves are blocking. They don't return until the DDL is complete.
I suspect you have one of the following going on:

*

*Some of the DDL statements did not succeed, but you're not checking for their error status.

*You are trying to use multiple threads, and you somehow allowed the RELEASE_LOCK() to run before the DDL thread is finished.

A: Your Session probably ended early because

A lock obtained with GET_LOCK() is released explicitly by executing RELEASE_LOCK() or implicitly when your session terminates (either normally or abnormally). Locks obtained with GET_LOCK() are not released when transactions commit or roll back.

https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html


text:
Q: Is that normal to have many idle connections in MySQL (without persistent parameters)? But we didn't use any persistent connections. Why are there many idle connections? We noticed that by using 'show processlist' command and the time was about 4000-8000 seconds. Those connections looked like always 'sleep'. We're using Nginx with PHP in fast-cgi mode, and we use PDO library. Any suggestions?

A: That sounds like a client isn't closing its connections properly, so the server keeps them hanging around until they time out. If a client just opens a connection, then runs a query and then abandons the connection, it is NOT closed (even though the client can't access it any longer after throwing the handle away). My understanding is that the web server should close these connections when the page completes. Looks like this isn't happening. As to why, I don't know.
The default timeout setting on the server is 6 hours, which means that on a web server this can easily build up to several thousand connections waiting for a timeout.

A: *

*Disable persistent MySQL queries in your php.ini configuration file.

*Edit your /etc/my.cnf file and set some additional limits.

set-variable    = long_query_time=120
set-variable    = wait_timeout=28000
set-variable    = connect_timeout=25

A: hmmm, it depends.
Certainly the DBMS won't invent these connections on its own. While the overhead in creating a connection to mysql is low, there's still going to be a gap between creating the connection and firing a query off, and between the query completing and the results being polled completely, and then a further gap before the script closes down the connection. These will be even more pronounced if your code opens the connection before its needed, and/or waits too long before closing the connection.
However in the absence of persistent connections, no web based software should be holding a connection open for more than a couple of seconds. If you have mysql replication enabled then this will show as a thread running since startup.
What does
SHOW FULL PROCESSLIST

(from the mysql shell) show?

A: I noticed you tagged fastcgi. I suspect thats your problem.
PHP (assuming thats what your doing this with) only terminates the connection once the interpreter has exited and cleanup starts, meaning the connection remains open as idle until garbage collection. FastCGI typically doesn't 'terminate' as it runs as a service which is why your experiencing these long sleep times.
The best way to fix this it to explicitly declare a mysql_close() at the end of your code. Anyway, its best practice to clean up after yourself! But as a kludge workaround you could set a wait_timeout in mysql to destroy the connections.


text:
Q: How to get a fake test user logged in for pytest if my log in route reads information in from forms in Flask I am using pytest to test my Flask application and the test for valid login fails because the fake user is not able to log in the way I'm doing it.
Once a user is logged in, server should redirect from Sign In page to Home page which contains some text and a flashed message. My test does not pass the asserts for the text/flashed messages on Home page. It passes assert for text that should be on Sign In page which means it's not successfully logging in and therefore not redirecting. I also printed the response data and it returns the html for Sign In page. It is not an issue with the app itself as on the server side everything is working fine. My valid_login_logout test in test_users.py and log in route in routes.py are below
def test_valid_login_logout(test_client, init_database):
    """
    #GIVEN a Flask application
    #WHEN the '/login' page is posted to (POST)
    #THEN check the response is valid
    """

    with test_client:
        response = test_client.post('/login',
                                data={'username':'AW', 'password':'FlaskWhat'},
                                follow_redirects=True)
        user = User.query.filter_by(username='AW').first()
        assert user.check_password('FlaskWhat')
        assert user in init_database.session
        assert response.status_code == 200
        #This is the point where it fails:
        print(response.data)
        assert b'Home' in response.data
        assert b'Click to Reset It' in response.data
        assert b'You were logged in' in response.data
        assert b'Hello, AW!' in response.data
        assert b"Here are available items on sale" in response.data
        assert b"Welcome" in response.data

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(username=form.username.data).first()
            if user is None or not user.check_password(form.password.data):
                flash("Invalid username or password.")
                return redirect(url_for('login'))
            login_user(user, remember=form.remember_me.data)
            flash('You were logged in')
            next_page = request.args.get('next')
            if not next_page or url_parse(next_page).netloc != '':
                next_page = url_for('index')
            return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)

I want the response data to be the redirected Home page but instead the response data is the original Sign In page which means the fake user isn't successfully logging in


text:
Q: Instance attribute unexpectedly loaded I learned Python last year, and was just getting back into it with a new project. I've hit a snag right at the beginning, and after a bunch of poring through documentation I'm still stumped. I have to believe it's something simple, but I can't find it. Here's the issue:
I have the following set up in a file:
class Wrapper(object):
    def __init__(self, title=None):
        self.header = Thing("HEADER")
        if title is not None:
            self.header.content.append( Thing("TITLE", content=[str(title)]) )
        self.body = Thing("BODY")
        self.content = Thing("COMPLETE", content=[self.header, self.body])

class Thing(object):
    def __init__(self, name, content=[]):
        self.name = name
        self.content = content

Then from an interactive prompt I do:
>>> import things
>>> a = things.Wrapper("This is a title")

Now, I would expect at this point that the body attribute of a would be a Thing instance with the name "BODY" and a content consisting of an empty list. What I'm surprised to find is that its content is actually a list containing the same "TITLE" instance that a.header.content holds.
>>> a.header.name
'HEADER'
>>> a.header.content
[<test.Thing object at 0xb752290c>]
>>> a.body.name
'BODY'
>>> a.body.content
[<test.Thing object at 0xb752290c>]
>>> a.body.content[0].name
'TITLE'
>>> a.body.content[0].content
['This is a title']

I can't for the life of me figure out how a.body.content got assigned that way. Can anyone shed some light on this?

A: Try this
class Thing(object):
    def __init__(self, name, content=None):
        if content is None:
            content = []
        self.name = name
        self.content = content

The issue with [] as a default is that the default parameters are only evaluated once, when the interpreter first creates the function.  For an int or other immutable type this is fine, but for mutable types (lists, dictionaries, anything that can be changed in place) this causes problems.  What winds up happening is that all instances of Thing share the same content.
This way, the empty list is created each time you call the constructor, creating a new list every time.


text:
Q: assume_role does not return and lambda times out (keywords: aws boto3 sts lambda python3.6) I am attempting to create a python3.6 AWS lambda function that assumes a role in another account to access an S3 bucket in that another account. I am testing this exact lambda function locally (with aws profile set) to test whether my cross account roles and policies are set up and locally it works flawlessly. However, when running the same code from within lambda it looks like assume_role does not return and the lambda times out. Would appreciate any hint how to approach debugging this or any ideas what could be an issue?
My code:
print ("==== before_assume_role")
assumed_role_object = sts_client.assume_role(
    RoleArn=FOREIGN_ROLE_TO_ASSUME, RoleSessionName='cross-account-session')
print ("==== after_assume_role")

"==== after_assume_role" does not get printed out, error handler (i.e. except (Exception) as error) does not get called and lambda times out.
Any ideas would be extremely appreciated!
Thank you,
Constantine

A: I faced this issue as well, the reason was I was deploying it in a private VPC. My fix was to specify the sts client explicitly.
sts_client = boto3.client('sts',region_name="ap-southeast-1",endpoint_url="https://sts.ap-southeast-1.amazonaws.com")

Change the region name and endpoint url accordingly.


text:
Q: Undoing auto-indentation Wnen you use irb with auto indent mode, the end statements get indented one level extra
 def foo
   ...
   end

instead of showing the ordinary indenting convention:
def foo
  ...
end

because you cannot tell irb in advance that you are going to escape one level in the next line. This question has been addressed elsewhere like here or here, but neither gives a satisfactory answer. They just suggest giving up.
However, if we can minimally overwrite some irb methods so that auto indent will insert white spaces not in the prompt area but at the beginning of the line you type in, then by default, irb will still be inserting spaces, but we will be able to erase some spaces with backspace. Is this possible?
Or, if that is not realistic, then is it possible to make irb erase the last line from the screen and redisplay it with proper indentation right after you press Enter on a line including end?

A: Rewriting the last line is possible. Doing it in irb is difficult due to its lack of documentation and consistent api across versions. An irb alternative, ripl, has already solved this issue for itself with an auto-indent plugin. If you want to give ripl and its auto-indenting a try:
$ gem install ripl-auto_indent
$ echo "require 'ripl/auto_indent'" >> ~/.riplrc

# Auto-indent away
$ ripl
>> def foo
>>   puts "it's auto-magic!"
>> end


text:
Q: ionic 3 angularfire2 code to ionic 4 angularfire2 code i have my code with ionic 3 angular 5 working as below
getUser(uid:string){
    console.log('start of getUser with uid:' + uid)
    return new Promise((resolve, reject) =>
      {
        this.db.object("/users/" + uid).snapshotChanges().map(
          (snapshot) => {return snapshot.payload.val()}
        ).subscribe(
          res => {
            console.log('response:' + res)
            resolve(res)
          },
          err => {
            console.log(err)
            reject(err)
          }
        )
      })
  }

however, with ionic 4 .map does not work any more. how do i convert this code?

A: Just like you can see here

Starting in version 5.5 we have shipped "pipeable operators", which
  can be accessed in rxjs/operators (notice the pluralized "operators").
  These are meant to be a better approach for pulling in just the
  operators you need than the "patch" operators found in rxjs-compat
  package.
NOTE: Using rxjs or rxjs/operators without making changes to your
  build process can result in larger bundles.

So now you can use map() like this:
// RxJS
import { map } from 'rxjs/operators/map';

// ...

getUser(uid:string){
    console.log('start of getUser with uid:' + uid)
    return new Promise((resolve, reject) => {
        this.db.object("/users/" + uid)
            .snapshotChanges()
            .pipe(
                map((snapshot) => {
                    return snapshot.payload.val();
                })
            )
            .subscribe(
                res => {
                    console.log('response:' + res)
                    resolve(res)
                },
                err => {
                    console.log(err)
                    reject(err)
                }
            )
    })
}

Not related to the question itself but just in case, if you want your getUser() method to return a promise, you can use RXJS operators as well (instead of creating and resolving a promise), like this:
// RxJS
import { map } from 'rxjs/operators/map';
import { tap } from 'rxjs/operators/tap';

// ...

public getUser(uid: string): Promise<any> {
    console.log('start of getUser with uid:' + uid)

    return this.db
        .object("/users/" + uid)
        .snapshotChanges()
        .pipe(
            map((snapshot) => {
                return snapshot.payload.val();
            }),
            tap((response) => {
                console.log('response:' + response);
            })
        )
        .toPromise()
}


text:
Q: Rspec + phantomjs/poltergeist GITLAB CI fails to run integration/feature Hi I am struggling to run my integration/feature tests via the Ci, please do let me know what am I doing wrong here.
Running specs locally works without any issues
The strangeness of this is that it dose not want to run because it seems to have problems finding application .css or .js
the gitlab CI setup :
image: ruby:2.3.0

cache:
paths:
- .bundle
- vendor/

stages:
 - test
 - integration
 - codecov

before_script:
 - export COMPILE=0
 - export PHANTOM_JS=phantomjs-2.1.1-linux-x86_64
 - export RAILS_ENV=test
 - gem install bundler
 - bundle install --path vendor/
 - mkdir ~/tmp
 - pushd ~/tmp
 - wget --max-redirect=40
   http://bitbucket.org/ariya/phantomjs/downloads/$PHANTOM_JS.tar.bz2
 - tar xf $PHANTOM_JS.tar.bz2
 - mv $PHANTOM_JS phantomjs
 - ln -s ~/tmp/phantomjs/bin/phantomjs /usr/bin/phantomjs
 - phantomjs --version
 - popd
rspec:
  stage: test
  services:
    - postgres:latest
    - redis:latest
variables:
    POSTGRES_DB: package_analysis_test
    POSTGRES_USER: runner
    POSTGRES_PASSWORD: runner

  script:
    - apt-get update -qq && apt-get install -y -qq nodejs postgresql-
      client libpq-dev
    - gem install bundler --no-ri --no-rdoc
    - cp config/_database.yml config/database.yml
    - cp config/_redis.yml config/redis.yml
    - cp config/_sidekiq.yml config/sidekiq.yml
    - cp config/_settings.yml config/settings.yml
    - bundle exec rake db:drop RAILS_ENV=test
    - bundle exec rake db:create RAILS_ENV=test
    - bundle exec rake db:schema:load RAILS_ENV=test
    - bundle exec rake db:structure:load RAILS_ENV=test
    - bundle exec rake db:seed RAILS_ENV=test
    - bundle exec rake assets:precompile RAILS_ENV=test
    - bundle exec rspec --exclude-pattern spec/features/*_spec.rb
  artifacts:
    paths:
      - coverage/

rspec-integration:
  stage: integration
  services:
    - postgres:latest
    - redis:latest
  variables:
    POSTGRES_DB: package_analysis_test
    POSTGRES_USER: runner
    POSTGRES_PASSWORD: runner

  script:
    - apt-get update -qq && apt-get install -y -qq nodejs postgresql-
      client libpq-dev
    - gem install bundler --no-ri --no-rdoc
    - cp config/_database.yml config/database.yml
    - cp config/_redis.yml config/redis.yml
    - cp config/_sidekiq.yml config/sidekiq.yml
    - cp config/_settings.yml config/settings.yml
    - bundle exec rake db:drop RAILS_ENV=test
    - bundle exec rake db:create RAILS_ENV=test
    - bundle exec rake db:schema:load RAILS_ENV=test
    - bundle exec rake db:structure:load RAILS_ENV=test
    - bundle exec rake db:seed RAILS_ENV=test
    - bundle exec rake assets:precompile RAILS_ENV=test
    - bundle exec rspec spec/features
pages:
  stage: codecov
  dependencies:
    - rspec
  script:
    - mv coverage/ public/
  artifacts:
    paths:
      - public
    expire_in: 30 days
  only:
    - staging

this is how the 'head' of the error looks like:
1) User processes late orders entering late orders #index
   Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #
  {env['PATH_INFO'].inspect}"

    ActionController::RoutingError:
     No route matches [GET] "/assets/application.css"
     # /builds/justcode/packageanalysis/vendor/ruby/2.3.0/gems/web-console-
   2.0.0/lib/action_dispatch/debug_exceptions.rb:22:in `middleware_call'
    # /builds/justcode/packageanalysis/vendor/ruby/2.3.0/gems/web-console-
  2.0.0/lib/action_dispatch/debug_exceptions.rb:13:in `call'
   # /builds/justcode/packageanalysis/vendor/ruby/2.3.0/gems/actionpack-
   4.2.5/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
    # /builds/justcode/packageanalysis/vendor/ruby/2.3.0/gems/railties-4.2.5/lib/rails/rack/logger.rb:38:in
   `call_app'

Once its the application js the other tie its the css file. I am confused on what to do with this
this is also my capybara setup from the test helpers :
require 'capybara/rspec'
require 'capybara/poltergeist'
require 'capybara/rails'

Capybara.register_driver :poltergeist do |app|
  options = {
    js_errors: true,
    cookies: true,
    inspector: true,
    window_size: [2_500, 2_500]
  }
  Capybara::Poltergeist::Driver.new(app, options)
end

Capybara.default_driver = :poltergeist
Capybara.javascript_driver = :poltergeist
Capybara.default_selector = :css

A: What worked for me was to move to headless chrome and use my own image.
https://hub.docker.com/r/grfx/ruby-chromedriver/
(ruby 2.3, chromedriver 2.33, node, postgresql-client)
ALSO do turn off caching for the time between now and merge to master(main) branch if You used a different image setting.
The gitlab-ci setup was reduced to essential settings :
image: 'grfx/ruby-chromedriver:latest'

cache:
  paths:
    #- .bundle
    #- vendor/
    #- public/

stages:
  - test
  - codecov

before_script:
  - export RAILS_ENV=test
  - bundle install --path vendor/
rspec:
  stage: test
  services:
    - postgres:latest
    - redis:latest
  variables:
    POSTGRES_DB: package_analysis_test
    POSTGRES_USER: runner
    POSTGRES_PASSWORD: runner

  script:
    - cp config/_database.yml config/database.yml
    - cp config/_redis.yml config/redis.yml
    - cp config/_sidekiq.yml config/sidekiq.yml
    - cp config/_settings.yml config/settings.yml
    - bundle exec rake db:drop RAILS_ENV=test
    - bundle exec rake db:create RAILS_ENV=test
    - bundle exec rake db:schema:load RAILS_ENV=test
    - bundle exec rake db:structure:load RAILS_ENV=test
    - bundle exec rake db:seed RAILS_ENV=test
    - bundle exec rspec
  artifacts:
    paths:
      - coverage/
      - public/

pages:
  stage: codecov
  dependencies:
    - rspec
  script:
    - mv coverage/ public/
  artifacts:
    paths:
      - public
    expire_in: 30 days
  only:
    - staging

gems used :
gem 'selenium-webdriver', '~> 3.9'
gem 'webdrivers'
gem 'capybara', '~> 2.16.1'

rspec setup (rails_helper)
require 'capybara/rspec'
require 'selenium-webdriver'
require 'capybara/rails'

Capybara.register_driver :chrome do |app|
  options = Selenium::WebDriver::Chrome::Options.new(
    args: %w(headless disable-gpu no-sandbox)
  )
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

Capybara.javascript_driver = :chrome
Capybara.default_driver = :chrome
Capybara.default_selector = :css

A: Looks like you're using single quotes instead of double quotes when defining the route:

"No route matches [#{env['REQUEST_METHOD']}] # {env['PATH_INFO'].inspect}"


text:
Q: SQL performance for string field vs multiple int/varchar fields I'm trying to get the database design right, and I'm uncertain about which of 2 options I should choose. There will be around 20 bool values that are used to filter (4 in the sample for simplicity).

*

*prop1

*prop2

*prop3

*prop4

Option 1)
A int(1) or varchar(1) field for each prop. The filter part of the query could be like
WHERE prop1=1 AND prop3=1 AND prop4=1

Option 2)
Using a single text field with characters representing the props

*

*a: prop1

*b: prop2

*c: prop3

*d: prop4

Then the filter part of the query similar to option 1 would be like
WHERE props LIKE '%a%' AND props LIKE '%c%' AND props LIKE '%d%'

or if the characters are sorted:
WHERE props LIKE '%a%' AND props LIKE '%cd%'

My thought is that option 2 makes it easier to add new props so I like this option, but will the LIKE comparator perform worse than the equality comparator? Does it make any difference to use a single text compared to multiple int(1) or varchar(1)? Any other benefits or drawback that I haven't thought of?

A: The primary question is whether you can run faster than scanning the entire table.  The answer is "no" unless a small number of the booleans can be handled separately with Index(es).
Your WHERE bools LIKE '%a%c%d%' is a clever trick for ANDing any number of flags together.  However, it will need to look at every row, and LIKE is slightly heavyweight.
INT(1) takes 4 bytes plus overhead.  TINYINT is what you are fishing for; it takes 1 byte, plus overhead.
A SET with up to 64 bools is another technique.  The coding is a bit clumsy, but it is rather efficient
INT UNSIGNED (for up to 32) or BIGINT UNSIGNED (for up to 64) flags is implemented similarly to SET and also takes up to 8 bytes.  But the coding is rather clumsy.  Let's number the bits starting with 0 in the least significant bit.
WHERE (bools & ( (1 << 0) | (1 << 2) | (1 << 3) ) ) =
               ( (1 << 0) | (1 << 2) | (1 << 3) )

would check that bits 0, 2, and 3 are all set.  (This is like your test for a,c,d.)  A variety of ANDs and ORs are possible with this approach.  (You could pre-compute those bit values-- 13 in this example.  Or use a bit literal: 0b1101.)
The benefit of SET or bits in an INT is the 'speed' within each row.  Still, all rows must be tested.
So, I recommend triaging your bools, etc, and decide what needs indexing and what can go into this combined column or in a combined JSON column for non-bools.

A: From performance's point of view both options have drawbacks:

*

*It is almost impossible to have proper indexing for 20 columns, regardless of their data types, because queries can vary from setting condition prop1, prop1 + prop2, prop2 + prop3, prop2 + prop4 etc. So you would need a lot of composite indexes. In addition, indexes on boolean values usually don't perform well because of low cardinality (value can be 0 or 1 only, see here for example).

*On the other hand side, LIKE statements with leading % are also a performance issue. Closing % can work, but leading % is determined to be slow.
What I see here that you want to assign a set of attributes to your records, each record can have 0..n assigned propX, and you want to filter that efficiently. Like a user can have 0,1,2,...n roles assigned. In relational databases it classifies as a classical many-to-many relationship. If you set up a table with the possible props and connect those to your records with a join table, like detailed here for example, you can make good queries with only a limited number of indexes.


text:
Q: Power Supply Circuit ±9V from a 6V centre tap transformer At work, there's a power supply which is used on one of our products. The guy who originally made the board has since left and none of the senior electronics guys could give me a good answer.
Here's a schematic of the PSU

There's the transformer (Myrra 45055) a bridge rectifier (KBP305G) and some 10000uF caps.
From my understanding, from the output of the transformer I've got 12V AC. With the centre tap being GND I would have expected my outputs to be +6V with respect to centre tap and -6V with respect to centre tap. What the actual circuit gives is ±9V (±0.2V), I'm unsure how I'm getting a total of 18V difference between + and - from 12V out the transformer.
I've never really dealt with transformers or AC before, is there a misunderstanding in my thinking? Or are the caps doing something more than just ripple smoothing?

A: RMS versus peak: -

RMS is the equivalent DC voltage that would dissipate the same heat in a resistor when the AC voltage is applied. You can do the math\$^1\$ if you want but, for a sinewave, the RMS is 70.71% of the peak OR the peak is \$\sqrt2\$ higher than the RMS.
When ever we talk about AC voltages (without specifying peak or peak-to-peak) we imply RMS hence, a 6V RMS signal will have a peak of 8.49 volts (nearly 9 volts). After passing through a rectifier diode this might be more like 8 volts DC on the smoothing capacitor.
However, transformers unloaded will run at a slightly higher voltage on the output so expect a volt more (or so) on the output.

\$^1\$ Take a 10V peak sinewave. Square the waveform - this produces a double-frequency sinewave between 0V (lowest peak) and 100V (highest peak). Take the Mean - 50V then take the Square Root - 7.071 volts i.e. 7.071 volts is the RMS value of a sinewave having a peak of 10V.
R = root, M = mean, S = square = root of the mean of the squared signal.

A: When you smooth the rectified output of an AC supply, you get the peak value which is root 2 (1.41) times the RMS AC value. Less any voltage drop in the rectifier diodes. Which is about 8.5 volts for 6 volts dc minus the losses. It shouldn't be right up at 9v, but it'll be well above 6. With the transformer lightly loaded, the AC value will be higher than nominal also. Generally small transformers have poorer regulation than large ones. I have a small nominal 12V (DC) PSU in front of me (from a "wall wart") which produces over 20V DC when unloaded. This can be a significant factor when rating other components. (For instance, it renders a 16V capacitor inadequately rated).


text:
Q: Using Dust.js with Node.js Tools for Visual Studio Is there a way to get highlighting, intellisense and all for Dust.js templates (.dust) in a node project in Visual Studio?
The projects created using TypeScript version of Node.js Tools for Visual Studio. It's Visual Studio 2013 SP4. Express.js is the core web provider here and bunch of other packages. Application is already working, but editing .dust files is not much of a pleasant thing.

A: Visual Studio - Tools - Options - Text Editor - File Extensions
Go there to add .dust, and set it to HTML Editor.
Visual Studio will syntax highlight Mustache-like templates, so Dust looks mostly okay.


text:
Q: Gwt and eclipse with jetty for production mode Is there a standard easy way to launch Jetty from eclipse for the production mode?
I followed the instructions at http://code.google.com/webtoolkit/usingeclipse.html to setup a new project using gwt and eclipse.
The hosted (debug) mode seems to be already configured to work properly and involves one click in eclipse using "Debug as".
I would like to configure "Run as" to run the production mode in jetty. Is there a good tutorial on the standard way to set this up?

A: You have to compile your GWT-project before you can "Run As". It's the button with a red box and "G" on it.

A: Since GWT compiles to java script you don't need jetty if you don't have server-side logic... anyway, in a normal scenario you'll have some server interaction, BUT you're not sticked to jetty; tomcat or other server side technology could be used.
You can deploy the compiled JS to a web server and the server side logic to tomcat, jboss, jetty... even you could interact with php at the server.
Deployment to Google AppEngine is another option, a natural option if you use the eclipse plugin since it's tightly integrated with it.
In eclipse, Jetty is no more than a java process started like any normal java main.
Go to [Run]->[Run Configurations]->[Web Application]->[Your GWT Project] and you'll see a normal java main exec config.

Look at the [Main Class] option -> this is the embeded jetty  ..or at
  the [VM arguments] for the JVM

The ?gwt.codesvr= param in the URL only instruct the browser plugin to interact with the eclipse plugin embeded jetty in a way that only the modified code is re-compiled to JS and sent to the browser.
If you do not use the ?gwt.codesvr= probabilly you'll have to recompile all the project every time you change a single line of code.
I recommend you to clearly separate the compiled-to-js code and the server side code in different eclipse projects.
I also run the embeded jetty only for the client-side code; the server side code is run in tomcat.
That way I have a clear separation of layers at the time I can debug client-side GWT code and server-side java code.


text:
Q: How to translate mouse point of Tab to Point of JTabbedPane? Sorry, but I am afraid!
I have mouse listener attached to my custom tab component.
When I click on this tab I want to translate mouse Point to coordinates of parent JTabbedPane.
How to do this in swing?
Thanks friends!

A: It appeares to be very easy to do.
Class javax.swing.SwingUtilities has a set of methods that convert Point and Rectangle from coordinate system of one component to another component.
It is also possible to convert MouseEvent.


text:
Q: Chrome, Linux Mint, Low FPS in games I'm running Linux Mint 16 on a desktop computer with Nvidia GeForce GTX 550 Ti (driver 331.20, older driver also has same problems) graphics, and have been using the current stable version of Chrome. After reboots and for some  amount of time if I play games such as Team Fortress 2, Minecraft, and other native running games (no Wine) I get good FPS (100-150) and the games run smooth. But at some point my FPS drops to 20 when the games start and drop to around 9 FPS. After closing the game and relaunching same problems, but sometimes I have exited Chrome (and the background processes) and relaunched both Chrome and the game and my FPS goes back to normal. This is not always the case, some times exiting Chrome dose not work and I have to restart to come back to normal FPS.
What may cause this? Chrome is one possible cause, but something else is causing problems too.


text:
Q: Fictitious forces and $\omega$ I have been studying fictitious forces, such as the centrifugal force and Coriolis force. The equation for the centrifugal force is given by:
$$F_{centrifugal}=-m\omega\times(\omega\times r)$$
My question is this, what does $\omega$ represent? I can see three possible options for a situation where the origins of the inertial frame and non-inertial frame do not coincide?

*

*The angular velocity of the origin of the non-inertial frame about the axis of the inertial frame.

*The angular velocity of the axis of the non-inertial frame about its own origin.

*A combination of the above.
If it is 3, please can you explain how we combine them.

A: Option 4, none of the above.
Your option 1 is wrong because points don't rotate. Your option 2 is closer to correct, but ultimately still wrong. You're overly hung up on points (the origin).
It might help to get a handle on what "rotation" is. Points don't rotate. Better said, a rotated point is indistinguishable from the original. What about one dimensional space? Rotating a line about itself doesn't change the coordinate of a point on that line one iota. Once again, rotation doesn't make quite sense here.
Two dimensional space is where the concept of rotation begins, and indeed, it helps to look at rotations in higher dimensional spaces as a composite of two dimensional rotations. Only one parameter ("angle") is needed to describe a rotation in two dimensional space. Rotation is not a two-vector in two dimensional space. Rotation is not a four-vector in four dimensional space. Six parameters are needed to describe rotations in four dimensional space, ten in five dimensional space.
Our three dimensional space is the only space where the number of parameters needed to describe a rotation is equal to the dimensionality of the space. This is one of the reasons why we can treat angular velocity in three dimensional space as if it was a vector. Another key reason is the concept of an axis of rotation. That this axis must exist is the key point of Euler's rotation theorem. Any sequence of rotations in three dimensional space can be described in terms of a single rotation about some axis by some angle. That axis specifies a direction and the rotation angle specifies a magnitude. Direction and magnitude: That's a vector!
One reason I said "option 4, none of the above" is that you appeared to be a bit hung up on the origin. The origin doesn't really matter. It might help if you visually making some coordinate system markers. It's easy. Something like these:

Imagine making a bunch of them. Next, go find a playground with a kid's roundabout:

Spread your markers about the roundabout. Put one dead center, put others elsewhere. Now give it a spin. Think of each of those markers as representing a coordinate system. The coordinate system at the center of the roundabout is undergoing pure rotation. All of the others are undergoing a combination of rotation and acceleration. The origin does matter when it comes to velocity and acceleration of the origin of the frame, but it doesn't matter when it comes to angular velocity. All of those reference frames share the same angular velocity vector.


text:
Q: Notebook cell properties: Count cell number. Count edited cells I have a Mathematica notebook with more than 20 cells, including some closed.

*

*How can I programmatically count the exact number of cells?

*How can I know how many of them have not been edited?


text:
Q: Reason for ambiguous error in java generics code while trying to overload/override While going through generics, I am not able to understand why the error is coming:
class Box <T> {
    private T theThing;
    public Box( T t)        { theThing = t; }
    public void reset( T t) { theThing = t; }
}
class WordBox< S extends CharSequence > extends Box< String > {
    public WordBox( S t)    { super(t.toString().toLowerCase()); }
    public void reset( S t) {
     //   super.reset(t.toString().toLowerCase());
    }

}
public class ss {
    public static void main(String[] args) {
        WordBox<String> city = new WordBox<String>("Skogland");
       city.reset("Stavanger"); // error: ambiguous**
    }
}

I can understand, method worldbox.reset () is not overriding the method from BOX, instead it is overloading.
After type erasure, I am assuming this will be code :
class Box  {
    private Object theThing;
    public Box( Object t)        { theThing = t; }
    public void reset( Object t) { theThing = t; }
}
class WordBox extends Box{
    public WordBox( CharSequence t)    { super(t.toString().toLowerCase()); }
    public void reset( CharSequence t) {
        super.reset(t.toString().toLowerCase());
    }

}
public class ss {
    public static void main(String[] args) {
        WordBox<String> city = new WordBox<String>("Skogland");
       city.reset("Stavanger");
    }
}

So, city.reset("Stavanger") should call the method from Worldbox.reset , as String extends charsequence and it seems to be closest match.
Could anyone please explain why the ambiguous error is coming in this code?


text:
Q: Poetry manage python package CLI I'm developing a Python package using Poetry with the following structure:
/packagename
 /packagename
  /tests
   __init__.py
   test_packagename.py
  __init__.py
  packagename.py
pyproject.toml

All the package code is inside packagename.py, which is imported in __init__.py.
I want to add a CLI and my goal is to execute the following in the command line:
<packagename> <packagefunction>

To do so, I used the click package for Python and wrote my <packagefunction> inside packagename.py as:
 @click.command()
 def packagefunction():

Currently, I have added entry points into poetry configuration file as:
[tool.poetry.scripts]
<packagefunction> = '<packagename>:<packagefunction>'

and run:
poetry run <packagefunction>

which execute perfectly.
However, I know this is not the correct way to do it and I want the CLI to execute with the commands shown above.

A: To achieve the command line you are after you, you can use a:
click.Group()
import click

@click.group()
def main():
    """packagename cli"""

And then to use the group, you can use @main.command() decorator like:
@main.command()
def packagefunction():
    """packagefunction subcommand"""

instead of @click.command() decorator.
Poetry scripts
To have poetry install packagename command and call the main group in the  packagename module:
[tool.poetry.scripts]
# command_name = module_for_handler : function_for_handler
<packagename> = '<packagename>:<main>'

instead of:
[tool.poetry.scripts]
<packagefunction> = '<packagename>:<packagefunction>'


text:
Q: ViewModel and endless collection I need to implement endless listbox (the one that is loading chunks of data when user scroll to the end) and I am using ViewModel.
I have ListBox bound to ObservableCollection, but I don't known how to get notified about reaching the end of it and yet not to break the MVVM paradigm.
How can I achieve this?
The only thing I need to know is how to retain MVVM features and constraints and yet to get notified when the collection has been enumerated to it's end.
Thanks.
EDIT
I have been digging around a little and I am afraid that this is not an easy solution. I think the only possibility is to implement custom collection which will implement ICollection and INotifyCollectionChanged. But I don't know how the internal mechanisms of ListBox and other ItemsSource enabled controls work so I don't know how to implement lazy loading.
Is the primary fetching mechanism of WP controls which utilize ItemsSource the IEnumerable interface? Or does it use indexer methods? How does it call count? Does it depend on count or can it be changed during it's lifecicle (and in which calls? I think that not all calls can change the Count and then call NotifyCollectionChanged).
Is there any documentation? Or is there any implementation available?

A: As this should support MVVM, I wouldn't tie the event to part of the listbox but as part of the Collection itself.
You should attempt to add more chunks when the requested index is towards the end of the list.
One way to achive this is to inherit from IList and monitor the this[int index] property.
For instance:
public class OC<T> : IList<T>, IList
{
    public T this[int index]
    {
        get
        {
            if  (index >= (this.Count - 20)) // Insert correct heuristics here!
            {
               // Load more chunks
            }
            return base[index];
        }
    }
}

(Of course Count - 20 is not the best way to do this and you probably want to enter your own heuristics (maybe if the index is in the last 10%), but it shows the concept)
This way, you don't care if the View is using a ListBox or a combo or whatever - You're keeping the MVVM pattern. When the current item requested is an item towards the end of the list, that's your queue to start loading more chunks...
Note that you'll want to derive from IList too since for Virtualization, WPF seems to check for an IList (no generics) and IList<T> does not derive from IList. Long story short, if you don't derive from IList
 as well, the indexer will be called for each item in the list.

A: I found a nice solution that does not break MVVM and yet supplies quite elegant solution to this problem (it seems on the first look, I haven't investigated it properly yet.)
Look at http://danielvaughan.orpius.com/post/Scroll-Based-Data-Loading-in-Windows-Phone-7.aspx
There's also stackoverflow topic for that, which I overlooked. Look at WP7 Auto Grow ListBox upon reaching the last item.


text:
Q: bootstrap 3: add icon outside of input I add icon outside input box with  method and

. but output is broken :
HTML:

    input

                <input class="form-control" type="text" name="files" placeholder="test">

Broken :

I need to :

Ouput Is: http://jsfiddle.net/W2zxk/1/
How do fix this?

A: I have created a fiddle just have a look at it !
http://jsfiddle.net/VwWK8/
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home</title>
<link href="assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="assets/css/font-awesome.css" />

input

<input class="form-control" type="text" name="files" placeholder="test">

A: Check this fiddle
HTML:

input

                <input class="form-control" style="width:200px" type="text" name="video" placeholder="">
                    icon

CSS:
.help-box {
 float: right;
 position: fixed;
 }

Please let me know if this was helpful

A: Please check this demo I have just made little change like add "float:left;" and decrease width 500px to 450px " according to jsfiddle display in s500 class and add inline css in div tag " float:left; and line-height:5px;
HTML :

input

                <input class="form-control" type="text" name="video" placeholder="">

icon

CSS :
.s500 {
width:450px;
float:left;

}
Demo : http://jsfiddle.net/jafaruddin/E2Ftp/2/


text:
Q: get source of click in javascript? I'm designing a webpage which uses very basic javascript.
Here's the code:
html:
<!DOCTYPE html>

<button type="button" onclick="reset()">Reset</button>

Here's the javascript:
function display()
{
document.getElementById("description").innerHTML="der Apfel - Apple
die Äpfel - Apples

Ein Apfel am

Tag hält den Arzt weg
- An apple a day keeps the doctor away";
}

function reset()
{
document.getElementById("description").innerHTML="";
}

Clicking on the image of the apple displays text in the description box. Clicking on the image of the pineapple displays some other text in the same place.
Instead of using different functions like apple(), pineapple() to insert text, I thought it would be easier to call a display function whenever something is clicked, and in the display function, if the script could identify the source of the click (that is, which image is clicked), it could insert text accordingly.
How do I go about this identifying the click source?

A: You can use this.id:

then catch the id:
function display(clicked_id)
{
 alert(clicked_id);
}

A: You would pass this to the display() handler, then you can access the properties of the DOM element that received the click. Here is the fiddle: http://jsfiddle.net/dandv/BaNdS/. Essentially,

A: There is a easier way. Use a variable:
 function selectFruit(fruit){
     if(fruit == 'apple'){
       .....
     }else if(fruit == 'pinapple'){
       .....
     }
     ...
 }

A: Simple and easy solution: pass arguments to the display function:

Better solution: Use the javascript-only (no JS in HTML markup) traditional or even the advanced event handling model. The listeners (which might be attached to multiple elements) will get passed an event object, from which you can determine which element was clicked. Example:
function clickHandler(eventObj) {
    var elem = eventObj.target;
    if (elem.nodeName.toLowerCase() == 'img' && elem.id)
        display(elem.id);
}

A: Probably the simplest way:
var code, node = document.getElementById('description');

code = {
    apple    : "Apple",
    pineapple: "Pineapple"
};

function display( src ) {

    node.innerHTML = node.innerHTML ? "" : code[ src.id ] ;

}

for ( var i in code ) {

    document.getElementById( i ).onclick = function() { display( this ) };

}

Demo on jsFiddle

A: I would go in a somewhat different direction:

*

*For each possible "term" have hidden block of text with the desired contents.

*In each image tag add the ID of its proper placeholder as a rel attribute.

*Have JavaScript running on page load, assigning the click event automatically.

Sample HTML would be:

der Apfel - Apple
die Äpfel - Apples

Ein Apfel am
Tag hält den Arzt weg
- An apple a day keeps the doctor away

der Apfel - Pineapple
die Äpfel - Pineapples

Ein Apfel am
Tag hält den Arzt weg
- An Pineapple a day keeps the doctor away

Don't forget CSS to make those hidden:
.item_placeholder { display: none; }

And finally the magic to bind them all:
window.onload = function() {
    for (var i = 0; i < document.images.length; i++) {
        var image = document.images[i];
        var rel = image.getAttribute("rel");
        if (rel && rel.length > 0) {
            image.onclick = ItemImageClick;
        }
    }
};

function ItemImageClick() {
    var rel = this.getAttribute("rel");
    var placeholder = document.getElementById(rel);
    if (placeholder) {
        document.getElementById("description").innerHTML = placeholder.innerHTML;
    } else {
        alert("DEBUG - element not found " + rel);
    }
}

Live test case.


text:
Q: Sequelize - Aggregate Function Many-to-Many I have a many-to-many relationship with a junction organizaiton_member between my user and organization tables. I am trying to create a query that counts the number of user_id's present where the organization_id matches a specific integer. The expected outcome on my end is a single row with the total count of user_ids as one column and the organization_Id as a second column. I thought that I would be able to achieve this with the following query, but I receive an error, Unhandled rejection SequelizeDatabaseError: column "user.user_id" must appear in the GROUP BY clause or be used in an aggregate function. Is there a reason why this has to be done? Sorry for the lack of experience working with SQL involving aggregates and many-to-many.
Query:
models.User.findAll({
        attributes: [[sequelize.fn('COUNT', sequelize.col('user.user_id')), 'user_count']],
        include: [{
            model: models.Organization,
            where: {
                organizationId: req.session.organizationId
            },
            attributes: ['organization_id'],
            group: ['organiztion.organization_id']
        }],
    })

User Schema:
user_id
first_name
last_name
email

Organization Schema:
organization_id
org_name

Organization_Member Schema:
user_id
organization_id

SQL Generated:
SELECT "user"."user_id"                                      AS "userId",
       Count("user"."user_id")                               AS "user_count",
       "organizations"."organization_id"                     AS
       "organizations.organizationId",
       "organizations"."organization_id"                     AS
       "organizations.organization_id",
       "organizations.organization_member"."created_at"      AS
       "organizations.organization_member.created_at",
       "organizations.organization_member"."updated_at"      AS
       "organizations.organization_member.updated_at",
       "organizations.organization_member"."user_id"         AS
       "organizations.organization_member.user_id",
       "organizations.organization_member"."organization_id" AS
       "organizations.organization_member.organization_id"
FROM   "user" AS "user"
       INNER JOIN ("organization_member" AS "organizations.organization_member"
                   INNER JOIN "organization" AS "organizations"
                           ON "organizations"."organization_id" =
"organizations.organization_member"."organization_id")
ON "user"."user_id" = "organizations.organization_member"."user_id"
AND "organizations"."organization_id" = 1;


text:
Q: Show that for all $n ∈ \mathbb Z$ , $n^2 ≥ n$.
Show that for all $n ∈ \mathbb Z$ , $n^2 ≥ n$.

Hi, I'm trying to do this question. Does this mean I have to take any integers? Do I suppose its true and try to prove it. Is there a way to intuitively see if it's true or false even before beginning to prove.
I am new to this subject and here as well and I am sorry if my questions are not clear or are not the way I have to ask.
Thanks.

A: Yes, integers.
Intuition?  Well for $n\ge 1>0$ then $n*n\ge n*1$ by multiplication inequality axiom.
And the only times that an integer isn't greater than or equal to one is if it is $0$ or negative.  (That's why this is only true for integers; other numbers can be between $0$ and $1$ and this just won't be true:  if $0 <x <1$ then $x*x <x*1$.)
If $n=0$ or $n <0$ can be thought of as  really just special case afterthoughts.  $0^2=0\ge 0$, and if $n <0$ then $n^2>0$ (does that need to be proven?) and so by transitivity  $n^2>0>n $.

A: For $n\leq0$ we have $n^2\geq0$, thus, $n\leq n^2$. For $n\geq1$ we can use induction; for the case $n=1$ we have the equality. Let us assume the statement is true for some $n=k$, then, for $n=k+1$ we have
$$n^2+2n+1\geq 3n+1$$
$$(n+1)^2\geq3n+1\geq n+1$$
Which completes the induction, notice that because $n>0, 3n+1>n+1$

A: Yes, to prove it in general you have to show it holds for any $n \in \Bbb Z$.
No, you don't want to "suppose it's true and try to prove it;" that is circular reasoning; you generally want your logic to proceed in a straight line.
Okay, let's look at a little proof:
If $n = 0$, it's clearly true, right?
If $n \ne 0$, then
$\vert n \vert \ge 1; \tag 1$
also
$\vert n \vert \ge \vert n \vert; \tag 2$
if we multiply these two inequalities we obtain
$n^2 = \vert n \vert^2 \ge \vert n \vert; \tag 3$
also,
$\vert n \vert \ge n; \tag 4$
combining (3) and (4) yields
$n^2 \ge n, \tag 5$
as desired.
The question about intuition is almost too difficult to deal with in a small space, but this I know from experience:  the more little "obvious" facts you can prove, the more you develop an "intuitive nose" for sniffing out truth and falsehood; but of course, you really ultimately need to convert your intuition to logic.  I guess the key take-out here is this:  write it down.

A: The other answers focus on how to prove that theorem. I will focus on another part of your question:

Is there a way to intuitively see if it's true or false even before beginning to prove?

It's a good idea to shortly think about whether the theorem might be true before starting to prove it.
One way to do so is by trying to find a counter-example to prove it wrong. So you just plug in some numbers, and see whether it is true for those. Try to choose numbers, that are somehow different from each other (e.g., positive numbers, negative numbers, small numbers, big numbers, $0$).
If you find a number for which the theorem is wrong, congratulations, you just prove the theorem to be wrong. If the theorem is true for all numbers you have tried, the theorem might be true or there might be a counterexample that you haven't found.
Now you need to prove the theorem as shown by the other answers. Only then you can be sure it is true.

A: $$Let\space n\in Z$$
$$\text{Now, let us consider two functions such that,}$$
$$ \space  f_1(n)=n^2 \space and \space f_2(n)=n$$
$$ \text{Let me change value of n to n+1 , therefore we have,}$$
$$f_1(n+1)=(n+1)^2=n^2+2n+1; \space \space and \space f_2(n+1)=n+1;$$
$$\text{let us subtract }f_1 \text{from} f_2 $$
$$\phi=f_1(n+1)-f_2(n+1)=n^2+2n+1-(n+1)=n^2+n=n(n+1)$$
$$\phi=n^2+n=n(n+1)\space \text{is positive} \space \forall n \in[1,\infty)$$
$$\phi=n(n+1)=0 \space \space \text{if}\space n=0 \space or \space -1 $$
$$\text{suppose n is lesser than -1 then both n and n+1 is negative,}$$
$$\text{ therefore }\phi\space \text{is positive} $$
$$ \text{if }\phi \text{ is positive then }f_1(n+1)>f_2(n+1) \text{and if }\phi=0 \text{ then}\space f_1(n+1)=f_2(n+1) $$
$$\text{Therefore, } n^2 \ge n, \space \forall \space n\in Z$$


text:
Q: Random number matrix within a specified range in Python I would like to generate a random number matrix within a specified range, say (0,1).
import numpy as np
A=np.random.random((3, 3))
print("A =",[A])

A: numpy.random.uniform can receive low, high and size parameters
Range 0-1 is the default
A = np.random.uniform(size=(3, 3))
print("A =", [A])

Output
A = [array([[0.76679099, 0.57459256, 0.07952816],
            [0.02736909, 0.05905416, 0.09909474],
            [0.08690106, 0.81983883, 0.18740471]])]

If you want another range specify it with parameters
A = np.random.uniform(0.2, 0.3, (3, 3))
print("A =", [A])

Output
A = [array([[0.20548205, 0.25373507, 0.28957419],
            [0.20496673, 0.27004844, 0.28633947],
            [0.22325187, 0.26327935, 0.24548129]])]

A: you will be use it generate range [0, 1)
np.random.rand(d0, d1, ..., dn)

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).
https://numpy.org/doc/stable/reference/random/generated/numpy.random.rand.html

A: You can use Numpy's built-in rand method, which generates a matrix with random numbers with a uniform distribution over [0, 1).
A = np.random.rand(3, 3)


text:
Q: Android application auto update In one of our projects where we are implementing an application using Android/HTML5/JavaScript there is a requirement for having an Android Auto update kinda feature which is as described below:
Update Native version: The Native version of our application should be easy to update. New versions should be possible to "push", or at least notify, the user of. Does this require that we publish it to the Android Market?
As of now Notification of the new version can be send to the device but we need an approach to automatically download the new version and install ie., either update the existing version or overwrite it. Hosting the new version in Android market is the last option according to the client
If someone/somebody has earlier come across or implemented such a feature, could you kindly reply back.

A: The android market allow to auto-update applications. Is you want to do it without using the android market, your users will have to enable apk install from unknown sources and they will have to confirm each installation (unless their phones are rooted I think)

A: If you are using the Android market , the best solution is to just notify the user that an update is available. Depending on the update or Application you may decide not to allow the user the access the app if an update is available.
You will always need to push a new APK to the market , the user may setup the auto update feature but I believe there is no way for an app to force the setting.
Any method which will allow the app to auto update would either need more privileges from users or a routed device , which I guess is not a big enough percentage of users to try the feature.

A: There is a nice service called http://push-link.com
This hosts you APK and manage updates. You can choose how the user is going to be notified and see the progress installation of all version.
Cheers...


text:
Q: Отправка файла с Android на FTP сервер Одна из задач моего учебного проекта - передать файл с Android-смартфона на FTP сервер.
Погуглив, нашел, что это можно сделать с помощью библиотеки Apache Commons.
Библиотеку успешно подключил в проект, добавил в AndroidManifest.xml разрешение:
<uses-permission android:name="android.permission.INTERNET" />

Далее, воспользовался примером загрузки файла на FTP сервер:
public static void ftpConn(String hostAddress, String log, String password) throws FileNotFoundException {
    FTPClient fClient = new FTPClient();
    FileInputStream fInput = new FileInputStream("Android/data/название_пакета/Yes.txt");
    String fs = "Yes.txt";
    try {
        fClient.connect(hostAddress);
        fClient.enterLocalPassiveMode();
        fClient.login(log, password);
        fClient.storeFile(fs, fInput);
        fClient.logout();
        fClient.disconnect();
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

Обработчик события на кнопку, по нажатию на которую будет производиться отправка файла:
try {
    ftpConn("n***.n****.ru","*****","*****");
} catch (FileNotFoundException ex) {
    Toast.makeText(getApplicationContext(), "Неудача", Toast.LENGTH_SHORT).show();
}

Файл, который необходимо отправить я поместил во внутреннюю память устройства: Android/data/название_пакета/Yes.txt. Пробовал прописывать различные пути файла в строку:
FileInputStream fInput = new FileInputStream("Android/data/название_пакета/Yes.txt");

Но ничего не получалось. Приложение ловило исключение и выводило Toast: "Неудача".
Подскажите, пожалуйста, в чем проблема? Я думаю, что ошибка в том, что я неверно указываю путь к файлу.
PS: Программу запускал на Nexus 5 с Android 6.
PSS: Данный пример отправки файла на FTP пытался запустить на компьютере - все получилось с первого раза.

A: В FileInputStream должен быть передан либо относительный путь к файлу (от корня файловой системы вашего проекта), либо абсолютный. Абсолютный начинается со слеша / и указывает полный путь к файлу от корня файловой системы устройства.
У вас сейчас путь относительный (без слеша в начале) но явно не корректный.
Насколько я понимаю, приложению недоступны другие расположения по внутренней памяти, кроме директории самого приложения. Поэтому, файл должен лежать в проекте.
Получить абсолютный путь к файлу можно примерно таким образом:
String yourFilePath = context.getFilesDir() + "/" + "hello.txt";

и использовать его следующим образом:
FileInputStream fInput = new FileInputStream(yourFilePath);

У меня на тестовом проекте вызов getApplicationContext().getFilesDir() вернул

/data/user/0/com.example.note.test/files

A: Используйте Context.getFilesDir(), чтобы получить путь к внутренней памяти устройства
Например:
FileInputStream fInput = new FileInputStream(getFilesDir() + "/Android/data/название_пакета/Yes.txt");


text:
Q: Restore comparator from saved instance bundle In my application I have a RecyclerView and the user is able to select different kinds of orderings for the items within it. The ordering is based on a Comparator.
Let's assume the user rotates the device: After the configuration change I want to restore the ordering of the items. I thought about doing it this way:
public interface ItemComparator<T> extends Comparator<T>, Serializable { }

public class TestActivity extends AppCompatActivity {
    private static final String KEY_COMP = "COMP";
    private ItemComparator<MyItem> comparator;

    protected void onCreate(@Nullable Bundle savedState) {
        // main setup

        if(savedState == null) {
            comparator = (a, b) -> a.getName().compareTo(b.getName());
        } else {
            // unsafe cast here - can I get rid of it?
            comparator = (ItemComparator<MyItem>) savedState.getSerializable(KEY_COMP);
        }
    }

    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(KEY_COMP, comparator);
    }
}

Is this valid code or can this cause a memory leak or any other problems?

A: To do this, you can make a Sorter comparator for every ordering. The class takes field and direction parameters to sort, which is the values you save to the bundle.
public class Sorter implements Comparator<Item> {

    public static final int SORT_BY_DATE = 0;
    public static final int SORT_BY_DESCRIPTION = 1;
    public static final int SORT_BY_AMOUNT = 2;

    public static final int SORT_DIR_ASCENDING = 1;
    public static final int SORT_DIR_DESCENDING = -1;

    private int field;
    private int direction;

    public Sorter(int field, int direction) {
        this.field = field;
        this.direction = direction;
    }

    public int getField() {
        return field;
    }

    public int getDirection() {
        return direction;
    }

    @Override
    public int compare(Item i1, Item i2) {
        int order = 0;

        switch (field) {
            case SORT_BY_DATE:
                order = Long.compare(i1.date, i2.date);
                break;

            case SORT_BY_DESCRIPTION:
                order = i1.description.compareTo(i2.description)
                break;

            case SORT_BY_AMOUNT:
                order = Integer.compare(i1.amount, i2.amount)
                break;
        }

        return order * direction;
    }

}

In onCreate():
if (savedState == null) {
    // Default parameters
    comparator = new Sorter(Sorter.SORT_BY_DATE, Sorter.SORT_DIR_ASCENDING);
} else {
    int field = bundle.getInt("comparatorField");
    int dir = bundle.getInt("comparatorDir");
    comparator = new Sorter(field, dir)
}

In onSaveInstanceState(Bundle savedState):
bundle.putInt("comparatorField", comparator.getField());
bundle.putInt("comparatorDir", comparator.getDirection());

Serialiazing the comparator is definitively not the way to go, in fact, you should avoid using that with Android in general.


text:
Q: Strange rendering issue occurring in IE8 only I'm having some strange rendering issues that are occurring only on IE8, not IE7, 6, or any of the other browsers I've tested (ff, chrome, opera mostly).
http://www.sealymattressonline.co.uk/Shop/Sealy-Silver-Collection-C246/
in IE8 scroll down to the bottom of that page (or indeed any of the other category links from the left sidebar) and on the first pageload there is an un-explained whitespace gap on random products
(see http://plixi.com/p/92068948)
All I need to do is highlight/select the dodgy render with the cursor, or refresh the page, and it renders correctly from then on.
(see plixi.com/p/92069037 for how it looks once it's been "fixed" by highlighting / refreshing the page)
I know that it's not my PC - I've tried several different PCs at my workplace and all do the same on IE8 - so not a browser plugin like some similar problems. I'm also unable to test IE9, as I'm on XP.
Any ideas at all? The winning helper will get cookies (imaginary cookies are yum!)
UPDATE:
I can't reproduce this on my machine's local server or another test server. It doesn't make any sense that this might be a server related error??!

A: This style seems to be the culprit:
.group {display:inline-block;}

I don't see why you need that.
It spans the width of its container, so normal old block should do. You could probably leave off the declaration altogether, as "block" is default for divs.
In IE8 developer tools, I changed display to "block" and the white-space disappeared without any side effects.


text:
Q: How does Java handle Certificates in Spring Ws? I need to consume a web Service using Spring Ws . I am using WEB service Template.
I need to know that  by only specifying the certificates in java keystore and trustore will the sending and receiving of certificates happen automatically? Also will the verification of server certificates happen automatically in Spring Ws if the keystore and trustore is configured properly or do I have to write some code?if not Ho do I send and receive certificates in Spring WS?

A: Once you have selected the security interceptor you like to use. Assuming you have all the certificates handy, you can follow below links to set up the one or two way ssl for each of the security interceptor. This links are not most up to date but should get you started.
XwsSecurityInterceptor
Server Security Set up
Client Security Set up
Wss4jSecurityInteceptor
Client and Server Security Set up


text:
Q: Distributed Tracing with Service Bus Triggered Function According to the docs around distributed tracing for Servicebus, the Diagnostic-Id property should be used to store the WC3 traceparent.
When an Azure Function is triggered via a service bus message, I would expect this value to be used to initialize the tracecontext (so AppInsight logs would get tagged with the appropriate operation_Id).
I've even tried to copy it over to the tracecontext and it doesn't seem to work.
Is it not possible to maintain distributed tracing with Service Bus in Azure functions?
Update
You can kinda of get this to work by implementing the wrapped app insights context, however, calls to context.log will still have the original traceparent reference :(
export default async function contextPropagatingHttpTrigger(context, req) {
  // overwrite with the proper traceparent from the incoming SB message.
  const sbTraceParent = context.bindingData.applicationProperties['diagnostic-Id'];
  if (sbTraceParent) {
    context.traceContext.traceparent = sbTraceParent;
  }

  const correlationContext = appInsights.startOperation(context, req) as CorrelationContext;

  // Wrap the Function runtime with correlationContext
  return appInsights.wrapWithCorrelationContext(async () => {
    const startTime = Date.now(); // Start trackRequest timer

    try {
      // operation_Id matches SB 'diagnostic-Id'
      appInsights.defaultClient.trackTrace({
        message: 'Correct Trace Context',
      });

      // operation_Id is the original function traceparent
      context.log('Incorrect Trace Context');

      return await trigger(context, req);

    } catch (e) {
      context.log.error(e);
      throw e;
    } finally {
      // Track Request on completion
      appInsights.defaultClient.flush();
    }
  }, correlationContext)();
}


text:
Q: likelihood function of a line regression equation I am a bit confused at how can i find the likelihood function and the solutions of likelihood function for a line equation, for example y=3x+15

A: The equation $y = 0.2x + 4$ is not a statistical model, but a mathematical equation. It doesn't even have parameters (unless you mean that $x$ is a parameter), so there is nothing to optimize. In case you meant $y = \beta_0 + \beta_1 x$, this would still be a deterministic function of the variables, that can be solved by pure algebra, that does not need statistics. Statistical model arises, when there is uncertanity about the data
$$
y = \beta_0 + \beta_1 x \color{red}{+ \varepsilon}
$$
Assuming that by linear regression you mean the standard model minimizing the squared error (e.g. with ordinary least squares), then the objective function to minimize is
$$
\operatorname{SSE}(y, \hat y) = \sum_{i=1}^n (y_i - \hat y_i)^2
$$
To obtain a likelihood function, you would need a probability distribution. Usually we maximize the log-likelihood (or minimize the negative log-likelihood), rather then pure likelihood. The distribution that is equivalent to minimizing squared errors would be
$$
\log p(y) \propto \sum_{i=1}^n -\frac{(y_i - \hat y_i)^2}{\sigma^2}
$$
where the proportionality ($\propto$) is due the fact, that for optimization we can drop the normalizing constant (the distribution does not have to integrate to one). As you can see, we introduced a new parameter for $\sigma^2$ for the variance of the residuals. If you take $\exp$ of it, to reverse the $\log$ we took, and get rid of the negative sign, this is a normal distribution
$$
p(y) \propto \exp\Big(-\frac{(y-\mu)^2}{2\sigma^2}\Big)
$$
So, minimizing sum of squared errors is equivalent to maximizing the Gaussian likelihood. The above is a different way of saying, that the linear regression model assumes normally distributed noise $\varepsilon$ that has mean of zero,
$$\begin{align}
y &= \beta_0 + \beta_1 x + \varepsilon \\
\varepsilon &\sim \mathcal{N}(0, \sigma^2)
\end{align}$$


text:
Q: Find html tags using RegEx in JavaScript I need to fing all "table" tags on page with attribute border on the page using Regular Expressions on JavaScript.
How can I do it?
P.S. Please, don't propose me any JQuery (or similar) solutions.

A: Use this code
 document.querySelectorAll("table[border]")

A: you can use regex object like this to match table which has border.
myTableElement.match(/<table.*?border.*?>.*?<\/table>/gi)

or like this
var x =  new RegExp(/<table.*?border.*?>.*?<\/table>/gi)

myTableElement.match(x);


text:
Q: Linking new Google Apps Marketplace application with an existing Chrome Web Store application I have an existing Chrome Web Store listing with many active users (Over 10k).
I have created a new Google Apps Marketplace application that support OAuth2.0.
The existing listing already have a manifest.json file.
It has an 'apps' definition as it's an installable chrome app:
"app": {
  "urls": ["http://www.mysite.com/landing_page"],
  "launch": {
    "web_url": "http://www.mysite.com/chrome_login"
  },
}

As instructed in the google apps marketplace publishing guide I've added the following information to the manifest file:
  "container": ["DOMAIN_INSTALLABLE"],
  "api_console_project_id": "<app_id>"

Unfortunately after doing this my application disappears from the chrome web store (Although I can see it in the new Google Apps Marketplace list).
I need a way to have both the Chrome Web Store and the Apps Marketplace link to the same listing (so they will share the user count).
I've seen some applications, e.g 'MindMeister', that have achieved this so I know that it is possible.
Could someone please advise me on how to configure this correctly?

A: After communicating this issue with Google's support the answer is that this is currently impossible to have a single listing published both for CWS and Google Apps Marketplace simultaneously.
Their best practice suggests to have two separate listings, one for each.


text:
Q: Jackson's @JsonView annotation does not work I annotated class User with @JsonView and when it returned I see all fields even than that not contains in view class. Here is my class
@Entity
@Table(name = "users")
public class User implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long userID;
@JsonView(View.Summary.class)
@Column(name="email")
private String email;
@JsonView(View.Summary.class)
@Column(name="user_name")
private String firstName;
@JsonView(View.Summary.class)
@Column(name="user_last_name")
private String lastName;
@JsonView(View.Summary.class)
@Column(name="phone")
private String phone;
@JsonView(View.Summary.class)
@Column(name="origin")
private String address;
@JsonView(View.Summary.class)
@Column(name="birth_date")
private Long birthDate;
@JsonView(View.Summary.class)
@Column(name="gender")
private Long gender;
@JsonView(View.Summary.class)
@Column(name="about_me")
private String aboutMe;
@JsonView(View.SummaryWithPhoto.class)
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="photo")
private Photo avatar;
@JsonView(View.SummaryWithSession.class)
@Transient
private UserSession session;

//getters and setters

Here is my View class
public class View {
public interface Summary {}
public interface SummaryWithPhoto extends Summary {}
public interface SummaryWithSession extends SummaryWithPhoto {}
}

SO then I request get method with @JsonView(View.SummaryWithPhoto.class) annotation I always get userID field but shouldn't. Here is endpoint code
@JsonView(View.SummaryWithPhoto.class)
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<User> getUser(@RequestHeader(value="Access-key") String accessKey,
                                     @RequestHeader(value="Secret-key") String secretKey)

A: I've spend a some debugging time with the same issue.
Results are:

*

*all fields are included by default if you do not change this behavior (see BeanSerializerFactory.processViews). To change default do:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);

*fields, marked by @JsonView omitted in result if controller method annotated with OTHER @JsonView (see FilteredBeanPropertyWriter.serializeAsField)
So for your use-case do not change default settings, annotate Long userID by @JsonView and getUser by any other (not the same) View.
Code com\fasterxml\jackson\core\jackson-databind\2.8.4\jackson-databind-2.8.4-sources.jar!\com\fasterxml\jackson\databind\MapperFeature.java
   * Feature is enabled by default.
   */
   DEFAULT_VIEW_INCLUSION(true)

is contradicted of blog https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring, so I have to look at code closer.


text:
Q: How to change d3 tooltip background color when mouseover dot? I need to change the tooltip background color when i mouseover the dot which is follow the color of dot. for example here, the background keep "lightsteeblue".
my dot color code is this:
.style("fill", function (d) { return myColor(d.HillName); })

my tooltip class:
div.tooltip {
    position: absolute;
    text-align: left;
    min-width: 80px;
    height: auto;
    padding: 2px;
    font: 16px tahoma;
    background: lightsteelblue;
    border: 0px;
    border-radius: 8px;
    pointer-events: none;
}

this is my color range for data:
var myColor = d3.scaleOrdinal()
            .range(d3.schemeCategory10);

this is where mouseover code:
.on("mouseover", function(d){
                div.transition()
                .duration(200)
                .style("opacity", 0.9);
                div.html("Hill name: " + d.HillName + "
" + "Latitude:" + d.Latitude + "°     " + "Longitude:" + d.Longitude + "°
" + "Osgrid:" + d.Osgrid + "
" + "Height:" + d.Height)
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY-28) + "px")
            })
 .on("mouseout", function(d){
                div.transition()
                .duration(500)
                .style("opacity", 0);
            });


text:
Q: viewing android app source code I was wondering, is there any way I could download an app from the google play store and view/modify the source code?
I'd like to break down some existing professional apps and see how they're designed, and possibly try to add features for personal use.
Is is possible to do this?  I imagine it would be a bit restrictive since programmers wouldn't want others to steal their source code and republish an app under another name.
Anyone have any insight on this matter?

A: I'd recommend checking out samples from https://developer.android.com/samples/index.html