text:
Q: Error with running vaadin 8 on Jetty8 I just migrated my application from vaadin 7 to vaadin 8.1.4. When I run my application on Jetty 8, I get the following error(only once). Application seems to be working fine, but now sure how can I get rid of this error
    2017-10-02 15:21:32.608:WARN:oejs.ServletHandler:Error for /PUSH
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.upgrade(Ljava/lang/Class;)Ljavax/servlet/http/HttpUpgradeHandler;
    at org.apache.tomcat.websocket.server.UpgradeUtil.doUpgrade(UpgradeUtil.java:234)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:77)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1467)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:370)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
    at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:667)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:748)

What could be the possible reason?
Attached is my POM file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sample</groupId>
<artifactId>sample</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>sample Maven Webapp</name>
<url>http://maven.apache.org</url>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <!-- JUnit -->
    <junit.version>4.12</junit.version>

    <!-- SureFire -->
    <surefire.version>2.18.1</surefire.version>

    <!-- Spring -->
    <spring.version>4.1.6.RELEASE</spring.version>
    <spring.security.version>4.0.4.RELEASE</spring.security.version>

    <!-- Hibernate / JPA -->
    <hibernate.version>4.3.9.Final</hibernate.version>
    <hibernate.validator.version>5.1.3.Final</hibernate.validator.version>

    <!-- Logging -->
    <log4j.version>1.2.17</log4j.version>

    <!-- Vaadin -->
    <vaadin.version>8.1.2</vaadin.version>
    <vaadin.charts.version>4.0.0</vaadin.charts.version>
    <vaadin.filteringtable.version>0.9.15.v7</vaadin.filteringtable.version>
    <vaadin.spring.version>1.1.1</vaadin.spring.version>
    <vaadin.spring.integration.version>3.1</vaadin.spring.integration.version>

    <!-- Servlet -->
    <javax.api.version>3.0.1</javax.api.version>
    <javax.jstl.version>1.2</javax.jstl.version>
    <asm.version>5.0.3</asm.version>

    <!-- Apache -->
    <apache.commons.version>2.6</apache.commons.version>

    <!-- SQL Connector -->
    <sqlconnector.version>5.1.35</sqlconnector.version>

    <!-- JBibText -->
    <jbibtex.version>1.0.15</jbibtex.version>

    <!-- Joda -->
    <joda.version>2.8.2</joda.version>

    <!-- Stax -->
    <stax.version>1.2.0</stax.version>

    <!-- iText -->
    <itext.version>5.0.6</itext.version>

    <!-- Java Home -->
    <JAVA_HOME>C:\Program Files\Java\jdk1.8.0_45\</JAVA_HOME>

    <!-- Java Version -->
    <java.version>1.8</java.version>

    <!-- Flyway -->
    <flyway.version>3.2.1</flyway.version>

</properties>

