spring mvc, maven build failure

Question: Screen shot of Installed Jre's in STS 3.6.0
This is my first maven build.Checked every thing still getting a Maven build failure. The IDE I am using is sts 3.6.0. The following example is from the website called crunchify. Did exactly as instructed. Not sure whats causing the error.
pom.xml
<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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>CrunchifySpringMVCTutorial</groupId>
        <artifactId>CrunchifySpringMVCTutorial</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <build>
            <sourceDirectory>src</sourceDirectory>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.6</version>
                    <configuration>
                        <warSourceDirectory>WebContent</warSourceDirectory>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>
            <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.2.5.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>

            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.1.3</version>
            </dependency>
        </dependencies>
    </project>

index.jsp

<title>Spring MVC Tutorial Series by Crunchify.com</title>

            Hey You..!! This is your 1st Spring MCV Tutorial..

            Click here to See Welcome Message... (to
            check Spring MVC Controller... @RequestMapping("/welcome"))

CrunchifyHelloWorld.java
package com.crunchify.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/*
 * author: Crunchify.com
 *
 */

@Controller
public class CrunchifyHelloWorld {

    @RequestMapping("/welcome")
    public ModelAndView helloWorld() {

        String message = "

"
                + "
********** Hello World, Spring MVC Tutorial
This message is coming from CrunchifyHelloWorld.java **********

";
        return new ModelAndView("welcome", "message", message);
    }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>CrunchifySpringMVCTutorial</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

    <servlet>
        <servlet-name>crunchify</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>crunchify</servlet-name>
        <url-pattern>/welcome.jsp</url-pattern>
        <url-pattern>/welcome.html</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

</web-app>

crunchify-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.crunchify.controller" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

console Errors:
[INFO] Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building CrunchifySpringMVCTutorial 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ CrunchifySpringMVCTutorial ---
[INFO] Deleting C:\Users\shamee\Documents\CodeView\CrunchifySpringMVCTutorial\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ CrunchifySpringMVCTutorial ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\Users\shamee\Documents\CodeView\CrunchifySpringMVCTutorial\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ CrunchifySpringMVCTutorial ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\Users\shamee\Documents\CodeView\CrunchifySpringMVCTutorial\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.641 s
[INFO] Finished at: 2016-06-01T16:14:45+05:30
[INFO] Final Memory: 7M/78M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project CrunchifySpringMVCTutorial: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Answer: Go into Window > Preferences > Java > Installed JREs > and check your installed JREs. You should have an entry with a JDK there. Select your jdk version and than Click OK
Then RightClick Project -> Maven -> Update Project
Comment: There is only an entry starting with a jre1.8.0 which is checked. there nothing starting with a jdk
Comment: I created a link to the screen shot of the  Installed Jre window up in the discription
Comment: Click on the add new-new runtime environment and that browse to your java installatiom folder and select jdk 1.8 folder
Comment: just select - Standard VM - as JRE type
Answer: You have to add JDK which is installed on your computer with "Add" button (cf. your screenshot)
Here's an example of correct JDK path : C:\Program Files\Java\jdk1.8.0_92
Then, you can follow the steps that KLajdPaja has provided in his answer.
If you don't have the JDK on your computer, you can have it on Oracle website. Here's the link for JDK : http://www.oracle.com/technetwork/java/javase/downloads/index.html
Comment: My build is successful now , but Im having different kind of deployment problem.

spring mvc, maven build failure


Why is my responsive CSS menu forcing page content to jump upward?

Question: I have a navigation menu that is positioned relative to other elements in my code. When you view this navigation menu in a browser that has a minimum width of 200px max 767px, and open the navigation menu, all of the content is pushed down, which is good, as you can view all of the content, however, if you start to scroll down with the menu open, the page content jumps upward at least 400+ pixels not allowing anyone to read 1/4 of the content on the page.
I have a script that makes this navigation menu stick to the top of the browser, and when I turn off that script and repeat the above actions everything is fine; the content doesnt jump etc. The only problem then is that the navigation menu no longer sticks to the the top of the page, and when the nav menu is opened it does not push any content down, it gets covered up by the expanding navigation menu.
I have attached a working fiddle that replicates the issue. http://jsfiddle.net/y7Cgg/1/
Any remedy for this scenario?
Script
$(document).ready(function(){
    $(this).scrollTop(0);
});

$(window).scroll(function()
{
    if( $(window).scrollTop() > 36 )
    {
        $('.mobile-nav-container').css({position: 'fixed'});
    }
    else
    {
        $('.mobile-nav-container').css({position: 'relative', top: '-3px'});
    }
});

HTML

<button class="open-menu"></button>
<button class="open-menu-small"></button>

CURRENT JOURNAL

SUBSCRIBE

SUBMIT MATERIAL

SUBMISSION GUIDELINES

3E BLOG

PAST JOURNALS

ABOUT 3ELEMENTS

THE EDITORS

CONTACT

USAGE RIGHTS

CURRENT JOURNALOur latest and greatest!

SUBMITYour writing

SUBMISSION GUIDELINESEverything you need to know is here

BLOGJust a blog

PAST JOURNALSBrowse our issue archives

ABOUT 3EWhat we're about

Usage Rights in our Journal

If 3Elements Review decides to publish your work, we ask for first-time publishing rights. Afterward, the rights are reverted back to you. If your work is reprinted elsewhere, we ask that you reference 3Elements Review as the original publisher. We also request the right to archive your work permanently. We reserve the right to include your work on our website, in printed form, and in collections of work acquired from our past issues, such as annual anthologies.

3Elements Review retains no rights on submitted artwork and images; rights belong to the artist/photographer. However, by submitting your artwork or photography, you agree to allow 3Elements Review to display your work on any of the following: 3elementsreview.com, Twitter, and Facebook. If used in any of the aforementioned forms, your artwork/photos will always be credited to you.

We reserve the right to modify the accepted work in terms of punctuation, word usage, spelling, and capitalization, with permission from the author. If the author declines the changes, we reserve the right to revert our decision to publish.

The author confirms that the work is wholly original, does not violate or infringe upon the copyright or privacy of any other person or company whatsoever, and that they, the author, are the sole owner and creator of the work to be published.

Back to top

FAQ

TERMS

USAGE RIGHTS

PRIVACY POLICY

CONTACT

MEET THE STAFF

Subscribe to our newsletter

   ©  3Elements Literary Review, Chicago, IL  Site design by Marlon Fowler

CSS
@media only screen and (min-width:200px) and (max-width:767px) {
/******************************************NAVIGATION  START*********************************************/
h1.page-headline {
    top:0px;
    text-align:center;
    margin-top:0px;
    margin-bottom:0px;
    width:98%;
    font-size:1.5em;
}

h2.sub-head {
    top:10px;
    text-align:center;
    width:98%;
    font-size:1.15em;
    line-height:1.25em;
}

.mobile-nav-container {
    position:relative;
    background-color:#252525;
    top:-3px;
    width:100%;
    height:22px;
    border-bottom:3px solid #ffd09d;
    z-index:300;
    display:inline-block;
}

ul.nav-menu {/*navigation menu as a whole*/
    position:relative;
    top:-21px;
    margin:0px;
    padding:0px;
    background-color:#252525;
    width:100%;
    border-bottom: 2px solid #ff6000;
}

nav ul li a {/*navigation list items*/
    position:relative;
    top:0px;
    padding-left:5%;
    padding-right:5%;
    padding-top:3px;
    line-height:1.9em;
    border-bottom: 1px solid #313131;
    width:90%;
    height:30px;
    display:inline-block;
    font-family:myriad pro;
    font-size:1em;
    list-style:none;
    transition:300ms;
    -webkit-transition:300ms;
}

nav ul li {/*drop down list padding settings*/
    list-style:none;
}

nav li a {/*main navigation text color and padding settings*/
    position:relative;
    top:0px;
    margin:0px;
    padding:0px;
    color:#ffd09d;
    text-decoration:none;
}

.nav-menu li:active a {/*main navigation TEXT HOVER effects*/
    color:#ff6000;
    background-color:#beb29a;
    transition:400ms;
    -webkit-transition:400ms;
}

.nav-menu li:hover a {/*main navigation TEXT HOVER effects*/
    color:#ffa84a;
    transition:300ms;
    -webkit-transition:300ms;
}

.home-btn-mobile {
    position:relative;
    margin:0px;
    top:-20px;
    left:65px;
    outline:none;
    list-style:none;
    display:inline-block;
}

button.open-menu-small {
    position:relative;
    top:1px;
    left:3%;
    margin:0px;
    padding:0px;
    width:23px;
    height:19px;
    display:inline-block;
    outline:none;
    background-color:#353535;
    border:2px solid #424242;
    box-shadow:0px 0px 2px #000;
    cursor:pointer;
}

button.open-menu-small:active {
    cursor:pointer;
    border:2px solid #353535;
    box-shadow:none;
}
/******************************************NAVIGATION  END*********************************************/

/******************************************CONTENT FOR ALL PAGES*********************************************/
#container {
    position:relative;
    top:-15px;
    height:300px;
}

#main-image img {
    position:relative;
    top:0px;
    width:100%;
    height:auto;
    margin:0px;
    padding:0px;
}

#main-image2 {
    position:relative;
    top:0px;
    width:100%;
    height:37px;
    margin:0px;
    padding:0px;
}

#main-logo-mobile {
    position:absolute;
    top:1px;
    left:43%;
    width:32px;
    background-repeat:no-repeat;
    z-index:1000;
    border:none;
    outline:none;
    display:block;
}

.image-sub-head {
    position:absolute;
    top:43px;
    left:0px;
    right:0px;
    text-align:center;
    font-family:myriad pro light, arial, sans-serif;
    font-size:1.3em;
    color:#ffffff;
    opacity:1;
    z-index:4;
}

.current-elements {
    top:30px;
    width:100%;
    left:0px;
    right:0px;
    text-align:center;
    font-size:1.65em;
    line-height:.85em;
    opacity:1;
}

#elements-ticker {
    top:15px;
    left:0px;
    width:100%;
    margin-left:auto;
    margin-right:auto;
    padding-bottom:5px;
}
/******************************************CONTENT FOR ALL PAGES  END*********************************************/

/*****************************************USAGE RIGHTS**************************************************/
p.usage-rights {
    top:20px;
    width:95%;
    left:1%;
    font-size:1em;
    text-align:left;
    line-height:1.5em;
}

.p-social:visited, .p-social:link {
    color:#ff6000;
    text-decoration:none;

}

