text:
Q: Change image resource using attributes and themes I can't figure out how to change image resource of ImageButton in code. I have defined following theme in themes.xml:
<resources>
   <style name="MMTheme.Blue">
        <item name="playButtonImg">@drawable/play_button</item>
        <item name="pauseButtonImg">@drawable/pause_button</item>
   </style>
</resources>

Attributes are defined in attrs.xml:
<resources>
    <attr name="pauseButtonImg" format="integer"/>
    <attr name="playButtonImg" format="integer"/>
</resources>

Now I want to change the image resource of ImageButton. I can change it by:
playButton.setImageResource(R.drawable.play_button);

But I want use themes. How to change it using the playByttonImg attribute so I can use different images for different themes ?

A: Now I have solution for the original question:
public static int getStyledDrawableId(Context context, int attribute)
{
    TypedArray a = context.getTheme().obtainStyledAttributes(new int[] { attribute });
    int id = a.getResourceId(0, -1);
    return id;
}

It returns me a drawable id when I call for example: getStyledDrawableId(getContext(), R.attr.playButtonImg) . Context HAS TO have the selected theme set.
Attributes should be changed to reference format:
<resources>
    <attr name="pauseButtonImg" format="reference"/>
    <attr name="playButtonImg" format="reference"/>
</resources>

A: I still don't know how to access the styles from themes programaticaly, so I had to use a trick with two separate buttons. Each has own style and instead of changing image/style of one button, I am setting the visibility of two styled buttons.


text:
Q: Ant, Tomcat Build Error: java.lang.NoClassDefFoundError: org/apache/tomcat/util/buf/B2CConverter Tomcat Version: 7.0.20
I am attempting to work my way through the following Spring MVC tutorial:
http://static.springsource.org/docs/Spring-MVC-step-by-step/part1.html
In this tutorial, an ant build script is setup to deploy to tomcat using the manager.  However, I run into some problems when I try to run any of the tomcat tasks.
First off, in the tutorial, they still use org.apache.catalina.ant.InstallTask which is deprecated, so I changed to org.apache.catalina.ant.DeployTask.
Now the problem is that when trying to run the Tomcat tasks I get:
java.lang.NoClassDefFoundError: org/apache/tomcat/util/buf/B2CConverter
    at org.apache.catalina.util.Base64.encode(Base64.java:177)
    at org.apache.catalina.ant.AbstractCatalinaTask.execute(AbstractCatalinaTask.java:204)
    at org.apache.catalina.ant.AbstractCatalinaTask.execute(AbstractCatalinaTask.java:150)
    at org.apache.catalina.ant.ReloadTask.execute(ReloadTask.java:45)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:390)
    at org.apache.tools.ant.Target.performTasks(Target.java:411)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
    at org.apache.tools.ant.Main.runBuild(Main.java:809)
    at org.apache.tools.ant.Main.startAnt(Main.java:217)
    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
 Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.util.buf.B2CConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 21 more

So I Googled around a bit and found some information stating that tomcat-utils.jar should be in the class path so I added that into the fileset with the catalina-ant.jar but apparently the org.apache.tomcat.util.buf.B2CConverter class is not in there.
So next I started probing the jars with jar -tf to find out if any contained the class.  I found out that tomcat-coyote.jar had the class.  Even with including this in the fileset, the problem is not resolved.
Does anyone have any ideas?

A: This seemed to work for me (Tomcat 7.0.21, OS X):
<path id="catalina-ant-classpath">
  <fileset dir="${tomcat_dir}/lib">
    <include name="catalina-ant.jar"/>
    <include name="tomcat-coyote.jar"/>
    <include name="tomcat-util.jar"/>
  </fileset>
  <fileset dir="${tomcat_dir}/bin">
    <include name="tomcat-juli.jar"/>
  </fileset>
</path>
<taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask" classpathref="catalina-ant-classpath"/>
<taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask" classpathref="catalina-ant-classpath"/>
<taskdef name="list" classname="org.apache.catalina.ant.ListTask" classpathref="catalina-ant-classpath"/>

A: In order to get all the ant commands to work the manager url can be changed in the build.properties file instead of changing the url when defining the "list" target in the build.xml file.
tomcat.manager.url=http://localhost:8080/manager/text

A: I got this working by changing the classpath to
<path id="catalina-ant-classpath">
    <!-- We need the Catalina jars for Tomcat -->
    <!--  * for other app servers - check the docs -->
    <fileset dir="${appserver.lib}">
        <include name="catalina-ant.jar"/>
        <include name="tomcat-coyote.jar"/>
        <include name="tomcat-util.jar"/>
    </fileset>
    <fileset dir="${appserver.home}/bin">
                <include name="tomcat-juli.jar"/>
    </fileset>
</path>

A: Like Jason, I tried Aidan's answer and it did not work. With TomCat 7 the manager interface has changed a little. Instead of using /manager/list in the URL you have to use /manager/text/list. So I changed the list task in build.xml to the following:
<target name="list" description="List Tomcat applications">
    <list url="${tomcat.manager.url}/text"
             username="${tomcat.manager.username}"
             password="${tomcat.manager.password}"/>
</target>

I also had to add the "manager-script" role to my admin user so that it would have the proper privileges for this operation:
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <user username="admin" password="admin" roles="manager-gui,manager-script"/>

A: I found the same error when following the same tutorial.
I had to make 3 changes so that the targets run correctly.
First, change the build.xml "list" target to add the /text above mentioned:
<target name="list" description="List Tomcat applications">
    <list url="${tomcat.manager.url}/text"
          username="${tomcat.manager.username}"
          password="${tomcat.manager.password}"/>
</target>

Second, change the catalina ant classpath:
<path id="catalina-ant-classpath">
    <fileset dir="${appserver.home}/lib">
        <include name="catalina-ant.jar"/>
        <include name="tomcat-coyote.jar"/>
        <include name="tomcat-util.jar"/>
    </fileset>
    <fileset dir="${appserver.home}/bin">
        <include name="tomcat-juli.jar"/>
    </fileset>
</path>

And finally, add this to the tomcat-users.xml file:
<role rolename="manager-script"/>
  <user username="tomcat" password="s3cret" roles="manager-gui,tomcat,manager-script"/>

And then it worked for me =)

A: None of the other answer work for me. Instead I copied TOMCAT_HOME/lib/catalina-ant.jar, TOMCAT_HOME/lib/tomcat-coyote.jar, TOMCAT_HOME/lib/tomcat-util.jar and TOMCAT_HOME/bin/tomcat-juli.jar to the ANT_HOME/lib directory.
It seems like the classpathref doesn't include these files properly.

A: what worked for me was adding the four jar files to the build path
Run -> run configuration -> choose you program, select Classpath tab on the right, click User Entries, then add external 4 jars from the tomcat directory
After this my build.xml runs like before

A: I'm not sure why is this happening, but here's a workaround:
http://www.coderanch.com/t/553582/Tomcat/java-lang-NoClassDefFoundError-org-apache
I'm looking for the solution, once I get it I will try not to forget to post it in here.
I use opensuse.

A: I am on Mac OS X. This worked for me:
<!-- ============================================================== -->
<!-- Tomcat tasks - remove these if you don't have Tomcat installed -->
<!-- ============================================================== -->

    <path id="catalina-ant-classpath">
        <!-- We need the Catalina jars for Tomcat -->
        <!--  * for other app servers - check the docs -->
        <fileset dir="${appserver.lib}">
            <include name="catalina-ant.jar"/>
        <include name="tomcat-coyote.jar"/>
        <include name="tomcat-util.jar"/>
      </fileset>
      <fileset dir="${appserver.home}/bin">
        <include name="tomcat-juli.jar"/>
      </fileset>
    </path>

A: I new to Spring or even first use to tomcat, i'm just trying add classpath  to subsection tomcat task in build.xml (in every tomcat task) and i dont why, but its works.
<taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask">
    <classpath>
        <path location="${appserver.home}/lib/catalina-ant.jar"/>
        <path location="${appserver.home}/lib/tomcat-coyote.jar"/>
        <path location="${appserver.home}/lib/tomcat-util.jar"/>
        <path location="${appserver.home}/bin/tomcat-juli.jar"/>
    </classpath>
</taskdef>

A: After doing above changes and running "ant list", I got error as,
java.io.FileNotFoundException: ..../manager/text/list".
It was resolved by starting tomcat from its installation directory and not using eclipse to start it.
After starting tomcat, first try "localhost:8080" in the browser. This should display tomcats page. Then try running "ant list". It works and above issue is resolved.

A: I would suggest a minor modification to the previous answers.
Configuring a user to have both manager-gui and manager-script roles is strongly discouraged in the Tomcat 7 documentation 1.  It can leave your site open to CSRF attacks.
Defining separate users with different passwords for each role would be safer:
<role rolename="manager-"/>
<role rolename="manager-script"/>
<user username="admin-gui" password="s3cret1" roles="manager-gui"/>
<user username="admin-script" password="s3cret2" roles="manager-script"/>

In general, you only need to memorize the user name and password for the GUI user, so it's no burden to have a safer configuration.

A: Three Things-

*

*If using Tomcat 7.x
Change fileset for catalina-ant-classpath
<path id="catalina-ant-classpath">
    <!-- We need the Catalina jars for Tomcat -->
    <!--  * for other app servers - check the docs -->
    <fileset dir="${appserver.lib}">
        <include name="catalina-ant.jar"/>
    <include name="tomcat-coyote.jar"/>
    <include name="tomcat-util.jar"/>
  </fileset>
  <fileset dir="${appserver.home}/bin">
    <include name="tomcat-juli.jar"/>
  </fileset>

*change the user in tomcat-users.xml to give user permission as manager-script

*Change tomcat.manager.url property to http://localhost:8080/manager/text

A: Three Things-
If using Tomcat 7.x Change fileset for catalina-ant-classpath
    <path id="catalina-ant-classpath">
    <fileset dir="${appserver.lib}">
        <include name="catalina-ant.jar"/>
    <include name="tomcat-coyote.jar"/>
    <include name="tomcat-util.jar"/>
  </fileset>
  <fileset dir="${appserver.home}/bin">
    <include name="tomcat-juli.jar"/>
  </fileset>
</path>

change the user in tomcat-users.xml to give user permission as manager-script
Change tomcat.manager.url property to http://localhost:8080/manager/text

A: You just need to add catalina-ant.jar tomcat-coyote.jar and tomcat-util.jar from tomcat_home/lib/ directory to ant_home/lib/ directory

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compares Istio to Docker Swarm? Reading the documentation about Istio I come with this questions.
Which are the points where Istio And Docker Swarm works the same?
Also, which one is better in different scenarios?

A: It's true that descriptions of Istio and Docker Swarm both refer the term "service mesh".
However, service mesh in Docker Swarm is more comparable to Services model seen  in Kubernetes, and the two orchestrators are generally comparable with respect to most features each of them has. In both of the orchestrators' service routing only touches network layers, and doesn't have a visibility into e.g. HTTP protocol.