<dependencies>
    <!-- JUnit -->
    <dependency>
        <groupId>JUnit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
    </dependency>
    <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aspects</artifactId>
         <version>4.1.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring.security.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
    </dependency>

    <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.api.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>${javax.jstl.version}</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.ow2.asm</groupId>
        <artifactId>asm</artifactId>
        <version>${asm.version}</version>
        <scope>compile</scope>
    </dependency>

    <!-- Hibernate -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>${hibernate.validator.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>${hibernate.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.6.11</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.0</version>
    </dependency>

    <!-- SQL -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${sqlconnector.version}</version>
        <scope>runtime</scope>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>

    <!-- Flyway -->
    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>${flyway.version}</version>
    </dependency>

    <!-- EventBus -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>

    <!-- Vaadin -->
    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-compatibility-server</artifactId>
        <version>${vaadin.version}</version>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-compatibility-client-compiled</artifactId>
        <version>${vaadin.version}</version>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-compatibility-client</artifactId>
        <version>${vaadin.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-compatibility-shared</artifactId>
        <version>${vaadin.version}</version>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-client-compiler</artifactId>
        <version>${vaadin.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-themes</artifactId>
        <version>${vaadin.version}</version>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-push</artifactId>
        <version>${vaadin.version}</version>
    </dependency>

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>

    <!-- Vaadin Addons -->
    <dependency>
       <groupId>com.vaadin</groupId>
       <artifactId>vaadin-charts</artifactId>
       <version>${vaadin.charts.version}</version>
    </dependency>

    <dependency>
       <groupId>org.vaadin.alump.labelbutton</groupId>
       <artifactId>labelbutton-addon</artifactId>
       <version>0.2.0</version>
    </dependency >

    <dependency>
        <groupId>org.vaadin.addons</groupId>
        <artifactId>vaadin-combobox-multiselect</artifactId>
        <version>2.0.1</version>
    </dependency>

    <dependency>
       <groupId>org.vaadin.addon</groupId>
       <artifactId>confirmdialog</artifactId>
       <version>3.2.0</version>
    </dependency>

    <dependency>
       <groupId>org.vaadin.addons</groupId>
       <artifactId>animator</artifactId>
       <version>3.0.0</version>
    </dependency>

    <!-- Apache Commons -->
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>${apache.commons.version}</version>
    </dependency>

    <!-- jbibtext -->
    <dependency>
        <groupId>org.jbibtex</groupId>
        <artifactId>jbibtex</artifactId>
        <version>${jbibtex.version}</version>
    </dependency>

    <!-- Joda -->
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>${joda.version}</version>
    </dependency>

    <dependency>
        <groupId>stax</groupId>
        <artifactId>stax</artifactId>
        <version>${stax.version}</version>
    </dependency>

    <!-- JSoup -->
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.8.3</version>
    </dependency>

    <!-- iText -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>${itext.version}</version>
    </dependency>

    <!-- Jackson 4 JSON -->
     <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.8</version>
    </dependency>

    <!-- Mail -->
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.5.2</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>3.2.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

</dependencies>

<repositories>
    <repository>
        <id>vaadin-addons</id>
        <url>http://maven.vaadin.com/vaadin-addons</url>
    </repository>

    <repository>
        <id>osssonatype</id>
        <name>OSS Sonatype</name>
        <url>https://repo1.maven.org/maven2/</url>
        <layout>default</layout>
    </repository>
</repositories>

<build>
 <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.sql</include>
            </includes>
        </resource>
         <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
    <finalName>sample</finalName>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${surefire.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>${surefire.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <verbose>true</verbose>
                    <!-- <fork>true</fork> -->
                    <executable>${JAVA_HOME}/bin/javac</executable>
                    <compilerVersion>${java.version}</compilerVersion>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <filesets>
                        <fileset><directory>${project.build.directory}/${project.build.finalName}</directory></fileset>
                    </filesets>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <webResources>
                        <webResource>
                            <directory>target/sample/CustomWidgetset</directory>
                            <targetPath>VAADIN/widgetsets/CustomWidgetset</targetPath>
                            <filtering>false</filtering>
                        </webResource>
                    </webResources>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${vaadin.version}</version>
                <configuration>
                    <extraJvmArgs>-Xmx512M -Xss1024k</extraJvmArgs>
                    <!-- <runTarget>mobilemail</runTarget> -->
                    <!-- We are doing "inplace" but into subdir VAADIN/widgetsets. This
                        way compatible with Vaadin eclipse plugin. -->
                    <webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
                    <hostedWebapp>${project.build.directory}/${project.build.finalName}</hostedWebapp>
                    <noServer>true</noServer>
                    <!-- Remove draftCompile when project is ready -->
                    <draftCompile>false</draftCompile>
                    <compileReport>true</compileReport>
                    <style>OBF</style>
                    <strict>true</strict>
                    <runTarget>http://localhost:8080/</runTarget>
                </configuration>
                <executions>
                    <execution>
                        <configuration>
                            <!-- if you don't specify any modules, the plugin will find them -->
                            <!-- <modules> <module>com.vaadin.demo.mobilemail.gwt.ColorPickerWidgetSet</module>
                                </modules> -->
                        </configuration>
                        <goals>
                            <goal>clean</goal>
                            <goal>resources</goal>
                            <goal>update-theme</goal>
                            <goal>update-widgetset</goal>
                            <goal>compile-theme</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.8</version>
            <configuration>
                <outxml>true</outxml>
                <verbose>true</verbose>
                <showWeaveInfo>true</showWeaveInfo>
                <forceAjcCompile>true</forceAjcCompile>
                <aspectLibraries>
                    <aspectLibrary>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aspects</artifactId>
                    </aspectLibrary>
                </aspectLibraries>
                <complianceLevel>${java.version}</complianceLevel>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>

            <executions>
                <execution>
                    <phase>process-classes</phase>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>

        </plugin>
        </plugins>
    </pluginManagement>
</build>


text:
Q: Array and loops I have an array contain 100 elements. Can anyone help me to figure out how to write loops that perform this:
data[0] = 1/(2*3*4)
data[1] = 1/(4*5*6)
data[2] = 1/(6*7*8)
...
data[99] = 1/(200*201*202)

data[0]-data[1]+data[2]-data[3]+data[4]-data[5]+...+data[98]-data[99]

I just can't understand how to start. Any suggestions would be appreciated!

A: Try this
double c=0;
for (int i=0;i<100;i++)
{
 c=i*2+2;
 data[i]=1/(c*(c+1)*(c+2));
}
for (int i = 0; i < 100; i+=2)
{
  op+= data[i] - data[i+1];
}

A: My suggestions how to start, if you really want them and want to manage this by your own:

*

*Generalize your algorithm:

*

*Find a function f(x) such that data[i] = f(i)

*Just write the algorithm in your native language.

*Then learn basic operators of C language, including loop construct.

*Write your "native language algorithm" in C language.

A: Just in one loop:
int total = 0;
for(size_t i=0; i<100; ++i){
  int temp = (i+1)*2;
  data[i] = 1/(temp*(temp+1)*(temp+2));
  total = total + (i%2==0?data[i]:-data[i]);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: react re render component based on api fetch I am building a single-page website, now I am fetching data from a movies API with different genres, and I do it on componentDidMount(), the first time its work and I get the data(movies) the without refreshing
the problem is that the component is not re-render when I switch to another genre(the movies are still the same), only when refreshing its changes to another genre movies, is there a way to so without refreshing?
and someone can please explain to me how and when to use componentDidUpdate()?
Search.js:

const genresId = {
    Action: '28',
    Animation: '16',
    Comedy: '35',
    Adventure: '12'
}

export class Search extends Component {
    constructor(props) {
        super(props);
        this.state = {
            genre: "",
            title: this.props.match.params.genre
        }
        this.checkGenre = this.checkGenre.bind(this);
    }

    checkGenre() {
        const whichGenre = this.props.match.params.genre;
        let temp;
        if (whichGenre === 'action') {
            this.setState({genre: genresId.Action});
            temp = genresId.Action;
        } else if (whichGenre === 'animation') {
            this.setState({genre: genresId.Animation})
            temp = genresId.Animation;
        } else if (whichGenre === 'comedy') {
            this.setState({genre: genresId.Comedy})
            temp = genresId.Comedy;
        } else if (whichGenre === 'adventure') {
            this.setState({genre: genresId.Adventure})
            temp = genresId.Adventure;
        }
        return temp
    }

    render() {
        return (

{this.state.title} Movies

                    <Container>
                        <SearchResult checkGenre={this.checkGenre} genreId={this.state.genre}/>
                    </Container>

        )
    }
}

SearchResult.js:
export class SearchResult extends Component {
    constructor(props) {
        super(props);
        this.state = {
            moviesArray: [],
            page: 1,
            isLoading: true
        }
    }

    async componentDidMount() {
        let urlWithParams = `${baseUrl}&page=${this.state.page}&with_genres=${this.props.checkGenre()}`
        const response = await axios.get(urlWithParams)
        this.setState({moviesArray: response.data.results, isLoading: false})
        console.log(this.state.moviesArray)

    }

    // async componentDidUpdate(prevProps, prevState) {
    //     if (prevProps.genre !== this.props.genre) {
    //         // ...
    //     }
    // }

    checkIfDataAvailable() {
        if (!this.state.isLoading) {
            return (
                <Row>
                    {this.state.moviesArray.map(movie =>
                         <Col key={movie.id}  sm="6" md="4" lg="3">
                         <SearchItem
                         id={movie.id}
                         title={movie.title}
                         src={`${baseImgUrl}/${movie.poster_path}`}
                         releaseDate={movie.release_date}
                         rating={movie.vote_average}
                         />
                     </Col>
                    )}
                </Row>
            )
        } else {
            return (

                    {console.log('Is Loading....')}

            )
        }
    }

    render() {
        return (

                {this.checkIfDataAvailable()}

        )
    }
}

A: componentDidMount doesn't refire on reactive updates. You will want to do your fetch in componentdidupdate instead. You probably want to check whether the genre has changed before fetching, in case there are other reactive changes that can cause an update. Something like this:
async componentDidUpdate(prevProps) {
  if (this.props.genre !== prevProps.genre) {
    let urlWithParams = `${baseUrl}&page=${this.state.page}&with_genres=${this.props.genre}`
    const response = await axios.get(urlWithParams)
    this.setState({moviesArray: response.data.results, isLoading: false})
    console.log(this.state.moviesArray)
  }
}


text:
Q: AngularJS2 and Socket.io, is this approach be improved? In my index.html I inserted the Socket.io script:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

This is a part of my component:
import {Component, OnInit, AfterContentInit} from 'angular2/core';
@Component({
  selector: '[cssEditor]',
  templateUrl: '/app/cssEditor/cssEditor.html'
})

export class cssEditor {
  cssData = {
    'body-bg':'#fff',
    'text-color':'#000'
  };

  ngAfterContentInit() {
    // for emit to the server
    this.socket.on('connect', () =>
      this.socket.emit('myCssData',this.cssData);
    );
    // for listening to the server
    this.socket.on('recordOK', (data) =>
      console.log(data);
    );
  }

  ngOnInit() {
    this.socket = io('http://localhost:2000');
  }
}

I entered the events servers listening in 'ngAfterContentInit'. This code works for me very well, but do you think that the best way?


text:
Q: JavaScript send value to the backend (hidden html input or all means) I have two really simple form that looks like this:
<form name='a' id='a'> // form a
     <input type="text" name="x" id="x"> //input 1
     <input type="text" name="y" id="y"> //input 2
     <button>submit</button>
</form>

when the form a is submitted, the URL query string will look like example.com/?x=1&y=2
<form name='b' id='b' method="POST"> //form b
     <input type="hidden" name="sum" id="sum"> // hidden input sum
</form>

I have a computation script code that calculates the sum of input 1 and input 2 then stores the sum to hidden "input sum" inside "form b"
<script>
     window.addEventListener("DOMContentLoaded", function(){
        function calculate(){
             // I want it also to work when someone paste the url example.com/?x=1&y=2
             const urlParams = new URLSearchParams(window.location.search);
             x = urlParams.get('x')
             y = urlParams.get('y')
             sum = parseInt(x)+parseInt(y)
             document.getElementById('sum').value = sum //store sum to hidden input
          }
      calculate()
    });

</script>

How do I send value of hidden "input sum" to the backend(Django) when someone submits form a or paste the URL?
I prefer something like this if such thing is viable:
if sum.value not empty:
   form_b.submit()
   form_b.prevent_page_refresh

I don't know if this is possible or how to implement such in js or ajax, if not I'm open to all ideas.
Edit: Ajax solution right after def function calculate(){...}, And removed the 2nd form:
 $.ajax({
           type:'POST',
           url:'{% url "index"%}',
           headers: {
           'X-CSRFToken': '{{ csrf_token }}'
           },
           data:{
              sum:sum,
               },
          success: function(){}});

A: Not sure I'm getting your point exactly, but I think this is what you're looking for?

const form = document.getElementById('a');
const sumInput = document.getElementById('sum');
function calculate() {
    const urlParams = new URLSearchParams(window.location.search);
    x = urlParams.get('x');
    y = urlParams.get('y');
    const sum = parseInt(x) + parseInt(y);
    sumInput.value = sum;
    fetch('http://localhost:8000', {
        method: 'POST',
        body: JSON.stringify({
            value: sum
        })
    });
}
window.addEventListener("DOMContentLoaded", () => {
    calculate()
});
<form name="a" id="a" onsubmit="calculate">
    <input type="text" name="x" id="x">
    <input type="text" name="y" id="y">
    <button>submit</button>
    <input type="hidden" name="sum" id="sum">
</form>

Basically, a simple form that calculates the result and posts it? Not sure what's use for the hidden input, then.


text:
Q: TimerHandler duplicating and cannot be unregistered in andengine I need some help with a strange problem I am having involving TimerHandlers. For some reason when I call unregisterUpdateHandler on my set of timers they don't get removed on the first pass. This problem has been driving me nuts since it makes absolutely no sense to me. I only add the timers once and unregistered them when restarting my level. If I don't register a new set of timers the old ones persist as if I never unregistered them and they stay until I restart the level again then they're finally gone. Has anyone else ever encountered this problem?
These are all part of the same class
@Override
public void createScene() {

    createBackground();
    createHUD();
    createPhysics();

    if(!firstTry)
    {
        createSprites();
        firstTry = true;

    }
    loadLevel(1);
    createGameOverText();
    loadData();
    //levelCompleteWindow = new LevelCompleteWindow(vbom);

    setOnSceneTouchListener(this);

}

public void createSprites()
{
    updater =  new TimerHandler(1f, new ITimerCallback()
    {
        public void onTimePassed(final TimerHandler pTimerHandler)
        {

            updateTime();
            /*if(timeRemaining <=0)
            {
                player.onDie();
            }*/
            pTimerHandler.reset();
        }
    });
    itemMaker = new TimerHandler(5f, new ITimerCallback()
    {
        public void onTimePassed(final TimerHandler pTimerHandler)
        {
            createItem();
            pTimerHandler.reset();
        }
    });
    enemyMaker = new TimerHandler(2.5f, new ITimerCallback()
    {
        public void onTimePassed(final TimerHandler pTimerHandler)
        {
            createEnemy();
            pTimerHandler.reset();
        }
    });

    player = new Player(SCREEN_WIDTH/10,SCREEN_HEIGHT-ResourceManager.getInstance().player_region.getHeight(), vbom, camera, physicsWorld)
    {

        @Override
        public void onDie() {
            // TODO Auto-generated method stub
            if (!gameOverDisplayed)
            {
                displayGameOverText();
                saveData();
                createMenuChildScene();
                //Log.d("TEST","CALLED");
                physicsWorld.unregisterPhysicsConnector(this.fall);
                //unregisterUpdateHandler(updater);
                //unregisterUpdateHandler(itemMaker);
                //unregisterUpdateHandler(enemyMaker);
                //unregisterUpdateHandler(increase);
            }
        }

    };
    this.registerUpdateHandler(updater);
    this.registerUpdateHandler(itemMaker);
    this.registerUpdateHandler(enemyMaker);
    //this.registerUpdateHandler(increase);
}

This is called when the player dies to restart the scene without reloading the class
private void cleanUp()
{
    this.detachChildren();
    menuChildScene.back();

    timeRemaining = 30;
    totalTime = 0;
    isRunning=false;
    gameOverDisplayed = false;
    //Log.d("TEST","PLayer Y:"+ player.getY());
    //player.setY(SCREEN_HEIGHT-ResourceManager.getInstance().player_region.getHeight());
    //player.
    //updater.reset();
    //itemMaker.reset();
    //enemyMaker.reset();
    //increase.reset();
    this.unregisterUpdateHandler(updater);
    this.unregisterUpdateHandler(itemMaker);
    this.unregisterUpdateHandler(enemyMaker);
    //this.unregisterUpdateHandler(increase);
    Log.d("TEST","Handlers Unregistered");
    //physicsWorld.registerPhysicsConnector(player.fall);
    player = new Player(SCREEN_WIDTH/10,SCREEN_HEIGHT-ResourceManager.getInstance().player_region.getHeight(), vbom, camera, physicsWorld)
    {

        @Override
        public void onDie() {
            // TODO Auto-generated method stub
            if (!gameOverDisplayed)
            {
                displayGameOverText();
                saveData();
                createMenuChildScene();
                //Log.d("TEST","CALLED");
                physicsWorld.unregisterPhysicsConnector(this.fall);
                //unregisterUpdateHandler(updater);
                //unregisterUpdateHandler(itemMaker);
                //unregisterUpdateHandler(enemyMaker);
                //unregisterUpdateHandler(increase);
            }
        }

    };
    //this.unregisterUpdateHandlers(pUpdateHandlerMatcher);
}

I'll add more code if needed but these are the only instances where TimerHandlers are referenced. As you can see, I tried to unregister the timers multiple times before but the results were the same with the timers not being removed until the second pass/death
EDIT: Here is the whole class (Kinda messy and a bit hard to read)
https://gist.github.com/powerbot99/6030edb3e4c1e84a6200

A: Since I can't emulate what you're doing, this is going to be a guess, and a fairly unsubstantiated one.
You code looks like it should work.
BUT
In all of the examples for TimerHandlers being saved to a variable, they are assigned within the registerUpdateHandler command.
registerUpdateHandler(spriteTimerHandler = new TimerHandler(mEffectSpawnDelay,true,new ITimerCallback()
        {
            @Override
            public void onTimePassed(final TimerHandler pTimerHandler)
            {

                //Random Position Generator
                final float xPos = MathUtils.random(30.0f, (CAMERA_WIDTH - 30.0f));
                        final float yPos = MathUtils.random(30.0f, (CAMERA_HEIGHT - 30.0f));

                        createSprite(xPos, yPos);
            }
        }));

We both know this should not make a difference. But for fun and giggles, try that and see. Like so:
this.registerUpdateHandler(updater =  new TimerHandler(1f, new ITimerCallback()
{
    public void onTimePassed(final TimerHandler pTimerHandler)
    {

        updateTime();
        /*if(timeRemaining <=0)
        {
            player.onDie();
        }*/
        pTimerHandler.reset();
    }
}));
this.registerUpdateHandler( itemMaker = new TimerHandler(5f, new ITimerCallback()
{
    public void onTimePassed(final TimerHandler pTimerHandler)
    {
        createItem();
        pTimerHandler.reset();
    }
});

this.registerUpdateHandler(    enemyMaker = new TimerHandler(2.5f, new ITimerCallback()
{
    public void onTimePassed(final TimerHandler pTimerHandler)
    {
        createEnemy();
        pTimerHandler.reset();
    }
})));

I'm not super optimistic, but let me know.


text:
Q: PayUMoney - Android: Only getting **paymentId** from payUMoney SDK after successful payment I'm integrating payUMoney in my Android application. I'm getting only paymentId after successful payment in both environment i.e Test & Production. I need Transaction Details as well from payUMoney. I have also contacted payUMoney technical team but not getting any response.
See image attached for payUMoney response which I have printed in Logcat.
What I have tried is like below.
public void makePayment() {
    String phone = "8882434664";
    String productName = "product_name";
    String firstName = "piyush";
    String txnId = "0nf7" + System.currentTimeMillis();
    String email = "piyush.jain@payu.in";
    String sUrl = AppConstant.BASE_URL + "/mob-payment/success";
    String fUrl = AppConstant.BASE_URL + "/mob-payment/failure";
    String udf1 = "";
    String udf2 = "";
    String udf3 = "";
    String udf4 = "";
    String udf5 = "";
    boolean isDebug = true;
    String key = "dRQuiA";
    String merchantId = "4928174";

    PayUmoneySdkInitilizer.PaymentParam.Builder builder = new PayUmoneySdkInitilizer.PaymentParam.Builder();

    builder.setAmount(1.0)
            .setTnxId(txnId)
            .setPhone(phone)
            .setProductName(productName)
            .setFirstName(firstName)
            .setEmail(email)
            .setsUrl(sUrl)
            .setfUrl(fUrl)
            .setUdf1(udf1)
            .setUdf2(udf2)
            .setUdf3(udf3)
            .setUdf4(udf4)
            .setUdf5(udf5)
            .setIsDebug(isDebug)
            .setKey(key)
            .setMerchantId(merchantId);

    PayUmoneySdkInitilizer.PaymentParam paymentParam = builder.build();
    calculateServerSideHashAndInitiatePayment(paymentParam);
}

private void calculateServerSideHashAndInitiatePayment(final PayUmoneySdkInitilizer.PaymentParam paymentParam) {

    String url = "https://test.payumoney.com/payment/op/calculateHashForTest";

    StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);

                if (jsonObject.has(SdkConstants.STATUS)) {
                    String status = jsonObject.optString(SdkConstants.STATUS);
                    if (status != null || status.equals("1")) {
                        String hash = jsonObject.getString(SdkConstants.RESULT);
                        paymentParam.setMerchantHash(hash);
                        PayUmoneySdkInitilizer.startPaymentActivityForResult(ActivityConfirmOrder.this, paymentParam);
                    } else {
                        Toast.makeText(ActivityConfirmOrder.this,
                                jsonObject.getString(SdkConstants.RESULT),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error instanceof NoConnectionError) {
                Toast.makeText(ActivityConfirmOrder.this,
                        ActivityConfirmOrder.this.getString(R.string.connect_to_internet),
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ActivityConfirmOrder.this,
                        error.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return paymentParam.getParams();
        }
    };
    Volley.newRequestQueue(this).add(jsonObjectRequest);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PayUmoneySdkInitilizer.PAYU_SDK_PAYMENT_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            StringBuilder str = new StringBuilder();
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                Set<String> keys = bundle.keySet();
                Iterator<String> it = keys.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    str.append(key);
                    str.append(":");
                    str.append(bundle.get(key));
                    str.append("\n\r");
                }
                Log.e("res: ", str.toString());
            }

        } else if (resultCode == RESULT_CANCELED) {
        } else if (resultCode == PayUmoneySdkInitilizer.RESULT_FAILED) {
            if (data != null) {
                if (data.getStringExtra(SdkConstants.RESULT).equals("cancel")) {
                } else {
                }
            }
        } else if (resultCode == PayUmoneySdkInitilizer.RESULT_BACK) {
        }
    }
}

PayUMoney SDK-Version: versionName "6.1.0"

A: I was also facing the same problem, but after little bit of research, I have found that we need to generate invoice separately using different invoice api. You can find the bellow URL for the documentation for invoice api...
https://www.payumoney.com/dev-guide/products/invoicing.html
@MaulikDodia Actually you need to create success url on your own, then the payumoney will send all the data directly like this in your success url...
Array
(
    [mihpayid] => 40399371551*******
    [mode] => DC
    [status] => success
    [unmappedstatus] => captured
    [key] => d****A
    [txnid] => INV0****0531
    [amount] => 1000.0
    [addedon] => 2017-05-31 13:16:12
    [productinfo] => ****
    [firstname] => ****
    [lastname] =>
    [address1] =>
    [address2] =>
    [city] => null
    [state] =>
    [country] => null
    [zipcode] =>
    [email] => ***@test.xxx
    [phone] =>
    [udf1] =>
    [udf2] =>
    [udf3] =>
    [udf4] =>
    [udf5] =>
    [udf6] =>
    [udf7] =>
    [udf8] =>
    [udf9] =>
    [udf10] =>
    [hash] => ***************
    [field1] => 715140****61
    [field2] => 99***9
    [field3] => 8523310*****511
    [field4] => -1
    [field5] =>
    [field6] =>
    [field7] =>
    [field8] =>
    [field9] => SUCCESS
    [PG_TYPE] => HDFCPG
    [encryptedPaymentId] => DB****EB8****02A****9FE4C****CB3
    [bank_ref_num] => 8****016137****
    [bankcode] => MAST
    [error] => E000
    [error_Message] => No Error
    [name_on_card] => payu
    [cardnum] => 512345XXXXXXXX46
    [cardhash] => This field is no longer supported in postback params.
    [amount_split] => {"PAYU":"1000.0"}
    [payuMoneyId] => 1******0
    [discount] => 0.00
    [net_amount_debit] => 1000
)

Then you can generate invoice using that on the server side or do whatever you want.
Source: I have done all the code and it is working. Hope it helps... thanks


text:
Q: Low-cost, low-current solution for dropping 1V from a battery I have a 3 x 1.5V NiMH battery pack giving a supply voltage in the range [3.0V ... 4.5V] depending on the remaining capacity. In order to prolong battery life I need to cut power from the entire PCB except for the MCU sleep module that consumes a few uA. The catch is that the sleep module is rated at [1.8V ... 3.6V] and I cannot afford an LDO for this purpose.
Is there a way to achieve a voltage drop between 0.9V and 1.2V without any significant current draw?

A: This microchip appnote suggests in section 8-3 to use some rectifier diodes in series as shown in Figure 3-1, which converts a 5V supply into an approximately 3.9V supply.

Each diode will give you a voltage drop, depending on the type of the diode and the current  through the diode.  Note the inclusion of R1, which the appnote mentions

is present to keep the voltage at the PIC MCUs \$V_{DD}\$ pin
  from exceeding the maximum \$V_{DD}\$
  at minimum loads (typically when the PIC MCU
  is in Reset or sleeping). Depending on the
  other circuitry connected to \$V_{DD}\$, this resistor
  may have its value increased or possibly even
  eliminated entirely. Diodes D1-D3 must be
  selected so that at maximum load, typically
  when the PIC is running and is driving its
  outputs high, the voltage drop across D1-D3 is
  low enough to meet the PIC MCUs minimum
  \$V_{DD}\$ requirements.

The downside of this approach would be that you will lower the voltage even when you are below the 3.6V, so you will not have the full operating range.
Be extremely careful when selecting diodes; \$V_F\$ is not constant with respect to current or temperature.   Here's an example relationship from the Fairchild 1N414 datasheet:

The forward voltage is proportional to the log of the current until about 100mA, when it begins to increase more rapidly due to carrier saturation.  You mention that your device has a minimum current of a few μA, for which you probably paid dearly.  You could increase this quiescent current to a little more than 20 μA with a 220 kΩ resistor and put 2 diodes in series to get 450mV drop per diode and a safe output voltage of 3.6V when your batteries are at 4.5V.
Of course, when the MCU wakes up and draws more current (assuming ~10mA) the voltage drop will go up to about 2⋅700mV=1.4V. Instead of operating from your batteries in their full charge range, you'd only be able to discharge your batteries to 1.8V + 1.4V / 3 = 3.2V / 3 = 1.06 V/cell.  There's some optimization to be had in increasing or decreasing the resistor value and diode count, but it's difficult to get good results as you could with an LDO.
Conclusion: Don't use this approach unless your application is extremely cost-sensitive!

A: A common diode in series is not a good idea, like PetPaulsen also showed: the voltage drop varies too much with current.
A voltage reference diode like the LM285 in series with your battery is a better choice if your current is maximum 20mA. Voltage drop is pretty much a constant 1.235V from about 3\$\mu\$A to the maximum of 20mA.

A: NimH at low current will provide say 1.1 - 1.35 Volt out. Voltage will drop below 1.3V/cell early in discharge range. At low Iout 1.1V is close to exhausted if very good cell life wanted, but you can go substantially lower. If you design 3.3-3.9V or say 3.0 - 3.9V you will recover the large majority of available energy. You do not say what operating current drain is or acceptable vsupply when operating, and these will influence the acceptable design.
Charging voltage max per cell depends on max current charge rate. At moderate charge rates Vmax_chg is typically 1.45V (3 = 4.35V) and 1.4V can be used with minimal capacity loss.
If a reduction of battery voltage range by a fixed amount or ratio was acceptable then an FET with exceptionally high value gate resistors could accomplish this. You can buy "zero gate voltage" FETS which used isolated charge storage to bias the gates to "just not on" at 0 volts \$V_{GS}\$ so that the source voltage then equals the applied gate voltage. "A bit of playing" would yield a solution similar in performance to the above IC solution  iQ wise but utterly inferior voltage accuracy wise. The IC provides an immensely sophisticated and accurate result and is well worth considering.

A: One 1N4007 will drop about 0.85 volts in the forward direction. It costs watt-hours, but not current.
Just because you supply 4.5V into the batteries doesn't mean you actually get 4.5V across the batteries. They will keep their charge state voltage, plus some voltage across the resistance of the hook-up. The rest of the voltage will be lost across the circuitry going into the batteries. The lower the battery charge, the higher the current they want, and thus the more losses you will have in the circuitry around the battery. Thus, the batteries won't get to 3*1.5V until they are completely full -- and you probably want to cut off before then, say at 3*1.4V. It's likely your regulator will buckle and provide less than 4.5V way before the batteries would start saturating and push the voltage up (but I don't recommend pushing it that hard.)
The only thing that may cost less watt-hours than a diode to drop the voltage is a highly efficient switching power regulator, which is going to both cost a lot of money, and take a lot of board space.


text:
Q: Merging two WAV files together with different durations so that the end times match I have several pairs of wav files (obtained by recovering the audio from VoIP packet captures). I'd like to merge the two files down to a single-channel WAV file, which is easy with ffmpeg or sox. However, the two files are different lengths, and I'd like to join them so that the end of the file matches, rather than the start.
So, for example, there are two files, P0.wav and P1.wav. I'd like to merge the two together so that P0.wav starts, and then P1.wav is mixed in so that both files end at the same time:
  <-------P0.wav----> file 1
      <---P1.wav----> file 2

I've tried both ffmpeg and sox, and both will merge the files down to a single channel, but the result is:
 <-------P0.wav----> file 1
 <---P1.wav---->     file 2

Is there way to achieve this using ffmpeg or sox, ideally "generically" (i.e. without having to example each individual file and work out the timings) so that I can throw it into a batch?

A: With full credit to @michaeljan for the inspiration, the answer is to reverse both files, merge them together and then reverse them again.
ffmpeg -i p0.wav -i p1.wav -filter_complex "[0:a]areverse[1r];[1:a]areverse[2r];[1r][2r]amerge[m];[m]areverse[f]" -map "[f]" output.wav

So that filter_complex magic:

*

*Takes p0.wav and reverses it as [1r]

*Takes p1.wav and reverses it as [2r]

*Merges [1r] and [2r] together to [m]

*Reverses [m] to [f]
.. and then [f] is the final file.
A small caveat is that the merge file is only as long as the shortest file: however, in my use case I actually wanted p0.wav to be truncated to match the length of p1.wav - if this isn't the desired affect then changing amerge to amix and using the duration option should fix this.


text:
Q: How to update chokidar files selection correctly without declaring new variable? Assume that we created the chokidar instance, but then files selection that should be watched has been changed. If I don't want to create a new variable, is it enough just to assign new chokidar watcher with new files selection to same variable? Of course, in below code, I would that filesSelection1 will no be watched anymore.
let filesSelection1 = 'test/files/selection/1/**.*';
let filesSelection2 = 'test/files/selection/2/**.*';

let stylesWatcher = chokidar.watch(filesSelection1);

// is it correct?
stylesWatcher = chokidar.watch(filesSelection2);

A: I don't know chokidar (and NodeJS streams) implementation in details, but after some experiments I understood that stylesWatcher = null in below code will not terminate watching:
let stylesWatcher = chokidar.watch(filesSelection1);
stylesWatcher = null;

If you want to update chokidar watcher without watching will be terminated, below code passed the tests:
let stylesWatcher = chokidar.watch(filesSelection1);
let bufferedOldWatcher = stylesWatcher;
stylesWatcher = chokidar.watch(filesSelection2);
bufferedOldWatcher.close(); // now we can close watching on old instance


text:
Q: How do you zoom in on a terminal? On PC with a Steam controller if that's relevant.
Questions's in the title, really. I can't figure out how to zoom in/out on a terminal. You can change the zoom on the Pip Boy using Back but that didn't do anything when using a terminal. Indeed, I've tried just about everything I can think of and nothing seems to work, zoom level on a terminal seems to be randomly changed.
It only ever seems to change when entering a terminal, I find I've never seen it change when using one.
Nobody else on the internet knows how it works either, I found a handful of Reddit/Steam threads with no definitive answers.

A: This is why not, and why there isn't even a mod for it.

I made a mod for this for New Vegas, and it has other features like adjusting IS FOV depending on your settings, as well as pipboy and terminal fov, and a few other things like dialogue and IS zoom time. I was hoping to bring this mod to Fallout 4 eventually, but looks like a lot of it is done through scaleform which I haven't got the skills to change.
–afkmods.iguanadons.net

A: I don't believe you can zoom in on a terminal I never have.


text:
Q: preg_replace para alterar src de imagem Eu tenho varias noticias cadastradas em um banco de dados, muitas delas, tem imagens, que apontam direto pro meu site.
Só que elas possuem http e como agora instalei SSL no meu site, preciso que elas fiquem com https.
Eu não quero alterar nada no banco, então preciso de uma preg_replace que altere de http para https, somente tags  no atributo src.
Isso não vale para links, apenas para imagens...
Alguém consegue me ajudar?

A: <?php

$re = '/([^<img src=\'"]+):/';

$str = ' ';

preg_match_all($re, $str, $matches);

$str = preg_replace($re, 'https', $str);

print_r($str);

A: Você pode fazer um replace simples substituindo o http://www.domain.com.br pela sua url.
$str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.

        ';

echo str_replace( 'http://www.domain.com.br' , 'https://www.domain.com.br' , $str );

A: exemplo - ideone
$str = 'Bla bla bla

http://www.seudominio.com/';

echo str_replace( '<img src="http' , '<img src="https' , $str );


text:
Q: PHP MySQL Login Issues I made a user portal and everything seems to work fine but with only one thing. Whenever I login using a different username and password, the name being displayed in the profile section remains the same even if I am already using different username.
Dashboard <?php echo $row_Recordset1['firstname']; ?> <?php echo $row_Recordset1['lastname']; ?> (<?php echo $row_Recordset1['username']; ?>)
Please help. I tried putting it in '$_SESSION' but nothing works.
EDIT: (the full code)
<?php require_once('Connections/Authentication.php'); ?>

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_Authentication, $Authentication);
$query_Recordset1 = "SELECT * FROM login";
$Recordset1 = mysql_query($query_Recordset1, $Authentication) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);

if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
  // For security, start by assuming the visitor is NOT authorized.
  $isValid = False;

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
  // Therefore, we know that a user is NOT logged in if that Session variable is blank.
  if (!empty($UserName)) {
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
    // Parse the strings into arrays.
    $arrUsers = Explode(",", $strUsers);
    $arrGroups = Explode(",", $strGroups);
    if (in_array($UserName, $arrUsers)) {
      $isValid = true;
    }
    // Or, you may restrict access to only certain users based on their username.
    if (in_array($UserGroup, $arrGroups)) {
      $isValid = true;
    }
    if (($strUsers == "") && true) {
      $isValid = true;
    }
  }
  return $isValid;
}