.p-social:hover {
    color:#ff6000;
    text-decoration:underline;

}
/*****************************************USAGE RIGHTS  END**************************************************/

/*****************************************FOOTER**************************************************/
footer.bottom-footer {
    position:absolute;
    width:100%;
    height:200px;
    background-color:#111111;
    padding-right:0px;
}

section.footer-section ul {
    position:relative;
    width:100%;
    height:120px;
    margin:0px!important;
    padding:0px!important;
    text-align:center;
}

section.footer-section li {/*footer navigation text*/
    top:20px;
    left:0px;
    margin-left:auto;
    margin-right:auto;
    font-size:.8em;
    text-decoration:none;
    -webkit-transition:.5s ease-in-out;
    -moz-transition:.5s ease-in-out;
    -ms-transition:.5s ease-in-out;
    -o-transition:.5s ease-in-out;
    transition:.5s ease-in-out;
    border-left:1px solid #ff6000;
    border-right:1px solid #ff6000;
    padding-left:7px;
    padding-right:5px;
    display:inline;
}

section.footer-section li a {
    color:#f8f4ec;
    text-decoration:none;
}

section.footer-section li:nth-child(1), section.footer-section li:nth-child(2), section.footer-section li:nth-child(3), section.footer-section li:nth-child(4), section.footer-section li:nth-child(5) {
    border-right:none;
}

section.footer-section li a:hover {/*footer navigation text hover effects*/
    color:#ffd09d;
    text-decoration:underline;
    -webkit-transition:.4s ease-in-out;
    -moz-transition:.4s ease-in-out;
    -ms-transition:.4s ease-in-out;
    -o-transition:.4s ease-in-out;
    transition:.4s ease-in-out;
    -webkit-appearance:
}

#social-links-container {
    top:-20px;
    left:8px;
    width:120px;
    height:38px;
    margin-left:auto;
    margin-right:auto;
    z-index:1000!important;
}

ul.social li {
    top:0px!important;
    width:100%;
    height:50px;
    margin-left:-16.5px!important;
    list-style-type:none;
    display:inline;
    left:0px!important;
    z-index:1000!important;
    transition:30ms;
    -webkit-transition:30ms;
    border:none!important;

}

ul.social li:hover {
    top:5px!important;
    transition:30ms;
    -webkit-transition:30ms;
    -webkit-filter:sepia(0%)!important;
    filter:sepia(0%)!important;
}

ul.social li a {
    outline:none;
    border:none;
}

h1.site-design {
    top:0px;
    left:0px;
    margin-bottom:0px;
    text-align:center;
    margin-left:auto;
    margin-right:auto;
    width:95%;
    padding-bottom:0px;
    font-size:.7em;
}

h1.site-design a:visited {
    color:#ff6000;
}

h3.subscribe-footer {
    position:absolute;
    top:65px;
    left:0px;
    margin:0px!important;
    padding-bottom:0px!important;
    width:100%;
    text-align:center;
    font-size:.9em;
}

#nav-arrow {
    top:95px;
    width:70px;
    height:30px;
    right:2px;
    z-index:2;
    text-align:center;
}

#nav-arrow:hover {
    cursor:pointer;
}

span.arrow-text {
    position:relative;
    top:-7px;
    font-size:.75em!important;
}
/*****************************************FOOTER  END**************************************************/

/*****************************************MAIN LAYOUT ITEMS THAT SHOULD NOT BE     DISPLAYED IN MOBILE VIEW**************************************************/
nav.container, nav.container ul, nav.container-home, nav.container-home ul {
    display:none;
}

.current, .submit, .guidelines, .blog, .past, .about {
    display:none;
}

.image-sub-head-home {
    display:none;
}

#main-logo {
    display:none;
}

.image-header {
    display:none;
}

Answer: I have a simple hack for you
$(window).scroll(function()
{
    if( $(window).scrollTop() > 36 )
    {
    $('.mobile-nav-container').css({position: 'fixed'});
        $('#container').css({
            marginTop: '400px'
        });
    }
    else
    {
        $('.mobile-nav-container').css({position: 'relative', top: '-3px'});
        $('#container').css({
            marginTop: '0px'
        });
    }
});

You can test it here my http://jsfiddle.net/nXPHZ/
To make it more appropriate I'd calculated height of menu in JS and passed it into css() call.
Answer: The problem is when nav is posiiton:relative it is in the document flow and it's height will determine the top offest of the content. Once it is position:fixed it is removed from the document flow and therefore the content isn't displaced by it.
Suggest you wrap content in a container and set appropriate margin


Why does The special menu items module break the bootstrap dropdown?