Please note that Kubernetes Ingress API should be considered separately, it actually sits above the service model, and is in fact implemented by an external controller, e.g. Traefik or HAProxy, and actually Istio brings another implementation of ingress controller.

While Istio is (approx) one level above an orchestrator, right now it runs only on Kubernetes, but it will very likely support Docker Swarm along with other popular orchestrators in the future.
More specifically, Istio's service mesh is much more advanced than what Docker Swarm offers (and, by analogy, what Kubernetes Services offer), e.g. it enables fault injection, and transparent TLS, among many other features.

A: Docker Engine swarm mode makes it easy to publish ports for services to make them available to resources outside the swarm. All nodes participate in an ingress routing mesh. The routing mesh enables each node in the swarm to accept connections on published ports for any service running in the swarm, even if there's no task running on the node. The routing mesh routes all incoming requests to published ports on available nodes to an active container.
Istio is an open platform to connect, manage, and secure services. Essentially, its an open service mesh, where we would like developers and operators to not have headaches about how to connect services, how to think about making them resilient, how to secure them, and how to manage the runtime. We would like Istio to be able to do that for developers and operators across all environments and clouds. And, when I say services its really all kinds of services not necessarily just micro. It could be anything like you are building MySQL API service, a really small micro-service within your application for payment or shopping, in any given language. So, istio takes an approach of working with a polyglot environment. You know, no matter which language you write your services in and where you have deployed, Istio would like to give you a uniform substrate between your application and network, which can take care of connectivity between services, resiliency between services. So resiliency includes things like retries, failover, all of the good stuff , and distributed systems securing services. We think internal services should be as secure as external once, so security by default. And, have complete observability and visibility of metrics all the way from L3 to L7 across all your services.
Essentially think about layer (some people called it L5) which is basically a layer between your application and network. And, when you think about it, you are basically creating, we are injecting the a proxy next to every service. And, those are in the data path of all service-to-service communication. They are all interconnected and also connected to a common control plane. And, that interconnected set of proxies which are living next to every service is what typically is being called as Service Mesh The reason it is so interesting is that once you think of mesh as a layer which exist as a network does, you can, at the application layer offload things like connectivity, resiliency, visibility to that layer. So, historically you could do this in either application libraries as if you are building in java, python or go there's bunch of libraries in each of these languages that you could import and write a logic into it. Or you could do L3 layer security and policy like IP white-listing, firewall rule setup, VPN networking, VPN peering, and so on. So, we think service mesh is a space between the two that can offload few things from L7 and give policy-driven contracts to operate your network. So, Istio service mesh is much better than the Docker Swarm service mesh.

A: It's an apples to oranges comparison in many respects. Istio (currently) runs on top of Kubernetes, a container orchestrator like Docker Swarm.


text:
Q: Two ordinates - gray tick lines overlay black axis line I want to plot two data series with different y-coordinates over the same x. Therefore a second ordinate is drawn with a second axis environment. When I now limit the range to be drawn, the gray tick lines of the second plot overlay the black axis line of the first one. Is there a way to adjust this or to change the color of the tick lines to black (workaround, but would be okay for me). See the following minimal code sample and the cropped image below.
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}
    \begin{tikzpicture}
    \begin{axis}[
    axis x line*=bottom,
    axis y line*=left,
    xmin=0,
    xmax=1,
    ymin=0,
    ymax=1
    ]
    \end{axis}
    \begin{axis}[
    axis x line*=top,
    axis y line*=right,
    xmin=0,
    xmax=1,
    ymin=0,
    ymax=1
    ]
    \end{axis}
    \end{tikzpicture}
\end{figure}
\end{document}

A: Use the option every tick/.style={black} to control tick color. You can add as many specifications as you want, e.g., color, line width, ..etc.
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}
    \begin{tikzpicture}
    \begin{axis}[
    axis x line*=bottom,
    axis y line*=left,
    xmin=0,
    xmax=1,
    ymin=0,
    ymax=1
    ]
    \end{axis}
    \begin{axis}[
    axis x line*=top,
    axis y line*=right,
    every tick/.style={black},
    xmin=0,
    xmax=1,
    ymin=0,
    ymax=1
    ]
    \end{axis}
    \end{tikzpicture}
\end{figure}
\end{document}

Ultra zoomed picture:


text:
Q: How to draw noncontinuous lines with one vertex array I want to draw using gldrawarray in opengl es with a vertex array of 33 numbers, which is 11 points in 3D. And I also want to add the points into the vertex array by 33*n, so I need to draw many same shapes using each 11 points in the vertex array which contains more than 11 points. How can I do that?

A: Use the first and count parameters to issue multiple draw calls, one per object:
int verticesPerObject = 11;
for(int i = 0; i < totalVerticesInArray; i += verticesPerObject)
{
    glDrawArrays(GL_LINE_LOOP, i, verticesPerObject);
}


text:
Q: Unable to open SQLite database in golang: "unable to open database file [recovered]"-error I am just starting learning golang and am not sure if my error is conceptual or with the language.
It is peculiar, because the error only occurs, when unit-testing my code. If I "go run" everything works fine. As a sqlite-driver I use mattn/go-sqlite3.
Here is where the problem occurs:
    func dbExec(command *string) {
    db, err := sql.Open("sqlite3", dbPath) // Path and driver are set correcrtly
    defer db.Close()
    if err != nil { //No problem here
        panic(err)
    }
    _, err = db.Exec(*command)
    if err != nil { //Here the errorNo14 "Unable to open the database file" occurs
        panic(err)
    }
 }

So it seems to me, that the database file can be found, but it can't be open because of other limits. I have no concurrency in all of my code. I have only one test-method so far, so even if the testing would be done concurrently, it would so far be only one thread. Maybe someone has an idea! The problem seems to basic, there really is not much more to my code then this.

A: sql.Open usually does not perform any database operations, it merely initializes the driver (see sql.Open docs for details). The driver's Open() method is called in the background.
This means that the first error is usually encountered on trying to perform an operation, in your case: the db.Exec.
As for the actual error: if this is in tests it is likely that your path is not correct (eg: if the test database is in the test's sub-directory, the test runner's current directory will be different, I think). Try to switch to absolute paths (or paths computed at runtime).
And a small nit: move defer db.Close() after the first error check.