$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo);
  exit;
}
?>
<!DOCTYPE html>

     <meta charset="UTF-8" />
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />
    <meta content="" name="description" />
    <meta content="" name="author" />

    <link rel="stylesheet" href="css/bootstrap.css" />
    <link rel="stylesheet" href="assets/css/main.css" />
    <link rel="stylesheet" href="assets/css/theme.css" />
    <link rel="stylesheet" href="assets/css/MoneAdmin.css" />
    <link rel="stylesheet" href="assets/plugins/Font-Awesome/css/font-awesome.css" />

                            Administrator Dashboard <?php echo $row_Recordset1['firstname']; ?> <?php echo $row_Recordset1['lastname']; ?> (<?php echo $row_Recordset1['username']; ?>)

                                 Dashboard

<?php
mysql_free_result($Recordset1);
?>

A: first you most not use the MySQL because it will be deleted in php-7 and will not using any more
try to edit your code and convert it all to MySQLi its really simple
second i think u most use session_destroy() if u r using unset($_SESSION['name'])

A: It seems like row_Recordset1 is always populated with the first row from the query result. I think you need to extend your query to select only 1 record, being the record of the logged in user.
// You select all rows here
$query_Recordset1 = "SELECT * FROM login";
$Recordset1 = mysql_query($query_Recordset1, $Authentication) or die(mysql_error());
// You put the first row of the resultset in this recordset,
// no matter which user is logged in
$row_Recordset1 = mysql_fetch_assoc($Recordset1);