Question: Hi Guys this is my issue on my parent menu item i am using the<nolink>shortcode to leave the link blank however in my tree i have 3 items underneath it.
If i add <nolink> the menu item becomes wrapped in a span tag with no link and the dropdown does not work. if i give the parent a link the dropdown works but only if i select the parent first.
Is this css or a js issue?
Comment: About the `` with `` see [Menu Tricks with Drupal, Bootstrap, and Special Menu Items](http://areatype.com/blog/menu-tricks-drupal-bootstrap-special-menu-items). About the click instead of hover see [Bootstrap 3 dropdown hover support](https://www.drupal.org/node/2248469), marked as fixed.
Answer: It's because bootstrap is expecting an anchor tag and by default Special Menu Items provides a span tag.
Go to admin/config/system/special_menu_items and specify an anchor tag as shown below:


Overflow de texto em elementos flex

Question: Olá,
Estou com um problema a fazer com que o conteudo que tenho dentro da div com a class "box-center", fique dentro da div Pai "wrapper".
Alguém me pode dizer compo posso solucionar o problema, já experimentei a propriedade flex-wrapper mas mesmo assim não consigo solucionar.
O código em questão está aqui:

.wrapper {
  width: 300px;
  height: 500px;
  background-color: aqua;
}

.top {
  display: flex;
  align-items: center;
}

.number {
  flex: 1 1;
  font-size: 14;
  font-weight: bold;
}

.box {
    display: flex;
    flex: 1 1;
    flex-wrap: wrap;
}

.box-left {
  background-color: red;
  margin-right: auto;
  width: 22px;
}

.box-center {
  flex: 1 1;
  background-color: blue;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: auto;
}

.box-right {
  background-color: yellow;
  margin-left: auto;
  width: 22px;
}

     1º

      A

    Bfdfskjfkdjfjsdfjsdjfksdjfkjsdklfjdskjfdsjflkdsjlkfdsfkdsjfklsjfksfdskjsdfdsjksdjfksdjfksdjfkdsj

    C

O resultado pretendido seria algo assim:
Answer: Creio que flex-grow seja útil nesse caso (veja esta resposta). O flex-grow divide as larguras dos elementos filhos de um flexbox. Agora, para o text-overflow: ellipsis; funcionar, você precisa setar min-width: 0; na classe .box (fonte). Veja:

.wrapper {
  width: 300px;
  height: 500px;
  background-color: aqua;
}

.top {
  display: flex;
  align-items: center;
}

.number {
 flex-grow: 1;
  font-size: 14;
  font-weight: bold;
}

.box {
    display: flex;
    xflex-wrap: wrap;
    flex-grow: 9;
    min-width: 0;

}

.box-left {
  background-color: red;
 flex-grow: 1;
}

.box-center {
  background-color: blue;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
 flex-grow: 8;
}

.box-right {
  background-color: yellow;
 flex-grow: 1;
}

         1º

            A

            Bfdfskjfkdjfjsdfjsdjfksdjfkjsdklfjdskjfdsjflkdsjlkfdsfkdsjfklsjfksfdskjsdfdsjksdjfksdjfksdjfkdsj

            C

Você pode ajustar as larguras alterando o valor do flex-grow, onde o
  valor 1, neste caso, significa 10% do contêiner.
Comment: Eu quero ver todas as divs (number, .box, .box-container, .box-right), mas apenas a .box-container tem over-flow
Answer: Olá,
Faça dessa forma amigo.

1º

A

 Bfdfskjfkdjfjsdfjsdjfksdjfkjsdklfjdskjfdsjflkdsjlkfdsfkdsjfklsjfksfdskjsdfdsjksdjfksdjfksdjfkdsj

C

Note que dei uma modificada em sua estrutura.
Espero que ajude!
Answer: Olha talvez não seja a solução que vc esperavam mas fazendo um calc() no width do Box vc consegua ajustar, o negócio é que no calc() vc tem que abater a largura da div.number.
Tipo assim,  width: calc(100% - 13px); onde 13px é a largura da div com o número 1°.
Segue o exemplo

.wrapper {
  width: 300px;
  height: 500px;
  background-color: aqua;
}

.top {
  display: flex;
  align-items: center;
}

.number {
  flex: 1 1;
  font-size: 14;
  font-weight: bold;
}

.box {
  display: flex;
  flex: 1 1;
  flex-wrap: wrap;
  width: calc(100% - 13px);
}

.box-left {
  background-color: red;
  margin-right: auto;
  width: 22px;
}

.box-center {
  flex: 1 1;
  background-color: blue;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: auto;
}

.box-right {
  background-color: yellow;
  margin-left: auto;
  width: 22px;
}

      1º

        A

        Bfdfskjfkdjfjsdfjsdjfksdjfkjsdklfjdskjfdsjflkdsjlkfdsfkdsjfklsjfksfdskjsdfdsjksdjfksdjfksdjfkdsj

        C

Answer: Olá,
Fiz as seguintes alterações:

Na classe top, adicionei flex: 1 1; e o flex-direction: row;
Na classe number, adicionei display: flex;
Na classe box, adicionei ```overflow: hidden;````

Espero ter ajudado!

.wrapper {
  width: 300px;
  height: 500px;
  background-color: aqua;
}

.top {
  display: flex;
  flex: 1 1;
  align-items: center;
  flex-direction: row;
}

.number {
  display: flex;
  flex: 1 1;
  font-size: 14;
  font-weight: bold;
}

.box {
    display: flex;
    flex: 1 1 100%;
    flex-wrap: wrap;
    overflow: hidden;
}

.box-left {
  background-color: red;
  margin-right: auto;
  width: 22px;
}

.box-center {
  flex: 1 1;
  background-color: blue;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: auto;
}

.box-right {
  background-color: yellow;
  margin-left: auto;
  width: 22px;
}

     1º

      A

    Bfdfskjfkdjfjsdfjsdjfksdjfkjsdklfjdskjfdsjflkdsjlkfdsfkdsjfklsjfksfdskjsdfdsjksdjfksdjfksdjfkdsj

    C

Answer: Seria isso?
Se sim, aconselho esse link do origamid inserir a descrição do link aqui sobre display flex.
É muito bom!

.wrapper {
  display: flex;
  height: 100px;
  padding: 10px;
  border: 2px solid red;
}

.child{
  display:flex;
  padding:5px;
  justify-content:center;
  align-items:center;
  flex:1;
  border:1px solid black;
}

.big-child{
  flex: 2;
}

1º

A

Bfdfskjfkdjfjsdfjsdjfksdjfkjsdklfjdskjf
  dsjflkdsjlkfdsfkdsjfklsjfksfdskjsdfdsjksdjfksdjfksdjfkdsj

C

Overflow de texto em elementos flex


Posso utilizar a função dd() em produção?

Question: Eu criei uma função que é chamada em outra classe pra realizar uma tarefa durante uma requisição num Controller da minha aplicação.
Eu coloquei um return nessa função para interromper sua execução em uma situação específica. Só que após esse return, a função principal do Controller continua rodando. Eu utilizei então a função dd() do Laravel para interromper toda a execução nessa situação mas, eu acho que essa função é utilizada somente para Debug.
Vocês utilizam essa função também para situações específicas em códigos que estão em Produção ou somente para Debug mesmo?
Essa a função na qual inseri o dd, que está dentro de outra classe:
public function verificaItens($shipmentPed,$AuxPedido){
    $pieces = explode("-", $shipmentPed);
    $tagSearch = TRIM($pieces[0]).' - '.TRIM($pieces[1]);

    $tag = \App\pedidosretira::where("shipment_tray",strtoupper($tagSearch))->first();

    if(!isset($tag->num))
     return response("Informação de Retirada '".$shipmentPed."' não
     encontrada na base local da integração.", 203);

    $this->num = $tag->num;
}

Abaixo, a linha que chama a função dentro do Controller:
$AuxPedido->verificaItens($pedido->shipment,$AuxPedido);

Comment: O return deveria parar a execução do seu controller. Você pode [edit] sua pergunta e incluir o trecho do código do controller? Sobre o dd() tens razão, é mais para debug. Recomendo você retornar algum tipo de mensagem para o usuário, pois só um `return;` pode não fazer sentido como um retorno.
Comment: Ocorre que eu chamo essa função dentro de um Controller mas, ela está em outra classe, não está dentro desse Controller. Por issoa função do Controller continua rodando depois desse return. Editei a pergunta e inseri o código.
Answer: É normal o controller não encerrar a execução, pois ele em si não retorna nada. O controller executa verificaItens mas não faz nada com a Response criada.
Isole no contexto do controller sua lógica para trabalhar com as responses, e na sua lógica de negócio implemente só suas regras de negócio.
Por exemplo, atualize seu controller e sua lógica de negócio para algo próximo a isso:
public function codigoController() {

    // alguma coisa

    // atenção para a negação no começo do if
    if (!$AuxPedido->verificaItens($pedido->shipment) {
        return response("Informação de Retirada '{$pedido->shipment}' não encontrada na base local da integração.", 203);
    }

    // segue o fluxo positivo

}

No código do seu método, tente deixar mais coeso o que aquele método deve fazer, evitando passar valores não usados naquele método:
// $AuxPedido não é usado dentro do método, e é estranho um método receber o próprio objeto
public function verificaItens($shipmentPed)
{
    $pieces = explode("-", $shipmentPed);
    $tagSearch = trim($pieces[0]).' - '.trim($pieces[1]);

    $tag = \App\pedidosretira::where("shipment_tray",strtoupper($tagSearch))->first();

    // assumindo que esse é um valor numérico, retorna verdadeiro se for maior que zero,
    // ou falso se for 0 ou nulo.
    // Não vai funcionar se for uma string (sempre vai voltar true)
    return (bool) $tag->num;
}

Vocês utilizam essa função também para situações específicas em
  códigos que estão em Produção ou somente para Debug mesmo?

O dd() é usado para fins de debug mesmo. Não é recomendado utilizá-lo para encerrar um fluxo. Recomendo a leitura de como funciona o ciclo de requisições do Laravel para entender o que acontece com seu código até chegar no seu controller.
Comment: Bacana. Interessante mesmo tratar a resposta da função no Controller. Vou fazer assim.
Answer: @Kênia em produção geralmente APP_ENV=production e APP_DEBUG=false sendo assim tanto exceções quanto a utilização do dd são desviados para o log \storage\logs\laravel.log, pois ao utilizar o dd a interrupção gera http 500 Internal Server Error, para o usuário em produção aparece uma tela padrão do laravel sem mostrar os dados.
Caso queira ver o dd teria que alterar os parâmetros citados. Porem para cenário de produção não é aconselhado pois ao deixar os logs e debug aparecendo na tela, eles trazem informações que podem favorecer alguém mal intencionado. O ideal para produção seria o log no arquivo assim somente você poderia ver:
Log::debug($message);

Caso queira mostrar uma mensagem para o usuário isso deve ser retornado para o controle, e do controle para a view.
Comment: Muito didático. Não sabia que o dd ia para o log na situação apresentada.


Can the graph of a function have more than one oblique asymptote?

Question:
Can the graph of a function have more than one oblique asymptote?

I think there is only one or none. Am I right?
Comment: Asking about "a function" covers _a lot_ of ground.  If we look at rational functions with radicals in the numerator or denominator, we can easily contrive different "positive" and "negative" asymptotes, as with (for instance) $ \ f(x) \ = \ \frac{x}{\sqrt[3]{x^2 - 1}} \ . $  Is there a particular sort of function you're asking about?
Answer: Consider $$|x|+\frac1x,$$ which has $y=\pm x$ as its oblique asymptotes.
Answer: $y = \dfrac{e^x-1}{e^x+1}+x$ has oblique asymptotes of $y = x+1$ as $x \to +\infty$ and $y = x-1$ as $x \to -\infty$.
Answer: Any hyperbola $\frac{x^2}{a^2}-\frac{y^2}{b^2}=1$ has two (oblique) asymptotes.


Returning an Int Array from a Custom String Method?

Question: I am creating a custom method that returns AnalyzerInts[] to count lowercase, uppercase, whitespace, punctuation, and character count of string input. I am getting an unhandled exception error. "System.IndexOutOfRangeException: Index was outside the bounds of the array." How do I correctly retrieve my Int[] AnalyzerInts values into my main method?
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a string/sentence: ");
        string userInput = Console.ReadLine();
        int[] answers = StringAnalyzer(userInput);
        Console.WriteLine("You have {0} uppercase letters in your string.", answers[0]);
        Console.WriteLine("You have {0} lowercase letters in your string.", answers[1]);
        Console.WriteLine("You have {0} whitespace characters in your string.", answers[2]);
        Console.WriteLine("You have {0} punctuation characters in your string.", answers[3]);
        Console.WriteLine("You have {0} characters in your string.", answers[4]);
    }

    static int[] StringAnalyzer (string input)
    {
        int[] AnalyzerInts = new int[4];
        for (int x = 0; x < input.Length; x++)
        {
            if (char.IsUpper(input[x]))
            {
                AnalyzerInts[0]++;
            }
            else if (char.IsLower(input[x]))
            {
                AnalyzerInts[1]++;
            }
            else if (char.IsWhiteSpace(input[x]))
            {
                AnalyzerInts[2]++;
            }
            else if (char.IsPunctuation(input[x]))
            {
                AnalyzerInts[3]++;
            }
            AnalyzerInts[4]++;
        }
        return AnalyzerInts;
    }

Comment: It throws an error becasue you declare the function as returning a `string` but try to return an `int[]`.  Change the return type to `int[]` if that's what the function should return.
Comment: Does that even compile?  I've never seen code that looks like `return AnalyzerInts[];`, nor would I expect to.
Comment: It didn't compile until I correctly changed my method signature to `static int[] StringAnalyzer (string input)`. Now I am just trying to correctly return my `AnalyzerInts;` value to my main method without getting an error.
Answer: A method definition can be viewed as [return type] [method name] ([parameters])
In your case, you defined StringAnalyzer to receive a string parameter named input and return a string value (that's indicated by string before the method name)
What you're looking for is to have the method accept a string but return an array of integers int[], so the method should be defined as
static int[] StringAnalyzer(string input) { /*...*/}

Also, when returning, you don't need the [], you only need return AnalyzerInts
Finally, you need to initialize your array to contain 5 elements not 4: int[] AnalyzerInts = new int[5];
Comment: This worked. Thank you. Now I am attempting to correctly retrieve the return value `AnalyzerInts;` to my main method. See the edit.
Comment: See edit to answer, the problem might be because your array was initialized with 4 elements only but you're using 5
Comment: I see. `Int[] name = new int[number of elements]`when declaring the new variable. But `name[0]` when calling the first element. So the index of 0 only is used when calling the elements, not when declaring the array. Am I right?
Comment: Yes. When declaring the array, you specify the *number of elements*, in your case 5. When *indexing* (accessing/calling) the array, the first index starts at 0, so for an array with size 5, indexing goes 0,1,2,3, and 4
Comment: Thank you so much. You are a major help.
Answer: Your return type is string and you are trying to return an int[].
Change your method signature to:
static int[] StringAnalyzer (string input)

and change your return statement to:
return AnalyzerInts;

Answer: Change this:
int[] AnalyzerInts = new int[4];

to:
int[] AnalyzerInts = new int[5];

Because if you look at your code, you will see that your array is assumed to have 5 items, not 4. (Hint: You're printing 5 sentences to the console, and the highest index you're accessing is 4. C# arrays start at index 0.)


Media Player killed by Android system

Question: In my app, I have Activity A ( home activity) --->> then Activity B --->> Then foreground service.
Application runs for an hour then in notification bar I get "This app is consuming power > 40mhA". Within another hour the app is killed.
Reference to this, it's possible to keep the service running even after killing the app , but this is not the target.
My question: is it possible to keep the app running and overcome system killing?
Thanks
Answer: As far as I know, if the OS has decided to kill your application due to power consumption - there is nothing you can do to keep it running.
The best thing you can do is check why it consumes that much battery and optimize it through your code.
I know that sometimes it seems like there is nothing you can do to optimize it, but trust me, there is.
Maybe you are using a service in a wrong way that abuses it?
If you will post your code here we can try help you fix it :)

Media Player killed by Android system


Iteration on jsp page  clone results during iteration

Question: I have problem with my controller Spring MVC and Iteration on jsp page. When I pass attributes on jsp page and try to iterate them, it is clone the results and view it on jsp page (results repeats everytime). Why it's happend and how to prevent it??
My form jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Страница выборки</title>

Выборка

<form name="extractForm" action="result" method="GET" accept-charset="UTF-8">

Дата для выборки:                <input type="text" name="particularDate">

Имя учреждения для выборки:      <input type="text" name="nameOfInstitution">

Тип учреждения для выборки:      <select name="typeName" size="1">
                                        <option selected="selected" value=""></option>
                                        <option value="MBOY">МБОУ</option>
                                        <option value="MBDOY">МБДОУ</option>
                                        </select>

<input type="submit" value="Выбрать"/>
</form>

My result jsp page:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

Наименование учреждения
Тип учреждения
Дата внесения данных
Режим дня
Режим работы
Очередность
Количество детей
Дети до 3-х лет
Дети старше 3-х лет
Дети пойдут в школу в ${creationDate.childGoSchoolDate}
Дети принятые в ${creationDate.childAdmissionDate}

<c:forEach items="${institutionAttrib}" var="institutionObj">
    <c:forEach items="${dateAttrib}" var="creationDate">
        <c:forEach items="${srcAttrib}" var="schRotChild">

${institutionObj.nameOfInstitution}
${institutionObj.typeName}
${creationDate.particularDate}
${schRotChild.dayScheduale}
${schRotChild.workScheduale}
${schRotChild.rotation}
${schRotChild.numberOfChild}
${schRotChild.childUnder3YearsOld}
${schRotChild.childUpper3YearsOld}
${schRotChild.childGoToSchool}
${schRotChild.childAdmitted}

</c:forEach>
    </c:forEach>
        </c:forEach>

<jsp:include page="index.jsp"/>

And my mvc method:
@RequestMapping(value ="/result", method=RequestMethod.GET)
        public String SecondActionPage(@RequestParam String particularDate,
                                       @RequestParam String nameOfInstitution,
                                       @RequestParam String typeName,
                                       Model model) throws Exception {

                if(particularDate !="" && nameOfInstitution !="" && typeName=="") {

                    controllerSupportClass.findWithDateAndName(nameOfInstitution, particularDate, model);

                } else if(particularDate !="" && nameOfInstitution =="" && typeName !="") {

                    controllerSupportClass.findWithAddedDateAndType(typeName, particularDate, model);

                } else if(particularDate !="" && nameOfInstitution =="" && typeName==""){

                    controllerSupportClass.findWithAddedDate(particularDate, model);

                } else if(particularDate !="" && nameOfInstitution !="" && typeName !="") {

                    throw new Exception("Search by choose all parameters is not exceptable");

                } else {

                    throw new Exception("You didn't put any search parameters");

                }

            return "result";

        }

Thank you.
Answer: did you confirm that the methods that are being called in your code are pushing correct data to the jsp page?
Comment: Yes sir. I guess so... If I would not pass data corectly it would just did not show me enything... Or What exactly you mean? Thank you.
Comment: by correct data, i mean you are not pushing same data multiple times which is then showed up on jsp page


Codeigniter Datamapper - self-relationship - include_related()

Question: I am looking at how to create self-relationship (upsteam) join in ORM Datamaper.
my self - relation class looks:
<?php
class Prospect extends DataMapper{

    var $has_one =array(
        'parent' => array(
            'class' => 'prospect',
            'other_field'=>'prospect'
        ),
        'prospect' => array(
        'other_field' => 'parent'
        )
    );

}

and I try to list
include_related (parent)
$p->include_related('parent')->get();

I have had error
Fatal error:  Cannot use object of type Prospect as array in [..]application/libraries/Datamapper.php on line 2739
I can do
$p->include_related('prospect')->get();

but in this case I have had a wrong join.
SELECT `prospects`.*, `prospect_prospects`.`id` AS prospect_id, `prospect_prospects`.`name` LEFT OUTER JOIN `prospects` prospect_prospects ON `prospects`.`id` = `prospect_prospects`.`parent_id`

Results shows relation parent -> child (downstream relation) not child-> parent (upstream relation)
I am lookig for:
SELECT `prospects`.*, `prospect_prospects`.`id` AS prospect_id, `prospect_prospects`.`name` LEFT OUTER JOIN `prospects` prospect_prospects ON `prospects`.`parent_id` = `prospect_prospects`.`id`

Any tips how to do it, and what I have to change it ? and how should look a good upstream relationship class / php code ?
ps: direct SQL query works brilliant.
Answer: I think what you're dealing with is a "Reciprocal" relationship. Take a look at this page: http://datamapper.wanwizard.eu/pages/advancedrelations.html
Go down to the section titled "Many-to-Many Reciprocal Self Relationships" and see if that helps you.
In essence, it should be a matter of adding reciprocal to the properties:
<?php
class Prospect extends DataMapper{

    var $has_one =array(
        'parent' => array(
            'class' => 'prospect',
            'other_field'=>'prospect',
            'reciprocal' => TRUE
        ),
        'prospect' => array(
            'other_field' => 'parent',
            'reciprocal' => TRUE
        )
    );
}

Comment: parent is prohibited, based on my source code of datamapper -> parent is used and It shouldn't be use to create relation
Comment: Reciprocal Self Relationships are needed when you want to maintain the relation both ways, and you have a setup with two FK's (a many-2-many or has_many's both ways).

If enabled and you create a relation, the relation in the other direction is added automatically.
Comment: WanWizard -> yes, I know. It would be good if you publish list of the restricted namespaces (as parent). BTW: you library is great :) THX for it
Answer: OK, Problem solved
variable parent is used in Datamapper library class to keep an array with relations, so 'parent' is restricted and it couldn't be used at all. i.e. in my case. I have changed from parent to parent_company and all is working brilliant. (this is solved my left join problem as well).


Numpy can't convert list to np array

Question: I have a python list than includes 90900 nparrays shaped (299, 299, 3). I tried to convert this list to numpy array
X_trains = np.asarray(X_train).reshape((len(X_train),299,299,3))

However, this gave me the error:

ValueError: could not broadcast input array from shape (299,299,3)
  into shape (299,299)

I suppose that the part of the code that cause the error is np.asarray, is there any way to fix that?
Full error code:
ValueErrorTraceback (most recent call last)
<ipython-input-34-2ba5db77f6b1> in <module>()
  1
  2
----> 3 X_trains = np.asarray(X_train)

/usr/local/lib/python3.4/dist-packages/numpy/core/numeric.py in asarray(a,          dtype, order)
529
530     """
--> 531     return array(a, dtype, copy=False, order=order)
532
533

ValueError: could not broadcast input array from shape (299,299,3) into shape (299,299)

Comment: I want to shape my data as a 4 dimensional array (It's image files) (number of images, height, length, color channels)
Comment: @kmario23 You were right! The problem was that I didn't realize that there were some grayscale images, which messed things up.
Comment: Ok. Good that you figured out the issue!
Answer: No, the problem is because of the reshape(). The asarray() function will convert your list to a proper Numpy array, you don't need to reshape it.
Here is an example:
In [1]: a = [[1, 2], [4, 5]]

In [2]: import numpy as np

In [3]: np.asarray(a)
Out[3]:
array([[1, 2],
       [4, 5]])

If you want to reshape the array still after converting to a Numpy array, the new shape should be proper enough for broadcasting the older array to the new one.
You can get the shape and see if it's convertible to your expected one:
X_trains = np.asarray(X_train)
old_shape = X_trains.shape

Comment: nope the problem is clearly in `np.asarray`, I included the full error code, hope it would make more sense
Comment: @Wideem This answer is because of the fact that your list contain similar shaped lists. But if the error is because of the `asarray` this means that you have a mismatch in your sub lists.
Answer: I understand your problem. There is no need to reshape it. Just np.asarray would do the job
X_trains = np.asarray(X_train)

Example:
In [18]: arr_3d
Out[18]:
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])

In [19]: list_of_arr = [arr_3d, arr_3d]

In [20]: arr_4d = np.asarray(list_of_arr)

In [21]: arr_4d.shape
Out[21]: (2, 2, 3, 3)

Numpy can't convert list to np array


How to calculate the probability of getting 2 heads wen the coins is biased?

Question: I can't understand how I can implement the Bayes' Rule here and the probability of getting two heads when tossing twice. Could anyone give me a hint?
Suppose you have two coins. One coin has probability 0.7 of coming up heads, and the other has probability 0.4 of coming up heads. You are playing a gambling game with a friend, and you draw one of those two coins at random from a bag.
Before you start the game, your prior belief is that the probability of choosing the 0.7 coin is 0.5. This is reasonable, because both coins were equally likely to be drawn. In this game, you win if the coin comes up heads.
Suppose the game starts, you have tossed twice, and have obtained two heads. Then what is your new belief about p, the probability that you are using the 0.7 coin?
Comment: Your question is still confusing in the first sentence where you have "coins" when it seems you should be saying "heads". Please edit.
Comment: 1. In your first sentence, do you mean "heads" where you say "coins"? 2. This reads like a textbook question. Is this a question for some class?
Comment: Thank you, we have already worked it through. No, it's just an accumulation of my misunderstanding with random numbers.
Comment: Good point. Have edited it accordingly.
Answer: I am a hardcore frequentist but we gotta know the enemy, so let's give it a try.

Let $A$ be the event "we are using the 0.7 coin"
Let $B$ be the event "we got two heads in a row"

According to the Bayes Theorem, $P(A|B)=\frac{P(B|A)P(A)}{P(B)}$

$P(A)=1/2$
$P(B|A)=0.7^2$
$P(B) = \frac{0.7^2+0.4^2}{2}$

We can easily do the computation for $P(A|B)$
Comment: I can't get how we compute P (B given A) since our prior belief is 0.5. Could you guide me throw, please?
Comment: If $A$ (we are using the 0.7 coin) is true, then the probability of $B$ (getting those two heads) is $0.7^2$
Answer: Let $C_1$ be the coin with $0.7$ head probability and $C_2$ be the other one. Priors are $P(C_i)=0.5$. The event occurred is $2$ Heads, call it $E$. We ask for $P(C_1|E)$.
$$P(C_1|E)=\frac{P(E|C_1)P(C_1)}{P(E)}$$
$P(E|C_1)=(0.7)^2$ and we have $P(C_1)$. From total probability law, we can also find $P(E)$:
$$P(E)=P(E|C_1)P(C_1)+P(E|C_2)P(C_2)=\frac{P(E|C_1)+P(E|C_2)}{2}$$
where $P(E|C_2)=(0.4)^2$.
Comment: How do you get P (E given C1) to be equal to 0.7^2?
Comment: $P(E|C_1)$ means the probability of two heads (i.e. HH) when know we use coin 1.
Comment: Then I can't understand why do we need prior here.
Comment: You need the prior when substituting $P(C_1)$ and $P(C_2)$
Comment: Then we get as for numerator: 0.7^2* 0.5, don't we?
Comment: Yes, the numerator in the Bayes formulation is $(0.7)^2(0.5)$
Comment: As for the denominator we have (0.7)^2(0.5) + (0.4)^2(0.5), right?
Comment: Yes, that is right.
Comment: Thank you for guiding me through.


How do I override the subscription block?

Question: I am developing a Drupal 8 website and I want to override the subscription block used by the Simplenews module. I know how to achieve that at Drupal 7, but the module is different now. For Drupal 7, I followed http://api.worldempire.ch/api/simplenews/theme%21simplenews-block.tpl.php/7-2.
I want to do the same for Drupal 8. How can I achieve it?
Comment: Are you trying to override the template file or something more complicated?
Comment: I want to override the template file but if you have a better solution, you can suggest it.
Comment: Exactly what do you want to do?
Answer: There is no exact equivalent currently. To override the actual block template for that block you can use 'block--simplenewssubscription.html.twig'. You can use the input and form templates to override other elements. I would suggest enabling debugging in Twig so you can see the template overrides.


Crontab - combining times

Question: I want to have my script run every 23'th around (so 11 PM) and between 7-19 every 2 hours. In directadmin I use this:
23,7-19/2 however, in crontab it will be ran every minute. What syntax should I use? My complete line:
* 23,7-19/2 * * * /usr/local/bin/php script.php
Comment: [Administration panels are off topic](http://serverfault.com/help/on-topic). [Even the presence of an administration panel on a system,](http://meta.serverfault.com/q/6538/118258) because they [take over the systems in strange and non-standard ways, making it difficult or even impossible for actual system administrators to manage the servers normally](http://meta.serverfault.com/a/3924/118258), and tend to indicate low-quality questions from *users* with insufficient knowledge for this site.
Answer: 0 7,9,11,13,15,17,19 23 * * /usr/local/bin/php script.php

will run the script exactly at every second full hour on every 23th between 7h and 19h. But I am not sure anymore this is what you want to do.
Another interpretation would be that you want to run it between 7h and 19h and at 23h, but daily. Then change it to
0 7,9,11,13,15,17,19,23 * * * /usr/local/bin/php script.php

The six fields of the crontab are
min hour dayofmonth month dayofweek  command

Comment: Thanks. I'm using `0 23,7-19/2 * * * /usr/local/bin/php script.php` now. I was using (as minutes) a '*', so every minute matched. Stupid me. Thanks anyway!
Answer: The key point with CRON is that it will run when ever the current time matches the pattern specified. So with all those *s, a lot of times will match.
I can't make sense of what exact times you are trying to describe though, so I can't give you the exact config that would work.
Comment: Thanks. I'm using `0 23,7-19/2 * * * /usr/local/bin/php script.php` now. I was using (as minutes) a '*', so every minute matched. Stupid me. Didn't saw the * at all...

Crontab - combining times


Using global pointers and custom destructor - How to avoid memory leak?

Question: I've been studying C++ for my Thesis with Bjarne Stroustrup's book [ C++ 11 ]. Even so, I'm still not getting somethings about handling memory leak in C++. He says a lot in the book to avoid the use of new, delete and also custom destructors.
I would like to say I'm using QT to build my UI, now please consider this example for my first three question:
    class KHUB : public QMainWindow
{
    Q_OBJECT

public:

    KHUB(QWidget *parent = 0)
    {
        createGroupScreen();
    };

    ~KHUB();

private:

        QWidget *groupScreen;
        void createGroupScreen()
        {
            groupScreen = new QWidget();
        };
}

This is resumes my app. I have a constructor named KHUB which creates a dialog (QWidget) giving some options to put name, category and so on, to create a new group.

Since I'm supposed to avoid naked new and delete, is there a different way (such as using unique_ptr, not sure if it's an applicable concept here) or not so error prone to create this QWidget and still have the object reference to manipulate it outside the my createGroupScreen member function?
if I create this object inside the member function, without a global pointer and also not using naked new, this object will remain in the memory as long as it's parent is alive or in the end of the member function it will be deleted?
if it remains alive with its parent, how can I acquire the object reference outside the member function so I can call ~QWidget()?

My fourth question regards to this same object destruction.

If I destroy groupScreen by calling groupScreen->~QWidget() this will only destroy my QWidget object and my pointer will remain there as a memory leak waiting for me to delete groupScreen?

Consider this another piece of code for my fifth, sixth and last question:
        class KHUB : public QMainWindow
{
    Q_OBJECT

public:

    KHUB(QWidget *parent = 0)

    ~KHUB()
    {
        delete groupScreen;
        delete buttonOne;
        delete buttonTwo;
        delete buttonThree;
    };

private:

        QWidget *groupScreen;

        QPushButton *buttonOne, *buttonTwo, *buttonThree;

        /* Components Setup */
        void btSetup(QPushButton** button, const QString name, int posX, int posY, int width, int height);
}

I'm trying to make some code reuse with buttons with a function to set the button name, position and size, thus the code won't become so big by typing the same parameters repeatedly to each one of them  - but I'm also worried with the program performance.

When I call my KHUB constructor, that doesn't mean all global pointers that I have in my .h file are being allocated right? That only happens when they are initialized, correct?
If I really need to create my custom destructor, I should delete in it every global pointer declared in my .h file? I'm wondering if that wouldn't be risk in case I didn't pass through the initialization of one of those pointers.
Is there a way to loop the pointers acquirement and delete? i.e. for(auto p : globalPtrs) delete p;

I tried to find some questions regarding this subject here at stack but none was really enlightening to me:

C++ destructor memory leak
Avoiding memory leak
Avoiding memory leaks
Comment: My understanding of the memory leaks (I am sure other people will correct me or have better information) is that whatever object you are working with pointer class ext.. They exist in memory or ram has long has it is within scope. Memory leaks come from unnecessary things in scope all taking up space from memory.If you can't use delete just maybe you can set what you are working with to NULL. The OS you are using magically will handle memory allocation for new objects. Smart Pointers are a thing btw this is a great atrial about them http://www.umich.edu/~eecs381/handouts/C++11_smart_ptrs.pdf
Comment: Finally, it doesn't make much sense to store unique pointers to child widgets in the parent widgets. The children can be simple direct members, not pointer members.
Comment: You should be using `std::make_shared` and `std::make_unique` whenever possible, instead of passing the result of `new` to the smart pointer constructor. That's what's *also* meant by not using `new` directly.
Comment: Finally, it's rather rare that you'd call a destructor directly and explicitly. I've just looked through a 50k LOC project I'm currently working on, and there isn't a single explicit destructor call anywhere. You need to have a very good reason to do so, pretty much. If you're not writing manual resource management library code, you probably shouldn't be calling destructors explicitly.
Comment: You're also forgetting that a `QObject` is a smart pointer collection (really!). A `QObject` is like `std::vector>`. A `QObject` is a smart pointer with unique ownership of its children. It's often counterproductive to apply additional layers of memory management to owned `QObject`s. If they have a parent, the parent worries about them.
Answer: Probably you should start by reading the C++ FAQ on memory management

Since I'm supposed to avoid naked new and delete, is there a different way (such as using unique_ptr, not sure if it's an
  applicable concept here) or not so error prone to create this QWidget
  and still have the object reference to manipulate it outside the my
  createGroupScreen member function?

Yes, if modern C++, you are supposed to use std::shared_ptr or std::unique_ptr or std::weak_ptr. All of them take care of the destruction of the memory they refer to. Each of them has different characteristics regarding ownership, sharing, etc.
I'd try to use them, as they simplify memory management. If not possible (e.g. your compiler is not up to C++11 and are not using boost... there might be many reasons), you can use new/delete... just be extra careful.

if I create this object inside the member function, without a global
  pointer and also not using naked new, this object will remain in the
  memory as long as it's parent is alive or in the end of the member
  function it will be deleted?

Not sure what you mean.
if you're creating a variable, method/function local, object attribute... etc.. The variable will be destroyed when the scope it is defined in goes away.
Say you have:
void myfunc() {
   int a=0;
}

when you enter the scope the memory for the integer a is created and when you go out of the scope the memory for the integer a is destroyed. In this case it will be memory on the stack (vs. memory on the heap)
If you have an attribute in an class, when the object is created, the attribute will be created (constructor). When the object is destroyed, the attribute will be destroyed (destructor).
When you are allocating with new, memory is allocated from the heap. If you store a reference to that memory in a (plain) pointer variable, when the pointer variable is destroyed, the memory referenced by the pointer is not destroyed (and you have a leak).
Same thing can be said when you have memory referenced by a pointer and you assign a different memory reference to that pointer. If the memory is not referenced elsewhere, it is lost to your program.

if it remains alive with its parent, how can I acquire the object
  reference outside the member function so I can call ~QWidget()?

if you allocated with new, then you must either destroy it when going out of scope or save the memory reference to a pointer variable in some other scope from where you can delete it what the time comes.
See the C++ FAQ:Why isn't the destructor called at the end of scope?
Something you might want to read about is RAII as the smart pointer I listed in the first question use this idiom.

If I destroy groupScreen by calling groupScreen->~QWidget() this will
  only destroy my QWidget object and my pointer will remain there as a
  memory leak waiting for me to delete groupScreen?

See the C++ FAQ:What are the two steps that happen when I say delete p?
Calling delete groupScreen will cause the ~QWidget() to be executed and the destructors of all the attributes (non-pointer/reference) and the destructor of the parent classes (if any) and the memory for the object deallocated.
When you are dealing with a hierarchy of classes, it is important to consider if the object might be deleted through a pointer to the parent class(es). If that's the case, the destructor method must be declared virtual, so that actual object class method is executed (instead of executing the destructor of the class pointed to by the pointer) (which is yet another form of leak).

When I call my KHUB constructor, that doesn't mean all global pointers
  that I have in my .h file are being allocated right? That only happens
  when they are initialized, correct?

When you call the constructor, before executing your custom constuctor, the attributes will be allocated. But a pointer will not be allocated memory an assigned to it, just memory for the pointer itself (and it is important that you take care of initializing it to some sane value, e.g. null_ptr)
variables you declare outside of a class or static attributes of a class, should not be initialized in a *.h, as they will cause symbols to appear multiple times (as the header is included in different compilation units)
Initialize them in the *.cpp. However be careful as it might be a cause of problems (see C++ FAQ)

If I really need to create my custom destructor, I should delete in it
  every global pointer declared in my .h file? I'm wondering if that
  wouldn't be risk in case I didn't pass through the initialization of
  one of those pointers.

You should create a custom destructor if

You want to do anything on object destruction
If your object contains dynamic memory (naked) pointers that it owns (i.e. that will not be taken care of by someone else)

Is there a way to loop the pointers acquirement and delete? i.e.
  for(auto p : globalPtrs) delete p;

not entirely sure what you mean by globalPtrs... if it is some magical variable that contains all the pointers in an object, there's not such a thing.
You must take care of the deletion of every pointer (you owned)... that's why the smart pointers are much less error-prone, as they will do it automatically.

Perhaps an example will help:
#include <iostream>

class B {
public:
  B() {
    std::cout << "B()" << std::endl;
  }

  ~B() {
    std::cout << "~B()" << std::endl;
  }
};

class A {
public:
  A() {
    std::cout << "A()" << std::endl;
  }

  ~A() {
    std::cout << "~A()" << std::endl;
  }
  B b;
};

int main() {
  std::cout << "A as variable" << std::endl;
  A a;

  std::cout << "A as pointer" << std::endl;
  A *a_ptr=0;

  std::cout << "running new" << std::endl;
  a_ptr=new A();

  std::cout << "running delete" << std::endl;
  delete a_ptr;

}

This produces the following output (with some annotations)
A as variable     // We are declaring a stack variable of type A
B()               // since A contains a B attribute object it creates it
A()               // ... and runs the constructor
A as pointer      // We are declaring a stack variable pointer to A
                  // ... nothing happens
running new       // but when we run new, we get
B()               // the creation of the attribute (and its constructor)
A()               // the execution of the constructor
running delete    // now we call delete
~A()              // that calls A's destructor
~B()              // and then proceeds to destroy the attributes.
~A()              // these are the destructor for the first variable
~B()              // which is now going out of scope

let's try something different. Same classes definition. Our main is now:
int main() {
  std::cout << "A as pointer" << std::endl;
  A *a_ptr=0;

  std::cout << "running new" << std::endl;
  a_ptr=new A();

}

We get
A as pointer
running new
B()
A()

No destructor, we've leaked the A object.
Comment: @VictorOliveira. I've added some sample code. You can use the same technique to test your assumptions: add traces to see what is executed when.
Comment: This answer is only half an answer. It's accurate, but it completely misses that it's `QObject`s that are talked about.
Comment: "Calling delete groupScreen will cause the ~QWidget() to be executed and the destructors of all the attributes (non-pointer/reference) and the destructor of the parent classes (if any) and the memory for the object deallocated." Are you sure about this? I thought this would make me lose the reference to my QWidget and cause memory leak, I thought I should destroy the object first and then delete the pointer. - I appreciate your help, but I will wait to see if someone else answers me, some of your answers doesn't really clarify my doubts but it helped
Comment: I checked your delete information with vld.h (memory leak manager) and you are right
Comment: I must ask, if I'm deleting my pointer that means its allocated space will no longer exist in the memory or I'm just freeing any reference that he is pointing to?


QoS for very basic LAN/WiFi network: Do I need SmoothWall or OpenWRT or just good advice?

Question: Here is the basic situation/topology of the network I manage:

Residential, but we are a co-op, so we have a business-class contract with ISP.

The residents are college students, so there is quite a bit of everything, including P2P (torrenting), gaming, file sharing (internal), as well as crucial needs for the basics like getting to websites for school/homework, email, FTP, etc. Basically, I get bad reviews when members can't have their fun, but then legitimate complaints when someone can't turn in an assignment.

There are at most 31 residents, but we are not always at full capacity. Of course, plenty of residents connect multiple devices (Laptop, Desktop, Mobile) all at once.
The property is spread out over 3 buildings, 2 of which are connected physically, the third is stand-alone but only a few steps from the main two buildings.

Here is the basic layout of the property:
<code>==========================                   =====================
|                        |                   =            |Router=
|                        |                   =             ----- =
|   Main House           |                   =    Annex          =
|   (3 stories)          |                   =  (2 stories)      =
|(first floor is commons |====================  (No commons)     =
| area, ie TV Room,etc)  | Breeze Way        =                   =
==================================================================

                                        ======================
                                        =                    =
                                        =    Cottage         =
                                        =   (2 Stories)      =
                                        =  (No Commons)      =
                                        ======================
</code>
The cable comes into a closet in the Annex where it goes from the modem (ISP provided) to the D-Link DIR-625 Wireless router. So from the very start the set up is not ideal, as one of the WAPs is in a closet on the ground floor. C'est la vie.
Then it spreads out like so:
<code>DIR-625 (DHCP Router and
- Netgear 8-port switch (2nd floor Annex)
- Linksys 5-port switch (1st floor Annex)
- Netgear 8-port switch (Cottage)
    - D-Link WBR-1310 Wireless Router acting as WAP
- Netgear 16-port switch (Main House)
    - D-Link WBR-1310 Wireless Router acting as WAP for Common's Area
    - D-Link WBR-1310 Wireless Router acting as WAP for 2nd and 3rd floor
</code>
Okay, that's about all the backstory anyone should ever need. Sorry if that was a bit much, but when I try to get advice from friends, they tend to think either "Only 31 people, what's the problem?" or "3 buildings, and you don't have a T1?" etc, etc. It's a fairly simply network in terms of what we need and our small population, but made very complicated by our physical layout.
Oh, and we are paying for 10 down/ 1.5 up, as far as service.
Now, here's the actual question (one of many, I'm sure):
I need a QoS system that is as low maintainance as possible. Not only to make my job easier, but to make it so the next IT officer that gets this fantastic job after me doesn't have to do what I did, which was basically start from scratch.
Ideally, this what I want in terms of QoS:

Bob really wants to play WoW. It's 2pm and no one is home but him. He gets dynamite throughput.
Half an hour later, Joe gets home and his torrenting program immediately starts up. He is a good co-oper, so he has his client capped for uploads, so he and Bob are both getting pretty good bandwidth.
Bob signs out of WoW and goes off to class. Joe's torrents are now going super-fast.
Jill gets home an hour later. She goes to check her email and watches some Hulu. She is in no way aware that Joe is torrenting. Joe notices his torrents are doing pretty good.
Everyone else comes home and each of them are doing a mix of all of the above. Everyone doing basic HTTP stuff or email think "I love our network admin." All of the gamers, file-sharers, and Skype-ers think, "This will be even more awesome when everyone goes to bed!" No one comes by my room with murderous intent. No one is crying to me how the girl down the hall snuck in with scissors to literally cut off their torrents so they could read their homework.

Right now, I have the main router (the DIR-625) set up with its built-in QoS and with the DNS ports set to highest, the HTTP, email, and whatnot set to 2nd highest priority, and with anything higher than 3000 set to lowest priority.
But even so, this doesn't stop the fact that if Joe is torrenting 50GB worth of junk, and Bob is gaming all day, that they are just using MORE of the bandwidth. They get a lower priority, but they basically get all of the router's attention and all of the bandwidth.
I've taken to blocking people if they seem to be using more than 25% of the current network activity, but I'm not even sure the reporting tools I'm using are accurate. And I shouldn't have to do that, or if I should, I really don't understand what QoS does at all.
So, again, here's the real question:
Will a Linux-based router/firewall provide smarter/more customizable QoS than my current setup? I have to get all purchases voted on, so I can't just experiment as much as I want. I have looked at Tomato, Gargoyle, and SmoothWall. But each one makes me nervous.
Smoothwall can do anything, I'm told, but it requires me getting/building a machine and it apparently reveals more information than I'd like to have access to, or anyone who takes over after me, (like who's emailing who). Not to mention I just can't tell if it will meet my specific needs.
Tomato and OpenWRT require getting yet another router, taking the risk of bricking said router (and having to explain the loss to a committee), and still may not give me what I want.
2) If there is no magical QoS that can do Mac/IP based throttling (instead of Port-based), is there any software/router solution that will give me IP based bandwidth usage? All of the screenshots I see are port-based or give traffic usage in terms of packets instead of bits/second. Or only show one IP at a time (which is great when I want to COMPARE usage).
Right now, I have Excel pulling two XML files from the D-Link Router, one for MAC/IP/hostname, one for "current connections" that gives each connection per IP. I then combine all of the data into another sheet that shows number of connections per IP and then does the percentage per IP based on the total. If it's over 25%, I either shut them down for awhile or go and have words. But I'm not even sure if the total number of connections is a good measure of bandwidth usage!
I have tons of other issues, like computers not seeing each other, not being able to share, dropped wifi connections, low internal transfer rates, possibly misconfigured WAPs, just to name a few. But right now the question I get the most stress over is "Why is my internet so slow? Can't you keep people from torrenting?"
Thanks for reading all of this.
Comment: Note, network performance will be better if you cap your upload bandwidth to 90%. On asymmetric DSL connections, if your upload bandwidth runs out, it will cause your downloads to slow down. I have found that WOW gets really slow if a torrent client uses all the upload bandwidth. If it is restricted to only 80%, then WOW runs much better.
Answer: Herea a shot in the dark, but if you look on ebay you can get some truly awesome deals on EoL'd Cisco's, I'm talking 2600/3600, with that you can do exactly what your proposing, There is a need for a little CLI config, but after that you will be truly impressed with what it can do for you, i.e shaping torrents to a minimum throughput during 5pm and 2am, but still not allocating them all the bandwidth the rest of the time, leaving space for everyone else to do their homework, and perhaps prioritzing http or reserving a minimum amount of bandwidth so that even if susy, joe, and! bob are torrenting and copying that ftp file, john can still browse, (and turn in his homework).
Let me know will be more than willing to help you out will a basic template config,
Comment: Another I would recommend is nTop + MySAR, help you nail down those miscreants :D I like to think of those tool as giving you a big fish, its your decision on who to slap :D
Answer: This may not be what you expect, but why not consider a non-technical solution? Buying more equipment is not going to solve your problem as your problem is a human one. Find another way to share the bandwidth better. There are various possibilities:

Cap the number of active connections that a machine can have. This will effectively parcel out the available bandwidth to each user fairly.
Assign everyone a fair quota, say 1Gb per day each and if they exceed that quota, their bandwidth will be capped to say 56k speeds.
Improve communications. Link everyone together on some jabber/irc server. If someone needs to use the internet, they can buzz those torrenting to pause for a while. Or even better, ask those torrenting to run them over-night instead.
Educate the users on how to schedule stuff. If there is a large file that they need to download for school, schedule it to run over-night or something.
If users need to perform software updates regularly, set up a local caching proxy to help reduce the Internet cost.

Ultimately, you will need to get everyone to communicate better. That is the only way to solve the problem. No amount of LARTC is going to help you.
Comment: Wow, thanks!  As far as the overnight thing, we have tried that. It's very difficult to enforce and breeds discontent when people suspect that someone is violating it. As to your other suggestions: 1) How do I cap active connections? Is there a acronym or jargon I should be looking for? 2)If I could set a bandwidth cap, I would. Again, how? I thought I'd need a username type setup for that sort of thing. 3) Local caching proxy! that sounds awesome! I'll research that one on my own. And we are totally getting a jabber server setup, as soon as we have a username system set up. My idea!
Comment: You don't need a username type setup for network control as you can use the MAC addresses of each person as ID for networking purposes. If you can force people to move their traffic through a transparent-proxy such as squid, you will have a lot of options to play with. You can cap live TCP connections per host but you will need to check out the LARTC to see what firewall rules to set up. Ditto with bandwidth speeds. I think that traffic shaping might be a good place to start looking.
Answer:
Tomato and OpenWRT require getting yet
  another router, taking the risk of
  bricking said router (and having to
  explain the loss to a committee), and
  still may not give me what I want.

I have upgraded two WRT54GL with the tomato firmware (http://en.wikipedia.org/wiki/Linksys_WRT54G_series#Hardware_versions_affect_firmware_compatibility), just make sure you get the open WRT54GL that is marked L and you don't have to worry about bricking the device. They are open and you are free to just upgrade them with whatever.
It has QoS but if it is good enough for your needs,
but maybe it is good enough and combined with a little human communication it may be all you need...?
/Johan
Answer: A little late, but well...
I'm in almost the same position as you are, just with 150 residents. When wie startet out, we had one wireless link to the university, totalling in 4Mbit if you were really lucky.
Mowadays we have another 16/1 and one 32/2 line and are managing those via a lot of magic going on with iptables, iproute and tc. Since we have a high number of exchange students there is quite a bit of turnover, combined with the high number of residents this makes communication and mutual agreements rather difficult, so we mostly try to stay on top of it all via technical measures.
The firewall setup is pretty complex, and has grown over years of refinement. Basically we we assign connections to one of the lines based on a number of hand-crafted rules based on port numbers, target IPs, etc. (i.e. all connections to the university network go via the wireless link which obviously has less hops and so on). One problem alway is, you can only control what goes out, since all incoming traffic is already through your line when you see it. So you have to shape only to the outgoing capacity of your uplink.
For the P2P problem the best solution seems to be: a) block all P2P traffic entirely (ipp2p from xtables-addons works rather well) and b) set up a dedicated P2P box to keep the people off your back and only allo P2P for this one box. ;)
A lot of P2P software nowadays supports "watched directories", people then can upload their .torrents of in this directory and it will be downloaded for them. This also eliminates 2 residents pulling the same stuff through your line. Be advised, though, that you probably put your ass on the line for the stuff the residents do with that box, since it's under your control.
If you want to talk more specifics, like setup, scripts, etc. I'd be glad to help...
Answer: Just want to add to this for other readers that the QOS on that dlink router is only for upstream data not downstream.
Comment: I felt the need to add this based on Matt's comment above. His statement is completely misleading and untrue. QOS effects everything, the upstream data is controlled and limited which in turn limits and controls the amount of data returned to the router. So it does in fact effect upstream and downstream. (also there is no point in trying to directly use QOS on downstream data since your ISP already does it before it gets to you) This is a common misconception posted throughout the internet by people who don't actually understand what they are talking about. (sorry matt) You should probably all


Why does my Rules Action about booking a time slot appear to not be executed?

Question: I recently installed the Booking time slot module and got it to work as expected.
The issue I have is that its "Rules event" does not trigger a Rules Action. Here is my rule (for now it only includes a Rules Action to show a Drupal message):
<code>{ "rules_booking" : {
"LABEL" : "Booking",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "entity" ],
"ON" : { "booking_insert" : [] },
"DO" : [ { "drupal_message" : { "message" : "Success!" } } ] } }
</code>
I have tried using various events (After saving a new booking, After updating an existing booking) but none appears to work.
I wondering if anyone has had this kind of experience or knows what could be wrong.
Update
Here is a screenshot of the Rules Events I can select:
Comment: I have edited the question to include the rules export format. Don't get what you mean by D5.
Comment: By D5 he meant version of Drupal.
Comment: Have you tried https://www.drupal.org/project/appointment_calendar module.
And also check the event which triggers rule to add booking slot and debug there if possible
Comment: I tried to debug. No debugging information is logged in the system log for my rule above. But when i change the event to e,g "when comment is deleted", the rule is fired and debugging is logged
Answer: I'm about sure that the answer to your question can be found here.
And to be 100%, I recommend you do some Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".
Update
Your (1st) comment confirms what I wrote in my answer even more. Have a look at the source code and let me know where I can find more details about any of those "Various events" that you try to use are actually coded. I trust they are somewhere (since your question says you use them), but with my limited knowledge of Rules (hm, hm) I cannot find them ... in the typical ".inc* file where the Rules module expect them to be located. But since "I" cannot find them, it may well be that that also explains why the Rules module cannot find them ...
Comment: Question is D7. I tried to debug. No debugging information is logged in the system log for my rule above. But when i change the event to e,g "when comment is deleted", the rule is fired and debugging is logged.
Comment: @seyi your prior confirms what I wrote in my answer even more. Have a look at [the source code](http://cgit.drupalcode.org/booking_timeslots/tree/) and let me know **where** I can find more details about any of those "Various events" that you try to use are actually coded. I trust they are somewhere (since your question says you use them), but with my *limited* knowledge of Rules I cannot find them ... in the typical ".inc* file where the Rules module expect them to be located. PS: since "I" cannot find them, it may well be that that also explains why the Rules module cannot find them, get it?
Comment: Interesting. I also checked and its not in the booking slot module. Do you have any idea where the rules are coming from? I have updated the question to include a screenshot of the rules events.


Signatures of underfitting and overfitting in logistic regression calibration curves

Question: My confusion stems from reading the following paper
http://www.bmj.com/content/351/bmj.h3868
It states in its abstract (and they later show an empirical study that conforms to the claim) - "Overfitted models tend to underestimate the probability of an event in low risk patients and overestimate it in high risk patients"
I'm confused with regards to the generality of this statement. I've seen many cartoons/figures depicting overfitting as a model modelling/capturing noise, and it isn't intuitively obvious to me how that noise would necessarily lead to overestimates of risk in high risk and underestimates of risk in low risk patients. Why can't an overfitted model capture noise in a way that it underestimates the risk in high risk patients? Is there a mathematic proof for their statement?
For the second part of my question, I would like to ask, if the claim they make is true, would calibration plots of underfitted models go the other way (slope<1 for observed v/s predicted; underestimating high risk risks, and overestimating low risk risks?). Again I can't intuitively predict why a simpler underfitting model would necessarily generate a predictable calibration curve.
Comment: The statement sounds right to me. That's what overfitting is in a binary context. Consider that you have maximum uncertainty when your guess is .5, & maximum certainty if your guess is 1.0 or 0.0. The ideal fit would be when your guess is equal to the true probability. So overfitting is guesses closer to 0 for observed 0's where the true probability is not 0, and closer to 1 for observed 1's where the true probability is not 1. Conversely, underfitting is guesses closer to .5.
Comment: The statement seems dubious to me. What about models that are approximately unbiased but just have very high variance?
Comment: @gung-ReinstateMonica Would you want to expand on that in an answer? (Even on its own, it could be an answer.)
Comment: Sorry, @Dave, I haven't had a chance to get to this.
Answer:
it isn't intuitively obvious to me how that noise would necessarily lead to overestimates of risk in high risk and underestimates of risk in low risk patients.

It does not "necessarily", but it "tends" to:

Overfitted models tend to [...]

Why can't an overfitted model capture noise in a way that it underestimates the risk in high risk patients?

It can, and occasionally it does. But it doesn't do it and cannot do it systematically. If it did, it wouldn't be overfitted, but underfitted. It would systematically give lower estimates (i.e. higher uncertainty, as @gung said it his/her comment) than the optimal model.
Fitting a function to the data means minimising some error measure. The more free parameters (coefficients) the function has, the better it can approximate the empirical data and, consequently, reduce the error.
Now, for low risk patients, we'll $-$ on average! $-$ have more non-events, and an overfitted model will better approach the non-event level (e.g. zero), as it attempts to minimise the error. Occasionally, we will encounter an event even for low-risk patients, and our overfitted model will likely pick that noise too, but, due to its flexibility (being overfitted) will rapidly return to zero as we move away from that observation. The mirror-image happens for high-risk patients: There are more events than non-events there and the overfitted model will try to approximate these.
To give you some intuition, observe the following artificial dataset and the fitted probabilities:

(two normally distributed classes, fitted by simple logistic regression (green), logistic regression with poly(x, 3) predictors (orange) and with poly(x, 5) predictors (red))
As you can see, the severely overfitted red curve is, for $x < 0$ almost constantly below the green (optimal) one, except for one single peak around $x = -0.5$, where it picked up the noise on the "event" side. For "high risk patients" it's the opposite: The red curve is almost always above the green one, except again for some noise around $x = +0.5$.
Comment: Thank you for this explanation (that it tends to, but isn't necessary).  It helped me think about this problem in the practical sense as opposed to seeking an absolute mathematical proof.


Erro ao gerar arquivo com PLSQL no oracle!

Question: Código
CREATE OR REPLACE PROCEDURE CRIARARQUIVOTXT AS
  Arquivo_saida  UTL_File.File_Type;
  Dir_Arq   VARCHAR2(60);

Cursor cur_arq is
  Select f.NOME from tfuncionario f;

BEGIN

-- Diretorio do Arquivo
Dir_Arq := 'C:\Users\xxxxxx\Documents\testes';

-- Abrindo o arquivo para a gravação
Arquivo_saida  := UTL_File.Fopen(Dir_Arq, 'teste.txt','w' );

-- Abrindo o cursor para realizar o loop das linhas que irão no arquivo
for Reg_Linha in cur_arq loop
  UTL_File.Put_Line(Arquivo_Saida, Reg_Linha.linha);
end loop;

-- Fechando o arquivo
UTL_File.Fclose(Arquivo_Saida);
  Dbms_Output.Put_Line('Arquivo gerado com sucesso.');

Exception
  WHEN UTL_FILE.INVALID_OPERATION THEN
    Dbms_Output.Put_Line('Operação inválida no arquivo.');

UTL_File.Fclose(arquivo_saida);
  WHEN UTL_FILE.WRITE_ERROR THEN
    Dbms_Output.Put_Line('Erro de gravação no arquivo.');

UTL_File.Fclose(arquivo_saida);
  WHEN UTL_FILE.INVALID_PATH THEN
    Dbms_Output.Put_Line('Diretório inválido.');

UTL_File.Fclose(arquivo_saida);
  WHEN Others THEN
    Dbms_Output.Put_Line('Problemas na gravação do arquivo.');

UTL_File.Fclose(arquivo_saida);

END CRIARARQUIVOTXT;

Mensagem de erro
Comment: Select f.NOME Linha from tfuncionario f;    o erro é que "linha" deveria estar no cursor.
Comment: De que forma corrijo isso ?
Comment: corrigido: Cursor cur_arq is
  Select f.NOME linha from tfuncionario f ;
Answer: A solução para o problema foi linha codigo:
Cursor cur_arq is
   Select f.NOME linha from tfuncionario f


Move nested value in jq

Question: I have a json like this:
{
  "key_1": {
    "type": "string",
    "value": "foo"
  },
  "key_2": {
    "type": "string",
    "value": "bar"
  }
}

that I would like to output like this
{
  "key_1": "foo",
  "key_2": "bar"
}

jq '.[].value' will give me the values:
"foo"
"bar"

while this jq '(.[] = .[].value)' will give me
{
  "key_1": "foo",
  "key_2": "foo"
}
{
  "key_1": "bar",
  "key_2": "bar"
}

So I'm not sure..
Answer: Since the task entails mapping the values of the top-level keys, map_values should come to mind:
map_values(.value)

You could also use with_entries, which might make sense if you wanted to manipulate the top-level keys as well:
with_entries( .value |= .value )

Comment: did you run it?  this produces the key: value object you requested!
Comment: This gives me an array with the values, but how can I reconstruct the key-value object?
Comment: I did and I'm not sure what I wrote! I tried again and it worked like a charm! Thanks!

Move nested value in jq


Java NTFS compression attribute

Question: I need to read and modify the 'Compressed' attribute of a file on an NTFS partition from Java. I imagined something in the java.nio.file.attribute package would do it -- hell it's a complex enough package, but I can't find this attribute.
The DosFileAttributes class has getters for the classic hidden/system/readonly/archive attributes only.
I tried Files.readAttributes which allows dynamically retrieving all attributes from a particular "attribute view". Under "dos:*" there was only the same attributes that are already available from the public methods of the DosFileAttributes class. I tried "ntfs:*" and "windows:*" but they weren't accepted as valid view names.
I also tried the UserDefinedFileAttributeView, but it gave me an empty list on any file I tried.
I wondered about shelling out to the attrib command (accepting the limitation that it wouldn't work for NTFS partitions mounted under Linux or other OSes) but that doesn't seem to support the attribute either. Help?
Answer: Since this does seem to be missing from the standard Java API, I took a look at doing it myself with JNA. It's my first experience with JNA. It's not as pretty as I'd like and JNA's code seems to be sorely lacking in generics, but it's a hundred times better than mucking about with JNI and trying to set up awful cross-compilers for the different platforms needed (minimum x86 & x64 even if you target only one OS). It's the annoying compilation process that drove me from C++ to Java in the first place, and I hope never to have to return to it.
Anyway, this seems to work. Hopefully it will be useful to someone else too. It provides four public methods:

isAvailable() -- whether or not calling the other methods should work (i.e., we are on Windows and the JNA native lib loaded okay)
isCompressed(File)
setCompressed(File, boolean)
volumeSupportsFileCompression(File) -- asks Windows if the partition where a file is located supports [individual] file compression. E.g., it's true on NTFS, and false on FAT (USB sticks and so on).

Compression in the Windows API is done through a dedicated I/O control operation, and is not merely a "SetAttributes" call. If it were simpler (isomorphic with other file attributes) I'd have put the encryption attribute in there as well for completeness' sake, but anyway.
import java.io.File;
import java.io.IOException;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.ShortByReference;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT.HANDLE;

public class WindowsFileOps {
    private WindowsFileOps() {}

    private static interface Kernel32Extra extends StdCallLibrary {
        int COMPRESSION_FORMAT_NONE = 0x00000000;
        int COMPRESSION_FORMAT_DEFAULT = 0x00000001;
        int FSCTL_SET_COMPRESSION = 0x0009C040;

        Kernel32Extra INSTANCE = (Kernel32Extra)Native.loadLibrary("kernel32",
            Kernel32Extra.class, W32APIOptions.UNICODE_OPTIONS);

        boolean GetVolumeInformation(
            String lpRootPathName,
            Pointer lpVolumeNameBuffer,
            int nVolumeNameSize,
            IntByReference lpVolumeSerialNumber,
            IntByReference lpMaximumComponentLength,
            IntByReference lpFileSystemFlags,
            Pointer lpFileSystemNameBuffer,
            int nFileSystemNameSize
        );
    }

    private static Boolean isAvailable;
    public static boolean isAvailable() {
        if (isAvailable == null) {
            try {
                isAvailable = Kernel32.INSTANCE != null && Kernel32Extra.INSTANCE != null;
            } catch (Throwable t) {
                isAvailable = false;
            }
        }
        return isAvailable;
    }

    private static String pathString(File file) {
        // "\\?\" is a Windows API thing that enables paths longer than 260 chars
        return "\\\\?\\" + file.getAbsolutePath();
    }

    private static int getAttributes(File file) throws IOException {
        int attrib = Kernel32.INSTANCE.GetFileAttributes(pathString(file));
        if (attrib == Kernel32.INVALID_FILE_ATTRIBUTES) {
            throw new IOException("Unable to read file attributes of " + file);
        }
        return attrib;
    }

    public static boolean isCompressed(File file) throws IOException {
        return (getAttributes(file) & Kernel32.FILE_ATTRIBUTE_COMPRESSED) != 0;
    }

    public static void setCompressed(File file, boolean compressed) throws IOException {
        HANDLE hFile = Kernel32.INSTANCE.CreateFile(
            pathString(file),
            Kernel32.GENERIC_READ | Kernel32.GENERIC_WRITE,
            Kernel32.FILE_SHARE_READ,
            null,
            Kernel32.OPEN_EXISTING,
            0,
            null);
        try {
            if (!Kernel32.INSTANCE.DeviceIoControl(
                hFile,
                Kernel32Extra.FSCTL_SET_COMPRESSION,
                new ShortByReference((short)(
                    compressed
                        ? Kernel32Extra.COMPRESSION_FORMAT_DEFAULT
                        : Kernel32Extra.COMPRESSION_FORMAT_NONE
                )).getPointer(),
                2,
                null, 0,
                new IntByReference(),
                null
            )) throw new IOException("Unable to alter compression attribute of " + file);
        } finally {
            Kernel32.INSTANCE.CloseHandle(hFile);
        }
    }

    public static boolean volumeSupportsFileCompression(File file) throws IOException {
        IntByReference flags = new IntByReference();
        if (!Kernel32Extra.INSTANCE.GetVolumeInformation(
            pathString(file.getAbsoluteFile().toPath().getRoot().toFile()),
            null, 0,
            null,
            null,
            flags,
            null, 0
        )) throw new IOException("GetVolumeInformation failure");
        return (flags.getValue() & Kernel32.FILE_FILE_COMPRESSION) != 0;
    }
}

Comment: I think it would be great if you contributed this code to jna. You can get in touch with them at https://github.com/twall/jna
Answer: Instead of DosFileAttributes try use BasicFileAttributes and check isOther() and isRegularFile() flags. That may tell you if file is compressed. If not you would have to create your own FileSystemProvider impl for NTFS or write small JNI code that will use WinAPI to read that flag for you.
Comment: I have check WindowsFileSystem class and found this:

private static final Set supportedFileAttributeViews = Collections.unmodifiableSet(new HashSet(Arrays.asList("basic", "dos", "acl", "owner", "user")));

It means that WindowsFileSystem expose only standard attribute views.
Comment: isOther(): false. isRegularFile(): true; same as other files. No luck.
Comment: I'd say: add that to the answer.

Java NTFS compression attribute


Finding a matrix where the column space is a subset of the null space

Question: Let $A_{3x3}$ be a matrix $ \ne 0$ such that the column space of $A$ is a subset of the null space of $A$. I need to find $A$.
Here's my process so far:
let $v_1, v_2, v_3$ be the column vectors of $A$
$Col(A)=c_1 v_1 + c_2 v_2 + c_3 v_3$ is a subset of $Null(A)$
let $b$ be the column space of A such that $Ax=b$, then assume $b$ is also in the null space of $A$ so $Ax=0=A(Ab)$
How do I go about finding a particular matrix that satisfies this? Am I even heading on the right direction?
Comment: Try $A=\begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}$. Then $\ker A = \operatorname{sp} \{ e_1 \} = {\cal R} A$.
Comment: @copper.hat I haven't yet been introduced to kernals in my course. Is there another way to go about this?
Comment: It is another term for null space.
Comment: @copper.hat can you explain what's happening in your comment above? I don't understand the 'sp' among other things.
Comment: @n8sty: I added an answer.
Answer: Take $A=\begin{bmatrix} 0 & 0 & 1 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}$.
Then $Ax=0$ iff $x_3 = 0$. It is easy to see that the null space (also known as the kernel, or $\ker A$) is given by $\ker A = \{ (x_1,x_2, 0)^T \}_{x_1,x_2 \in \mathbb{R}}$.
Then $y = Ax$ for some $x$ iff $y = (x_3,0,0)^T$ for some $x_3 \in \mathbb{R}$, so the range space is is given by ${\cal R} A = \{ (x_1,0, 0)^T \}_{x_1 \in \mathbb{R}}$.
It should be clear that ${\cal R} A \subset \ker A$.