text:
Q: Libgdx and android studio EDIT: I fixed it, the problem was that I was not using the same android api and sdks as the ones used by libgdx.
I am trying to build my first libgdx project on android studio but I get an error:
A build operation failed. 'void org.apache.commons.compress.archivers.zip.ZipFile.<init>(java.nio.channels.SeekableByteChannel)' 'void org.apache.commons.compress.archivers.zip.ZipFile.<init>(java.nio.channels.SeekableByteChannel)'
image of the error
I am using the latest version of android studio, the latest libgdx setup tool and jdk 18.
The following is my build.gradle file
`buildscript {
repositories {
    mavenLocal()
    mavenCentral()
    gradlePluginPortal()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    google()
}
dependencies {
    classpath 'org.wisepersist:gwt-gradle-plugin:1.1.16'
    classpath 'org.gretty:gretty:3.0.7'
    classpath 'com.android.tools.build:gradle:7.2.2'
    classpath 'com.mobidevelop.robovm:robovm-gradle-plugin:2.3.16'

}

}
allprojects {
apply plugin: "eclipse"
version = '1.0'
ext {
    appName = "JumpMaster"
    gdxVersion = '1.11.0'
    roboVMVersion = '2.3.16'
    box2DLightsVersion = '1.5'
    ashleyVersion = '1.7.4'
    aiVersion = '1.8.2'
    gdxControllersVersion = '2.2.1'
}

repositories {
    mavenLocal()
    mavenCentral()
    google()
    gradlePluginPortal()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    maven { url "https://oss.sonatype.org/content/repositories/releases/" }
    maven { url "https://jitpack.io" }
}

}
project(":desktop") {
apply plugin: "java-library"
dependencies {
    implementation project(":core")
    api "com.badlogicgames.gdx:gdx-backend-lwjgl3:$gdxVersion"
    api "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
    api "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-desktop"
    api "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"
    api "com.badlogicgames.gdx-controllers:gdx-controllers-desktop:$gdxControllersVersion"
    api "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"

}

}
project(":android") {
apply plugin: "com.android.application"
configurations { natives }

dependencies {
    implementation project(":core")
    api "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
    natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
    natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a"
    natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
    natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64"
    api "com.badlogicgames.gdx:gdx-bullet:$gdxVersion"
    natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi-v7a"
    natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-arm64-v8a"
    natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-x86"
    natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-x86_64"
    api "com.badlogicgames.box2dlights:box2dlights:$box2DLightsVersion"
    api "com.badlogicgames.ashley:ashley:$ashleyVersion"
    api "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
    natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
    natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-arm64-v8a"
    natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"
    natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86_64"
    api "com.badlogicgames.gdx:gdx-ai:$aiVersion"
    api "com.badlogicgames.gdx-controllers:gdx-controllers-android:$gdxControllersVersion"
    api "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
    natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
    natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-arm64-v8a"
    natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
    natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86_64"

}

}
project(":ios") {
apply plugin: "java-library"
apply plugin: "robovm"
dependencies {
    implementation project(":core")
    api "com.mobidevelop.robovm:robovm-rt:$roboVMVersion"
    api "com.mobidevelop.robovm:robovm-cocoatouch:$roboVMVersion"
    api "com.badlogicgames.gdx:gdx-backend-robovm:$gdxVersion"
    api "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"
    api "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-ios"
    api "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-ios"
    api "com.badlogicgames.gdx-controllers:gdx-controllers-ios:$gdxControllersVersion"
    api "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-ios"

}

}
project(":html") {
apply plugin: "java-library"
apply plugin: "gwt"
apply plugin: "war"
apply plugin: "org.gretty"
dependencies {
    implementation project(":core")
    api "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion"
    api "com.badlogicgames.gdx:gdx:$gdxVersion:sources"
    api "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources"
    api "com.badlogicgames.box2dlights:box2dlights:$box2DLightsVersion:sources"
    api "com.badlogicgames.ashley:ashley:$ashleyVersion:sources"
    api "com.badlogicgames.gdx:gdx-ai:$aiVersion:sources"
    api "com.badlogicgames.gdx-controllers:gdx-controllers-core:$gdxControllersVersion:sources"
    api "com.badlogicgames.gdx-controllers:gdx-controllers-gwt:$gdxControllersVersion"
    api "com.badlogicgames.gdx-controllers:gdx-controllers-gwt:$gdxControllersVersion:sources"
    api "com.badlogicgames.gdx:gdx-box2d:$gdxVersion:sources"
    api "com.badlogicgames.gdx:gdx-box2d-gwt:$gdxVersion:sources"

}

}
project(":core") {
apply plugin: "java-library"
dependencies {
    api "com.badlogicgames.gdx:gdx:$gdxVersion"
    api "com.badlogicgames.gdx:gdx-bullet:$gdxVersion"
    api "com.badlogicgames.box2dlights:box2dlights:$box2DLightsVersion"
    api "com.badlogicgames.ashley:ashley:$ashleyVersion"
    api "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
    api "com.badlogicgames.gdx:gdx-ai:$aiVersion"
    api "com.badlogicgames.gdx-controllers:gdx-controllers-core:$gdxControllersVersion"
    api "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"

}

}
`
I tried rebuilding it several times and making new projects but for some reason my project won't build in android studio. I even tried in IntelliJ Idea but that didn't work either (im pretty sure that's because android studio is built off of intellij idea).


text:
Q: Taking twice the Fourier transform of a probability measure Take a function $f$ then and use the following definition of Fourier transform $\mathcal{F}$:
$$\mathcal{F}(f)(\xi) = \hat{f}(\xi)=\int_{-\infty}^{\infty} f(x) e^{-i \xi x} d x, \quad \forall \xi \in \mathbb{R} $$
One can prove that taking the Fourier transform twice leads to:
$$\mathcal{F}^2(f)(x) = 2 \pi f(-x)$$
a proof of this fact can be found at this post Fourier transform of the Fourier transform.
However now I am interested in Fourier transforms of probability measures. We know that if we let $\mu$ be a probability measure on $(\mathbb{R}, \mathcal{B})$. Its characteristic function $\phi: \mathbb{R} \rightarrow \mathbb{C}$ is defined by
$$
\phi(u)=\int_{\mathbb{R}} e^{\mathrm{i} u x} \mu(\mathrm{d} x)
$$
Now if we let the $f$ from above to be the density of $\mu$ then we see the equality:
$$\phi(u)=\hat{f}(-u)$$
Then we can play the same game as above and see that if we take again the Fourier we obtain again the density $f$ times $2 \pi$. But what happens if $\mu$ does not admit density?
Q: What object do we get if we take twice the Fourier transform of a probability measure that does not admit density?


text:
Q: How to find trailing and leading words of a word using R? I have a text document which has a million words. Now, I need to know how to find trailing and leading words of a word using R.
For example, If I want to find out the words that are coming before and after the word "error". It could be anything like following with leading words
"typo error"
"manual error"
"system error"

and with trailing words like
"error corrected"
"error found"
"error occurred"

Any idea how to do this? Thanks in advance for your inputs.

A: For words coming before error:
x <- "no error and no error and some error" # input

library(gsubfn)
rx <- "(\\w+) error"
table(strapplyc(x, rx)[[1]])

giving:
  no some
   2    1

Replace rx with the following for words after error:
rx <- "error (\\w+)"

A: My solution would be str_match_all:
library(stringr)
txt <- "system error corrected hardcore error detected wtf error holymoly"
str_match_all(txt, "\\s*(\\w+)\\serror\\s*(\\w+)")

[[1]]
     [,1]                       [,2]       [,3]
[1,] "system error corrected"   "system"   "corrected"
[2,] " hardcore error detected" "hardcore" "detected"
[3,] " wtf error holymoly"      "wtf" "holymoly"

A: How about this:
test <- c("I don't want to match error this This is a random error what I want to match")
# convert to a list
words <- strsplit((test),' ')
# get indexes that match 'error'
indexes <-   grep('error',words[[1]], perl=TRUE)

# select words that come after 'error'
words[[1]][indexes+1]
# before 'error'
words[[1]][indexes-1]


text:
Q: Seting a Curl command to run in a Zapier Webhook I'm trying to find the way to run cURL query in Zapier webhook, but I can't seem to figure it out. How would I enter this in the Webhook?
curl 'https://api.com/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: https://api.com' -H 'access_token: <my token>' --data-binary '{"query":"{\n  booking(booking_id: \"11111\"){\n    user{\n      name\n    }\n    body\n  }\n}\n"}' --compressed

This is the error I'm getting:

A: You need to put query in the left box under Query String Params. query is the key, the value is {\n booking(book.... You don't need quotes, either.


text:
Q: Pagination doesn't work after perform search I have a form in Laravel. I used pagination in this form and search option too. Pagination works fine when I didn't search anything. If I search something which has records more than 10 (my pagination record limit is 10), it shows result perfectly in first page but in second page or third page it shows the records of whole database. It's ignore the search criteria.
Controller Code:
public function index()
{
    if (Input::has('invoiceNumber')) {
        $invoiceNumber = Input::get('invoiceNumber');
        $invoices = Invoice::where('invoiceNumber','like', '%'.$invoiceNumber.'%')->orderBy('date','desc')->paginate(10);
    } elseif (Input::has('client')) {
        $client = Input::get('client');
        $invoices = Invoice::where('client','like', '%'.$client.'%')->orderBy('date', 'desc')->paginate(10);
    } elseif (Input::has('startDate') && Input::has('endDate')) {
        $startDate = Input::get('startDate');
        $endDate = Input::get('endDate');
        $invoices = Invoice::whereBetween('date', [$startDate, $endDate])->orderBy('date', 'desc')->paginate(10);
    } elseif (Input::has('startDate')) {
        $startDate = Input::get('startDate');
        $invoices = Invoice::where('date', $startDate)->orderBy('date', 'desc')->paginate(10);
    } elseif (Input::has('endDate')) {
        $endDate = Input::get('endDate');
        $invoices = Invoice::where('date', $endDate)->orderBy('date', 'desc')->paginate(10);
    } else {
        $invoices = DB::table('invoices')
            ->join('vehicles', 'invoices.vehicle', '=', 'vehicles.registration')
            ->select(
                'invoices.*',
                'vehicles.brand',
                'vehicles.model',
                'vehicles.seat',
                'vehicles.remarks'
            )
            ->orderBy('date', 'desc')
            ->paginate(10);
    }
    return view('invoice.index',compact('invoices'));
}

After performing search my URL look like this:
http://my-site.com/invoice?invoiceNumber=&client=&startDate=2016-01-01&endDate=2016-02-08

After this search when I click on page 2, the URL become this:
http://my-site.com/invoice?page=2

A: Try to use this bellow code (change as per your requirement)
return view('invoice.index')->withInvoices($invoices->appends(Input::except('page'));

Hope it's working for you...

A: In your view file, the render has to be like given below:
{!! $invoices->appends(Input::except('page'))->render() !!}

A: Simply use this on the result page.Pagination will be automatically visible at the bottom of the page
{!! $invoices->render() !!}


text:
Q: AVPlayer (and MPMoviePlayerController) tries to buffer the whole (streaming) video, runs out of memory I'm a new iOS developer, I'm working on a video player app for a video sharing site, where sometimes a recording consists of two video streams (one showing the presenter, the other showing the recording of his screen). I'm trying to play this second video with AVFoundation, creating an AVPlayer. With some videos it works very well, but with some others it runs out of memory. After lot of investigating I figured that it tries to buffer the whole video into the memory.
I've spent hours googling it, but couldn't find anything.
I created a small project just to demonstrate this:
github project. It sets up two AVPlayer's, for two different video streams, and updates the UI to show the loadedTimeRanges of the players' AVPlayerItem. For the first video it only buffers ~60 seconds, which is nice, but for the second video it keeps buffering.
self.player1 = [AVPlayer playerWithURL:url1];
self.player2 = [AVPlayer playerWithURL:url2];

and the two text labels:
self.data1.text = [NSString stringWithFormat:@"Player 1 loadedTimeRanges: %@",
                      self.player1.currentItem.loadedTimeRanges];
self.data2.text = [NSString stringWithFormat:@"Player 2 loadedTimeRanges: %@",
                      self.player2.currentItem.loadedTimeRanges];

Maybe this could be important: The over-buffering video does not have an audio track, just a video.
UPDATE: I reproduced the problem with using MPMoviePlayerController instead of AVPlayer, and checking the playableDuration property. With the first movie it stops around 60 seconds, with the second movie it keeps going and then it runs out of memory.
UPDATE2: I got the actual video files and put them up to Dropbox, and tried to stream those: then I don't have the problem! It buffers the whole movie, but it does not run out of memory. It only runs out of memory if I stream them from the original site (our video sharing site). The URLs are there in the github project.
I'm really looking forward to any hints what could cause this.
Thank you!

A: This problem is indeed caused by the lack of an audio track for video streams sent from Wowza media server. (I have inferred from your stream URLs that you're using Wowza media server to stream your videos).
To verify this issue, I created a 5 minute video file with no audio track.
mplayer -nolirc -vo null -ao null -frames 0 -identify test_60.mp4
...
Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family
Selected video codec: [ffh264] vfm: ffmpeg (FFmpeg H.264)
==========================================================================
ID_VIDEO_CODEC=ffh264
Audio: no sound
Starting playback...
...

Then I added a mp3 track to that video file using mp4box.
MP4Box -new -add test_60.mp4 -add test_music.mp3 test_60_music.mp4

And verified that there was indeed an audio track.
mplayer -nolirc -vo null -ao null -frames 0 -identify /tmp/test_60_music.mp4
...
AUDIO: 44100 Hz, 2 ch, floatle, 320.0 kbit/11.34% (ratio: 40000->352800)
ID_AUDIO_BITRATE=320000
ID_AUDIO_RATE=44100
ID_AUDIO_NCH=2
Selected audio codec: [ffmp3float] afm: ffmpeg (FFmpeg MPEG layer-3 audio)
==========================================================================
AO: [null] 44100Hz 2ch floatle (4 bytes per sample)
ID_AUDIO_CODEC=ffmp3float
Starting playback...
...

Then, I put both the test_60.mp4 and test_60_music.mp4 in the Wowza content directory, and tested them. I actually wrote a small test app similar to yours to examine the loadedTimeRanges, but just loading the videos via safari from the device should be sufficient to see the difference.
I opened wowza_server:1935/vod/mp4:test_60.mp4/playlist.m3u8 and pressed pause as soon as it started playing. The buffer indicator kept increasing until the full 5 minute video was loaded.
Then, I opened wowza_server:1935/vod/mp4:test_60_music.mp4/playlist.m3u8 and did the same, but only the first 1/5th (roughly 1 minute) was loaded.
So it seems like a problem with the Wowza server's packetization - note this problem does not happen for me on adobe (flash) media server 5.0. Only 60 seconds is buffered regardless of whether the video contains an audio track.
Hope that's helpful. I've asked for input from Wowza folks at the Wowza forums


text:
Q: tensorflow.compat in Google Colab not found I'm in Google Colab and I am trying to import tensorflow.compat but it says that it's missing the import.
I used !pip install tensorflow==2.11.0 and tried to install lower versions too. But Colab still can't find tensorflow.compat. How can I resolve this?


text:
Q: ¿ SUMA DE COLUMNAS DE DIFERENTES TABLAS POR MYSQL? soy nuevo en esto, y me pidieron hacer una actividad con mysql, tengo una base de datos pequeña con dos tablas donde una tiene informacion de clientes, nombre apellido, telefono, direc, y el dinero a prestar, y tengo otra tabla que tiene solo 3 columnas, id(del cliente que paga) el abono, y la fecha, el tema esta en que cuando hago la consulta para sumar los prestamos, y los abonos, me sale la consulta bien pero los valores son errados. y desconozco cual seria el erro, pls su ayuda.

A: Saludos y bienvenido a SO! te recomiendo revisar los links que te enviaron en los comentarios, allí se explica como preparar una pregunta con la información necesaria para que te puedan ayudar.
Volviendo a tu pregunta, tu consulta tiene dos problemas principales:

*

*Estas uniendo dos tablas sin indicar cual campo es el que las relaciona: si no colocas el/los campos de la relación en una clausula JOIN, MySQL va a usar todas las combinaciones posibles (los montos serán incorrectos).

*Si vas a usar una función de agrupamiento (SUM()) normalmente necesitas también usar la clausula GROUP BY: si no la usas, te dará un total global, en tu caso creo que la necesitas, para obtener el total de cada cliente.

Prueba cambiando la consulta así:
SELECT clientes.id,
       clientes.prestamo,
       SUM(prestamos.abono) total_abono
FROM prestamos
JOIN clientes ON clientes.id = prestamos.id
GROUP BY clientes.id, clientes.prestamo

Cambios:

*

*Se incluye el id del cliente: verás los prestamos y abonos por cliente

*En el FROM solo se coloca una tabla, la segunda se agrega con un JOIN indicando los campos de relación.

*En el GROUP BY debes colocar los campos que no estén en funciones de agrupamiento.

*Sugerencia: prueba cambiando JOIN por LEFT JOIN para incluir los clientes que no hayan hecho ningún abono.

(NOTA: yo trabajo con SQL Server, no MySQL, aunque creo que esta sintaxis que es idéntica)

A: ¿Qué tal si vamos un paso más allá y actualizamos ese campo calculado de saldo que tienes tan desactualizado?
UPDATE cliente JOIN (
    SELECT id,SUM(abono) abonos
      FROM prestamos
      GROUP BY 1
  ) c1 USING(id)
  set saldo=prestamo-abonos;

A partir de este dataset:
CREATE TABLE cliente(
  id int AUTO_INCREMENT PRIMARY KEY,
  nombre varchar(31),
  prestamo float,
  saldo float,
  fecha date
  );
CREATE TABLE prestamos(
  id_apunte int AUTO_INCREMENT PRIMARY KEY,
  id int,
  abono float,
  fecha date,
  FOREIGN KEY(id) REFERENCES cliente(id)
  );
INSERT INTO cliente (id, nombre, prestamo, fecha) VALUES
  (1005,'Jair',24000,NOW());
INSERT INTO prestamos (id, abono, fecha) VALUES
  (1005,2000,NOW()),
  (1005,1500,NOW());

Obtendrías:
+------+--------+----------+-------+------------+
| id   | nombre | prestamo | saldo | fecha      |
+------+--------+----------+-------+------------+
| 1005 | Jair   |    24000 | 20500 | 2022-08-21 |
+------+--------+----------+-------+------------+


text:
Q: Hide menu if user doesn't have access - CanCan I have one menu entry called "admin" with sub-entries "client", "users" and "sales". I then have 3 different roles (admin, manager, employee). Role "admin" can access "users" and role "employee" can access "client" and "sales". "Manager" can't access any option in the menu.
I'm able to hide other menus but as this have two different roles I'm having some issues... I'm using rails 3 with devise and cancan (with roles defined in User model).
For example, this works:
<% if can? :read, Client %>

Inside the menu entry I then evaluate each sub-entry to show/hide accordingly to the user role, and that also works. Following the same logic I tried this to hide the main entry, more than one role:
<% if can? :manage, (Client || User || Sales) %>

But this only evaluates the first one (in this case "Client"). Is it possible to do what I want? What's the best way to "evaluate" more than one role at the same time?

A: You can do what you want this way:
<% if can?(:manage, Client) || can?(:manage, User) || can?(:manage, Sales) %>

But I think in this case a better solution is just to check if the User is not a Manager. It is depending of how you save users roles. For example:
 <% if current_admin_user.role != 'Manager' %>


text:
Q: JPA/EclipseLink Error in Creating Tables I am trying to create a table using EclipseLink. The java class being used is :-
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Id;

@Entity
public class Submissions {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long Id;
 private String XID;
 private String Y;
 @Temporal(TemporalType.DATE)
 private Date uDate;
 private String level;
 private String state;

 public Submissions() {
 }

 //All Relevant getter and setter functions
}

The relevant persistence xml in question is as follows:-
<persistence-unit name="SubmissionIds">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>com.obp.selenium.DataObjects.OriginationSubmissions</class>
    <properties>

        <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
        <property name="javax.persistence.jdbc.url"
            value="jdbc:oracle:thin:@localhost:1521:orcl" />
        <property name="javax.persistence.jdbc.user" value="------" />
        <property name="javax.persistence.jdbc.password" value="------" />

        <!-- EclipseLink should create the database schema automatically -->
        <property name="eclipselink.ddl-generation" value="create-tables" />
        <property name="eclipselink.ddl-generation.output-mode"
            value="database" />
        <!-- <property name="eclipselink.canonicalmodel.subpackage"
            value="originationSubmissions" /> -->
    </properties>
</persistence-unit>

We use the standard method is by implementing the EntityManagerFactory as :-
EntityManagerFactory factory = Persistence.createEntityManagerFactory("SubmissionIds");
    EntityManager em = factory.createEntityManager();
    em.getTransaction().begin();
    em.getTransaction().commit();
    em.close();

However I keep getting the following errors :-

EL Warning]: 2017-04-07 14:04:53.768--ServerSession(1650327539)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
  Internal Exception: java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier
Error Code: 904
  Call: CREATE TABLE SUBMISSIONS (ID NUMBER(19) NOT NULL, XID VARCHAR2(255) NULL, Y VARCHAR2(255) NULL, LEVEL VARCHAR2(255) NULL, STATE VARCHAR2(255) NULL, UDATE DATE NULL, PRIMARY KEY (ID))
  Query: DataModifyQuery(sql="CREATE TABLE SUBMISSIONS (ID NUMBER(19) NOT NULL, XID VARCHAR2(255) NULL, Y VARCHAR2(255) NULL, LEVEL VARCHAR2(255) NULL, STATE VARCHAR2(255) NULL, UDATE DATE NULL, PRIMARY KEY (ID))")

A: Avtually Eclipse reported a bug that rises when there is a reserved word usage you can fine here :
https://bugs.eclipse.org/bugs/show_bug.cgi?id=260637.
the problem comes from using a reserved word I dont actually know your DBMS, if it is Mysql your attributs
XID and LEVEL
 is a reserved word. you can find mysql reserved word here :
 https://dev.mysql.com/doc/refman/5.7/en/keywords.html.
You can also se from the sql code used to build your tables that there is a column name update of type DATE

UDATE DATE NULL

So to my opinion, you also need watch your attribut name on uDate

A: The problem lay in the LEVEL named Field. @Chris has suggested the correct answer in the comment. "LEVEL" is a reserved word and cannot be used as a column name. Add the column annotation to your level attribute and name it something else in the table for this to work, or just give the attribute a different name.
Changing the field name worked easily.

A: This is very often due to the use of keywords as a column or table name.
For columns you can use @Column(name = "new_name_with_keywords")


text:
Q: How to use Stripe payouts with customer invoices I have a question about how to implement proper payouts for my system/platform.
Let me explain a little further. I have a platform like Lyft, but instead of creating and issuing charges right after each ride. I'm creating invoice items, so that the rider is only charged once every invoice billing cycle(ex. every 2 weeks). Now, I understand there is no destination id for an invoice or invoice item using Stripe. So I need to tell Stripe somehow what funds need to go to the driver. How do I do that? It seems like the method would be to create a Stripe payout with the destination as the drivers bank account id. But after attempting this with both the drivers external acount id and the bank account id, Stripe threw an exception saying 'No such external account exists acct_123456ABCD'
Would the method I described above be the correct way to implement this? Or is there a better way or more prescribed way?
FYI - To understand why I'm creating invoice items, instead of instant charges immediately after a ride, it's because the charges for my service are all very small ($1.00-$3.00), so to avoid a Stripe flat fee of $.30/charge I'm aggregating them into an invoice, where there will be only one flat fee per billing cycle.
Thanks for any help.
For ex purposes I'll include an example of what I'm doing below.
First I create an invoice item, then I create a payout.
            var invoiceItemOptions = new StripeInvoiceItemCreateOptions()
            {
                Amount = tipPricing.GetTotalAmountCharged(),
                Currency = "USD", //defaultCard.CurrencyCode,
                CustomerId = '12334567',

                Metadata = new Dictionary<String, String>() { { "EventId", 123 } }
            };

            var invoiceItemService = new StripeInvoiceItemService();
            StripeInvoiceLineItem invoiceItem = invoiceItemService.Create(invoiceItemOptions);
            StripeResponse invoiceResponse = invoiceItem.StripeResponse;

            ////////////////////////////////////////////////////////////////////////

            var payoutOptions = new StripePayoutCreateOptions()
            {
                Amount = tipPricing.GetTotalDestinationAmount(hasBeenChargedThisMonth),
                Currency = "USD",
                Destination = bankAccount.ExternalAccountId, //bankAccount.AccountId,
                Metadata = new Dictionary<String, String>() { { "EventId", 123 } }
            };
            var payoutService = new StripePayoutService();
            StripePayout payoutCharge = payoutService.Create(payoutOptions);
            StripeResponse payoutResponse = payoutCharge.StripeResponse;

A: Payouts are intended to happen on the Connected Account's Balance -> Bank Account, rather than from your Platform to the Connected Account's Bank Account.
You've got at least two choices for funds flows here:

*

*You could run the Invoices (or even a $0 subscription with a two week billing cycle) on your Platform. You could listen for webhooks when invoice.payment_succeeded, then move the funds to the destination connected account using a Transfer, see https://stripe.com/docs/connect/charges-transfers. From the Connected Account's balance it will pay out to their bank account, or you can initiate a Payout (if on manual payouts, https://stripe.com/docs/connect/payouts#using-manual-payouts)

*You could create an Invoice Items / Invoices or a Subscription directly on the Connected Account. This gets slightly tricker as you will need to remit the fee for your platform, but you can do that with Application Fees, see https://stripe.com/docs/connect/subscriptions#working-with-invoices


text:
Q: How to read attribute value having special character in html I have a requirement where I am getting id from a json response.
 id="TICKET NUMBER (TK)"
The html component contains an attribute CI which has same value as ID.
When I am trying to access any attribute using ID, I am getting error as "unrecognized expression"
This is because of the special character present in Id.
Below is my sample html

  Ticket

    <input  id="ticket"  ng-model="Ticket" >

Please help me on resolving the issue.

A: @Jefrey is correct, id shouldn't have spaces. Though you can access it using \\ before spaces and special characters:-
$('#TICKET\\ NUMBER\\ \\(TK\\)')

DEMO

$('#TICKET\\ NUMBER\\ \\(TK\\)').css('border', '1px solid red')

<input type="text" id="TICKET NUMBER (TK)" />

A: Please note the id attribute can't have spaces (source).

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

Consider using just the CI attribute. If you must identify the element through its ID attribute, consider MD5-ing the ID first.


text:
Q: Current Location(on Google Maps API) not showing in app We have the Google Maps API working; however, current location will not show up in our app but will show up when redirected to Google Maps(app). We want the blue dot to show up in our app and not just when it is forwarded to Google Maps(app).
Here are some code snippets (we are using Android Studio V2.3.3):
Can anyone offer any guidance, please?
Here is our MapActivity.java
package com.example.administrator.bubbleproject;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng losAngeles = new LatLng(34.0522, -118.2437);
        mMap.addMarker(new MarkerOptions().position(losAngeles).title("Los Angeles"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(losAngeles, 18.0f));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mMap.setMyLocationEnabled(true);
    }
}

Here is our Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.bubbleproject">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="BUBBLE"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:parentActivityName="com.example.administrator.bubbleproject.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".tracker1PageActivity"
            android:parentActivityName=".MainActivity" />

        <activity android:name=".settingsActivity" />
        <activity android:name=".setupActivity" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
        <activity
            android:name=".MapActivity"
            android:label="@string/title_activity_map">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Here are some screenshots of My app and Forwarded to google maps.

A: My guess is that in OnMapReady() your permission check is failing and it's executing the return; instead of calling mMap.setMyLocationEnabled(true); Set a breakpoint and check it.
My code to check this looks like the following:
public static boolean haveLocationPermission(Context context)
{
    return ContextCompat.checkSelfPermission(context, permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
               ContextCompat.checkSelfPermission(context, permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}

Then call this snippet when you want to check permission:
// Enable my location if we have permission
if (haveLocationPermission(getActivity()))
{
    try
    {
        mMap.setMyLocationEnabled(true);
    }
    catch (SecurityException e) {}
}

We also have Location Services turned on, but I'm not sure whether that is necessary for the map to show location (use GoogleApiClient with the LocationServices.API).
Edit:  From the duplicate issue it looks like you do need Location Services turned on.  https://stackoverflow.com/a/34582595/1022886


text:
Q: Is there a way to automatically deliver rucksacks to your homestead from a vehicle? In the first State of Decay, you could automatically deposit all rucksacks from your trunk to your homestead by parking the vehicle in the parking space outside of your homestead.  Is there any way of doing that in State of Decay 2? I tried parking in the space designated but nothing happened and it doesn't look like I can upgrade the parking space to do this. Right now I'm having to make 6 trips back and forth.

A: If you park in the spot, and open the trunk, you can transfer one item at a time without walking back and forth. On Xbox, it's RT. On PC it is T for transfer.


text:
Q: Branded / Opaque type for aliasing any in Typescript I am use to build TS code using branded types with this little snippet
type Brand<Base, Brand> = Base & { __brand: Brand }

and this way emulate nominal typing
type Euro = Brand<number, "Euro">
type Dollar = Brand<number, "Dollar">
let e: Euro ;
let d: Dollar;

d = e // Type Euro is not assignable to type Dollar

I'd like to know if I could do the same with the any type and brand it in order to distinguish in my codebase the different usecases of this infamous any such as
type NeedCodec = Brand<any, "NeedCodec">
type TodoLater = Brand<any, "TodoLater">

let x: NeedCodec;
let y: TodoLater;

x = y // sadly works

I understand that any is kind of the joker type and once its encounter loose the type system, but I would like to know if there is a way to distinguish 2 any types.
I want that because I dont want the name to be resolved in any but keep the original name NeedCodec.

I want in the hover to have x: NeedCodec
Thanks in advance for you help


text:
Q: ASP.NET Core Fetch POST FormData() application/x-www-form-urlencoded I want to validate.
The controller does not want to receive data.
Eat remove ValidateAntiForgeryToken, then accepts null.
In view Html.AntiForgeryToken().

Here is my code:
getDataTable = async (e) => {
    try {
        const { Login, Password } = this.state;
        var data = new FormData();
        data.append("Login", Login);
        data.append("Password", Password);
        data.append("__RequestVerificationToken", this.props.__RequestVerificationToken);
        const response = await fetch(urlControlActionAccountLogin, {
            method: "POST", // *GET, POST, PUT, DELETE, etc.
            mode: "cors", // no-cors, cors, *same-origin
            cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
            credentials: "same-origin", // include, *same-origin, omit
            headers: {
                "Accept": "application/json, application/xml, text/plain, text/html, *.*",
                //"Content-Type": "application/json",
                "Content-Type": "application/x-www-form-urlencoded",
            },
            redirect: "follow", // manual, *follow, error
            referrer: "no-referrer", // no-referrer, *client
            body: data, // body data type must match "Content-Type" header
        });
        const json = await response.json();
        //this.setState({ textarea: json.description });
        this.setState({
            isLoaded: true,
        });
        console.log(json);
    } catch (error) {
        this.setState({
            isLoaded: true,
            error
        });
        console.error(error);
    }
};

C# Controller ASP.net core 2.2
JS should send the login password data, and the controller will accept
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm]string _model) //[FromBody]LoginModel model
{
    var model = JsonConvert.DeserializeObject<LoginModel>(_model); //[FromForm]string _model
    //var model = _model.ToObject<LoginModel>(); //[FromForm]JObject _model
    var a = db.GetUserContext();

    if (ModelState.IsValid)
    {
        User user = await db.Users.FirstOrDefaultAsync(u => u.Login == model.Login && u.Password == model.Password);
        if (user != null)
        {
            await Authenticate(model.Login); // аутентификация

            return Json(new
            {
                user
            });
        }
        ModelState.AddModelError("", "Некорректные логин и(или) пароль");
    }
    return View(model);
}

A: Since you are sending data using FormData the Content-Type of your request should be application/form-data. But as you can see in browser network tab there is some strange values between the actual data values
-----WebKitFormBoundarySomeValue

This is a boundary separating your data entries. And the actual value of Content-Type header should be application/form-data; boundary=-----WebKitFormBoundarySomeValue. Since this value is generated randomly by a browser you cannot set it manually and you should just omit Content-Type header, browser will set it for you.
headers: {
    "Accept": "application/json, application/xml, text/plain, text/html, *.*"
    //no content-type
}

In your controller code use [FromForm] attribute to read request data as form data. And you should abandon using Consumes attribute in this case since you cannot specify correct Content-Type value because it varies between requests.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm]LoginModel model)


text:
Q: How do I make a full journal in Latex? I'm working on putting together multiple different articles and I want them to be put together you know like normal articles would, the only problem is I'm trying to do it on one Latex document and I'm struggling with titles and what not.
Maybe there's an easy fix I'm missing but I'm really struggling. Here's what I have so far.
\documentclass{book}

\usepackage[svgnames]{xcolor}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{titling}

\usepackage{blindtext}
\usepackage{amssymb}
\usepackage{amsthm}

%----------------------------------------------------------------------------------------
%   TITLE PAGE
%----------------------------------------------------------------------------------------

\newcommand*{\titleAT}{\begingroup % Create the command for including the title page in the document
\newlength{\drop} % Command for generating a specific amount of whitespace
\drop=0.1\textheight % Define the command as 10% of the total text height

\rule{\textwidth}{1pt}\par % Thick horizontal line
\vspace{2pt}\vspace{-\baselineskip} % Whitespace between lines
\rule{\textwidth}{0.4pt}\par % Thin horizontal line

\vspace{\drop} % Whitespace between the top lines and title
\centering % Center all text
\textcolor{Black}{ % Red font color
{\Huge High School Journal}\\[0.5\baselineskip] % Title line 1
{\Large OF}\\[0.75\baselineskip] % Title line 2
{\Huge \ Mathematics}} % Title line 3

\vspace{0.25\drop} % Whitespace between the title and short horizontal line
\rule{0.3\textwidth}{0.4pt}\par % Short horizontal line under the title
\vspace{\drop} % Whitespace between the thin horizontal line and the author name

{\Large \textsc{Vol. 1, June 1, 2017}}\par % Author name

\vspace*{\drop} % Whitespace under the publisher text

\rule{\textwidth}{0.4pt}\par % Thin horizontal line
\vspace{2pt}\vspace{-\baselineskip} % Whitespace between lines
\rule{\textwidth}{1pt}\par % Thick horizontal line

\endgroup}

%----------------------------------------------------------------------------------------
%   BLANK DOCUMENT
%----------------------------------------------------------------------------------------

\begin{document}

\pagestyle{empty}

\titleAT % This command includes the title page

\newtheorem{theorem}{Theorem}
\newtheorem{lemma}{Lemma}
\newtheorem*{remark}{Remark}

\theoremstyle{definition}
\newtheorem{definition}{Definition}

\vspace{100mm}

\tableofcontents

\newpage

HS JOURNAL MATH FELLOWSHIP:

We at the High School Journal of Mathematics are very excited to announce the establishment of the first official High School Journal of Mathematics Fellowship. This Fellowship gives five high school students from around the world the opportunity to undertake high quality mathematical research under the tutelage of professional mathematicians or grad students in math.

This fellowship allows high school students to spend seven months studying, conversing with their mentors, and creating new mathematics which will eventually culminate in a final paper which will be published in the High School Journal of Mathematics.

The fellowship begins on October 1st with the research projects to be submitted on May 1st of the following year.

The advantages of this program are many. Firstly, it allows students to conduct mathematical research at an advanced age and prepares them for mathematical research which they will conduct later in life. Secondly, students can submit their projects to Siemens, Davidson Fellowship, Google Science fair, and the Regeneron Science Talent Search. Thirdly, research projects can greatly help with college admissions.

An application can be filled out and submitted at any time between now and September 1st, with all decisions and parrings to be made during the month of September. The application consists of the following:

APPLICATION:

Your name:

Your city of residence (does not affect decision):

Your age (must be between 14 and 18 years old to apply):

Grade (must be between 9 and 12 next school year):

School:

Email:

Gender:

List all of your relevant math experiences (Articles published, blogs, contests won, math camps, etc.).

List the three specific areas of mathematics in which you are most interested in pursuing research.

Most advanced math courses taken (with grades, indicating where you took them):

Your favorite proof/theorem in mathematics and why:

Why you think you're qualified to undertake this project (approximately 300 words):

All of these will factor into acceptance. Note that each application will be checked thoroughly and any cases of lying or deceit will result in immediate disqualification and the notification of your school and/or parents.

It should be noted that neither gender nor race will bear any part in whether or not you're accepted into the program, it will be strictly a merit-based program. Also note that if an applicant is not accepted into the program this year he/she should feel free to apply in future years. We may favor older students who are nearing the end of their high school career.

\newpage

\title{A Recursive Way to Calculate P(n)}
\author{Shaun Schoeman}
\date{April 2017}

\maketitle

\section{A Recursive Way to Calculate P(n)}

The partition function, $p(n)$ , is a function which takes an input $n$ and returns the number of partitions of $n$ i.e. the number of different ways one could write out $n$  as the sum of other non-negative integers without regarding the order of the summands or added summands of $0$.

Conventionally, any partition of $n$ is written out as $n=t_1+t_2+...+t_k$ with $(t_k\leq...\leq t_2\leq t_1\leq n)$. For this paper we will be focusing on a specific type of partition, namely di-partitions.

\begin{definition}
A di-partition of $n$ consists of two positive integers summing to $n$.
\end{definition}
Let $\Delta(n,i)$ denote the $i^{th}$ di-partition of $n$. Then
$n=\Delta(n,i)=s_1+s_2$ and let $(s_2\leq s_1<n)$ for convention.
At the moment it means nothing to talk about the $i^{th}$ di-partition of $n$ as we have not yet ordered di-partitions. So, let us order them according to decreasing values of $s_1$, which also means increasing values of $s_2$. Ordering di-partitions this way is an arbitrary choice, and choosing to order them differently would only result in different expressions of $s_1$ and $s_2$ in terms of $n$ and $i$. With our current way of ordering, we obtain {\Delta}(n,i)=(n-i)+i.

\begin{theorem}
$i\leq n-i$ must be true according to the bounds on $i$.
\end{theorem}
\begin{proof}
By definition, it is obvious that the minimum of $i$ be at least $1$ and the maximum be equal to the total number of unique di-partitions of $n$. We can then see that for any even $n$, this number is $\frac{n}{2}$
and for any odd $n$, $\frac{n-1}{2}$. Thus,  $i$'s bounds are $1\leq i \leq \lfloor{\frac{n}{2}}\rfloor$. Multiplying through by $2$ gives
$$2\leq 2i \leq 2\lfloor\frac{n}{2}\rfloor$$
Observe $n-1\leq 2\lfloor \frac{n}{2}\rfloor  \leq n$. Since $2i$ increases from either $n-1$ to $n+1$ or from $n$ to $n+2$ as $2i$ extends $2\lfloor \frac{n}{2}\rfloor$, we see that $n$ achieves the same restriction on $2i$ as $2\lfloor \frac{n}{2}\rfloor$. Thus, we can accurately say that $2\leq 2i \leq n$ which gives
$$2-i\leq i\leq n-i$$
completing the proof.
\end{proof}
With the fact that $1\leq i$, we clearly see that $2-i\leq 1$. As earlier said, the lower bound of $i$ must be at least $1$, and so here again it must be $1$. Thus,
\begin{equation}
\label{i's_bound}
1\leq i \leq n-i
\end{equation}
\subsection{Breaking down di-partitions}
Observe $n=\Delta(n,i) = (n-i) +i$. This is considered as the breaking down of $n$ into its di-partitions. To break it down further all terms formed must be broken down the same way.
\begin{equation}
\label{next_break}
n=\Delta(n-i,a)+\Delta(i,b)=(n-i-a)+a+(i-b)+b
\end{equation}
with some non-negative integers $a,b$.

There are now more, and obviously smaller, terms which have been formed. This process of breaking down $n$ can be repeated until we are inevitably left with $n$ many terms of $1$, as $1$ cannot break down any further. This is called completely breaking down $n$, and can be summarized by

\begin{equation}
\label{completely_break}
\Delta(n,i)=\sum_{a=1}^{n-i-a}[\Delta(n-i,a)] + \sum_{b=1}^{i-b}[\Delta(i,b)]
\end{equation}

This equation undoubtedly finds many duplicates as well as unique partitions of $n$.

\begin{definition}
A duplicate is a partition which has been previously formed during the process of completely breaking down $n$, whereas a unique partition has not.
\end{definition}

\begin{theorem}
All partitions of $n$, not necessarily all unique, are revealed when completely breaking down $n$.
\end{theorem}
The significance of this theorem is to give us reasonable motivation to explore further. We need to know that equation \ref{completely_break} at least gives us all possible partitions of $n$ before we deem it worthwhile to investigate eliminating the duplicates formed.
\begin{proof}
Each time we break down a term according to equation \ref{completely_break}, another partition of $n$ is revealed; whether new or a duplicate of one previously formed.

The argument follows: take all partitions of $n$ with $x$ many terms. Within each said partition, break each term down into all of its di-partitions; one term at a time, one partition at a time. This will definitely reveal, in total, all possible (including duplicate) partitions of $n$ with $x+1$ many terms. Setting $0<x<n$ and applying the argument for all set values of $x$ clearly completes the proof.
\end{proof}
\begin{lemma}
\label{T2}
If $\Delta(n,i_1)=\Delta(n,i_2)$, then whichever di-partition has a greater value between $i_1,i_2$ is a duplicate.
\end{lemma}
\begin{proof}
The way in which we have chosen to order di-partitions can be described as according to increasing values of the second input in the $\Delta$ function. The process of completely breaking down $n$ follows this same order, which can be clearly seen. Thus, the di-partition with a lesser value between $i_1,i_2$ will have been formed before the one with a greater value, which concludes the proving argument.
\end{proof}
\begin{theorem}
\label{T3}
Any partition formed during the process of completely breaking down $n$ must appear in descending order for it to not be a duplicate.
\end{theorem}
\begin{proof}
In other words, this theorem states that within equation \ref{next_break}, $b\leq i-b\leq a\leq n-i-a$ must be true so that $\Delta(n,i)$, given by equation \ref{completely_break}, does not reveal a duplicate partition of $n$. We already know from equation \ref{i's_bound} that $b\leq i-b$ and $a\leq n-i-a$. What is then left for us to prove is that $i-b\leq a$.

Observe equation \ref{next_break}, $\Delta(n,i)=(n-i-a)+a+(i-b)+b$. Summing the first and third terms then the second and fourth gives
$$\Delta(n,i)=(n-a-b)+(a+b)=\Delta(n,a+b)$$
From lemma \ref{T2} we see that $i\leq a+b$ which completes the proof.
\end{proof}
\begin{theorem}
\label{term_right}
The term on the right of each di-partition must not break down or else will reveal a duplicate.
\end{theorem}
\begin{proof}
To prove this theorem we simply need to prove that within equation \ref{completely_break}, $b=0$. This can be done similary to proving the previous theorem. Observe equation \ref{next_break}, $\Delta(n,i)=(n-i-a)+a+(i-b)+b$. Summing the first three terms gives
$$\Delta(n,i)=(n-b)+b=\Delta(n,b)$$
From lemma \ref{T2}, we require $i\leq b$, which clearly contradicts equation \ref{i's_bound}. Therefore, at least one of $a,b=0$ in order to avoid this contradiction. If we set $b\neq 0$, then $a=0$ from what we previously proved, meaning $b>a$ since $b$ is non-negative. This would contradict theorem \ref{T3} and so
\begin{equation}
\label{b's_value}
b=0
\end{equation}
\end{proof}
We can end off this section by assuring that our bounds on $a,b$ are optimal to achieve no duplicates formed within equation \ref{completely_break}. Note that $b$ is proved to be a constant ($b=0$), which is of course an optimal bound. Observe our current bounds for $a$ (from theorem \ref{T3}), $i\leq a\leq n-a-i$. We obtained this bound from summing the first and third terms within equation \ref{next_break}, $\Delta(n,i)=(n-i-a)+a+i$. The only other options we had were summing the first two or the last two terms. Summing the first two gives us the redundant result of $\Delta(n,i)=\Delta(n,i)$. Summing the last two would give us $\Delta(n,i)=\Delta(n,a+i)$ which, from lemma \ref{T2}, gives $i\leq a+i$ meaning $0\leq a$ which is also a non-contributing fact.
\section{Computing the partition function}
We can alter equation \ref{completely_break} to count the number of times a term is broken down by adding a term of $1$ to the equation. Whenever a term is broken down, a unique partition should be revealed using our optimal bounds on $a,b$ (theorems \ref{T3} and \ref{term_right}). Denoting this altered equation as $\nu(n,i)$,
$$\nu(n,i)=1+\sum_{a=i}^{n-i-a}[\nu(n-i,a)]$$
Keep in mind that $1\leq a$. Since $n\equiv\Delta(n,0)$, we have $$p(n)=\nu(n,0)$$

\\

\end{document}

A: As the combine is better documented, here are an example of a volume journal with a few articles using the paper class with cover and a table of contents of articles.
Indeed the cover is simple, the first article start in even page, there are not fancy headers, etc. but is only a minimal working example to show how to join articles in a volume, right? Anything else is left as exercise to the reader. ;)
Output of pages 1-2:

\documentclass[journal,noindent,headline]{paper}
\usepackage[rmargin=1.5cm]{geometry}
\usepackage[english,latin]{babel}
\usepackage{microtype}
\usepackage{xcolor}
\usepackage{lipsum} % for dummy text only
\usepackage[colorlinks,linkcolor=blue!50!black]{hyperref}
\usepackage{graphicx}
\begin{document}
\oddrunhead{J.  Hiber. Res., Vol. \textsc{\romannumeral27}}
\begin{titlepage} \begin{center}
{\huge\sf Journal of Hibernation Research} \vfill
{\Large 2017, Vol. 27, No. 4} \vfill
{\large\bf Whesleepinwinter University Press}
\end{center} \end{titlepage}
\journalcontents

\twocolumn

\journalpart[Research articles]{}

% ARTICLE 1

\title{Do nothing improve a lot the maintenance of the winter's fat layer}
\subtitle{Sleep more and move less is good for prevent fat depletion before   spring.}
\shorttitle{Do nothing improve the fat layer}
\author{Jon Marmot,\,%
\thanks{Corresponding author: \href{mailto:jmarmot@iamsleeping.com}{jmarmot@iamsleeping.com}.}
Teddy Bear\,%
\thanks{Do not disturb.},
and Ted Squirrel\,%
\thanks{Do not disturb me too.}}
\shortauthor{J. Marmot, T. Bear and T. Squirrel}
\institution{Fat Research Center}
\date{\today}
\maketitle
\begin{abstract}
    \lipsum[5]
\end{abstract}
\begin{keywords}
    fat, hibernation, activiity
\end{keywords}

\section{Introduction}
\begin{figure}[b!]
\includegraphics[width=\linewidth]{example-image-a}
\caption{The A of hibernAtion}
\end{figure}
\lipsum[10-13]
\section{Material and methods}\lipsum[14-17]
\section{Results and discussion}\lipsum[18-22]

% ARTICLE 2

\title{Torpor decrease one half of body weight}
\subtitle{Eat more, eat faster that anybody is yo want survive.}
\shorttitle{Torpor decrease body weight}
\institution{Center of High Metabolism Research}
\author{Walter Shrew\,
\thanks{Corresponding author: \href{mailto:shrew@eatfaster.com}{shrew@eatfaster.com}.}}
\shortauthor{W. Shrew}
\date{\today}
\maketitle
\section{Introduction}\lipsum[1-3]
\section{Material and methods}\lipsum[4-5]
\section{Results and discussion}\lipsum[6-9]

\journalpart[Review articles]{}

% ARTICLE 3

\title{Evolution of hibernation strategies}
\subtitle{Sleep more or less? That's the question.}
\shorttitle{Evolution of hibernation strategies}
\institution{University of Sleepingbeauty}
\author{David Searcher\,
\thanks{Corresponding author: \href{mailto:dsearcher@googling.net}{dsearcher@googling.net}.}}
\shortauthor{D. Searcher}
\date{\today}
\maketitle
\section{Introduction}\lipsum[23-24]
\section{Hibernation in tropical climates}\lipsum[25-32]
\section{Torpor as adaptation to global warming}\lipsum[33-39]

% Book reviews

\newpage
\journalpart{New published books}
\review[Tutorial]{Larry Lazy}{How-two sleep well four months}
Eleven edition, 2017, Ed. J. Marmot, Winter Press, Manitoba.
\bigskip

\lipsum[40-44]
\revauthor{Edouard Masterly\\Stanford University}

\end{document}

Note: I have done that MWE in a single file but in practice you may want  maintain the contents of  each article  in child documents. To construct a MWE with child document cut  from % ARTICLE 1 until % ARTICLE 2, save it as article1.tex, and replace this chunk of text by \input{article1} or   \include{article1} (there are no difference in this case).  If you want render single articles, use \includeonly or see the docmute package to maintain child documents as complete LaTeX files.
Reminder: Do not forget check look also the combine class.


text:
Q: overridePendingTransition & addView with LayoutTransitions I am in a situation where I want to have no visible animation during a transition between Activities. I am currently doing the following:
startActivity( intent );
getActivity().overridePendingTransition( 0, 0 );

Works fine. Once in the second Activity, I want to animate LayoutTransitions (for better or for worse) -- specifically, calling addView() on the root view coupled with android:animateLayoutChanges="true" in XML.
Right now, addView() is being called in my onResume() of the second Activity and shows no LayoutTransition animations (just pops the added view in place). I'm guessing that either overridePendingTransitions(int, int) or startActivity() (and thus the override as well) are "in effect" until some specified lifecycle event occurs in the second Activity. But I can't find this information. Should I just assume that it's until the end of onResume()?
Removing a View later, say when the user presses the back button, triggers the LayoutTransition animation fine. But this is unrelated to the Activity lifecycle.
So my question is, at what point does overridePendingTransition( 0, 0 ) release control of animations?

A: Release of overridePendingTransition is not associated with any lifecycle event.
overridePendingTransition will release control after the duration of animation is completed.
That is,  300 ms (default duration) or user specified duration (set in XML or using setDuration())
For no visible animation during a transition between Activities, use FLAG_ACTIVITY_NO_ANIMATION
instead of overridePendingTransition

intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
  startActivity( intent );


text:
Q: Countdown from 100 to the number (N) and separate even and odd numbers. Show even numbers in the first line and odd numbers in the second line
100

Example Test Cases:
Input: 10

Output:
100 98 96 94 92
99 97 95 93 91

Another one:
Input: 5

Output:
100 98 96
99 97

A: I think this is a possible solution, without many changes to your original code:

100

Basically you decrease it by 2 till you reach the half, then you go back to the start - 1, looping through the odd numbers (or even, if the counter value was odd at first).

A: I have made my own script which counts down from 100-0, and places each number into an Array variable depending on whether it's Odd/Even.
Here it is:

var even = [];
var odd = [];

var number = 100;

changeNumber();
function changeNumber() {
    document.getElementById("counter").innerText = number;
    if (checkParity(number) == "even") {
        console.log("even");
        even.push(number);
    } else {
        console.log("odd");
        odd.push(number);
    }
    if (number == 0) {
        console.log("[Finished]");
        console.log("Even numbers:");
        console.log(even);
        console.log("Odd numbers:");
        console.log(odd);
    } else {
        setTimeout(function () {
            number--;
            changeNumber();
        }, 100);
    }
}

function checkParity(n) {
    if (n % 2 == 0) {
        return "even"
    } else {
        return "odd"
    }
}

100

A: I hope that can help.

(function () {
    const input = prompt("Please enter One number (N) where (N) is a positive integer.", "");
    let count = 100;

    if (isNaN(input) || input < 1) return;

    const inerval = setInterval(() => {
        count--;

        if (count % 2 == 0) {
            console.log('This is even Numbers ' + count);
        } else {
            console.log('This is odd Numbers ' + count);
        }

        if (input == count) return clearInterval(inerval);
    }, 1000);
})();


text:
Q: Драйвер переключения раскладки клавиатуры на Delphi Пытаюсь сочинить код для переключения раскладки клавиатуры клавишей Caps-Lock. Нахожу это наиболее удобным переключать раскладку мизинцем левой руки вместо громоздких комбинаций с Ctrl и Alt, которые сбивают ритм набора (вот и сейчас именно так). Что-то рабочее получилось, но проблема в том, что кнопка Caps-Lock отрабатывается системой и хотя код переключает ее обратно, но эти миллисекунды при быстром наборе сильно мешают и тормозят набор текста. Кроме того я не программист поэтому не судите строго, не пойму как сделать код глобальным. Вот сам код:
procedure TForm1.Timer1Timer(Sender: TObject);
var Layout: array[0.. KL_NAMELENGTH] of char;
begin
  if GetAsyncKeyState(VK_CAPITAL)<>0 then
  begin
      GetKeyboardLayoutName(Layout);
          if Layout = '00000419' then LoadKeyboardLayout('00000409', 1)
             else
             if Layout = '00000409' then LoadKeyboardLayout('00000419', 1);

    Keybd_Event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY or 0, 0);
    //Keybd_Event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
    //keybd_event(VK_CAPITAL, 1, 0, 0);
    keybd_event(VK_CAPITAL, 1, vk_up, 0);
    timer1.Enabled:=false;
  end;
end;

procedure TForm1.Timer2Timer(Sender: TObject);
begin
  if GetAsyncKeyState(VK_CAPITAL) = 0 then timer1.Enabled:=true;
end;


text:
Q: "AttributeError: 'ArgumentParser' object has no attribute 'parse_intermixed_args'" I am attempting to develop an application using argparse module in Python3.  I am getting the above error on when attempting to call the function parse._intermixed_args(some_string).
    parser = argparse.ArgumentParser(prog='string',description='description')
    parser.add_argument('--optional', nargs='+', type=int, help='help text')
    parser.add_argument('name', help='help text')

    if len(commands) > 0:
        args=parser.parse_intermixed_args(commands)

A: According to the docs parse_intermixed_args was introduced in Python 3.7. You must be using an earlier version.


text:
Q: Shivering Animation effect in html css js jquery Hello i want this shivering animation or effect on hover same in the url. Kindly guide me Please.Any reference would be appreciated.
Demo https://expatexplorer.hsbc.com/survey/#/countries
(On the map hover any country circle  and see moving other small circles.

A: Very simple example: There are many libraries that handle animation >
jRumble / CSSshake / Animate.css

body {
  background-color: #fff;
  text-align: center;
  margin: 50px
}
.wrapper {
  top: 100px;
  left: 50%;
  text-align: center;
  display: inline-block;
}
.shake {
  display: inline-block;
  position: relative;
}
.circle {
  border: 4px solid #f00;
  background: #f00;
  height: 150px;
  width: 150px;
  border-radius: 50%;
  margin: 0px -10px;
}
@-webkit-keyframes circled {
  0% {
    -webkit-transform: translate(2px, 1px) rotate(0deg);
  }
  10% {
    -webkit-transform: translate(-1px, -2px) rotate(-1deg);
  }
  20% {
    -webkit-transform: translate(-3px, 0px) rotate(1deg);
  }
  30% {
    -webkit-transform: translate(0px, 2px) rotate(0deg);
  }
  40% {
    -webkit-transform: translate(1px, -1px) rotate(1deg);
  }
  50% {
    -webkit-transform: translate(-1px, 2px) rotate(-1deg);
  }
  60% {
    -webkit-transform: translate(-3px, 1px) rotate(0deg);
  }
  70% {
    -webkit-transform: translate(2px, 1px) rotate(-1deg);
  }
  80% {
    -webkit-transform: translate(-1px, -1px) rotate(1deg);
  }
  90% {
    -webkit-transform: translate(2px, 2px) rotate(0deg);
  }
  100% {
    -webkit-transform: translate(1px, -2px) rotate(-1deg);
  }
}
.shake:hover,
.shake:focus {
  cursor: pointer;
  -webkit-animation-name: circled;
  -webkit-animation-duration: 0.9s;
  -webkit-transform-origin: 50% 50%;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;
}

A: It's done using Flash rather than css & jQuery - so unless you know Flash or can find that fla file then it will not be a straightforward task.


text:
Q: Aligning pictures while letting captions flow I have multiple pictures I want to align in a row and need captions under each of them. I want to align the pictures and allow the captions to flow freely underneath the picture (some will take more lines than others). Learning from previous posts on SO, I found a way to limit the captions to the width of the pictures. I would expect the pictures to align, however, when I have multiple lines in the caption, the picture gets pushed up and all the captions align instead of the pictures, which I do not want.
HTML

Joe Smith
Co-Founder
 Project Coordinator

Bob Joe
 Co-Founder

CSS
     #wwaimg img{
        padding: 10px 5px 0px 5px;
    }

    .wwapictures #wwaimg {
        display: inline-block;
        padding-bottom: 100px;
    }

    .wwapictures figure {
        width: min-content;
    }

How can I align the pictures and still have captions of different sizes underneath each picture?

A: Making my comments into an answer.

*

*IDs should be unique in xml/html so #wwaimg is made into a css class .wwaimg

*Adding a min-height css property on the figures which is same as the max height expected from the longest caption will align everything and leave space if caption takes less lines (assuming images are of the same height as they should be)

example (below solution uses display:inline-block and float:left to make the grid, but you can consider using flexbox as well):

.wwapictures {
  position: relative;
  width: 100%;
  display: block;
  box-sizing: border-box;
}
.wwaimg img{
  position: relative;
  display: block;
  width: 100%;
  height: 200px; /* images should have same height*/
}
.wwaimg figcaption{
  position: relative;
  display: block;
  margin-top: 10px;
  min-height: 70px;
}
.wwaimg {
  position: relative;
  width: 45%;
  box-sizing: border-box;
  display: inline-block;
  margin: 0;
  border: 1px solid #f00;
  padding: 10px;
  float: left;
}

Joe Smith
Co-Founder
 Project Coordinator

Bob Joe
 Co-Founder

Joe Smith
Co-Founder
 Project Coordinator

Bob Joe
 Co-Founder


text:
Q: Concurrency in Erlang The problem I am trying to solve is as follows:
Write an Erlang function named squared that takes no parameters. This function should wait to receive a message. The message will be in the format { Pid, N }, where you may assume that Pid is a process ID and N is a number. The function should send a message to the process ID Pid in the form { Me, X } where Me is the process ID of the process running the function and X is the value of N squared. The function should then end.
so far I have this:
-module(main).
-export([squared/0]).

squared() ->
 receive
    {Pid,N} -> Pid ! {Me, X}, squared();
 terminate -> ok
 end.

The error that I am getting is as follows:
3> c(main).
main.erl:7: variable 'Me' is unbound
main.erl:7: variable 'X' is unbound
main.erl:7: Warning: variable 'N' is unused
error
I am also having trouble in the second part of the problem where it is asking us to send a message to the process ID in the form {Me, X}. Where Me is the process ID and X is the value of N squared. How will we do that?

A: for implement your function you can write a function like bellow
-module(main).
-export([squared/0]).

squared() ->
 receive
    {Pid,N} ->
        Pid ! {self(), N*N},
        squared();
    terminate ->
    ok
 end.

A: Me should be the pid of the receiving process, i.e. self(). N squared is just N*N.
-module(main).
-export([squared/0]).

squared() ->
    receive
        {Pid, N} ->
            Pid ! {self(), N*N};
        terminate -> ok
    end.

Or, if you want to be more verbous:
squared() ->
    Me = self(),
    receive
        {Pid, N} ->
            X = N * N,
            Pid ! {Me, X};
        terminate -> ok
    end.


text:
Q: What is a satiated model, and how is it non-linear? I am just beginning to learn econometrics, and am a little confused by my lecture notes.
They say that the conditional mean function has a known functional form, and is linear in parameter, e.g.,:
$$m(x_1,x_2) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \beta_3 x_1^2 $$.
Okay - so looking above, whilst we have some non-linear regressors, the $\beta$'s are all linear, so this is what it means "linear in parameter"?
I think I understand so far.
Next, the notes say:
"There are cases in which linearity is not a binding constraint. This is sometimes
referred to as a satiated model. For example, let $x_1$ and $x_2$ be binary variables,
both taking values 0 and 1." In this case:
$$m(x_1,x_2) = m(0,0) + m(1,0)x_1(1-x_2)+m(0,1)(1-x_1)x_2 + m(1,1)x_1x_2 $$
I am really confused by what this sentence is trying to say or convey.

A: I believe this should be "saturated," rather than "satiated."
This just means you use regression to calculate four means for all the possible combinations of $x_1$ and $x_2$: $(0,0),(1,0),(0,1),(1,1)$
This is a kind of a non-parametric model, which is non-linear since it allows the means to be very flexible.


text:
Q: How can I handle a sensitive settings file during deployment? I am deploying a Django application to AWS using the following steps:
Push updates to GIT
Log into my server.
Pull updates from GIT
The issue I am having is my settings production.py file. I have it in my .gitignore so it does not get uploaded to GITHUB due to security. This, of course, means it is not available when I PULL updates onto my server.
What is a good approach for making this file available to my app when it is on the server without having to upload it to GITHUB where it is exposed?

A: Have a look into using environment variables for settings you wish to keep secret (like the SECRET_KEY). Have a look at the docs to see how to use it for settings files. You can apply the same thing to your SECRET_KEY etc.
Also have a look at these two similar Stack Overflow questions.
https://stackoverflow.com/questions/44693485/where-do-i-set-environment-variables-for-django
https://stackoverflow.com/questions/4906977/how-to-access-environment-variable-values


text:
Q: Error while embedding external AAR's into my AAR We ship to the customer an aar, which internally has a dependency on 2 aar's from a 3rd party vendor. To embed those into our project we have been using the below library:
https://github.com/adwiv/android-fat-aar
After the latest upgrade to gradle 2.14.1 we get the below error when assembling the release aar file.:
C:\Mobile 3.7 Android\testproj\build\generated\source\r\release\com\eye\R.java:1264: error: cannot find symbol
public static int Theme_popupMenuStyle = com.company.mobile.android.sdk.activity.R.styleable.Theme_popupMenuStyle;
^
symbol: variable Theme_popupMenuStyle
location: class styleable
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
100 errors
:testproj:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':testproj:compileReleaseJavaWithJavac'.
Compilation failed; see the compiler error output for details.
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED

Another observation, there are 2 aar's that we are trying to embed, one of them doesnt have a R.java file, I saw this when I opened the exploded AAR. Maybe this is causing some issue.
Below are the contents of my gradle file where these dependencies are embedded:
/Creation of fat-aar is based on this project: https://github.com/adwiv/android-fat-aar
apply from: 'fat-aar.gradle'
dependencies {
  embedded 'com.eye.version@aar'
  embedded 'com.eye.versioninterface@aar'
}

Below is the section of fat-aar.gradle where the build is failing:
task generateRJava << {
  println "Running FAT-AAR Task :generateRJava"

  // Now generate the R.java file for each embedded dependency
  def libPackageName = new

XmlParser().parse(android.sourceSets.main.manifest.srcFile).@package

  embeddedAarDirs.each { aarPath ->

def aarManifest = new XmlParser().parse(file("$aarPath/AndroidManifest.xml"));
def aarPackageName = aarManifest.@package
String packagePath = aarPackageName.replace('.', '/')

// Generate the R.java file and map to current project's R.java
// This will recreate the class file
def rTxt = file("$aarPath/R.txt")
def rMap = new ConfigObject()

if (rTxt.exists()) {
  rTxt.eachLine {
    line ->
      //noinspection GroovyUnusedAssignment
      def (type, subclass, name, value) = line.tokenize(' ')
      rMap[subclass].putAt(name, type)
  }
}

def sb = "package $aarPackageName;" << '\n' << '\n'
sb << 'public final class R {' << '\n'

rMap.each {
  subclass, values ->
    sb << "  public static final class $subclass {" << '\n'
    values.each {
      name, type ->
        sb << "    public static $type $name = ${libPackageName}.R.${subclass}.${name};" << '\n'
    }
    sb << "    }" << '\n'
}

sb << '}' << '\n'

mkdir("$generated_rsrc_dir/$packagePath")
file("$generated_rsrc_dir/$packagePath/R.java").write(sb.toString())

embeddedRClasses += "$packagePath/R.class"
embeddedRClasses += "$packagePath/R\$*.class"

}
}

Can someone please helpout.


text:
Q: Python Boto 3 version incompatible Need steps for downloading the correct versions botocore and s3transfer.
I did pip install awscli and got the following error because of which no module found shows up while running the .py script.
ERROR: boto3 1.10.50 has requirement botocore<1.14.0,>=1.13.50, but you'll have botocore 1.15.8 which is incompatible. ERROR: boto3 1.10.50 has requirement s3transfer<0.3.0,>=0.2.0, but you'll have s3transfer 0.3.3 which is incompatible


text:
Q: Permanent electric dipole moment parity violation In particle physics we deal with parity transformations and in particular when we regard weak interactions. While learning this subject I found something that needs more clarification for me. Namely, suppose that a particle has an electric dipole moment $\vec{d}$ and some magnetic moment $\vec{\mu}$. Every source I see states that a permanent dipole moment 'violates' parity symmetry, but I do not see why.
I tried the show that the energy is not invariant under parity symmetry but I am not sure whether this is a rigorous theoretical way of proving this.
$$E = -\vec{\mu}\cdot \vec{B} - \vec{d}\cdot \vec{E}$$
is the energy, suppose I apply the parity operator on this:
$$\mathcal{P}(E) = -\vec{\mu}\cdot \vec{B} + \vec{d}\cdot \vec{E}.$$
So we see that $\mathcal{P}(E)\neq E$ so I would say that parity is 'violated' in order to let the energy $E$ be invariant under parity transformation ($E$ is a scalar so it should be mapped to itself). I used that $\vec{d} \propto \vec{S}$ and that $\vec{E}$ is a vector and $\vec{\mu},\vec{B},\vec{S}$ pseudovectors. $\vec{S}$ is the spin vector. My conclusion is therefore: $\vec{d}=\vec{0}$ or that parity is violated.
Is this 'proof' of showing this theoretically rigorous or am I missing someting?

A: The usual answer is something along these lines:  The only thing specifying a "direction" of an elementary  particle is the direction of its spin---so the dipole moment is either parallel to, or  antiparallel to, the spin. Suppose that the electric dipole moment of the particle is ${\bf d} = \lambda {\bf S}$ for some scalar $\lambda$. Now look at the system in a mirror. The mirror image of the particle appears to spin in the opposite direction but the electric charge, and hence the electric dipole moment, is unchanged. Thus, in the mirror world, ${\bf d} = -\lambda {\bf S}$.


text:
Q: Matching certain path pattern and excluding other forward slashes I am new to Regex.
I want to match a certain URL pagePath pattern for Analytics.
The Problem:
The pattern looks like this:
/(de|en|fr|it)/../any-word-including-dashes/word-or-words-including-dashes-and-numbers

I want to match only this pattern and exclude all pagePathes with another forward slash or not matching the initial pattern:
Include:
/de/ab/word-word/word1-and-something-else
/de/ab/word-word/word1-and-something-else?any_ting1=any.-thing2

Exclude:
/de/ab/word-word/word1-and-something-else/
/de/ab/word-word/word1-and-something-else/anything
/de/ab/word-word
/fr/moreThanTwoCHAR/anything

My Regex:
After having searched on SO (Exclude forward slash before end , "Match anything but" and Finding exactly n occurences of "/", disallow 0 or more occurences of a CHAR) I came up with the following regex:

^(\/de|\/fr|\/en|\/it)\/..\/.+\/\w+[^\/]*

What it does correctly
It excludes correctly the following path:
/fr/moreThanTwoCHAR/anything

What it fails on
The problem with the above regex is that it matches also (tested on regex101):
/de/ab/word-word/word1-and-something-else/anything

And I can't seem to understand why it matches the string with an additional forward slash even if I stated to exclude 0 or more additional occurences (at least from what I understood). Anyone can explain me where I'm mistaken?

A: Note that . matches any char (except line break chars if no DOTALL option (/s) is used) thus your regex just matches more types of input than you need.
You may use
'~^/(de|fr|en|it)/[^/]{2}(?:/[^/]+){2}$~'

See the regex demo.
Pattern details:

*

*^ - start of input

*/ - a / char

*(de|fr|en|it) - one of the three alternative substrings: de, fr, en or it

*/[^/]{2} - / and then any 2 chars other than /

*(?:/[^/]+){2} - 2 consecutive sequences of a / and then 1+ chars other than /

*$ - end of input.