text:
Q: Is there any way to tell vim to highlight any asterisks preceded by a type? ...without having to define regex matches for each one of the types.
Eg match the following:
char *ch
char* ch
char **ch
char*  ** *ch
char **
ch

In the above example I want everything but ch to be highlighted.
Currently I specify a regex match for each type individually:
syn match cType "char[*[:space:]\n]*[[:space:]\n][*[:space:]\n]*"

...but this way I resort in having to modify all the syntax files myself.

A: There's no way to modify an existing syntax group to append matching text, so you have to override or redefine the cType definitions.
approach 1
If you define a separate cTypeAsterisks group that matches the * / whitespace combinations (and specify contained so that it doesn't match on its own in the wrong places), all you have to do is augment the cType definitions with nextgroup=cTypeAsterisks skipwhite.
That still means duplicating all the cType definitions from syntax/c.vim, though it possibly could be done dynamically with meta-programming (i.e. parsing the :syn list cType output, modifying, and re-executing it).
approach 2
You can make overriding the cType group easier / reduce duplication by specifying all types in regular expression branches, like this:
syn match cType "\%(char\|int\|long\|short\|void\)[*[:space:]\n]*[[:space:]\n][*[:space:]\n]*"

approach 3
Though this isn't 100% correct, you can define a separate cTypeAsterisks group, and just assert that it matches after a general pattern for C types (e.g. \w\+\s*). This would also erroneously highlight things like foo **, but it's easy and doesn't require duplication.


text:
Q: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. - DECLARE to use SPLIT_ROW I have that query:
DECLARE @test AS varchar =
(select * from users where Usr_ID in
(select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931))

And I've got an error "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS." The result of select statement are three numbers, which i need to split into three rows.

A:  (select * from users where Usr_ID in
   (select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931))

you query returns multiple rows as a result  variable can not contain multiple rows value.
if your query just return one value then it will return correct result
but if you change your query like below then it will works
DECLARE @test AS varchar =
    (select top 1 Doc_Shortstringcolumn1 from users where Usr_ID in
    (select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931)
     )

A: Looking at your Query, It seems that you are trying to store a table into a variable which is of Varchar data type which you cannot do in SQL Server.
There are 2 possible solutions
1.
You May select only the Required filed instead of the * ad in that case if there are more than one row is returned, then only the first one will be stored in the variable and all other values will be ignored.
If this is ok with you then you may go ahead with this approach
DECLARE @test AS varchar =

select
    @test = YourColumnName
    from users where Usr_ID in
    (
        select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931
    )

2
The Second approach is to use a table variable or a Temporary table to store the values so that you can store all the values and retrieve the same when needed.
Using Temp Table
select
    *
    into #temp
    from users where Usr_ID in
    (
        select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931
    )

using Table Variable
DECLARE @test AS TABLE
(
    Column1 VARCHAR(50),
    Column2 VARCHAR(50),
    Column3 VARCHAR(50)
)

INSERT INTO @Test
(
    Column1,
    Column2,
    Column3
)
select
    YourColumnName1,
    YourColumnName2,
    YourColumnName3
    from users where Usr_ID in
    (
        select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931
    )


text:
Q: just_audio Package Flutter Playlist not work on Release mode I use just_audio package for my app, and now I face a problem with the playlist Error on release mode, I get sounds from uri.parse and worked perfectly but only the playlist does not work!
I attached an image for a better understanding, and share my code
On Debug mode Playlist does not have issues like this Image
But in release mode, it looks like this
I've tried it on different devices but it's the same
My Code for playlist
SizedBox(
            height: 240.0,
            child: StreamBuilder<SequenceState?>(
              stream: _player.sequenceStateStream,
              builder: (context, snapshot) {
                final state = snapshot.data;
                final sequence = state?.sequence ?? [];
                return ReorderableListView(
                  onReorder: (int oldIndex, int newIndex) {
                    if (oldIndex < newIndex) newIndex--;
                    _playlist.move(oldIndex, newIndex);
                  },
                  children: [
                    for (var i = 0; i < sequence.length; i++)
                      Expanded(
                        key: ValueKey(sequence[i]),
                        child: Material(
                          //color with seekbar percentage color
                          color: i == state!.currentIndex
                              ? Color.fromARGB(42, 167, 24, 48)
                              : Colors.transparent,
                          child: ListTile(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10.0),
                            ),
                            trailing: Text(
                              (i + 1).toString(),
                              style: TextStyle(
                                  fontSize: 20.0,
                                  color: i == state.currentIndex
                                      ? Color.fromARGB(255, 190, 26, 53)
                                      : Color.fromARGB(255, 58, 58, 58)),
                            ),
                            title: Text(
                              sequence[i].tag.title,
                              textAlign: TextAlign.right,
                              style: boldTextStyle(
                                  size: 16,
                                  fontFamily: 'medium',
                                  weight: FontWeight.normal,
                                  color: i == state.currentIndex
                                      ? Color.fromARGB(255, 190, 26, 53)
                                      : Color.fromARGB(255, 107, 107, 107)),
                            ),
                            leading: i == state!.currentIndex
                                ? Material(
                                    color: Color.fromARGB(230, 217, 52, 40),
                                    borderRadius: BorderRadius.circular(10),
                                    child: Container(
                                      height: 31,
                                      width: 30,
                                      child: IconButton(
                                        padding: EdgeInsets.zero,
                                        alignment: Alignment.center,
                                        icon:
                                            Icon(Icons.graphic_eq_outlined),
                                        iconSize: 22,
                                        color: Color.fromARGB(
                                            255, 245, 245, 245),
                                        onPressed: () {
                                          _player.pause();
                                        },
                                      ),
                                    ),
                                  )
                                : Material(
                                    color:
                                        Color.fromARGB(255, 227, 228, 237),
                                    borderRadius: BorderRadius.circular(10),
                                    child: Container(
                                      height: 31,
                                      width: 30,
                                      child: IconButton(
                                        padding: EdgeInsets.zero,
                                        alignment: Alignment.center,
                                        icon: Icon(Icons.play_arrow),
                                        iconSize: 22,
                                        color:
                                            Color.fromARGB(255, 49, 53, 60),
                                        onPressed: () {
                                          _player.pause();
                                        },
                                      ),
                                    ),
                                  ),
                            onTap: () {
                              _player.seek(Duration.zero, index: i);
                            },
                          ),
                        ),
                      ),
                  ],
                );
              },
            ),
          ),

