text:
Q: Failed to load servlet class org.glassfish.jersey.servlet.ServletContainer The context here is that I am trying to configure the project to run with Spring JSF and deploy a web-service using Jersey using Maven as a dependency manager.
However, as I try to run the project, the log told me that servlet class org.glassfish.jersey.servlet.ServletContainer is failed to load. But I looked into the jar files and I saw that there is the class inside.
I did search for many way to fix it but it seems like not my case.
Below is my pom.xml file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>weservice</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>weservice Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
    <!-- JUnit dependencies -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <!-- JSF dependencies -->
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.4</version>
    </dependency>
    <!-- Java Servlet dependencies -->
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- Spring 4.0.4 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring3</artifactId>
        <version>2.15</version>
    </dependency>
    <!-- Jersey dependencies -->
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.15</version>
    </dependency>
</dependencies>
<build>
    <finalName>weservice</finalName>
</build>

And this is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:web="http://xmlns.jcp.org/xml/ns/javaee">
    <display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
    <servlet>
        <description>JAX-RS Tools Generated - Do not modify</description>
        <servlet-name>JAX-RS Servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.aavn.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JAX-RS Servlet</servlet-name>
        <url-pattern>/jaxrs/*</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
            <servlet-name>Faces Servlet</servlet-name>
            <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
</web-app>

Error Log :
    !ENTRY org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.582
!MESSAGE
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.582
!MESSAGE Failed to load servlet class org.glassfish.jersey.servlet.ServletContainer
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.582
!MESSAGE org.apache.geronimo.common.DeploymentException: Failed to load servlet class org.glassfish.jersey.servlet.ServletContainer
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.582
!MESSAGE    at org.apache.geronimo.jaxws.builder.AdvancedWARWebServiceFinder.getPortInfo(AdvancedWARWebServiceFinder.java:169)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.582
!MESSAGE    at org.apache.geronimo.jaxws.builder.AdvancedWARWebServiceFinder.discoverPOJOWebServices(AdvancedWARWebServiceFinder.java:143)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.jaxws.builder.AdvancedWARWebServiceFinder.discoverWebServices(AdvancedWARWebServiceFinder.java:44)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.jaxws.builder.AdvancedWARWebServiceFinder.discoverWebServices(AdvancedWARWebServiceFinder.java:37)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.jaxws.builder.WARWebServiceFinder.discoverWebServices(WARWebServiceFinder.java:51)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.jaxws.builder.WARWebServiceFinder.discoverWebServices(WARWebServiceFinder.java:28)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.jaxws.builder.JAXWSServiceBuilder.discoverWebServices(JAXWSServiceBuilder.java:245)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.jaxws.builder.JAXWSServiceBuilder.findWebServices(JAXWSServiceBuilder.java:103)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.tomcat.deployment.TomcatModuleBuilder.postInitContext(TomcatModuleBuilder.java:454)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.initContext(AbstractWebModuleBuilder.java:437)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.j2ee.deployment.SwitchingModuleBuilder.initContext(SwitchingModuleBuilder.java:168)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.j2ee.deployment.EARConfigBuilder.buildConfiguration(EARConfigBuilder.java:686)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.deployment.Deployer.deploy(Deployer.java:281)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.deployment.Deployer.deploy(Deployer.java:145)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.lang.reflect.Method.invoke(Method.java:606)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.gbean.runtime.ReflectionMethodInvoker.invoke(ReflectionMethodInvoker.java:34)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.gbean.runtime.GBeanOperation.invoke(GBeanOperation.java:131)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.gbean.runtime.GBeanInstance.invoke(GBeanInstance.java:883)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.kernel.basic.BasicKernel.invoke(BasicKernel.java:245)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.kernel.KernelGBean.invoke(KernelGBean.java:344)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.reflect.GeneratedMethodAccessor112.invoke(Unknown Source)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.lang.reflect.Method.invoke(Method.java:606)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.gbean.runtime.ReflectionMethodInvoker.invoke(ReflectionMethodInvoker.java:34)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.gbean.runtime.GBeanOperation.invoke(GBeanOperation.java:131)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.gbean.runtime.GBeanInstance.invoke(GBeanInstance.java:883)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.kernel.basic.BasicKernel.invoke(BasicKernel.java:245)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.system.jmx.MBeanGBeanBridge.invoke(MBeanGBeanBridge.java:172)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:468)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.security.AccessController.doPrivileged(Native Method)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1427)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.reflect.GeneratedMethodAccessor64.invoke(Unknown Source)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.lang.reflect.Method.invoke(Method.java:606)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.Transport$2.run(Transport.java:202)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.Transport$2.run(Transport.java:199)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.security.AccessController.doPrivileged(Native Method)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.Transport.serviceCall(Transport.java:198)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:567)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.access$400(TCPTransport.java:619)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:684)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:681)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.security.AccessController.doPrivileged(Native Method)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.lang.Thread.run(Thread.java:745)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:513)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:429)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:417)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.hook.equinox.GeronimoClassLoader.loadClass(GeronimoClassLoader.java:85)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:345)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:229)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1207)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    at org.apache.geronimo.jaxws.builder.AdvancedWARWebServiceFinder.getPortInfo(AdvancedWARWebServiceFinder.java:160)
!SUBENTRY 1 org.apache.geronimo.st.v30.core 4 0 2015-02-11 13:15:56.583
!MESSAGE    ... 57 more

If there is any other information you guys need, please let me know.
Thank you very much


text:
Q: Trouble with a sub menu in my WordPress menu I'm creating my first WordPress theme. It's a very simple one for a friend's website, who is a music producer. I'm creating the navigation menu. One of the items on the menu is listen. It's not an actual link. You hover over it and a submenu should appear. So I made Listen a custom link.
The problem is that the submenu doesn't appear. The Submenu has its own class. But I don't think WordPress is reading the CSS
Here is the CSS:
ul.sub-menu {
display: none;
position: absolute;
padding: 0px;
margin-left: -20px;
}

ul.sub-menu li {
display: block;
text-align: left;
background-color: grey;
}

ul.sub-menu li:hover {
background-color: #dae0e6;
}

ul.main_nav li:hover ul.sub-menu {
display: block;
}

Here is the HTML and php code in the header.php:

<?php

$defaults = array(
    'container' => false,
    'theme_location' => 'primary-menu',
    'menu_class'    => 'main_nav'
);

wp_nav_menu( $defaults );

?>

A: Here is my approach:
I changed css so its shows menu sub menu with CSS.
JsFiddle Demo

nav
{
 margin-top:15px
}

nav ul
{
 list-style:none;
 position:relative;
 float:left;
 margin:0;
 padding:0
}

nav ul a
{
 display:block;
 color:#333;
 text-decoration:none;
 font-weight:700;
 font-size:12px;
 line-height:32px;
 padding:0 15px;
 font-family:"HelveticaNeue","Helvetica Neue",Helvetica,Arial,sans-serif
}

nav ul li
{
 position:relative;
 float:left;
 margin:0;
 padding:0
}

nav ul li:hover
{
 background:#f6f6f6
}

nav ul ul
{
 display:none;
 position:absolute;
 top:100%;
 left:0;
 background:#fff;
 padding:0
}

nav ul ul li
{
 float:none;
 width:200px
}

nav ul ul a
{
 line-height:120%;
 padding:10px 15px
}

nav ul ul ul
{
 top:0;
 left:100%
}

nav ul li:hover > ul
{
 display:block
}

         Home

         Bio

         Listen

Originals

TV/Film

Credits

Contact

A: In example above your menu is commented out. Also parent of ul.sub-menu should be positioned relative.

A: since you are new ... I think you should start by get general idea about the sub menu and style them in WordPress .
this Tut will help you
http://wproots.com/how-to-style-wordpress-menus-dropdowns/
also I will suggest other option for you .

*

*start form other theme like wordpress deafult theme and edit it

*start form starter theme like http://bootstrapwp.rachelbaker.me/

*start from template
its hard to build theme from scratch if you are new ... step by step

A: please assign width to ul like
ul.sub-menu {
 display: none;
}

and plaece
ul.main_nav li:hover ul.sub-menu {
 display: block;
 position: absolute;
 padding: 0px;
 margin-left: -20px;
 top:0;
 left:0;
 width:800px;
}

just after it

redpajama_set_name: RedPajamaStackExchange


text:
Q: Timing issue with jQuery and $(document).ready() I have the following code block code when the document is ready:
$(document).ready(function() {
    createDivs(); // creates some divs with class 'foo';

    // iterate
    $(".foo").each(function(index) {
        alert(index + " - " + $(this).text());
    });
}

I find that the "iterate" part misses the divs I created in the createDivs() method entirely! Is there some timing issue I'm not aware of? Why doesn't jquery see the divs that were just created?

A: In my experience DOM manipulation can act asynchronous at times, possibly due to optimization by the browser, my usual solution is to have createDivs() return the divs created then use the returned elements aswell
var divs = createDivs();
$('.foo').and(divs).each(function(){
    //happy fun time
})

A: The timing is not the issue. Maybe createDivs() doesn't add the elements to the DOM?

A: I've found that Javascript is like a bull in an F1 racer when it comes to executing code. There's no making it wait to execute code in any particular chain.
You should probably create a situation where createDivs() is able to fire any dependent code after it is complete vis-a-vis a callback. Without seeing the createDivs code, it's tough to give you a way to implement it.
UPDATE
Really only applies if you're doing an asynchronous call (according to my friends below).


text:
Q: How to roll back (reset) a committed change in git on a single file I have a commit on my feature branch, consisting of 3 files, one of which now has a merge conflict with master.
I'd like to:

*

*roll back the commit on the conflicted file

*rebase from master onto the file that had the conflict

*manually reapply my rolled back changes on that file

I've tried reverting but this works on the whole commit not the single file.
I've tried checking out the single file (at its revision prior to the commit I want to roll back) and committing that (to essentially revert the single file). However when I rebase the conflict still happens.
I feel like I need to do a hard reset on this single file somehow but I can't see a way of resetting an individual file.

A: You can use git checkout to get a single file from another commit like so:
git checkout <commit> -- path/to/file

To prevent the conflict, you should squash the new commit into the previous (conflicting) commit.

A rebase will apply each commit in the list, one at a time. If you have a conflict, then every single time you rebase you will have to re-address that conflict. That's one reason that I prefer a good ol' merge. Merges happen at the top of the stack (so your anti-conflict commit will apply), and any conflicts you do run into only need to be solved once.
If you really want to use a rebase, then you can git rebase -i HEAD~N (where N is however many commits you need to go back to get to the conflicting commit) then edit that commit directly (place an e next to it in the editor) or squash the second commit into the first (place an s next to the new commit). Basically, you need to change your commit history. Then you should be able to rebase off master.

A: The problem here is conceptual: you're taking commands that apply to commits, and trying to apply them to files, and this is skewing your reasoning about how to address the problem at hand.
To clarify: files are not committed individually.  Each commit has a single TREE, which represents the state of the entire project content.  You change three files, this creates a new state of the content; you git commit, this creates a single new COMMIT object with a TREE representing the new state of the project.
Perhaps the confusion comes from familiarity with other source control tools.  The commit model used by git is in contrast to CVS, where changes are committed to individual versioned files, for example.
So if you roll back using something like reset, you undo all of your changes.  If you rebase to get changes from master, you get all of the changes from master.
This doesn't mean you can't get where you want to go; you just have to approach it a bit differently.
The simplest (and IMO most correct for the situation) thing to do is to resolve this during the merge operation.  Once get tells you there are conflicts, you can get masters version of the one conflicting file
git checkout master -- path/to/conflicting/file

Then you can use whatever editor or IDE you're using to manually re-apply your changes.  (You can always git diff HEADgit merge-base HEAD master-- path/to/conflicting/file if you need to review the changes you originally made.)  Then
git add path/to/conflicting/file

to mark the conflict as resolved, and
git commit

to finish the merge.


text:
Q: Applying function to Pandas dataframe by column I have a function which I want to apply to certain columns of a pandas dataframe.
So rather than explicitly stating the columns, I want to dynamically select the columns I want and then call the function e.g.
How to implement something like:
for column in dataframe:
    if column.name != 'manager':
       apply function():

A: I think you can first find all columns by list comprehension and then apply func:
import pandas as pd

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

cols = [col for col in  df.columns if col != 'B']
print (cols)
['A', 'C', 'D', 'E', 'F']

def func(x):
    return x + 1

df[cols] = df[cols].apply(func)

print (df)
   A  B   C  D  E  F
0  2  4   8  2  6  8
1  3  5   9  4  4  5
2  4  6  10  6  7  4

Another solution with boolean indexing:
cols = df.columns[df.columns != 'B']
print (cols)
Index(['A', 'C', 'D', 'E', 'F'], dtype='object')

A: use drop() and apply():
df.drop('manager', axis=1).apply(func)

demo:
In [115]: df
Out[115]:
   a  b  c
0  4  5  3
1  6  6  6
2  3  4  1
3  2  1  6
4  8  8  1

In [116]: df.drop('b', axis=1)
Out[116]:
   a  c
0  4  3
1  6  6
2  3  1
3  2  6
4  8  1

In [117]: def func(i):
   .....:     return i ** 2
   .....:

In [118]: df.drop('b', axis=1).apply(func)
Out[118]:
    a   c
0  16   9
1  36  36
2   9   1
3   4  36
4  64   1


text:
Q: Trouble with C++ maps and their content This is rather extensive, so in advance, if you get through this, even without an answer or solution, thank you.
So, I have this program that is meant to be a basic social network, minus the user-interface, in which a user is represented by a Person object, which is responsible for maintaining a friend list, a block list, a list of messages, and a queue of pending friend requests. These lists are, respectively, of types std::map<std::string, Person>, std::map<std::string, Person>, std::vector<Message>, and std::queue<Message>, where the std::string for the two maps is a concatenation of the user's first and last names and the Message in the final two containers are and additional class I have defined. I have overloaded the << operator for Person such that it prints the user's first and last names, with a space in between. For some reason, when I go to print these names out, the return is empty, and I have no idea why. The following code is essentially a walkthrough what is happening.
The lines I am using to test my code in the main class:
std::string cFirst ("Chris");
std::string cLast ("Cringle");
SocialNetwork sn;
sn.addUser(cFirst,cLast);

The addUser() function in SocialNetwork:
void SocialNetwork::addUser(std::string first, std::string last){
std::string name = (first + last);
Person user (first, last);
_users.insert(std::pair<std::string, Person>(name, user));
}

Where _users is member data on the SocialNetwork of type std::map<std::string, Person>. The constructor for Person is:
Person::Person(std::string first, std::string last){
_first = first;
_last = last;
}

Where _first and _last are member data on Person that represent the user's first and last names. Then, back in the main class, after sn.addUser(cFirst,cLast);:
sn.printUsers();

Which looks like:
void SocialNetwork::printUsers(){
std::map<std::string, Person>::iterator it;
it = _users.begin();
while(it != _users.end()){
    cout << it->first << endl;
    cout << it->second << endl;
    it++;
    }
}

With the given code I have, the expected output for cout << it->first << endl; should be ChrisCringle, and it is. The expected output for cout << it->second << endl; should call the overloaded operator and should be Chris Cringle, but it simply prints a blank space. Any indications as to why would be greatly appreciated. Do I need to pass my params by reference? I have tried this already and seem to run into a lot of trouble. If something appears to be missing that may help, feel free to ask! Thanks again! I know I'll probably get a lot of flak for this long question but I do not think I can manage to make this any more of a simple question.
EDIT: The code for the overloaded operator is:
ostream& operator<<(ostream& os, const Person& per){
os << per._first << " " << per._last;
return os;
}

A: I just used all the code you've shown: http://ideone.com/mFBxTC
#include <string>
#include <iostream>
#include <map>
using namespace std;

struct Person {
    Person(std::string first, std::string last);
    std::string _first, _last;
};

ostream& operator<<(ostream& os, const Person& per){
    os << per._first << " " << per._last;
    return os;
}

struct SocialNetwork {
    void addUser(std::string first, std::string last);
    std::map<std::string, Person> _users;
    void printUsers();
};

void SocialNetwork::addUser(std::string first, std::string last){
  std::string name = (first + last);
  Person user (first, last);
  _users.insert(std::pair<std::string, Person>(name, user));
}

Person::Person(std::string first, std::string last){
  _first = first;
  _last = last;
}

void SocialNetwork::printUsers(){
std::map<std::string, Person>::iterator it;
it = _users.begin();
while(it != _users.end()){
        cout << it->first << endl;
        cout << it->second << endl;
        it++;
    }
}

int main() {
    std::string cFirst ("Chris");
    std::string cLast ("Cringle");
    SocialNetwork sn;
    sn.addUser(cFirst,cLast);
    sn.printUsers();
    return 0;
}

And it works fine. So error is elsewhere
Thats why one should post SSCCE when posting debugging questions.


text:
Q: Expression.Call Skip or Take I made generic functionality that on run time it's compiling from JSON filter to Expression and have issue on make Skip and Take call, on my IQueryable, to be entire compiled (without exec sp_executesql) in SQL
My Method:
public static class PagingExtensions
{
    public static IQueryable<T> Page<T>(this IQueryable<T> query, QueryRequest queryRequest) where T : class
    {
        //if (queryRequest.Skip.HasValue)
        //{
          //query = query.Skip(queryRequest.Skip.Value);
        //}

        //if (queryRequest.Take.HasValue)
          //{
            //query = query.Take(queryRequest.Take.Value);
        //}
        var methodName = "Skip";
        var resultExp = Expression.Call(
            typeof(IQueryable),
            "Skip",
            Type.EmptyTypes,
            Expression.Constant(queryRequest.Skip.Value));

        query = query.Provider.CreateQuery<T>(resultExp);

        return query;
    }
}

Exception:

InvalidOperationException: No method 'Skip' on type 'System.Linq.IQueryable' is compatible with the supplied arguments.

A: It is thowing that exception because there is no Skip method in the IQueryable interface.
You should use the Queryable class that provides a set of static methods (including Skip) for querying data structures that implement IQueryable.
Regards.

A: The Skip method is not an instance method of IQueryable, but an extension in the static Queryableclass.
You need to get the generic method info and pass the source query as first argument:
MethodInfo method = typeof(Queryable).GetMethod("Skip").MakeGenericMethod(typeof(T));
var resultExp = Expression.Call(
                       method,
                       query.Expression,
                       Expression.Constant(queryRequest.Skip.Value));


text:
Q: PLINQO and Transactions problem I just started working with PLINQO to implement the repository layer and the data tier in my n-tier distributed system.
The data tier consists of the following layers: repository, data provider, data service
The repository layer responsible for getting data from database and setting data in the database.
The data provider layer is the gate between the repository and the service layer
The data service layer holds all the business logic and rules.
I am having a problem in this architecture when using transactions: I am getting InvalidOperationException with error message: "Cannot attach an entity that already exists." very often.
The reason is because the desing of the repository layer. The common steps in all the repository methods are:
MyDataContext context;
if(InTransaction == true)
    context = GetExistingContext();
else
    context = GetNewContext();

//Do some database operation for example:
var user = context.User.GetByKey("username");

//Detach from context
user.Detach();

if(InTransaction == false)
    context.Dispose();

The InvalidOperationException happens when InTransaction is true and I am calling to two methods that operates on the same entity. Becuase the InTransaction is true the two methods uses the same datacontext. the first method attach the entity and in the end detach and the second method also tries to attach and then the exception occurs.
What am I doing wrong and how can I prevent this from happen ?
Thanks,
Koby

A: I found a solution to my problem.
The exception occurred when I tried to attach an entity that is already attached to a datacontext and this happened because I didn't had an indication in my Update() method if the entity is already attached to the data context that the method uses.
When I removed the attach I didn't got the exception but the entity sometimes was not udpated (in cases the datacontext is new).
So I thought how to bridge between those 2 conflicting situation and the solution is TransactionScope.
I created TransactionScope class that allows methods to Join and Leave the scope.
The Join() method creates new datacontext and initialize usage counter so any consecutive call to this method increase this counter by one.
The Leave() method decrements the usage counter and when it reaches to zero the datacontext is disposed.
There is also property that returns the data context (instead of each method to try and get its own context).
I changed the methods that need data context from what described in my question to:
_myTranscationScope.Join();

try
{
  var context = _myTransactionScope.Context;

  //Do some database operation for example:
  context.User.GetByKey("username");

}
finally
{
    _myTranscationScope.Leave();
}

In addition I overrided the Dispose method of the datacontext and moved the detach of the entities to there instead of doing this in each method.
All I need to make sure is that I have the correct transaction scope and make sure each call to join has also call to leave (even in exception)
This now make my code works perfect with all the scenarios (including single database operations, complex transactions, working with serialized objects).
Here is the code of the TransactionScope class (I removed line codes that depends on the project I am working on, but still it is fully working code):
using System;
using CSG.Games.Data.SqlRepository.Model;

namespace CSG.Games.Data.SqlRepository
{
    /// <summary>
    /// Defines a transaction scope
    /// </summary>
    public class TransactionScope :IDisposable
    {
        private int _contextUsageCounter; // the number of usages in the context
        private readonly object _contextLocker; // to make access to _context thread safe

        private bool _disposed; // Indicates if the object is disposed

        internal TransactionScope()
        {
            Context = null;
            _contextLocker = new object();
            _contextUsageCounter = 0;
            _disposed = false;
        }

        internal MainDataContext Context { get; private set; }

        internal void Join()
        {
            // block the access to the context
            lock (_contextLocker)
            {
                CheckDisposed();

                // Increment the context usage counter
                _contextUsageCounter++;

                // If there is no context, create new
                if (Context == null)
                    Context = new MainDataContext();
            }
        }

        internal void Leave()
        {
            // block the access to the context
            lock (_contextLocker)
            {
                CheckDisposed();
                // If no one using the context, leave...
                if(_contextUsageCounter == 0)
                     return;

                // Decrement the context usage counter
                _contextUsageCounter--;

                // If the context is in use, leave...
                if (_contextUsageCounter > 0)
                    return;

                // If the context can be disposed, dispose it
                if (Context.Transaction != null)
                    Context.Dispose();

                // Reset the context of this scope becuase the transaction scope ended
                Context = null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            lock (_contextLocker)
            {
                if (_disposed) return;

                if (disposing)
                {
                    if (Context != null && Context.Transaction != null)
                        Context.Dispose();

                    _disposed = true;
                }
            }
        }

        private void CheckDisposed()
        {
            if (_disposed)
                throw new ObjectDisposedException("The TransactionScope is disposed");
        }

    }
 }


text:
Q: how can i insert image in ckeditor when we click on button i have ck editor and add gap button.in the ckeditor's text area i added an image.when i click on "add gap" button the same image will again add in the text area of the ck editor.i tried a lot but can't.please help me
thanks&regaurd's
sindu

                                        <textarea name="editor1" id="myTextarea">
bdfv
 </textarea>

                                        <input type="button"  value="Add Gap"  onclick="insertText();">

A: you can try the insertHTML function for ckeditor.
var editor = var editor = CKEDITOR.instances.yourEditorInstance;
var data = '';
editor.insertHtml(data, 'unfiltered_html');


text:
Q: How to find the norm for 'L + U' in LU decomposition I am new to Python 3 and currently learning about LU Decomposition and how to express its functions in Python. We were given as a class a question that involves writing a code in order to find the LU decomposition of a matrix A (using scipy) as well as the norm of 'L+U' within that decomposition. I understand how to get P L and U with scipy.linalg.lu but I am having trouble understanding how to add L and U together after getting that answer. this is my code so far...
from numpy import array, sqrt
import scipy as sp
from scipy.linalg import norm

def scipy_LU(A):

    Q = sp.linalg.lu(A)
    print(Q)

elements_of_A = list(map(float, input(). split(' ')))
order = int(sqrt(len(elements_of_A)))
A = array(elements_of_A).reshape(order, order)
print(round(norm(L+U, 1), 4))

A: The return of scipy.linalg.lu is three separate matrices: P, L, and U.  Rather than assigning them as a tuple to the variable Q, you can assign it to 3 variables, compute the addition, and then compute the norm:
def norm_LU(A):

    P, L, U = sp.linalg.lu(A)
    L_plus_U = L + U
    return norm(L_plus_U)


text:
Q: XSD : How to check that only last element contains attributes I have an XML document :
<Feature>
    <Filter> ... </Filter>
    <Filter> ... </Filter>
    <Filter isTargetFilter="true"> ... </Filter>
</Feature>

Feature can hold max 3 Filter elements.
Using XSD I want to check that only last Filter element will contain an attribute "isTargetFilter".
No other Filter element can contain this attribute.
I did not find any XSD expression that can help me.
Any pointers are appreciated.

A: In XSD (both 1.0 and 1.1), if two elements are siblings and have the same name, then they must have the same type. (The constraint is called Element Declarations Consistent, if you want to look it up).
So the only way to do this is with XSD 1.1 assertions. Define assertions on the Feature element:
<xs:assert test="every $f in Filter[not(position()=last())] satisfies empty(@isTargetFilter)"/>
<xs:assert test="Filter[position()=last()][@isTargetFilter]"/>


text:
Q: Dismissing ViewController after a time interval? Is there a way, that I can present or dismiss my ViewController after a time of 5 seconds? Maybe like...If the user presses a button after 5 seconds the new view appears.
Any solutions or suggestions? Sorry but I didn't found a solution on the web.
My code which doesnt work:
    -(IBAction)lol:(id)sender {

    [self performSelector:@selector(dissMissviewController) withObject:self afterDelay:3];
}

-(void)dissMissViewController{

    [self dismissModalViewControllerAnimated:YES];
}

Thanks.

A: You can use below one..
//for dismissing the ViewControler on clicking button just use below piece of code.

[self performSelector:@selector(dismissViewController) withObject:self afterDelay:5];

//dismissviewController is the method which has the code for dismissing the viewController.

//and can follow the same for showing the viewController.

 - (void)dismissViewController
 {
 //if you are pushing your viewControler, then use below single line code
 [self.navigationController popViewControllerAnimated:YES];
 //if you are presnting ViewController modally. then use below code
 [self dismissModalViewControllerAnimated:YES];
 }

I hope it may clears to you...!!!

A: As you want that a new viewController is presented or dismissed after a delay of 5sec when a button is pressed, try implementing the below code
       -(IBAction)btnpressed:(id)sender
       {
          [self performSelector:@selector(dismissVC) withObject:self afterDelay:5.0];

          //dismissVC is the method which has the code for dismissing the viewController. same is the case for presenting a ViewController by passing a selector which has the code for presenting the viewController

       }

Hope this helps.


text:
Q: Aerospike Version, any other major upgrades before 3.13.x necessary? Our Enterprise AS cluster is on v 3.7.3, do we need to upgrade to any of the versions before 3.13.x or can we directly upgrade to the major 3.13.x version?

A: Nope, shouldn't be a problem to upgrade from 3.7 to 3.13.
Note: As an Enterprise user you have access to our 24 hr support team at support.aerospike.com.


text:
Q: Thread safety and System.Text.Encoding in C# Is it safe to use the same Encoding object from different threads?
By "using" I mean, calling Encoding.GetString(), Encoding.GetBytes() and write some XML with an XmlWriter (created by something like XmlWriter.Create(myStream, new XmlWriterSettings() { Encoding = myEncoding }).
The msdn site states that "Any instance members are not guaranteed to be thread safe".
So, how can I safely write two XML documents concurrently? (thank you!!)

A: Yes, it should be safe to use the same Encoding object, as it's designed to be stateless - whereas Encoder and Decoder are stateful, maintaining incomplete characters etc if necessary. I suppose you could write a stateful Encoding class, but it would be a really bad idea. As far as I'm aware, all of the built-in encoding implementations are stateless and thread-safe.
For example, the Encoding.UTF8, Encoding.ASCII etc properties are singletons.


text:
Q: Fetching objects from that are inside other objects I've been using MongoDB since a week and I'm having a lot of fun with it!
So far the test application I'm building as Projects and Milestones. See the structure below:
{
  "code": "test-project",
  "milestones": [
    {
      "name": "Test Milestone",
      "code": "test-milestone"
    },
    {
      "name": "Test Milestone 2",
      "code": "test-milestone-2"
    }
  ],
  "name": "Test Project"
}

I'm now making an edit form for the Milestones. I'd like to edit let's say, "Test Milestone 2". So, so far I've been getting the related Project, and then select the right Milestone from the associated collection. But I'd like to know if there's a way to directly get a Milestone? (in my case)
If yes then could you give me an example of how to do it please?
Thanks!

A: You can do this with a straight query. You just need to use the Positional Operator.
Let's say you want to update "Test Milestone 2" to "Test Milestone Two". You can run the following query:
 db.Projects.update( {"milestones.name" : "Test Milestone 2"}, {$set : {"milestones.$.name" : "Test Milestone Two"}} )

The $ holds the place of your original array find (the first portion of the update statement). This lets you jump right to the element of the array you wish to modify.
Glad to hear you're enjoying MongoDB - it's quite fun.

A: Embed your milestone array into the project itself.
Or keep doing what you are doing right now. (you are not doing it wrong. it's simply the nature of it)


text:
Q: useEffect for real time data update I am creating an easy chat app, with different text channels. I am facing an infinite loop issue when using the useEffect hook to update the messagesList on real time. You can see the code below but this is what I am trying to achieve:

*

*First useEffect is for the chat window to scroll to the last message every time there is a change in the messagesList array. This means: I am in the middle of the messages window, I write a new message and it takes me to the bottom. This is working fine.

*Second useEffect is for the messagesList to be rendered whenever the channel is changed or there is any change in the messagesList. Adding the messagesList as a dependency is causing the infinite loop... but I think I need it cause otherwise the following happens: user1 is inside the chat channel and user2 writes a new message. User1 wont see the new message displayed as his chat is not being re-rendered. How would you make it for the new message to be displayed for user1?

Sorry for the confusing question and thanks a lot in advance!
    useEffect(() => {
    anchor.current.scrollIntoView(false);
  }, [messagesList]);

    useEffect(() => {
    const unsubscribe = onSnapshot(
      collection(firestore, `channels/${activChannel}/messages`),
      (snapshot) => {
        console.log(snapshot.docs);
        getMessagesList();
      }
    );
    return () => unsubscribe();
}, [activChannel, messagesList]);

A: I am not familiar with firestore, but perhaps you could tie the updating of the messages to the event that an user submits his message or use useSyncExternalStore. This piece of documentation on useEffect use cases might help you.
an excerpt from the docs:

Here, the component subscribes to an external data store (in this
case, the browser navigator.onLine API). Since this API does not exist
on the server (so it can't be used to generate the initial HTML),
initially the state is set to true. Whenever the value of that data
store changes in the browser, the component updates its state.
Although it's common to use Effects for this, React has a
purpose-built Hook for subscribing to an external store that is
preferred instead. Delete the Effect and replace it with a call to
useSyncExternalStore:


text:
Q: Focus IE window in powershell My code:
$ie = new-object -com "InternetExplorer.Application"
$ie.navigate("http://localhost")
$ie.visible = $true
$ie.fullscreen = $true

However, after fullscreen, the window still appears behind the Windows taskbar. When I click the window to give it focus, the taskbar falls behind and it appears how I want it to. How can I do this programmatically? Thank you!

A: This was a toughy... Not as simple as I thought.
I ended up using a cheat and adding the VB assembly:
Add-Type -Assembly "Microsoft.VisualBasic"

$ie = new-object -com "InternetExplorer.Application"
$ie.navigate("http://localhost")
$ie.visible = $true
$ie.fullscreen = $true
While ($ie.Busy) { Sleep -m 10 }
$ieProc = Get-Process | ? { $_.MainWindowHandle -eq $ie.HWND }
[Microsoft.VisualBasic.Interaction]::AppActivate($ieProc.Id)


text:
Q: Converting a JSON structured url to data in R I am currently stuck on a problem with converting data from an API url to an actual list or data frame. I have used the same functions on different url sites and there was no issue regarding these. However, on my latest attempt something seems to be off. I have tried the following ways:
library(httr)
library(jsonlite)
url <- "https://cds-api.bwin.com/bettingoffer/fixtures?x-bwin-accessid=NTZiMjk3OGMtNjU5Mi00NjA5LWI2MWItZmU4MDRhN2QxZmEz&lang=en&country=NL&offerMapping=Filtered&offerCategories=Gridable&sportIds=4&sortBy=Tags"

r <- GET(url)
raw_data_bwin <- fromJSON(content(r, "text"), simplifyVector = FALSE)

and
url <- "https://cds-api.bwin.com/bettingoffer/fixtures?x-bwin-accessid=NTZiMjk3OGMtNjU5Mi00NjA5LWI2MWItZmU4MDRhN2QxZmEz&lang=en&country=NL&offerMapping=Filtered&offerCategories=Gridable&sportIds=4&sortBy=Tags"

js <- url %>%
  read_html() %>%
  html_text()

js <- fromJSON(gsub("bettingoffer/fixtures?x-bwin-accessid=NTZiMjk3OGMtNjU5Mi00NjA5LWI2MWItZmU4MDRhN2QxZmEz&lang=en&country=NL&offerMapping=Filtered&offerCategories=Gridable&sportIds=4&sortBy=Tags", "", js))

The first piece of code gives the following error:
Error: lexical error: invalid char in json text.

<!DOCTYPE html> <html lang="en

(right here) ------^

and the second one gives this error:
Error: parse error: premature EOF

{"fixtures":[{"games":[],"parti

(right here) ------^

I am trying to understand more about getting data from API's and JSON structured data sets, but with my limited knowledge I cannot find a solution to this problem. Could anyone assist me with these errors?


text:
Q: Why does this gives me an error (Multi Thread or ArrayList)? I have two threads which are running and I need to control if the bullet is touching the enemy but it gives me this problem where I printed "s4". Any idea what happened there? I'm quite a beginner. I'm using Java.
ArrayList<Nemico> nemici= o_orda.getNemici();
        for (Nemico nemico : nemici) {
            if(Collisioni.ControllaCollisioni(o_navicella, nemico)){
                nemici.remove(nemico);
                this.o_navicella.vita-=10;

                break;
            }
            for (Proiettile pro : proiettili){
                System.out.println("s1");
                    if(Collisioni.CollsioniProiettile(pro, nemico)){
                        System.out.println("s2");
                        nemici.remove(nemico);
                        System.out.println("s3");
                        proiettili.remove(pro);
                        System.out.println("s4");
                        break;

                }
                    System.out.println("s5");
            }

            if(ControllaSconfitta()){
                this.giocON=false;
                Disegna();
            }
        }

This is the code, I'm sure it will help you.
This code is in a function that checks and update everything every n millisecond.
Thanks for the help
Exception in thread "Thread-7" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at java.lang.Thread.run(Thread.java:745)

and it freeze the game when the collsion happens.

A: The below code has been updated to use Iterator.remove() instead of ArrayList.remove(). Thank you to @PeterRader for clarifying how these should be used.

If you are intending to modify an ArrayList while iterating over it, you should not use a for-each loop to iterate over it directly. There are two alternative approaches, using an iterator to avoid iterating over the ArrayList itself, or using Java 8's removeIf() function.
I will give a simple (and tested) example of using an iterator, and then attempt to modify your code to do the same thing:
Iterator Example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class IteratorExample{

     public static void main(String []args){

        ArrayList<Integer> arrList = new ArrayList<Integer>(Arrays.asList(1,2,3));

        // Get an Iterator to iterate over the Integers in arrList

        Iterator<Integer> iterator = arrList.iterator();

        // While iterator hasNext element, access this element with .next() and print it.
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }

     }
}

Modifying your code to use an iterator
Apologies for any spelling mistakes or syntax errors in this version - I have been unable to test it, but given it's only a small piece of code there shouldn't be many and hopefully you will be able to remedy them using the example above. Don't forget to import java.util.Iterator too!
ArrayList<Nemico> nemici= o_orda.getNemici();

Iterator<Nemico> nemiciIterator = nemici.iterator();

while (nemiciIterator.hasNext()) {

    nemico = nemiciIterator.next();

    if(Collisioni.ControllaCollisioni(o_navicella, nemico)){
        nemiciIterator.remove(nemico);
        this.o_navicella.vita-=10;
        break;
    }

    Iterator<Proiettile> proIterator = proiettili.iterator();

    while (proIterator.hasNext()) {

        pro = proIterator.next();

        if(Collisioni.CollsioniProiettile(pro, nemico)){
            nemiciIterator.remove(nemico);
            proIterator.remove(pro);
            break;
        }
    }

    if(ControllaSconfitta()){
        this.giocON=false;
        Disegna();
        }
    }
    ...

Resources
Here is a relevant resource. This also includes an example of using removeIf()! https://www.baeldung.com/java-concurrentmodificationexception.


text:
Q: OAuth2.0 - maximum requests for refresh token Is there any maximum number of requests to get a brand new access token using a refresh token?

A: Yes. 25 according to Google's developer documentation

A: Access tokens have a lifetime of 3600 seconds. Requesting a new access token before that time is up works fine but it's inefficient for your app to do so often. I don't think Google publishes a limit on how many non-expired access tokens a refresh token can have but you may get errors and it's non-optimal.
For most apps, refreshing an access token 10 minutes before the current access token expires (later if your not to worried about clock drift) works well.

A: The number of requests depend on the authorization server security policy.
Some servers allow only one request (the refresh token is invalidate after the request), other servers may allow 10, 100 or even unlimited requests.


text:
Q: Can we create one IAM User that has access to create other IAM users in AWS In S3, can we create an IAM user and give it rights to create other IAM users?

A: S3 and IAM are 2 different AWS services. S3 has nothing to do with IAM user creation.
I'll go ahead and assume that you meant creating an IAM user with permissions to create other users.
Yes, it is possible to do so. You just have to attach a suitable IAM policy to the newly created user. Following policy should get you started.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "iam:CreateUser",
                "iam:CreateAccessKey"
            ],
            "Resource": "*"
        }
    ]
}

A: The policy specified by Maverick in the above answer can create a new user and create access and secret keys for the user. However, it cannot create or attach any policies to the created user. So, I'm adding the required permission to create and attach IAM and inline policies for IAM users.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iam:AttachUserPolicy",
                "iam:CreateAccessKey",
                "iam:CreatePolicy",
                "iam:CreateUser",
                "iam:PutUserPolicy"
            ],
            "Resource": "*"
        }
    ]
}

Refer this for more information about actions related to Identity and Access Management (IAM) in AWS: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_identityandaccessmanagement.html


text:
Q: Webpack module federation - module instance duplicated by import I'm building a React app with plugin support using module federation:

*

*It consist of a host app and multiple plugins (remote apps).

*Plugins are imported dynamically into the host app.

*Host app exposes some of its functionality to plugins.

// host app config
new ModuleFederationPlugin({
   name: "host",
   exposes: {
       // Host API used by plugins
       ".": "./src/api"
   },
   // ...
}

Now, I can import the API inside a plugin
import {FooBar} from "host";

and I can also import the same thing within the host app:
import {FooBar} from "./src/api";

The problem is that these imports are not resolved as a singleton. Host app and the plugin receives each own unique instance of the imported module. This is a problem because:

*

*I need to access a global state through the API.

*If there is a class shared through the API, then its instances created inside host/plugin are not equal (in terms of instanceof operator).

Plugin:
import {FooBar} from "host";

export const fooBar = new FooBar;

Host app:
import {FooBar} from "./src/api";

import("plugin").then(plugin => {
    plugin.fooBar instanceof FooBar; // false
});

Question: How to configure module federation for this to work? Or is this behavior a bug?
I have also reproduced it in this repository.
EDIT: After some investigation, the cause seems to be that main.js chunk and remoteEntry.js of the host app have separate __webpack_module_cache__ for module resolution.

A: I wrote a custom webpack plugin that fixes the described behavior by creating a shared module cache between main.js chunk and remoteEntry.js.
import webpack, {RuntimeGlobals} from "webpack";
import {ConcatSource, OriginalSource} from "webpack-sources";

const {Template} = webpack;
const {JavascriptModulesPlugin} = webpack.javascript;

const PLUGIN_NAME = "SharedModuleCachePlugin";

export default class SharedModuleCachePlugin {
    constructor(options = {}) {
        this.cacheVar = options.cacheVar || "__shared_module_cache__";
    }

    apply(compiler) {
        compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
            const compilationHooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
            compilationHooks.renderStartup.tap(PLUGIN_NAME, startupSource => {
                const cacheCode = Template.asString([
                    "if (typeof window !== 'undefined') {",
                    Template.indent([
                        `if (!window.${this.cacheVar}) {`,
                        Template.indent(`window.${this.cacheVar} = {};`),
                        "}",
                        "",
                        `__webpack_module_cache__ = window.${this.cacheVar};`,
                        `${RuntimeGlobals.moduleCache} = window.${this.cacheVar};`,
                    ]),
                    "}",
                ]);
                const cacheSource = new OriginalSource(cacheCode, "webpack/shared-module-cache");
                return new ConcatSource(cacheSource, startupSource);
            });
        });
    }
}

This needs to be used only in host app webpack configuration.


text:
Q: PHP Show .m3u8 Live Stream I build a live streaming website. The .m3u8 and .ts files are stored in server. I want to hide these files. I made a password protect page, if the user logged in, open this .php file will do the same thing as open .m3u8 file.
$reqpath = 'test/test.m3u8';
header("Cache-Control: no-store, no-cache,must-revalidate");
header("Cache-Control: post-check=0, pre-check=0",false);
header("Pragma: no-cache");
header('Content-type:application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($reqpath));
header('Content-Length: ' . filesize($reqpath));
@readfile($reqpath);

When I logged in and open this php file on safari, nothing happened... It does not show the video. Can anyone help me?
 Or do you have other solutions to protect .m3u8?
Thanks


text:
Q: WPF - ListView xml Bindign works only once I have a ListView Binded to an xml file (a simple log file).
This list view is in a secondary dialog Window in my project.
When I open the window for the first time it shows the info in the list view correctly. Then, if I close this window and do some stuff, my xml file changes. If now I reopen the dialog Window containing the xml file, it shows the last status (the info showed the firs time I opened the window), not the whole status with updates.
Why??

A: The XML doesn't trigger the INotifyPropertyChanged events that WPF databinding relies on to know when items change and need to be re-bound. You may want to set the ItemsSource or DataContext explicitly each time you open the dialog window.
Also, the XML objects don't detect file changes. You may need to reload the XML if you are relying on outside events (system logs?) to create the new XML nodes.

A: It's hard to tell exactly what will fix your problem because your description is imprecise.  You say:

I have a ListView Binded to an xml file (a simple log file).

and this is not actually possible.  You can't bind a ListView, only its ItemsSource.  And you can't bind to an XML file, but only to an object in memory that contains the data read from the XML file.  This sounds like I'm picking nits, but I'm not:  the clearer you are in describing what you're actually doing, the easier it will be to provide you with a usable answer.
It sounds as though you probably are defining an XmlDataProvider in XAML with its Source set to the name of the XML file.  If you set this as a resource in your main window, it's going to be loaded when the main window is loaded.  If your child window has something like
<ListView ItemsSource="{StaticResource MyXmlDocument}" .../>

it's going to look up the XmlDataProvider using the resource dictionary's Find method, and find it in the main window's resource dictionary.  You can close and reopen the child window all day long and the XmlDataProvider it uses won't change.
If this is the case, what you probably need is one of two things.
First, you could move the definition of the XmlDataProvider resource to the child window's XAML.  That will force the child window to reload the XML every time the child window loads.
Second, you could add a method to the main window that recreates the XmlDataProvider whenever the XML file changes on disk.  (How you know when the XML file changes, and how you trigger the method in the main window, are relatively tricky problems to solve - you could use FileSystemWatcher events, for instance.)  You'd need to use the DynamicResource markup extension in your child window XAML if you do this.) That will refresh the child window every time the XML file changes - even if it's already open.


text:
Q: How to get string in a Text using regex in Flutter I am trying to get /data/user/0/com.example.notes/app_flutter/image_picker8474259280565710843.jpg this in dart (Flutter).
I have tried the below code.
var opDataString = '{image: /data/user/0/com.example.notes/app_flutter/image_picker8474259280565710843.jpg}';

print(opDataString.split(new RegExp(r"{image: ^}*$"))[0]);

but nothing works.

A: Instead of using split, you can match using a capture group
{image: ([^}]+)}

Regex demo | Dart demo
For example
var opDataString = '{image: /data/user/0/com.example.notes/app_flutter/image_picker8474259280565710843.jpg}';
RegExp r = new RegExp("{image: ([^}]+)}");
var match = r.firstMatch(opDataString);
print(match.group(1));

Output
/data/user/0/com.example.notes/app_flutter/image_picker8474259280565710843.jpg

Or using split, getting the second item:
print(opDataString.split(new RegExp(r"{image: |}"))[1]);


text:
Q: Arrange many plots using gridExtra I have spent many hours trying to fit 11 graphs in one plot and arrange them using gridExtra but I have failed miserably, so I turn to you hoping you can help.
I have 11 classifications of diamonds (call it size1) and other 11 classifications (size2) and I want to plot how the median price for each increasing size1 and increasing clarity (from 1 to 6) varies by increasing size2 of the diamonds, and plot all the 11 plots in the same graph.
I tried using gridExtra as suggested in other posts but the legend is far away to the right and all the graphs are squished to the left, can you please help me figure out how the "widths" for the legend in gridExtra has to be specified? I cannot find any good explanations. Thank you very much for your help, I really appreciate it...
I have been trying to find a good example to recreate my data frame but failed in this as well. I hope this data frame helps understand what I am trying to do, I could not get it to work and be the same as mine and some plots don't have enough data, but the important part is the disposition of the graphs using gridExtra (although if you have other comments on other parts please let me know):
library(ggplot2)
library(gridExtra)

df <- data.frame(price=matrix(sample(1:1000, 100, replace = TRUE), ncol = 1))

df$size1 = 1:nrow(df)
df$size1 = cut(df$size1, breaks=11)
df=df[sample(nrow(df)),]
df$size2 = 1:nrow(df)
df$size2 = cut(df$size2, breaks=11)
df=df[sample(nrow(df)),]
df$clarity = 1:nrow(df)
df$clarity = cut(df$clarity, breaks=6)

# Create one graph for each size1, plotting the median price vs. the size2 by clarity:
for (c in 1:length(table(df$size1))) {

  mydf = df[df$size1==names(table(df$size1))[c],]
  mydf = aggregate(mydf$price, by=list(mydf$size2, mydf$clarity),median);
  names(mydf)[1] = 'size2'
  names(mydf)[2] = 'clarity'
  names(mydf)[3] = 'median_price'

  assign(paste("p", c, sep=""), qplot(data=mydf, x=as.numeric(mydf$size2), y=mydf$median_price, group=as.factor(mydf$clarity), geom="line", colour=as.factor(mydf$clarity), xlab = "number of samples", ylab = "median price", main = paste("region number is ",c, sep=''), plot.title=element_text(size=10)) + scale_colour_discrete(name = "clarity")  + theme_bw() + theme(axis.title.x=element_text(size = rel(0.8)), axis.title.y=element_text(size = rel(0.8)) , axis.text.x=element_text(size=8),axis.text.y=element_text(size=8) ))
  }

# Couldnt get some to work, so use:
p5=p4
p6=p4
p7=p4
p8=p4
p9=p4

# Use gridExtra to arrange the 11 plots:

g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

mylegend<-g_legend(p1)

grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                     p2 + theme(legend.position="none"),
                     p3 + theme(legend.position="none"),
                     p4 + theme(legend.position="none"),
                     p5 + theme(legend.position="none"),
                     p6 + theme(legend.position="none"),
                     p7 + theme(legend.position="none"),
                     p8 + theme(legend.position="none"),
                     p9 + theme(legend.position="none"),
                     p10 + theme(legend.position="none"),
                     p11 + theme(legend.position="none"),
                     main ="Main title",
                     left = ""), mylegend,
                    widths=unit.c(unit(1, "npc") - mylegend$width, mylegend$width), nrow=1)

A: I had to change the qplot loop call slightly (i.e. put the factors in the data frame) as it was throwing a mismatched size error. I'm not including that bit since that part is obviously working in your environment or it was an errant paste.
Try adjusting your widths units like this:
widths=unit(c(1000,50),"pt")

And you'll get something a bit closer to what you were probably expecting:
And, I can paste code now a few months later :-)
library(ggplot2)
library(gridExtra)

df <- data.frame(price=matrix(sample(1:1000, 100, replace = TRUE), ncol = 1))

df$size1 = 1:nrow(df)
df$size1 = cut(df$size1, breaks=11)
df=df[sample(nrow(df)),]
df$size2 = 1:nrow(df)
df$size2 = cut(df$size2, breaks=11)
df=df[sample(nrow(df)),]
df$clarity = 1:nrow(df)
df$clarity = cut(df$clarity, breaks=6)

# Create one graph for each size1, plotting the median price vs. the size2 by clarity:
for (c in 1:length(table(df$size1))) {

  mydf = df[df$size1==names(table(df$size1))[c],]
  mydf = aggregate(mydf$price, by=list(mydf$size2, mydf$clarity),median);
  names(mydf)[1] = 'size2'
  names(mydf)[2] = 'clarity'
  names(mydf)[3] = 'median_price'
  mydf$clarity <- factor(mydf$clarity)

  assign(paste("p", c, sep=""),
         qplot(data=mydf,
               x=as.numeric(size2),
               y=median_price,
               group=clarity,
               geom="line", colour=clarity,
               xlab = "number of samples",
               ylab = "median price",
               main = paste("region number is ",c, sep=''),
               plot.title=element_text(size=10)) +
           scale_colour_discrete(name = "clarity") +
           theme_bw() + theme(axis.title.x=element_text(size = rel(0.8)),
                              axis.title.y=element_text(size = rel(0.8)),
                              axis.text.x=element_text(size=8),
                              axis.text.y=element_text(size=8) ))
}

# Use gridExtra to arrange the 11 plots:

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

mylegend<-g_legend(p1)

grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                         p2 + theme(legend.position="none"),
                         p3 + theme(legend.position="none"),
                         p4 + theme(legend.position="none"),
                         p5 + theme(legend.position="none"),
                         p6 + theme(legend.position="none"),
                         p7 + theme(legend.position="none"),
                         p8 + theme(legend.position="none"),
                         p9 + theme(legend.position="none"),
                         p10 + theme(legend.position="none"),
                         p11 + theme(legend.position="none"),
                         top ="Main title",
                         left = ""), mylegend,
             widths=unit(c(1000,50),"pt"), nrow=1)

Edit (16/07/2015): with gridExtra >= 2.0.0, the main parameter has been renamed top.


text:
Q: HTMLInputElement throwing a type error when switching an element between types I'm trying to code along to this React GraphQL TypeScript tutorial
Goal: Basically the HTML element type should be set to be the element 'Textarea' if the default variable: 'textarea' = true, and set to element 'Input' if variable:'textarea' = false.
Currently I'm at minute 6:05:28 and I'm stuck with the following error which does not appear in the video, I'm not sure why. I realised this doesn't really affect anything (the thing still works) but its showing a red underline error which is rather annoying:
Type 'ComponentWithAs<"textarea", TextareaProps>' is not assignable to type 'ComponentWithAs<"input", InputProps>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'MergeWithAs<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, any, InputProps, any>' is not assignable to type 'MergeWithAs<DetailedHTMLProps<TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>, any, TextareaProps, any>'.
Type 'MergeWithAs<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, any, InputProps, any>' is not assignable to type 'OmitCommonProps<DetailedHTMLProps<TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>, keyof TextareaProps>'.
Types of property 'ref' are incompatible.
Type 'LegacyRef<HTMLInputElement> | undefined' is not assignable to type 'LegacyRef<HTMLTextAreaElement> | undefined'.
Type '(instance: HTMLInputElement | null) => void' is not assignable to type 'LegacyRef<HTMLTextAreaElement> | undefined'.
Type '(instance: HTMLInputElement | null) => void' is not assignable to type '(instance: HTMLTextAreaElement | null) => void'.
Types of parameters 'instance' and 'instance' are incompatible.
Type 'HTMLTextAreaElement | null' is not assignable to type 'HTMLInputElement | null'.
Type 'HTMLTextAreaElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, capture, and 26 more.

The line giving error is: InputOrTextarea being highlighted in red with the above error
InputOrTextarea = Textarea;

The full code is:
type InputFieldProps = InputHTMLAttributes<HTMLInputElement> & {
  label: string;
  name: string;
  textarea?: boolean;
};

export const InputField: React.FC<InputFieldProps> = ({
  label,
  textarea,
  size: _,
  ...props
}) => {
  let InputOrTextarea = Input;
  if (textarea) {
    InputOrTextarea = Textarea;
  }
  const [field, {error, }] = useField(props);
    return (
      <FormControl isInvalid = {!!error}>
        <FormLabel htmlFor={field.name}>{label}</FormLabel>
        <InputOrTextarea {...field} {...props} id = {field.name} placeholder={props.placeholder}/>
        {error ? <FormErrorMessage>{error}</FormErrorMessage> : null}
      </FormControl>
    );
}

A: For you or anyone else:
I had the same issue and I was watching the same video. You need to change the import from '@chakra-ui/react' to '@chakra-ui/core'.
I was using '@chakra-ui/core' and it gave me an error. As soon I install 'yarn add @chakra-ui/core @emotion/core @emotion/styled emotion-theming' and I used the core import, the error is gone.

A: You could try forcing the type on InputOrTextarea to allow an input or textarea to be assigned to it. For example:
  let InputOrTextarea: HTMLInputElement | HTMLTextAreaElement | null = Input;
  if (textarea) {
    InputOrTextarea = Textarea;
  }


text:
Q: Richfaces ExtendedDataTable selection question Please help.
Have a look at http://richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=extendedDataTable&sample=exTableSelection&skin=blueSky
You'll see nice "Cars marketplace" table with multiple selection support. You'll also notice that one of the selected rows appears in bold. What does this bold line mean at all? Is it managed somehow via methods of org.richfaces.component.UIExtendedDataTable or any other RF classes? Cant find an API for that line.
What I'm trying to do, is to create new item inside backing bean and force table selection to point to newly created item. I've managed to set selection via setSelection(), but I have no control over that bold line, it remains on it's previous position, please help.

A: The bold style for the selected row is managed by the stylesheet shipped with richfaces .Each theme in the richfaces has their own stylesheet.  You can refer to the official documentation ( It is still a draft version) to see which style classes are available for customizing the look and feel of the rich:extendedDataTable.
For example , rf-edt-r-sel or rf-edt-r-act define the style of the selected row,  you can override them  by declaring a style for these style class names in the page where you use rich:extendedDataTable
<style type="text/css">
.rf-edt-r-sel{
     background-color: yellow;
}

.rf-edt-r-act{
   font-weight: bold;
   color: red;
}
</style>

Reply to the comment:
The RowKey seems to be the row number of the extended table. If you want to get the underlying object (i.e. InventoryItem ) from the UIExtendedDataTable , you have  to  set the row number you want to retrieve using setRowKey(selectionKey) before calling getRowData() to get the actual object . So dataTable.setRowKey(selectionKey) is used to get the selected InventoryItem  from the UIExtendedDataTable in order to  put them into the selectionItems (which will be displayed in the "Selected Rows" box that is besides the extended table) . For the  purposes of Object originalKey = dataTable.getRowKey(); and dataTable.setRowKey(originalKey); , you can refer to this link .
In richfaces 3.3 , I find UIExtendedDataTable has a method called setActiveRowKey()  , which seems can set the active record . But it is removed in the latest version of richfaces 4.0 CR1 .So maybe you can use the UIExtendedDataTable 's java script API to achieve the same effect .
You first define an int property called boldRow in your MBean . Then you will have a <a4j:commandButton> to call a Mbean 's method .This method will assign the row number that you want to select according to your logic. The oncomplete attribute of the button should call the UIExtendedDataTable 's JavaScript API to select a row  which row number is equal to boldRow, and then  use render attribute to  refresh the UIExtendedDataTable. So the <a4j:commandButton> and <rich:extendedDataTable>  should probably look like this:
 <a4j:commandButton value="Submit" action = "#{MBean.action}" render="#{rich:clientId('table')}"
           oncomplete="#{rich:component('table')}.selectRow(#{MBean.boldRow}); #{rich:component('table')}.setActiveRow(#{MBean.boldRow});" />

<rich:extendedDataTable id="table" .....
................
</rich:extendedDataTable>


text:
Q: Create a key of 3 columns including a relation to another table (code first) i have a problem creating my database structure. For example i have those 3 classes
public class Product
{
    [Key, Column(Order = 1)]
    [Required]
    public string ItemNo { get; set; }

    [Key, Column(Order = 2)]
    [Required]
    public string VariantCode { get; set; }

    public virtual List<ProductAttribute> Attributes { get; set; }

    public Product()
    {
        Attributes = new List<ProductAttribute>();
    }
}

public class ProductAttribute
{
    [Key]
    [Required]
    public string FieldName { get; set; }

    public string FieldValue { get; set; }

    public virtual Product Item { get; set; }

}

public class DbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<ProductAttribute> Attributes { get; set; }
}

The primary key for the Product table is ItemNo + VariantCode and will be created correctly. The second table ProductAttribute should have a key of ItemNo + VariantCode + FieldName but with the code above EF6 creates a primary key FieldName and a foreign key of ItemNo + VariantCode. I have tried several things including setting the [Key] attribute to the Item property in the ProductAttribute class but this doesn't work. Any ideas how to do this?

A: Try following:
public class ProductAttribute
{
    [Key]
    [Required]
    public string FieldName { get; set; }

    public string FieldValue { get; set; }

    [Key]
    [ForeignKey("Item"), Column(Order = 1)]
    public string ItemNo { get; set; }

    [Key]
    [ForeignKey("Item"), Column(Order = 2)]
    public string VariantCode { get; set; }

    public virtual Product Item { get; set; }
}


text:
Q: Upload de array de imagens PHP e MySQL Eu tenho o seguinte código:
<?php

if(isset($_FILES['files'])){
    $errors = array();

    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size = $_FILES['files']['size'][$key];
        $file_tmp = $_FILES['files']['tmp_name'][$key];
        $file_type = $_FILES['files']['type'][$key];
        $file_parts = pathinfo($file_name);//Returns an associative array containing file information
        $extensions = array("jpeg","jpg","png");//Allowed file

    if($file_size > 2097152){

            echo 'Tamanho do arquivo de ser menor que 2MB';

    }else{

    if(in_array ($file_parts['extension'],$extensions)){

        //Rename file
        $file_parts = ".".$file_parts['extension'];
        $file_name = uniqid().$file_parts;

            if(empty($errors)==true){
            //Move the file to a specific folder
            move_uploaded_file($file_tmp, "img/".$file_name);

            }else{
                print_r($errors);
            }//if(empty($errors)==true){

        }else{

            echo'Extensão não permitida';

        }//if(in_array ($file_parts['extension'],$extensions))

    }//if($file_size > 2097152){

    if(empty($errors)){

        print_r("<pre>".$file_name."</pre>");

    }//if(empty($errors))

    }//foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name)

}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Upload</title>
</head>
<body>
    <form action="" method="POST" enctype="multipart/form-data">
        <input type="file" name="files[]" multiple>
        <input type="submit" value="Enviar">
    </form>
</body>
</html>

Minha dúvida é, o que é melhor, fazer criar uma tabela no banco de dados para as imagens, assim quando eu precisa dessas imagens em algum formulário faço interação um para muitos, ou transformar o array em uma string?
Será que tem outra solução também?

A: Eu salvaria tudo num JSON, muito mais rápido a leitura e você pode inserir keys pra vincular a registros também...ficando a seu critério, mas a princípio apenas savaria no JSON mesmo:
$file = "img/images.json";
$json = json_decode(file_get_contents($file), true);
array_push($json, $file_name);
file_put_contents($file, json_encode($json));

Como neste exemplo, o json pode até ficar no mesmo diretório que as imagens, você pode incrementar outras informações da imagem que se fizer necessário no array também...

A: Salva no banco de dados, como citou!
Segue um exemplo de como eu faço:
Sugiro uma tabela chamada "Documentos"
Com campos como Id, e Tipo de documento
E outra tabela chamada "DocumentoArquivos"
Com campos como Id, Nome, DocumentoFk, Tamanho, Extensão, Diretorio.
Quanto você enviar os arquivos, salve no seu diretório de imagens e posteriormente use um Begin Transaction para salvar o "Envio" como um "Documento" e cada arquivo como "DocumentoArquivos",
Posteriormente você pode editar este mesmo documento inserindo ou removendo arquivos dele.


text:
Q: how can I count every item in a list by a specific range? Also, why the last item in my output is not sorted? I have written a code to receive the user input as a list.
def lst_data():
    lst = []
    total = int(input('Number of Data: '))
    for number in range(0, total):
        user_data = int(input('Enter the Data: '))
        lst.sort()
        lst.append(user_data)
    print(lst)

the output is:
[50, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 68, 70, 70, 71, 72, 73, 74, 75, 76, 77, 79, 79, 80, 80, 81, 82, 84, 86, 87, 88, 89, 89, 90, 91, 83]

The next step I want to do is count every item on that list by every 6 numbers like 50-55 = ???, 56-61 = ???, 62-67 =???, and so on.
I've been trying with:
counter =  0
for i in last:
    if 50 < i < 55:
    counter += 1

print(counter)

it works but I have to repeat the code over and over and value in the "if statement" has to be from the user input
how can i figure this out? and I want to check if there is any way to make my code simpler

A: You are first sorting then adding the element, so in your loop sorting is done first and then the last element is added. Hence its left out. So you can swap the lines like below.
Your code
def lst_data():
    lst = []
    total = int(input('Number of Data: '))
    for number in range(0, total):
        user_data = int(input('Enter the Data: '))
        # First append
        lst.append(user_data)
        # Then sort
        lst.sort()
    print(lst)

Suggested code
Below is the code with list comprehension.

*

*loop interates over the total to take that many number of inputs

*The values are then added to the list.

*The list is then sorted out and printed
def lst_data():
    lst = []
    total = int(input('Number of Data: '))
    lst = sorted([int(input('Enter the Data: ')) for i in range(total)])
    print(lst)

A: def lst_data():
lst = []
total = int(input('Number of Data: '))
for number in range(0, total):
    user_data = int(input('Enter the Data: '))
    lst.append(user_data)
    lst.sort()
print(lst)

use this code

A: I think this is what you're trying to do:
def count(lo, hi, _list):
    return sum(lo <= e <= hi for e in _list)

nd = int(input('Number of data items: '))
data = []

for _ in range(nd):
    datum = int(input('Enter datum: '))
    data.append(datum)

lo = int(input('Enter low range value: '))
hi = int(input('Enter high range value: '))

print(f'There are {count(lo, hi, data)} items in the range {lo}-{hi}')

Example:
Number of data items: 5
Enter datum: 2
Enter datum: 1
Enter datum: 3
Enter datum: 5
Enter datum: 6
Enter low range value: 1
Enter high range value: 5
There are 4 items in the range 1-5

Note:
There is no reason to sort the list


text:
Q: Statistics of n dice adding up to 117 1. The problem statement, all variables and given/known data
(I translated this from french)
Some n dice are thrown and the sum of all their face values is 117.
Estimate n through a confidence interval of 90%.
In other words, of all the possible rolls of n dice that sum up to 117, find a range in which n should be located 90% of the time.
For example, 20≤n≤117, 100% of the time because a 117-dice roll can sum up to 117, but not a 118-dice roll, and 19 dice can give a maximum sum of 114.
2. Relevant equations
To estimate the population average (here, the population is every possible roll of n dice that sums to 117) while the variance is unknown, and X is normally distributed (which it probably is), we use the following formula
$\frac{X^―−μ}{\sqrt{S^{2} _{n-1}/n}} : T_{n−1}$
Where :
X― is the sample average if that has anything to do with anything.
$S^{2} _{n-1}$ would be equal to $(n/n−1) S_2$where $S_2$ would be the sample's variance and n the number of items in the sample.
Tn−1 is the symbol for Student's t-distribution.
There are five other, closely related, formulae, but this is the one that seems the most reasonable to use.
But I'm not even sure how that can be used to estimate n.
3. The attempt at a solution
What has been shown above probably shows at which point I am lost in this affair. We have to use some distribution, but I'm not even sure my choice is right.

A: As I stated in a comment, the question makes no sense as posed since a confidence interval for just one value is meaningless; what is required to speak of a confidence interval is an entire prescription for determining confindence intervals from arbitrary observations. The formulation "find a range in which $n$ should be located $90\%$ of the time" seems to suggest that the person formulating the problem may misunderstand the concept of a confidence interval, as it seems to suggest a fixed interval which may or may not contain a varying $n$ $90\%$ of the time, rather than vice versa.
I doubt that you literally want an exact $90\%$ confidence interval; that would be a rather tedious calculation. I suspect that the idea is to approximate the distribution by a normal distribution. (No, it isn't one already.) A suitable $90\%$ confidence interval would then be one that includes all values of $n$ for which the observed sum $s$ is within approximately $1.645$ standard deviations of the mean. The mean of a single roll is $7/2$, and the variance of a single roll is $35/12$, so the mean is $\frac72n$ and the variance is $\frac{35}{12}n$. Thus the condition for $s$ to be within $1.645$ standard deviations of the mean is
$$
\left\vert s-\frac72n\right\vert\le1.645\sqrt{\frac{35}{12}n}\approx2.809\sqrt n\;.
$$
Squaring yields a quadratic equation for the interval boundaries:
$$
\left(s-\frac72n\right)^2\approx7.893n\;,\\
n^2-\frac47sn+\frac4{49}s^2-0.644n\approx0\;,\\
n\approx\frac27s+0.322\pm\sqrt{0.184s+0.104}\;.
$$
For $s=117$, this yields $n\approx33.751\pm4.651$, corresponding to a confidence interval of approximately $[29.1,38.4]$. Thus, with $90\%$ confidence $n$ lies betwen $30$ and $38$.


text:
Q: DQL - JOIN WITH properties of a relation My question is similar to this, but different.
Can you join on a subquery with Doctrine 2 DQL?
I want to get all the rooms regardless, and left join any occupants who belong to a booking that exists on a given date.
For example (a plain mysql result set - doctrine would return objects):
Room ID   | Occupant ID | Booking ID | Booking Start | Booking End
1         | 1           | 1          | Before today  | After today
1         | 2           | 1          | Before today  | After today
2         | NULL        | NULL       | NULL          | NULL

Here's what I'm trying:
SELECT r, a, b
FROM MyBundle:Room r
LEFT JOIN r.occupants a
WITH a.booking is not null
LEFT JOIN a.booking b
WITH b.enrolmentStart <= :date
AND b.enrolmentEnd >= :date
AND b.status = 1
ORDER BY r.number ASC

Unfortunately, this gets all the rooms, with all the people who ever stayed in that room ever, but only the bookings that exist on that given date.
On the other hand, if I change to the following,
I'm given only rooms that have bookings on that given date.
LEFT JOIN r.occupants a
WITH a.booking is not null
JOIN a.booking b

If I try the following, Doctrine says it didn't expect a dot after the 'a'.
LEFT JOIN r.occupants a
WITH a.booking.enrolmentStart <= :date
AND a.booking.enrolmentEnd >= :date
AND a.booking.status = 1
LEFT JOIN a.booking b

And lastly, if I try the following, doctrine is not happy about the order.
LEFT JOIN r.occupants a
WITH b.enrolmentStart <= :date
AND b.enrolmentEnd >= :date
AND b.status = 1
LEFT JOIN a.booking b

Any ideas?

A: I think that you can achieve this query only using left joins:
SELECT
    r.number, o.id_occupant, b.id_booking, b.enrolmentStart, b.enrolmentEnd
FROM
    MyBundle:Room r
    LEFT JOIN r.occupants o
    LEFT JOIN o.booking b
    AND b.status = 1
    AND b.enrolmentEnd >= :date
    AND b.enrolmentStart <= :date
ORDER BY r.number ASC

Take a look to this equivalent sql (SQL Fiddle) query.
Debugged sql:
select r.number, ref.id_occupant, ref.id_booking
from rooms r
LEFT JOIN (select * from rooms r2
left join occupants o on o.room = r2.id_room
left join booking b on b.id_booking = o.booking
where b.status = 1
and b.enrolmentEnd >= '2015/03/09'
and b.enrolmentStart <= '2015/03/10') as ref on r.id_room = ref.id_room


text:
Q: borderRadius in react-native-autocomplete-input I want to create AutoComplete as in the image, how could I do?

Below example of my current implementation,
inputContainerStyle: {
   minHeight: 0,
   borderWidth: 0,
   borderBottomWidth: 0,
   backgroundColor: Colors.white,
   fontSize: Sizes.textBig,
   fontFamily: Fonts.regular,
}

A: From the styling you posted it seems like you missed some properties. Have you tried adding width, height and borderRadius properties to the container ?


text:
Q: How to get past 24 hours data using SQL in VBScript? I am using VBScript. I'm connected to an SQL database using an ADODB connection. I wrote an inline SQL query in VBScript.
Requirement is: to fetch all the records from last 24 hours (systemtimestamp - 24 hours). The query is running as expected and fetching data in SQL Server. But if I use the same query in the VBScript file I am not getting the records, it is returning null.
SELECT *
FROM customer
WHERE CAST(InsertDate AS DATETIME) > = CAST(DATEADD(day, -1, GETDATE()) AS DATETIME)

VBScript code:
Dim Connection
Dim Recordset
Dim SQL
Dim Server
Dim field
Dim Header
dt= Date
dt = Replace(dt,"/","-")
dt1= DateAdd("d", -1, Date)
dt1 = Replace(dt1,"/","-")
t=FormatDateTime(now, 4)
t1=FormatDateTime(now-24, 4)

Set objFSO = CreateObject("Scripting.FileSystemObject")

outFile="D:\"

if not objFSO.FileExists(outfile) then
Set objFile = objFSO.CreateTextFile(outFile,True)
else
Set objFile = objFSO.OpenTextFile(outFile,8,True)
End if

objFile.Write " "& vbCrLf & vbCrLf &"LOG Details on  "

objFile.Write(NOW) & vbCrLf & vbCrLf

SQL = "SELECT * FROM customer WHERE CAST(InsertDate AS DATETIME) > = CAST(DATEADD(day, -1, GETDATE()) AS DATETIME)"
'create an instance of the ADO connection and recordset objects
Connection.Open "Provider=SQLOLEDB; Data Source=DS;UID=id;PWD=pwd;Database=db"
Set Connection = CreateObject("ADODB.Connection")
Set Recordset = CreateObject("ADODB.Recordset")
objFile.Write "1. Connected to the Database" & vbCrLf & vbCrLf
'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL, Connection
'first of all determine whether there are any records
    If Recordset.EOF Then
    objFile.Write "2. No Records Retrieved From the Database" & vbCrLf & vbCrLf
    mail()

'if there are records then loop through the fields
    Else
    objFile.Write "2. Records Retrieved From the Database" & vbCrLf & vbCrLf
    'Send the Email with data
    sendMail()
    End If
'close the connection and recordset objects to free up resources

Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing


text:
Q: Show updated record without refresh I have 2 page.
When double click row data in first page will be go to second page.
second page is for update purpose.
when successful update in second page and i want back to first page, the data show not updated in first page but when refresh the data will show updated record.
How can i get the updated record show in first page without click refresh?
below is first page aspx code:
<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <tr style="cursor: hand;" onmouseover="this.style.backgroundColor='#E6F0FF'"
            onmouseout="this.style.backgroundColor='#FFFFFF'"
            onclick="javascript:window.location.href='V_Updated.aspx?mail=<%#Eval("mail") %>'">

            <%#Eval(" mail    ")%>
            <%#Eval(" remarks     ")%>

    </ItemTemplate>
</asp:Repeater>

second page aspx button back code:
Back

A: Better to use AJAX for updating data, if it is suitable for your project. This way you do not have to use two different pages.
http://www.webblogsforyou.com/ajax-introduction-how-to-use-ajax-in-asp-net-with-example/
Thanks!

A: Don't go back using the browser history (e.g. using history.back()). Different browsers handle caching differently, so it's difficult to control if your page would get refreshed. Provide a proper link to the previous page instead.

A: Simply put a link in second page like below :
 Back


text:
Q: Can i use sata adapter for more memory for gaming? my old laptop broke and my new one has only 32 gb of memory. My old laptop had 750 gb hdd. If i connect my old laptops hd to my new laptop via sata cable will i be able to save games to it via steam and play them? thanks in advance

A: I assume that by 'memory' you mean storage, not RAM.
Yes, you can connect the old laptop's disk through a SATA⇆USB adapter and it'll be usable with Steam – although you should make sure both the adapter and the port are USB 3, otherwise it might be too slow for some games.

A: If you are lucky (owner of some HP laptop that has combined eSATA/USB port)  then you need only a eSATA cable for that (2-5 bucks) and it will give you the same transfer speed as an internal hdd. If you will get USB2<->SATA adapter  then you will be limited to a maximum speed 30-38 Mbytes/s, so make sure you have USB3(blue one) on new laptop and make sure then to get UBS3<->SATA adapter to get compatible with SATA speed


text:
Q: How to send generated PDF document to frontend in Restfull way in Spring Boot? I have implemented by guide pdf generating.
my class PdfView has a method:
@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) {
    response.setHeader("Content-Disposition", "attachment; filename=\"animal-profile.pdf\"");

    List<Animal> animals = (List<Animal>) model.get("animals");
    try {
        document.add(new Paragraph("Generated animals: " + LocalDate.now()));
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    PdfPTable table = new PdfPTable(animals.stream().findAny().get().getColumnCount());
    table.setWidthPercentage(100.0f);
    table.setSpacingBefore(10);

    Font font = FontFactory.getFont(FontFactory.TIMES);
    font.setColor(BaseColor.WHITE);

    PdfPCell cell = new PdfPCell();
    cell.setBackgroundColor(BaseColor.DARK_GRAY);
    cell.setPadding(5);

    cell.setPhrase(new Phrase("Animal Id", font));
    table.addCell(cell);

    cell.setPhrase(new Phrase("Animal name", font));
    for (Animal animal : animals) {
        table.addCell(animal.getId().toString());
        table.addCell(animal.getName());
    }
    document.add(table);
}

How should I implement controller with GET method to download PDF?

A: The sample code looks like below to download the image using an API -
@RequestMapping("/api/download/{fileName:.+}")
public void downloadPDFResource(HttpServletRequest request, HttpServletResponse response,@PathVariable("fileName") String fileName) throws IOException {
    String path = somePath + fileName;
    File file = new File(path);
    if (file.exists()) {
        String mimeType = URLConnection.guessContentTypeFromName(file.getName()); // for you it would be application/pdf
        if (mimeType == null) mimeType = "application/octet-stream";
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\""));
        response.setContentLength((int) file.length());
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }
}

Goto the url - http://localhost:8080/download/api/download/fileName.pdf
Assuming your sevices are deployed at port 8080
You should be able to preview the file.
Note :  If you want to download the file set the Content-Disposition as attachment

A: The AbstractPdfView is a View itself and instance of it can be simply returned from a handler method to render the document.
From Spring Reference. PDF Views:

A controller can return such a view either from an external view definition (referencing it by name) or as a View instance from the handler method.

Here is a minimal example:
SimplePdfView.kt:
class SimplePdfView : AbstractPdfView() {
    override fun buildPdfDocument(
            model: MutableMap<String, Any>,
            document: Document, writer: PdfWriter,
            request: HttpServletRequest, response: HttpServletResponse
    ) {
        document.add(Paragraph("My paragraph"))
    }
}

SimpleController.kt:
@Controller
class SimpleController {
    @GetMapping
    fun getPdf() = SimplePdfView()
}

When the / endpoint is hit, the pdf is rendered in browser.

If you need to download already existing pdf, you may take a look at this answer


text:
Q: Topological question from the book '' Differential Topology '' of Guillemin and Pollack Here's the question : A smooth bijective map of manifolds need not be a diffeomorphism. In fact, show that $$f:\mathbb{R^1}\rightarrow {R^1}$$ $$x\rightarrow f(x)=x^3,$$ is an example.
I would like to do this problem, but I'm really not sure I understand it. The question does mean that there are smooth bijective map of manifold without as the map is a diffeomorphism. Could someone explain to me the meaning of this question?

A: The important fact here is that you need to take a closer look at the inverse $f^{-1}$.
The inverse of $x^3$ is $\sqrt[3]{x}$ the differential of the inverse $\frac{d}{dx}f^{-1}=\frac{1}{3 \sqrt[3]{x^2}}$ outside of $0$ and nonexistent at $0$ therefore $f$ is no diffeomorphism since the inverse is not differentiable at $0$.


text:
Q: Where is -32768 coming from? This is LC3 Assembly code I am working with
.ORIG x3000
LOOP LDI R0, KBSR
BRzp LOOP

From LC3 Assembly, I know that LDI is a load indirect addressing mode, meaning it read in an address stored at an location and then read the value at that location
From  Lc3 Keyboard, I know that KBSR is the keyboard status register, which is one when keyboard has received a new character.
Here is my test run in Lc3 simulator? I entered the character 'a'
After executing LDI R0, KBSR, register 0 stores a value of -32768.
Does anyone know, based off my definitions for ldi and KBSR where this number is coming from? I was expecting something like 1 to be stored because the keyboard has received a new character.

A: In KBSR (keyboard status register) bit 15 is set when a key is read, so you get 0b1000_0000_0000_0000 (or 0x8000) ... which - interpreted as a 2's complemented negative number - happens to be -32768 decimal.