A: I guess you get your songs from a remote source, for this you need to give your app internet permission. Internet permission is automatically set in debug mode, this is why it only works in debug.
<manifest xmlns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>


text:
Q: Will it be possible to use std::filesystem::path with std::fstream in C++17? In C++17 we will have file system support. This example from cppreference is supposed to work correctly:
fs::path p = fs::u8path(u8"要らない.txt");

// native string representation can be used with OS APIs
std::ofstream(p) << "File contents"; // this uses operator string()

However, I don't see how it will work on Windows, since std::filesystem::path::operator string_type() will return std::wstring on Windows, and std::basic_ofstream constructor accepts only std::string. Is this right? I hope not, thus where is my mistake?


text:
Q: react-native cookie auth not working on Android My server returns a accesstoken and refreshtoken, I've setup iOS to correctly authenticate users using cookies (I do this by using credentials: 'include'). However when I try to run the Android version of my app, it won't persist any cookies and when I refresh the emulator, the backend server will return an error code causing my app to be logged out (the error code is being returned because it does not pass the cookies up!).
I had a look around to see what was up and I've came to the conclusion that it's not supported on the current version of react-native (0.59)? (check the link: https://github.com/facebook/react-native/issues/21795)
Are there any workarounds for this? I heard rumours that this will be fixed in RN  0.60, but there is no release date set for this yet so I'll need to find my own solution.

A: Yes cookies authentication is currently not in stable state in react native,for android device.
for more details you can go with this link.
https://facebook.github.io/react-native/docs/network


text:
Q: Kalman filter 3D implementation I want to implement the kalman filter for a moving object in r3 (X,Y,Z-coordinate) in OpenCV.
I tried to understand the OpenCV documentation but this is really not helpful and very rare.
The syntax for the initialization is:

KalmanFilter::KalmanFilter    (   int     dynamParams, int    measureParams, int
    controlParams = 0, int  type = CV_32F  )

In my case, is dynamParams = 9 and measureParams=3?
And what is the transitionMatrix in my case?

A: In that case the Transition Matrix A looks like:
A = [1, 0, 0, v, 0, 0, a, 0, 0;
     0, 1, 0, 0, v, 0, 0, a, 0;
     0, 0, 1, 0, 0, v, 0, 0, a;
     0, 0, 0, 1, 0, 0, v, 0, 0;
     0, 0, 0, 0, 1, 0, 0, v, 0;
     0, 0, 0, 0, 0, 1, 0, 0, v;
     0, 0, 0, 0, 0, 0, 1, 0, 0;
     0, 0, 0, 0, 0, 0, 0, 1, 0;
     0, 0, 0, 0, 0, 0, 0, 0, 1]

With
v = dt
a = 0.5*dt^2

See http://campar.in.tum.de/Chair/KalmanFilter

A: I found out, that for the 3D-Case often the position, velocity and acceleration is used. That means, that for the OpenCV implementation dynamParams=9 and measureParams=3 is right.


text:
Q: Get a reference to Gtk.OffscreenWindow cairo surface I am using Gtk and WebKit from gi.repository using python on X11 server (on raspbian).
I have a Gtk.OffscreenWindow with a WebKit.WebView widget in it and I am looking for a way to get a reference to the actual surface data of the OffscreenWindow.
Gtk.OffscreenWindow.get_surface returns a cairo.XlibSurface object but it doesn't seem there is a way to access pixel data of the surface (get_drawable is missing).
Gtk.OffscreenWindow.get_pixbuf returns a pixel buffer but to my understanding this is a copy of the actual surface data.
I used get_snapshot method of the WebKit.WebView but it creates a new cairo.ImageSurface.
My final goal is to use the reference to draw the surface using pi3d and get any surface updates without having to get a new snapshot of the OffscreenWindow (which is quite slow).

A: From the GTK3 developer reference,

GtkOffscreenWindow derives from GtkWindow only as an implementation detail. Applications should not use any API specific to GtkWindow to operate on this object.

GTKOffscreenWindows cannot or should not be operated on as windows, thus Cairo cannot be used on them.

A: @kapetanos, You are probably familiar with the pi3d.groups conversation here https://groups.google.com/forum/#!topic/pi3d/4x0fPerYKRU
and the subsequent integration into pi3d
https://github.com/pi3d/pi3d_demos/blob/master/GtkCube.py and https://github.com/pi3d/pi3d_demos/blob/master/PyQtCube.py
I realize this is too late for your original question but it might help someone arriving here from a google search!
I still don't understand why the X11 drawing surface system that works on other linux implementations doesn't work on the Raspberry Pi but other developers seem to resort to using libbcm_host.so


text:
Q: Why is a static IP address required to use financial FIX protocol connectivity? Why do vendors who provide FIX protocol connectivity require a static IP address? Is the only reason user identification/validation? Or is there any other reason behind that?
Thanks

A: Yes, the reason is that the (free registration required, sadly) FIXT specification test cases (specifically test case 1S/c) requires IP validation for Logon messages. It does not exclude the possibility of allowing an entire IP block (just references "system configuration" as a source of the allowed IP), but most vendors follow the spirit of highest possible security.
The spec (page 39) further mentions unauthorized attempts to break into your system as the reason for doing the validation.


text:
Q: Sum everything in dynamic cell - javascript I have javascript code that generates html table and fill the info in it taken from the text areas. I want to show the total of specific cell each time the button is clicked for new product (the new value - price to be added in the total). In few words, the sum of all products to be shown. The same thing when deleting the specific cell, it needs to be removed from the total.
Now this works fine until i enter different number...
Also see this fiddle
<!DOCTYPE html>

<form id="fid">
Total:

Product:
<input type="text" id="product"/>

Price:
<input type="text" id="price"/>

<INPUT type="button" value="add" id="add" onclick="addRow('fid','dataTable')" />
<INPUT type="button" value="delete" id="delete" onclick="deleteRow('dataTable')" />

    id
product
    price

</form>

A: var tot=0;
for(var i=0;i<rowCount;i++){
    tot += parseInt(cell4.innerHTML,10);
}

In the above piece of code, you're not iterating the row but referring only to the last column.
So on each iteration, the last column value is getting added.
Instead try below code
var tot=0;
for(var i=1;i<=rowCount;i++){
    tot += parseInt(table.rows[i].cells[3].innerHTML,10);
}

Here I have used i = 1 because 0 represents the heading tr and to get the price column I have used
                    |---------------------3rd column
table.rows[i].cells[3].innerHTML
           |__row index

Similar in delete method you have to do the same in reverse  fashion like
var tot = +document.getElementById("total").innerHTML; // get total
for (var i = 0; i < rowCount; i++) {

    var row = table.rows[i];
    var chkbox = row.cells[0].childNodes[0];
    if (null != chkbox && true == chkbox.checked) {
        tot -= parseInt(table.rows[i].cells[3].innerHTML, 10) //only for checked row
        table.deleteRow(i);
        rowCount--;
        i--;
    }
}
document.getElementById("total").innerHTML = tot;  // update the total
}

Check this in fiddle

A: You made a few mistakes.
Firstly, let me just make it clear that there are certain part I used jQuery, coz I'm not that familiar with javascript syntax.
Here's the working example: http://jsfiddle.net/caL5p/1/
First mistake:
You used: cell4.id = "pricee";
This is wrong. Id cannot be repeated, and hence your result will always add the last number * the amount of rows you have. If you were to alert parseInt(cell4.innerHTML,10);, you'll find out what I mean.
This is what you should do instead.
cell4.setAttribute('class',"pricee");
For the rest, refer to the code in the fiddle.


text:
Q: HTML in PHP - displaying variables from MYSQL table I have a MYSQL table containing tournament data for players. Each player has stats like games_won, games_lost, etc. I am trying to display this information in a table.
My PHP code looks like this:
//Connecting to $db
//...

//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");

while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " " . <a href=$row['link']$row['username'] . " " . $row['tourney_wins'] . " " . $row['game_wins'] . " " . $row['game_losses'] . " " . $row['last_played'];
echo "
";

I get an error (Unexpected "<") on
<a href=$row['link']$row['username']

I am trying to display each username in the table as a hyperlink to their respective profile on another site. Can anyone give me a correction? Thanks!

A: Change
<a href=$row['link']$row['username']

to
"<a href=$row['link']$row['username']"

A: You forgot to quote your html:
echo $row['id'] . " " . <a href=$row['link']$row['username'] . " " ...snip...
                       ^--here                                  ^--here

Since it's not quoted, PHP is interpreting it <a as concatenate less than undefined constant 'a', which makes no sense.

A: This is how it should be quoted (assuming I interpreted how you wanted the link properly):
//Connecting to $db
//...

//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");

while($row = mysqli_fetch_array($result))
{
    echo( $row['id']." ".$row['username']." ".$row['tourney_wins']." ".$row['game_wins']." ".$row['game_losses']." ".$row['last_played'] );
    echo("
");
}


text:
Q: Wix properties not being persisted from a WXI () to a WXS () I hope you can help me with the following WIX issue:
In my main.wxs, I initialize "MYPROPERTY" that then in ui.wxi, I put up a dialog box with a checkbox (that is checked/enabled from the MYPROPERTY that I've setup in the .wxs).  I can verify that by unchecking the checkbox, it does flip the value because I enable/disable the "Next" button depending on the MYPROPERTY value - I have more than one checkbox BTW.
The problem is that if I uncheck the checkbox in the UI when running the .msi produced, the Custom Action is ran no matter if the checkbox is checked or unchecked (as if the "MYPROPERTY" is always 1, see the condition in ).  How do I make the checkbox that sets the MYPROPERTY value to actually persist to the the Custom Action?
Any help is appreciated.  Thanks.
MAIN.WXS:
<Property Id='MYPROPERTY'>1</Property>
<?include ./ui.wxi ?>
...
<InstallExecuteSequence>
   <Custom Action="MyCustomAction" After="InstallFiles">
        (NOT Installed) AND (MYPROPERTY = 1)
   </Custom>
...

ui.wxi:
<UI Id='xxx'>
...
<Dialog
        Id="Choose"
        Title="My Setup">
    <Control
        Id="MyCheckBox"
        Type="CheckBox"
        CheckBoxValue="1"
       Property="MYPROPERTY"
    />
...

A: You have defined a public property but not made it secure.   If you were on Windows XP as an administrator it would work  but if you were on Windows XP as a standard user perfoming an advertised / managed / elevated install or on Windows Vista with UAC enabled it would not work because you must also add the Secure attribute to the property to mark it as a SecureCustomProperty.
SecureCustomProperties Property


text:
Q: Как допилить проверку email нормально Здравствуйте,есть такой код:

<form id="contact" method="POST" onsubmit="this.action=window.location.href+'#contact';this.submit()">

Введіть своє ім'я:

<input type="text" name="name">

Введіть свій email:

<input type="text" name="email">

Введіть текст повідомлення:

<textarea name="message" cols="40" rows="5" ></textarea>

Введіть цифри:

  <?php
  $i=1;
  do
  {
  $num[$i] = mt_rand(0,9);
  echo "";
  $i++;
  }
  while ($i<5);
  $captcha = $num[1].$num[2].$num[3].$num[4];
  ?>
<input name="captcha" type="hidden" value="<?php echo $captcha ;?>">
<input name="pr" style=" margin-bottom:11px" type="text" size="6" maxlength="4">

<input type="submit" class="bt1" value="Відправити повідомлення">

<?php
/* Проверяем существуют ли переменные, которые передала форма обратной связи.
   Если не существуют, то мы их создаем.
   Если форма передала пустые значения мы их удаляем */
if (isset($_POST['name'])) {$name = $_POST['name']; if ($name == '') {unset($name);}}
if (isset($_POST['email'])) {$email = $_POST['email']; if ($email == '') {unset($email);}}
if (isset($_POST['message'])) {$message = $_POST['message']; if ($message == '') {unset($message);}}
if (isset($_POST['pr'])){$pr = $_POST['pr']; if ($pr == '') {unset($pr);}}
if (isset($_POST['captcha'])){$captcha = $_POST['captcha'];}

/* Проверяем заполнены ли все поля */
if (isset($name) && isset($email) && isset($message) && isset($pr))
{

/* Убираем все лишние пробелы, а также преобразуем все теги HTML в символы*/
$name = htmlspecialchars(trim($name));
$email = htmlspecialchars(trim($email));
$message = htmlspecialchars(trim($message));

/* Проверяем правильность ввода email-адреса */
if(!preg_match("/[0-9a-z_]+@[0-9a-z_^\.]+\.[a-z]{2,3}/i", $email))
{
echo "
Невірний формат e-mail адреси!
";
}

/* Проверяем правильность ввода капчи */
  if ($captcha == $pr)
  {
/* Формируем сообщение */
$address = "my@gmail.com";
$sub = "Повідомлення з site.ru";
$mes = "Автор: $name \nE-mail відправника: $email \nТекст листа: \n$message";

/* Отправка сообщения */
$verify = mail ($address,$sub,$mes,"Content-type:text/plain; charset = utf-8\r\nFrom:$email");
      if ($verify == 'true')
      {
       echo "Дякуємо! Ваше повідомлення відправлено";
      }
      else
   {
   echo "Ваше повідомлення не відправлено!";
   }
  }
  else
  {
  echo "Ви не вірно ввели числа";
  }
}
else

?>

Но,его недостаток в том,что он отправляет сообщение даже если email указан без @ как это исправить ?

A: Т.к. у Вас сейчас при даже неверном email скрипт благополучно работает дальше, вам надо изменить следующее:
UPD: Лучше использовать filter_var().
/* Проверяем правильность ввода email-адреса */
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    // Тут либо завершайте скрипт, либо делайте else и туда суйте следующий код.
} else {
    // А тут надо остальное ...
}

P.S. Не стоит использовать это регулярное выражение =)

Результат:

<form id="contact" method="POST" onsubmit="this.action=window.location.href+'#contact';this.submit()">

Введіть своє ім'я:

    <input type="text" name="name">

Введіть свій email:

    <input type="text" name="email">

Введіть текст повідомлення:

    <textarea name="message" cols="40" rows="5"></textarea>

Введіть цифри:

    <?php
$i = 1;
do {
    $num[$i] = mt_rand(0, 9);
    echo "";
    $i++;
} while ($i < 5);
$captcha = $num[1] . $num[2] . $num[3] . $num[4];
?>
      <input name="captcha" type="hidden" value="<?php
echo $captcha;
?>">
      <input name="pr" style=" margin-bottom:11px" type="text" size="6" maxlength="4">

<input type="submit" class="bt1" value="Відправити повідомлення">

  <?php
/* Проверяем существуют ли переменные, которые передала форма обратной связи.
Если не существуют, то мы их создаем.
Если форма передала пустые значения мы их удаляем */
if (isset($_POST['name'])) {
    $name = $_POST['name'];
    if ($name == '') {
        unset($name);
    }
}
if (isset($_POST['email'])) {
    $email = $_POST['email'];
    if ($email == '') {
        unset($email);
    }
}
if (isset($_POST['message'])) {
    $message = $_POST['message'];
    if ($message == '') {
        unset($message);
    }
}

if (isset($_POST['pr'])) {
    $pr = $_POST['pr'];
    if ($pr == '') {
        unset($pr);
    }
}

if (isset($_POST['captcha'])) {
    $captcha = $_POST['captcha'];
}

/* Проверяем заполнены ли все поля */
if (isset($name) && isset($email) && isset($message) && isset($pr)) {

    /* Убираем все лишние пробелы, а также преобразуем все теги HTML в символы*/
    $name    = htmlspecialchars(trim($name));
    $email   = htmlspecialchars(trim($email));
    $message = htmlspecialchars(trim($message));

    /* Проверяем правильность ввода email-адреса */
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "
Невірний формат e-mail адреси!
";
    } else {
// ADDED ELSE
      /* Проверяем правильность ввода капчи */
      if ($captcha == $pr) {
          /* Формируем сообщение */
          $address = "my@gmail.com";
          $sub     = "Повідомлення з site.ru";
          $mes     = "Автор: $name \nE-mail відправника: $email \nТекст листа: \n$message";

          /* Отправка сообщения */
          $verify = mail($address, $sub, $mes, "Content-type:text/plain; charset = utf-8\r\nFrom:$email");
          if ($verify == 'true') {
            echo "Дякуємо! Ваше повідомлення відправлено";
          } else {
              echo "Ваше повідомлення не відправлено!";
          }
       } else {
        echo "Ви не вірно ввели числа";
       }
    }
}

?>


text:
Q: Best way to use CSV files in Java Im having trouble with the best approach to reading a CSV file in order to extract and compare certain things in it. The file is made up of strings, and I need to keep track if there are duplicated items. Here is what I have so far.
import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class CSVReader {

  public static void main(String[] args) {

  String csvFile = "Cchallenge.csv";

  String line = "";

  String cvsSplitBy = ",";

     try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

         while ((line = br.readLine()) != null) {

            // use comma as separator

           String[] country = line.split(cvsSplitBy);

 } catch (IOException e) {

     e.printStackTrace();

 }

 }

 }

So I made an array called country with all the data. But when I go to print out the arrays length, it gives my a lot of different arrays with varying sizes. I am having a hard time traversing the arrays and extracting the duplicates. Any ideas will help, thanks.

A: If you simply wish to get a list of the items without any duplicates, then you could collect the items into a set, as sets do not allow duplicate items:
Set<String> items = new HashSet<>();

try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
    while ((line = br.readLine()) != null) {
        items.addAll(Arrays.asList(line.split(cvsSplitBy)));
    }
} catch (IOException e) {
    e.printStackTrace();
}

If you also want to keep track of the duplicates, you could use another set and add items into it if they already exist in the first set. This would be an easy feat to accomplish, as the add method of Set returns a boolean in regards to if the set already contained the specified element or not:
Set<String> items = new HashSet<>();
Set<String> duplicates = new HashSet<>();

try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
    while ((line = br.readLine()) != null) {
        for (String item : line.split(cvsSplitBy)) {
            if (items.add(item)) {
                continue;
            }
            duplicates.add(item);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}


text:
Q: How to tag a passing build? I saw a configuration option that allows tagging every build, but it seems this would just needlessly pollute the tag history. Is there a way in Jenkins to tag a build only once it has been marked as passed?

A: Absolutely, using the Flexible Publish plugin.
This plugin will allow you to wrap post-build actions in a Run condition.
All this really boils down to is, installing & using that plugin, you can wrap your git publish in a Run condition using the Current build status as it's condition, setting it to only run when the entire build has passed (success).


text:
Q: Flutter - If get this keyword in the title from a push notification do this action I'd like to be able to do actions when receiving specific keywords in the title of notifications coming from specific apps. I've read about the notifications package and notificationlistener. The first one says that it can just give me the app name and timestamp, but I don't understand if it would fit my needs, and the second one (notificationlistener) I'm not sure it could solve my issue.
How can I do what I want? Let's say I receive a notification containing in the title "Breaking News" and I want to copy paste the title and the notification content in my app automatically every time I receive that, how do I do that?
I'm very new to Flutter, so, please explain easily what I should do and if it's feasible in Flutter without recurring to native code.


text:
Q: Get value from Option parameter in scala I have a parameter
case class Envelope(subject: Option[String]) {
}

and I want to apply a require function only if subject is non null.
Something like below:
require(StringUtils.isNotBlank(subject))

A: You can try this also:
case class Envelope(subject: Option[String])

def check(en: Envelope): Boolean = {
    require(en.subject.isDefined)
    true
    }

It will be finer and you don't have any need to import StringUtils.
For fetching the value from Option you should go for the getorElse. Here we can define the default value for the variable. Ex:
def check(str: Option[String]): String = {
  str.getOrElse("")
 }

scala> check(None)
res1: String = ""

scala> check(Some("Test"))
res2: String = Test

Only get will throw the exception when it will get None. Ex:
def check(str: Option[String]): String = {
      str.get
     }

scala> check(Some("Test"))
res2: String = Test

scala> check(None)
java.util.NoSuchElementException: None.get
  at scala.None$.get(Option.scala:347)
  at scala.None$.get(Option.scala:345)
  at check(<console>:24)
  ... 48 elided

A: I think you can go that way:
subject.map(s => if(StringUtils.isNotBlank(s)) require(s) else s)

A: Options should, from a practical perspective, almost never be null in Scala (I'd argue never, but there are all sorts of compromises and exceptions, especially when working with Java dependencies where null checks are more common-place).
With some pre-processing and pattern-matching, you may find this approach acceptable:
// When working with `Option`s, naming convention usually is "[name_of_var]Opt"
case class Envelope( subjectOpt: Option[String] ) {

    // Utility to check whether or not this `Envelope` has a subject
    def hasSubject: Boolean = subjectOpt.isDefined

    // Get the subject or throw an exception if it does not have one (None)
    def getSubject: String = {
        subjectOpt match {
            case None => throw Exception( "Envelope has no subject!" )
            case Some( subject ) => subject
        }
    }
}

object Envelope {

    // Utility to create an `Envelope` with no subject
    def apply(): Envelope = Envelope(None)

    // Utility to do a bit of pre-processing, checking for `null` or empty strings
    def apply( subject: String ): Envelope = {
        if ( subject == null || subject.isEmpty ) Envelope()
        else Envelope( Some( subject ) )
    }
}

val nullString: String = null

// Example usages (will have no subject):
val envelopeWithNoSubject: Envelope = Envelope()
val envelopeWithEmptySubject: Envelope = Envelope( "" )
val envelopeWithNullSubject: Envelope = Envelope( nullString )

// envelopeWithNoSubject, ...EmptySubject, and ...NullSubject all return:
... .hasSubject // False
... .getSubject // Exception: Envelope has no subject!

// Example use with subject
val envelopeWithSubject: Envelope = Envelope( "Scala" )

envelopeWithSubject.hasSubject// True
envelopeWithSubject.getSubject // "Scala"

A: You should be changing the require function call to the following
require(StringUtils.isBlank(subject.get))

.get method returns the string that the subject Option carries.


text:
Q: Form is not posting while inserting maths equation in ckeditor I have created a from with 5-6 textareas every one having ckeditor and while we insert equation through editor. It works fine @ local but i have got empty post array while using on server.
So any one know about any server permission that might be missing.
For information i am using ckeditor with latex equation editor plugin
here is my equation

81^{1/4}\times9^{3/2}\times27^{-4/3} (3^{4})^{1/4}\times (3^{2})3/2
  \times (3^{3})^{-4/3}  \because  81=3^{4}, 9=3^{2}, 27=3^{3}
  = (3)^{4\times 1/4 }\times (3)^{2\times3/2} \times (3)^{3\times-4/3}\because (a^{m}){n}=a^{mn}
  =3^{1}\times 3^{3} \times 3^{-4}
  = 3^{1+3-4}  \because a^{m}.a^{n}.a^{p} = a(m+n+p)
  = 3^(1+3-4)
  = 3^{0} = 1 \because a^{0}=1

While i am trying this equation my $post is empty, although if i remove  2or 3 "=" sign it works. I really struck with what happens there
I am working from last two days and done almost every thing i got on web
Please help me


text:
Q: Android SQLit Search: NullPointerException? I need to perform a search operation into my SQLite DB.
In my Activity, I have EditText for entering the keyword and a search Button. Once the user clicks the button, the EditText text will be stored in the keyword and sent to a search(String keyword) method in the DBHelper class.
I have this code in my SearchActivityfor onCreate() and onClick():
//SearchActivity class extends ListActivity and implements OnClickListener
Button search;
DataBaseHelper myDbHelper;
SimpleCursorAdapter ca;
ListView lv;
EditText txt;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_layout);

    txt = (EditText) findViewById(R.id.search_term);
    search = (Button) findViewById(R.id.search_button);

    search.setOnClickListener(this);
}

public void onClick(View v) {
    try {
        myDbHelper.openDataBase();
    } catch (SQLException sqle) {}

    try {
    String keyword= txt.getText().toString();
    Cursor cursor = myDbHelper.search(keyword); //A method in my DB
    cursor.moveToFirst();
    String[] columns = {cursor.getColumnName(1)};
    int[] columnsLayouts = {R.id.item_title};
    ca = new SimpleCursorAdapter(this.getBaseContext(), R.layout.items_layout, cursor,columns , columnsLayouts);
    lv = getListView();
    lv.setAdapter(ca);

    } catch(Exception e){}
}

However, I got NullPointerException in the LogCat!! I couldn't find where the error is.
Anyone can help ?

A: The description to the NullPointerException could be a little more informative. But it is very likely that the NullPointerException occurs here:
1: Cursor cursor = myDbHelper.search(keyword); //A method in my DB
2: cursor.moveToFirst();
3: String[] columns = {cursor.getColumnName(1)};

or here:
1: try {
2:    myDbHelper.openDataBase();
3: } catch (SQLException sqle) {}

Either in the first part in line 1: or 2: or in the second part in line 2:
You should always check if objects which rely on the existence of data are not null. So you should check if cursor is null. Another thing could be that you never initialize myDbHelper.