问:
Javascript Slider doesn't work correctly with transition end
I don't know why people's are not answering this question.I'm making a horizontal infinite loop slider. What approach i'm using is making a ul container which has 3 images, for example if there are 3 images then clone the first image and place it to the end of the slider, same with last image make clone and place it before the first image. So now total images are 5. Default slider translation always start from first image not from clone one. Here is an example. What i'm facing is, I want to reset the slider after slider comes to the last clone image with same continuous loop like a carousel slider. I try using addEventListener with the event name transitionend but that event doesn't perform correctly and showing unsatisfied behavior. Is there a way to fix this?

(function () {
    var resetTranslation = "translate3d(-300px,0px,0px)";
    var elm = document.querySelector('.Working');
    elm.style.transform = resetTranslation;
    var arr = document.querySelectorAll('.Working li');
    var clonefirst,
        clonelast,
        width = 300;
    index = 2;
    clonefirst = arr[0].cloneNode(true);
    clonelast = arr[arr.length - 1].cloneNode(true);

    elm.insertBefore(clonelast, arr[0]);
    arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
    //Update
    arr = document.querySelectorAll('.Working li');
    elm.style.transition = 'transform 1.5s ease';

    setInterval(function () {

        elm.style.transform = 'translate3d(-' + index * width + 'px,0px,0px)';
        if (index == arr.length - 1) {
            elm.addEventListener('transitionend', function () {
                elm.style.transform = resetTranslation;
            });
            index = 1;
        }
        index++;

    }, 4000)

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
    box-sizing: border-box;
}
.wrapper{
    position: relative;
    overflow: hidden;
    height: 320px;
    width: 300px;

}

.Working{
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    width: 3125%;

}
.Working li{
    position: relative;
    float: left;
}

img{
    max-width: 100%;
    display: block;
}

.SubContainer:after{
    display: table;
    clear: both;
    content: "";
}</code>```

```

答:
Your transition end event is not immediately fire because last transition doesn't computed when last clone image appear. You can easily achieve this thing by using setTimeout function and pass number of milliseconds to wait, after that reset the translation. I don't know it's an efficient solution but i think its easily done by using this function.
Now I'm fixing your code with this.

(function () {
    var elm = document.querySelector('.Working');
    var arr = document.querySelectorAll('.Working li');
    var clonefirst,
        clonelast,
        width = 300;
    index = 2;
    clonefirst = arr[0].cloneNode(true);
    clonelast = arr[arr.length - 1].cloneNode(true);

    elm.insertBefore(clonelast, arr[0]);
    arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
    //Update
    arr = document.querySelectorAll('.Working li');

     setInterval(function () {
        $(elm).css({
            'transform': 'translate3d(-' + (index * width) + 'px,0px,0px)',
            'transition': 'transform 1.5s ease'
        });
        if (index == arr.length - 1) {
            setTimeout(function () {
                $(elm).css({'transform': 'translate3d(-300px,0px,0px)', 'transition': 'none'});
                index = 1;
            }, 1400);

        }
        index++;

    }, 2000)

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    box-sizing: border-box;
}

.wrapper {
    position: relative;
    overflow: hidden;
    height: 320px;
    width: 300px;
    margin-top: 8px;

}

.Working {
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    transform: translateX(-300px);
    width: 3125%;

}

.Working li {
    position: relative;
    float: left;
}

img {
    max-width: 100%;
    display: block;
}

.SubContainer:after {
    display: table;
    clear: both;
    content: "";
}

#checkboxer:checked + .wrapper {
    overflow: visible;
}</code>```

Remove Overflow Hidden
<input type="checkbox" id="checkboxer" name="checkboxer"/>

```

Body:
I don't know why people's are not answering this question.I'm making a horizontal infinite loop slider. What approach i'm using is making a ul container which has 3 images, for example if there are 3 images then clone the first image and place it to the end of the slider, same with last image make clone and place it before the first image. So now total images are 5. Default slider translation always start from first image not from clone one. Here is an example. What i'm facing is, I want to reset the slider after slider comes to the last clone image with same continuous loop like a carousel slider. I try using addEventListener with the event name transitionend but that event doesn't perform correctly and showing unsatisfied behavior. Is there a way to fix this?

(function () {
    var resetTranslation = "translate3d(-300px,0px,0px)";
    var elm = document.querySelector('.Working');
    elm.style.transform = resetTranslation;
    var arr = document.querySelectorAll('.Working li');
    var clonefirst,
        clonelast,
        width = 300;
    index = 2;
    clonefirst = arr[0].cloneNode(true);
    clonelast = arr[arr.length - 1].cloneNode(true);

    elm.insertBefore(clonelast, arr[0]);
    arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
    //Update
    arr = document.querySelectorAll('.Working li');
    elm.style.transition = 'transform 1.5s ease';

    setInterval(function () {

        elm.style.transform = 'translate3d(-' + index * width + 'px,0px,0px)';
        if (index == arr.length - 1) {
            elm.addEventListener('transitionend', function () {
                elm.style.transform = resetTranslation;
            });
            index = 1;
        }
        index++;

    }, 4000)

})();

*{
    box-sizing: border-box;
}
.wrapper{
    position: relative;
    overflow: hidden;
    height: 320px;
    width: 300px;

}

.Working{
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    width: 3125%;

}
.Working li{
    position: relative;
    float: left;
}

img{
    max-width: 100%;
    display: block;
}

.SubContainer:after{
    display: table;
    clear: both;
    content: "";
}

Body:
Your transition end event is not immediately fire because last transition doesn't computed when last clone image appear. You can easily achieve this thing by using setTimeout function and pass number of milliseconds to wait, after that reset the translation. I don't know it's an efficient solution but i think its easily done by using this function.
Now I'm fixing your code with this.

(function () {
    var elm = document.querySelector('.Working');
    var arr = document.querySelectorAll('.Working li');
    var clonefirst,
        clonelast,
        width = 300;
    index = 2;
    clonefirst = arr[0].cloneNode(true);
    clonelast = arr[arr.length - 1].cloneNode(true);

    elm.insertBefore(clonelast, arr[0]);
    arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
    //Update
    arr = document.querySelectorAll('.Working li');

     setInterval(function () {
        $(elm).css({
            'transform': 'translate3d(-' + (index * width) + 'px,0px,0px)',
            'transition': 'transform 1.5s ease'
        });
        if (index == arr.length - 1) {
            setTimeout(function () {
                $(elm).css({'transform': 'translate3d(-300px,0px,0px)', 'transition': 'none'});
                index = 1;
            }, 1400);

        }
        index++;

    }, 2000)

})();

* {
    box-sizing: border-box;
}

.wrapper {
    position: relative;
    overflow: hidden;
    height: 320px;
    width: 300px;
    margin-top: 8px;

}

.Working {
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    transform: translateX(-300px);
    width: 3125%;

}

.Working li {
    position: relative;
    float: left;
}

img {
    max-width: 100%;
    display: block;
}

.SubContainer:after {
    display: table;
    clear: both;
    content: "";
}

#checkboxer:checked + .wrapper {
    overflow: visible;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="checkboxer">Remove Overflow Hidden</label>
<input type="checkbox" id="checkboxer" name="checkboxer"/>

<div class="wrapper">
    <ul class="SubContainer Working">
        <li> <img class="" src="http://i.imgur.com/HqQb9V9.jpg" /></li>
        <li><img class="" src="http://i.imgur.com/PMBBc07.jpg" /></li>
        <li><img  class="" src="http://i.imgur.com/GRrGSxe.jpg" /></li>
    </ul>
</div>


来源: stackexchange

问:
Why map in OSM not display in android studio?
I already add this library in libs directory
osmdroid jar file.
slf4j jar file.

I followed tutorial in https://androidcookbook.com/Recipe.seam?recipeId=2521
but the map didnt show, i dont know whats happening

This is my MainAcitvity.java

```<code>package com.example.pc_parinussa.osm;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ScaleBarOverlay;

public class MainActivity extends Activity {
    private MapView         mMapView;
    private MapController   mMapController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setTileSource(TileSourceFactory.MAPQUESTOSM);
        mMapView.setBuiltInZoomControls(true);
        mMapController = (MapController) mMapView.getController();
        mMapController.setZoom(13);
        GeoPoint gPt = new GeoPoint(51500000, -150000);
        mMapController.setCenter(gPt);
    }
}
</code>```

My activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <org.osmdroid.views.MapView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/mapview">
    </org.osmdroid.views.MapView>

</LinearLayout>
</code>```

My gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.pc_parinussa.osm"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile files('libs/osmdroid-android-4.0.jar')
}
</code>```

答:
It looks like you didn't set your user agent. Try setting it via:

Configuration.getInstance().setUserAgentValue(...)

e.g.:

Configuration.getInstance().setUserAgentValue(getPackageName())

ContentLicense: CC BY-SA 3.0

Body:
I already add this library in libs directory
osmdroid jar file.
slf4j jar file.

I followed tutorial in https://androidcookbook.com/Recipe.seam?recipeId=2521
but the map didnt show, i dont know whats happening

This is my MainAcitvity.java

package com.example.pc_parinussa.osm;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ScaleBarOverlay;

public class MainActivity extends Activity {
    private MapView         mMapView;
    private MapController   mMapController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setTileSource(TileSourceFactory.MAPQUESTOSM);
        mMapView.setBuiltInZoomControls(true);
        mMapController = (MapController) mMapView.getController();
        mMapController.setZoom(13);
        GeoPoint gPt = new GeoPoint(51500000, -150000);
        mMapController.setCenter(gPt);
    }
}

My activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <org.osmdroid.views.MapView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/mapview">
    </org.osmdroid.views.MapView>

</LinearLayout>

My gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.pc_parinussa.osm"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile files('libs/osmdroid-android-4.0.jar')
}


问:
Neo4j - Java heap space. Wrong query or settings?
i have a problem with neo4j.
I don't know if problem is my query or something else.

Intro

I have to build an application that store bus/train routes.
This is my schema:

Nodes:

Organizaton: company that have routes/bus etc..

Route: A bus route like: Paris - Berlin.

Vehicle(Bus in this case): Fisical bus with a unique license plate.

Stops: point in a map with latitude and longitude.

Important Relationships:

NEXT: This is a really important relationship.

NEXT relationships contains those properties:

startHour

startMinutes

endHour

endMinutes

dayOfWeek (from 0 to 6 - Sun, Mon etc..)

vehicleId

Problem

My query is:

```<code>MATCH (s1:Stop {id: {departureStopId}}), (s2:Stop {id: {arrivalStopId}})
OPTIONAL MATCH (s1)-[nexts:NEXT*]->(s2)
WHERE ALL(i in nexts WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN nexts
LIMIT 10
</code>```

For example: I wanna found all nexts relationships where dayOfWeek is Sunday (0) and property startHour > 11

After that I usually parse and validate final object on my nodejs backend.

This works when i was at the start.. with 1k relationships..
Now i have 10k relationships and my query have a TIMEOUT problem or queries are solved in 30s.. too much time...
I have no idea how to solve this.
I use neo4j with docker and i tried to read settings docs but i have no idea how Java works.

Can you help me guys?

UPDATE

Thank you all guys!
For now i solved with "allShortestPaths" but I think i will rename all relationships (like Michael Hunger said).

答:
Have you tried:

```<code>MATCH p=allShortestPaths((s1:Stop {id: {departureStopId}})-[:NEXT*]-> (s2:Stop {id: {arrivalStopId}}) )
WHERE ALL(i in RELS(p) WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN rels(p) as nexts
LIMIT 10
</code>```

This should use the fast shortest path algorithm because:

Planning shortest paths in Cypher can lead to different query plans depending on the predicates that need to be evaluated. Internally, Neo4j will use a fast bidirectional breadth-first search algorithm if the predicates can be evaluated whilst searching for the path.

See https://neo4j.com/docs/developer-manual/current/cypher/execution-plans/shortestpath-planning/#_shortest_path_with_fast_algorithm for more details.

Body:
i have a problem with neo4j.
I don't know if problem is my query or something else.

Intro

I have to build an application that store bus/train routes.
This is my schema:

Nodes:

Organizaton: company that have routes/bus etc..

Route: A bus route like: Paris - Berlin.

Vehicle(Bus in this case): Fisical bus with a unique license plate.

Stops: point in a map with latitude and longitude.

Important Relationships:

NEXT: This is a really important relationship.

NEXT relationships contains those properties:

startHour

startMinutes

endHour

endMinutes

dayOfWeek (from 0 to 6 - Sun, Mon etc..)

vehicleId

Problem

My query is:

MATCH (s1:Stop {id: {departureStopId}}), (s2:Stop {id: {arrivalStopId}})
OPTIONAL MATCH (s1)-[nexts:NEXT*]->(s2)
WHERE ALL(i in nexts WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN nexts
LIMIT 10

For example: I wanna found all nexts relationships where dayOfWeek is Sunday (0) and property startHour > 11

After that I usually parse and validate final object on my nodejs backend.

This works when i was at the start.. with 1k relationships..
Now i have 10k relationships and my query have a TIMEOUT problem or queries are solved in 30s.. too much time...
I have no idea how to solve this.
I use neo4j with docker and i tried to read settings docs but i have no idea how Java works.

Can you help me guys?

UPDATE

Thank you all guys!
For now i solved with "allShortestPaths" but I think i will rename all relationships (like Michael Hunger said).

Body:
Have you tried:

MATCH p=allShortestPaths((s1:Stop {id: {departureStopId}})-[:NEXT*]-> (s2:Stop {id: {arrivalStopId}}) )
WHERE ALL(i in RELS(p) WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN rels(p) as nexts
LIMIT 10

This should use the fast shortest path algorithm because:

Planning shortest paths in Cypher can lead to different query plans depending on the predicates that need to be evaluated. Internally, Neo4j will use a fast bidirectional breadth-first search algorithm if the predicates can be evaluated whilst searching for the path.

See https://neo4j.com/docs/developer-manual/current/cypher/execution-plans/shortestpath-planning/#_shortest_path_with_fast_algorithm for more details.


问:
How does lambda capture local static variable?
In below code I do not specify any capture mode, yet some_static is visible inside closure. So the question is whether it is actually captured, or maybe somehow referenced in other way.

Bonus question is whether compiler is allowed to turn such lambda into a free function instead of closure - that would be possible as no capture list is specified.

```<code>std::vector<std::function<bool(int)>> filters;

int main()
{
    static int some_static = 1;
    filters.emplace_back([](int){
      return some_static == 2;
    });
}
</code>```

答: Generally a lambda is implemented as a class with variables and a single member function (behind the scenes). However when it captures a static this isn't necessary - because the code is generated by the compiler, it has no scope rules, and it can simply access the static directly. So a lambda that captures only static variables will have an empty class member list, and might well be optimised to a simple function pointer.  </p>

Body:
In below code I do not specify any capture mode, yet some_static is visible inside closure. So the question is whether it is actually captured, or maybe somehow referenced in other way.

Bonus question is whether compiler is allowed to turn such lambda into a free function instead of closure - that would be possible as no capture list is specified.

std::vector<std::function<bool(int)>> filters;

int main()
{
    static int some_static = 1;
    filters.emplace_back([](int){
      return some_static == 2;
    });
}


问:
Neo4j: unit testing the bolt driver properly
I am adding the Neo4j Bolt driver to my application just following the http://neo4j.com/developer/java/:

```<code>import org.neo4j.driver.v1.*;

Driver driver = GraphDatabase.driver( "bolt://localhost", AuthTokens.basic( "neo4j", "neo4j" ) );

Session session = driver.session();
session.run( "CREATE (a:Person {name:'Arthur', title:'King'})" );

StatementResult result = session.run( "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title" );

while ( result.hasNext() )

{
    Record record = result.next();
    System.out.println( record.get( "title" ).asString() + " " + record.get("name").asString() );
}
session.close();
driver.close();
</code>```

However, always from the official documentation unit testing is made using:

```<code>GraphDatabaseService db = new TestGraphDatabaseFactory()
            .newImpermanentDatabaseBuilder()
</code>```

So if I want to test in some way the code above, I have to replace the GraphDatabase.driver( "bolt://localhost",...) with the GraphDatabaseService from the test. How can I do that? I cannot extract any sort of in-memory driver from there as far as I can see.

答:
An easy way now is to pull neo4j-harness, and use their built-in Neo4jRule as follows:

```<code>import static org.neo4j.graphdb.factory.GraphDatabaseSettings.boltConnector;
// [...]
@Rule public Neo4jRule graphDb = new Neo4jRule()
        .withConfig(boltConnector("0").address, "localhost:" + findFreePort());
</code>```

Where findFreePort implementation can be as simple as:

```<code>private static int findFreePort() {
    try (ServerSocket socket = new ServerSocket(0)) {
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
</code>```

As the Javadoc of ServerSocket explains:

A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Moreover, the socket is closed before the port value is returned, so there are great chances the returned port will still be available upon return (the window of opportunity for the port to be allocated again in between is small - the computation of the window size is left as an exercise to the reader).

Et voilà !

Body:
I am adding the Neo4j Bolt driver to my application just following the http://neo4j.com/developer/java/:

import org.neo4j.driver.v1.*;

Driver driver = GraphDatabase.driver( "bolt://localhost", AuthTokens.basic( "neo4j", "neo4j" ) );

Session session = driver.session();
session.run( "CREATE (a:Person {name:'Arthur', title:'King'})" );

StatementResult result = session.run( "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title" );

while ( result.hasNext() )

{
    Record record = result.next();
    System.out.println( record.get( "title" ).asString() + " " + record.get("name").asString() );
}
session.close();
driver.close();

However, always from the official documentation unit testing is made using:

GraphDatabaseService db = new TestGraphDatabaseFactory()
            .newImpermanentDatabaseBuilder()

So if I want to test in some way the code above, I have to replace the GraphDatabase.driver( "bolt://localhost",...) with the GraphDatabaseService from the test. How can I do that? I cannot extract any sort of in-memory driver from there as far as I can see.

Body:
An easy way now is to pull neo4j-harness, and use their built-in Neo4jRule as follows:

import static org.neo4j.graphdb.factory.GraphDatabaseSettings.boltConnector;
// [...]
@Rule public Neo4jRule graphDb = new Neo4jRule()
        .withConfig(boltConnector("0").address, "localhost:" + findFreePort());

Where findFreePort implementation can be as simple as:

private static int findFreePort() {
    try (ServerSocket socket = new ServerSocket(0)) {
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

As the Javadoc of ServerSocket explains:

A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Moreover, the socket is closed before the port value is returned, so there are great chances the returned port will still be available upon return (the window of opportunity for the port to be allocated again in between is small - the computation of the window size is left as an exercise to the reader).

Et voilà !


问:
How can I animate these two things on one div?
Here is a live version http://lucasdebelder.be/googledoodle/

First of all I kinda want to fix it without using javascript/jquery, I want to keep it pure HTML & CSS based :)

Focus on the portals, I want to make them open and shrink after my ufo passed them. I've tried it multiple things but it doesn't want to work. How can I make a transition without using a :hover statement? I have a glowing, which is the box-shadows already on it, to make it look interactive, but how can I make them shrink?

(Portaal stands for portal, links stands for left and rechts stands for right, it's dutch)

HTML:

```<code><!-- portaal links en rechts -->
            <div class="portaal portaal_links_glow"></div>
            <div class="portaal portaal_rechts_glow"></div>
</code>```

CSS:

```<code>/*portaal algemeen*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}
/*portaal links*/
.portaal_links_glow {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.75;
    left: 50px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: 2;
    animation-timing-function: ease-in-out;
}
/*portaal rechts*/
.portaal_rechts_glow {
    background: radial-gradient(ellipse at center, rgba(237,160,118,1) 0%,rgba(241,116,50,1) 50%,rgba(234,85,7,1) 51%,rgba(251,149,94,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.65;
    left: 750px;
    animation-name: animation_portaal_glow_rechts;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: infinite;
    animation-timing-function: ease-in-out;
}
/*portaal glow animatie LINKS*/
@keyframes animation_portaal_glow_links {
    0% { box-shadow: 0 0 0px #57B6FF; }
    50% { box-shadow: 0 0 55px #57B6FF; }
    100% { box-shadow: 0 0 0px #57B6FF; }
}
/*portaal glow animatie rechts*/
@keyframes animation_portaal_glow_rechts {
    0% { box-shadow: 0 0 0px #ea2803; }
    50% { box-shadow: 0 0 55px #ea2803; }
    100% { box-shadow: 0 0 0px #ea2803; }
}
</code>```

Thanks for all the effort and time.

答:
Using css only

replace you keyframes @keyframes animation_portaal_glow_links and animation_portaal_glow_rechts  and the classes .portaal_links_glow and .portaal_rechts_glow with the following codes below

```<code>.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}
/*portaal links*/
.portaal_links_glow {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.75;
    left: 50px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 5s;
    animation-duration: 4s;
    animation-iteration-count: 1;
    animation-timing-function: ease-in-out;
    animation-fill-mode:forwards;
}

/*portaal rechts*/
.portaal_rechts_glow {
    background: radial-gradient(ellipse at center, rgba(237,160,118,1) 0%,rgba(241,116,50,1) 50%,rgba(234,85,7,1) 51%,rgba(251,149,94,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.65;
    left: 750px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 12s;
    animation-duration: 4s;
    animation-iteration-count: 1;
    animation-timing-function: ease-in-out;
animation-fill-mode:forwards;
}
/*portaal glow animatie LINKS*/
@keyframes animation_portaal_glow_links {
    0% { box-shadow: 0 0 0px #57B6FF; }
    50% { box-shadow: 0 0 55px #57B6FF; }
    100% { box-shadow: 0 0 0px #57B6FF; opacity:0;width:0;height:0}
}
/*portaal glow animatie rechts*/
@keyframes animation_portaal_glow_rechts {
    0% { box-shadow: 0 0 0px #ea2803; }
    50% { box-shadow: 0 0 55px #ea2803; }
    100% { box-shadow: 0 0 0px #ea2803; }
}
</code>```

pen is here
Note in the pen I copied you entire css spreadsheets and place it in the css section

Body:
Here is a live version http://lucasdebelder.be/googledoodle/

First of all I kinda want to fix it without using javascript/jquery, I want to keep it pure HTML & CSS based :)

Focus on the portals, I want to make them open and shrink after my ufo passed them. I've tried it multiple things but it doesn't want to work. How can I make a transition without using a :hover statement? I have a glowing, which is the box-shadows already on it, to make it look interactive, but how can I make them shrink?

(Portaal stands for portal, links stands for left and rechts stands for right, it's dutch)

HTML:

CSS:

/*portaal algemeen*/
.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}
/*portaal links*/
.portaal_links_glow {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.75;
    left: 50px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: 2;
    animation-timing-function: ease-in-out;
}
/*portaal rechts*/
.portaal_rechts_glow {
    background: radial-gradient(ellipse at center, rgba(237,160,118,1) 0%,rgba(241,116,50,1) 50%,rgba(234,85,7,1) 51%,rgba(251,149,94,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.65;
    left: 750px;
    animation-name: animation_portaal_glow_rechts;
    animation-delay: 1s;
    animation-duration: 4s;
    animation-iteration-count: infinite;
    animation-timing-function: ease-in-out;
}
/*portaal glow animatie LINKS*/
@keyframes animation_portaal_glow_links {
    0% { box-shadow: 0 0 0px #57B6FF; }
    50% { box-shadow: 0 0 55px #57B6FF; }
    100% { box-shadow: 0 0 0px #57B6FF; }
}
/*portaal glow animatie rechts*/
@keyframes animation_portaal_glow_rechts {
    0% { box-shadow: 0 0 0px #ea2803; }
    50% { box-shadow: 0 0 55px #ea2803; }
    100% { box-shadow: 0 0 0px #ea2803; }
}

Thanks for all the effort and time.

Body:
Using css only

replace you keyframes @keyframes animation_portaal_glow_links and animation_portaal_glow_rechts  and the classes .portaal_links_glow and .portaal_rechts_glow with the following codes below

.portaal {
    position: absolute;
    width: 100px;
    height: 200px;
    border-radius: 50px / 100px;
    bottom: 315px;
}
/*portaal links*/
.portaal_links_glow {
    background: radial-gradient(ellipse at center, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.75;
    left: 50px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 5s;
    animation-duration: 4s;
    animation-iteration-count: 1;
    animation-timing-function: ease-in-out;
    animation-fill-mode:forwards;
}

/*portaal rechts*/
.portaal_rechts_glow {
    background: radial-gradient(ellipse at center, rgba(237,160,118,1) 0%,rgba(241,116,50,1) 50%,rgba(234,85,7,1) 51%,rgba(251,149,94,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    opacity: 0.65;
    left: 750px;
    animation-name: animation_portaal_glow_links;
    animation-delay: 12s;
    animation-duration: 4s;
    animation-iteration-count: 1;
    animation-timing-function: ease-in-out;
animation-fill-mode:forwards;
}
/*portaal glow animatie LINKS*/
@keyframes animation_portaal_glow_links {
    0% { box-shadow: 0 0 0px #57B6FF; }
    50% { box-shadow: 0 0 55px #57B6FF; }
    100% { box-shadow: 0 0 0px #57B6FF; opacity:0;width:0;height:0}
}
/*portaal glow animatie rechts*/
@keyframes animation_portaal_glow_rechts {
    0% { box-shadow: 0 0 0px #ea2803; }
    50% { box-shadow: 0 0 55px #ea2803; }
    100% { box-shadow: 0 0 0px #ea2803; }
}

pen is here
Note in the pen I copied you entire css spreadsheets and place it in the css section


问:
Android rxjava2 Flowable with compositedisposable
I have a problem with Flowables and adding them to the compositeDisposables.
I want to switch from an Observable to a Flowable as the operation might emit 1000 or more values. Im somewhat unexperienced with rxjava2 so please forgive me if that question is stupid :)

So far I used the observable like this:

```<code> public Observable<String> uploadPictureRx(String path)
    {
        return Observable.create(new ObservableOnSubscribe<String>()
        {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception
            {
                Uri file = Uri.fromFile(new File(path));
                String segment = file.getLastPathSegment();
                UploadTask uploadTask = reference.child("SomeChild").child(segment).putFile(file);

                uploadTask.addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception)
                    {
                        e.onError(exception);
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        downloadUrl = taskSnapshot.getDownloadUrl();
                        String url = downloadUrl.getPath();
                        e.onNext(url);
                        e.onComplete();
                    }
                }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        long bytes = taskSnapshot.getBytesTransferred();
                        String bytesS = String.valueOf(bytes);
                        e.onNext(bytesS);
                    }
                });
            }
        });
    }
</code>```

and called the method like this:

```<code>private void uploadPicToFireBaseStorage(String path)
    {
        compositeDisposable.add(storageService.uploadPictureRx(path)
                .subscribeOn(Schedulers.io())
                .observeOn(mainScheduler)
                .subscribeWith(new DisposableObserver<String>()
                {

                    @Override
                    public void onNext(String s)
                    {
                        String ss = s;
                        System.out.println(ss);
                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete()
                    {
                        view.displayToast("Picture Upload completed");
                    }
                })
        );
    }
</code>```

This works fine! However when I try to do the same with a Flowable instead of observable it wont compile:

```<code>public Flowable<String> uploadPictureRx(String path)
    {
        return Flowable.create(new FlowableOnSubscribe<String>()
        {

            @Override
            public void subscribe(FlowableEmitter<String> e) throws Exception
            {
                Uri file = Uri.fromFile(new File(path));
                String segment = file.getLastPathSegment();
                UploadTask uploadTask = reference.child("somechild").child(segment).putFile(file);

                uploadTask.addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception)
                    {
                        e.onError(exception);
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        downloadUrl = taskSnapshot.getDownloadUrl();
                        String url = downloadUrl.getPath();
                        e.onNext(url);
                        e.onComplete();
                    }
                }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        long bytes = taskSnapshot.getBytesTransferred();
                        String bytesS = String.valueOf(bytes);
                        e.onNext(bytesS);
                    }
                });
            }
        }, BackpressureStrategy.BUFFER);

    }
</code>```

The Error is:
 Inferred type 'E' for type parameter 'E' is not within its bound; should implement 'org.reactivestreams.Subscriber

My guess is, that Flowable does not implement Disposable and thats why it wont compile. I have no clue if thats true or not, just my best guess so far.
Or do I have to change subscribeWith() to subscribe()? I dont know what the impact of that change would be.

Anyway suggestions how to make this work and get this Flowable into my compositedisposable is really appreciated.

Thanks guys!

Edit:

Tried to change the DisposableObserver into a Subscriber. But this results in the following Error:
Compiler Error

答:
Flowables use Subscription instead of Disposable for the reason of Backpressure. Basically use Subscription.request() method to tell observable how many items I want for that moment.

Change your code:

```<code>private void uploadPicToFireBaseStorage(String path)
{
    compositeDisposable.add(storageService.uploadPictureRx(path)
            .subscribeOn(Schedulers.io())
            .observeOn(mainScheduler)
            .subscribeWith(new DisposableObserver<String>()
            {

                @Override
                public void onNext(String s)
                {
                    String ss = s;
                    System.out.println(ss);
                }

                @Override
                public void onError(Throwable e)
                {
                    e.printStackTrace();
                }

                @Override
                public void onComplete()
                {
                    view.displayToast("Picture Upload completed");
                }
            })
    );
}
</code>```

into

```<code>private void uploadPicToFireBaseStorage(String path)
{
    compositeDisposable.add(storageService.uploadPictureRx(path)
            .subscribeOn(Schedulers.io())
            .observeOn(mainScheduler)
            .subscribeWith(new ResourceSubscriber<String>()
            {
                @Override
                public void onNext(String s)
                {
                    String ss = s;
                    System.out.println(ss);
                }

                @Override
                public void onError(Throwable e)
                {
                    e.printStackTrace();
                }

                @Override
                public void onComplete()
                {
                    view.displayToast("Picture Upload completed");
                }
            })
    );
}
</code>```

Body:
I have a problem with Flowables and adding them to the compositeDisposables.
I want to switch from an Observable to a Flowable as the operation might emit 1000 or more values. Im somewhat unexperienced with rxjava2 so please forgive me if that question is stupid :)

So far I used the observable like this:

 public Observable<String> uploadPictureRx(String path)
    {
        return Observable.create(new ObservableOnSubscribe<String>()
        {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception
            {
                Uri file = Uri.fromFile(new File(path));
                String segment = file.getLastPathSegment();
                UploadTask uploadTask = reference.child("SomeChild").child(segment).putFile(file);

                uploadTask.addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception)
                    {
                        e.onError(exception);
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        downloadUrl = taskSnapshot.getDownloadUrl();
                        String url = downloadUrl.getPath();
                        e.onNext(url);
                        e.onComplete();
                    }
                }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        long bytes = taskSnapshot.getBytesTransferred();
                        String bytesS = String.valueOf(bytes);
                        e.onNext(bytesS);
                    }
                });
            }
        });
    }

and called the method like this:

private void uploadPicToFireBaseStorage(String path)
    {
        compositeDisposable.add(storageService.uploadPictureRx(path)
                .subscribeOn(Schedulers.io())
                .observeOn(mainScheduler)
                .subscribeWith(new DisposableObserver<String>()
                {

                    @Override
                    public void onNext(String s)
                    {
                        String ss = s;
                        System.out.println(ss);
                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete()
                    {
                        view.displayToast("Picture Upload completed");
                    }
                })
        );
    }

This works fine! However when I try to do the same with a Flowable instead of observable it wont compile:

public Flowable<String> uploadPictureRx(String path)
    {
        return Flowable.create(new FlowableOnSubscribe<String>()
        {

            @Override
            public void subscribe(FlowableEmitter<String> e) throws Exception
            {
                Uri file = Uri.fromFile(new File(path));
                String segment = file.getLastPathSegment();
                UploadTask uploadTask = reference.child("somechild").child(segment).putFile(file);

                uploadTask.addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception)
                    {
                        e.onError(exception);
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        downloadUrl = taskSnapshot.getDownloadUrl();
                        String url = downloadUrl.getPath();
                        e.onNext(url);
                        e.onComplete();
                    }
                }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>()
                {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
                    {
                        //noinspection VisibleForTests
                        long bytes = taskSnapshot.getBytesTransferred();
                        String bytesS = String.valueOf(bytes);
                        e.onNext(bytesS);
                    }
                });
            }
        }, BackpressureStrategy.BUFFER);

    }

The Error is:
 Inferred type 'E' for type parameter 'E' is not within its bound; should implement 'org.reactivestreams.Subscriber

My guess is, that Flowable does not implement Disposable and thats why it wont compile. I have no clue if thats true or not, just my best guess so far.
Or do I have to change subscribeWith() to subscribe()? I dont know what the impact of that change would be.

Anyway suggestions how to make this work and get this Flowable into my compositedisposable is really appreciated.

Thanks guys!

Edit:

Tried to change the DisposableObserver into a Subscriber. But this results in the following Error:
Compiler Error

Body:
Flowables use Subscription instead of Disposable for the reason of Backpressure. Basically use Subscription.request() method to tell observable how many items I want for that moment.

Change your code:

private void uploadPicToFireBaseStorage(String path)
{
    compositeDisposable.add(storageService.uploadPictureRx(path)
            .subscribeOn(Schedulers.io())
            .observeOn(mainScheduler)
            .subscribeWith(new DisposableObserver<String>()
            {

                @Override
                public void onNext(String s)
                {
                    String ss = s;
                    System.out.println(ss);
                }

                @Override
                public void onError(Throwable e)
                {
                    e.printStackTrace();
                }

                @Override
                public void onComplete()
                {
                    view.displayToast("Picture Upload completed");
                }
            })
    );
}

into

private void uploadPicToFireBaseStorage(String path)
{
    compositeDisposable.add(storageService.uploadPictureRx(path)
            .subscribeOn(Schedulers.io())
            .observeOn(mainScheduler)
            .subscribeWith(new ResourceSubscriber<String>()
            {
                @Override
                public void onNext(String s)
                {
                    String ss = s;
                    System.out.println(ss);
                }

                @Override
                public void onError(Throwable e)
                {
                    e.printStackTrace();
                }

                @Override
                public void onComplete()
                {
                    view.displayToast("Picture Upload completed");
                }
            })
    );
}


问:
Using your own Data in Tensorflow
I already know how to make a neural network using the mnist dataset. I have been searching for tutorials on how to train a neural network on your own dataset for 3 months now but I'm just not getting it. If someone can suggest any good tutorials or explain how all of this works, please help.
PS. I won't install NLTK. It seems like a lot of people are training their neural network on text but I won't do that. If I would install NLTK, I would only use it once.</p>

答:
I suggest you use OpenCV library. Whatever you uses your MNIST data or PIL, when it's loaded, they're all just NumPy arrays. If you want to make MNIST datasets fit with your trained model, here's how I did it:

1.Use cv2.imread to load all the images you want them to act as training datasets.

2.Use cv2.cvtColor to convert all the images into grayscale images and resize them into 28x28.

3.Divide each pixel in all the datasets by 255.

4.Do the training as usual!

I haven't tried to make it your own format, but theoratically it's the same.

Title: Using your own Data in Tensorflow


问:
Pycharm Community 2017.1 - Unable to get the virutalenv interpreter
My goal is to add the virtualenv interpreter in pychar
I installed pycharm community edition 2017.1 on ubuntu 14.04. I have virtualenv running using the command

```<code>$source /opt/e360/hello/py_27_env/bin/activate
</code>```

when I try to add the virtual env using settings->project Interpreter . I can see the /usr/bin/python2.7 and /usr/bin/python3.4 python versions.
when trying to add interpreter for /opt/e360/hello/py_27_env/bin/activate I get the error message

"The selected file is not a valid home for python SDK"

Please suggest if I am doing anything wrong

答:
You don't set the python interpreter to the activate file, you need to set it to the python binary file in that folder. Should be something in like this:

```<code> /opt/e360/hello/py_27_env/bin/python2.7
</code>```

Body:
My goal is to add the virtualenv interpreter in pychar
I installed pycharm community edition 2017.1 on ubuntu 14.04. I have virtualenv running using the command

$source /opt/e360/hello/py_27_env/bin/activate

when I try to add the virtual env using settings->project Interpreter . I can see the /usr/bin/python2.7 and /usr/bin/python3.4 python versions.
when trying to add interpreter for /opt/e360/hello/py_27_env/bin/activate I get the error message

"The selected file is not a valid home for python SDK"

Please suggest if I am doing anything wrong

Body:
You don't set the python interpreter to the activate file, you need to set it to the python binary file in that folder. Should be something in like this:

 /opt/e360/hello/py_27_env/bin/python2.7


问:
PHP saves null to JSON file
I have a problem with my PHP file. I want to save data from my HTML form to external JSON file "data.json". When I fire button to save it it returns message that everything is fine and data is added. Unfortunetaly, when I check my data.json file, it contains null instead of data from a form. Here is my code:

HTML:

```<code> <form class="form form-group" action="save.php" method="POST">
   <label class="control-label" for="focusedInput">Nazwa knajpy</label>
   <input name="name" class="input form-control" id="focusedInput" type="text" value="Wpisz nazwę knajpy">

   <label class="control-label" for="focusedInput">Kategoria knajpy</label>
   <input name="category" class="input form-control" id="focusedInput" type="text" value="Bar/restauracja">

   <label class="control-label" for="focusedInput">Adres</label>
   <input name="addres" class="input form-control" id="focusedInput" type="text" value="Wpisz adres knajpy">

   <label class="control-label" for="focusedInput">Nazwa zdjęcia</label>
   <input name="img" class="input form-control" id="focusedInput" type="text" value="Wpisz nazwę zdjęcia jpg">

   <label class="control-label" for="focusedInput">Cena</label>
   <input name="price" class="input form-control" id="focusedInput" type="text" value="Wpisz cenę piwa">

   <input type="submit" class="btn btn-primary" value="Dodaj knajpę">
  </form>
</code>```

save.php:

```<code><?php

   $myFile = "data/data.json";
   $arr_data = array(); // create empty array

  try
  {
       //Get form data
       $formdata = array(
          'name'=> $_POST['name'],
          'category'=> $_POST['category'],
          'address'=>$_POST['address'],
          'img'=> $_POST['img'],
          'price'=> $_POST['price']
       );

       //Get data from existing json file
       $jsondata = file_get_contents($myFile);

       // converts json data into array
       $arr_data = json_decode($jsondata, true);

       // Push user data to array
       array_push($arr_data,$formdata);

       //Convert updated array to JSON
       $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

       //write json data into data.json file
       if(file_put_contents($myFile, $jsondata)) {
            echo 'Data successfully saved';
        }
       else
            echo "error";

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

?>
</code>```

Thanks for help!

答:
This line is probably causing issues: $arr_data = json_decode($jsondata, true);

You should make sure it's not empty before you start working with it.

You could add a check like: $arr_data = !empty($jsondata) ? json_decode($jsondata, true) : array();

You may want to perform another check after that as well to make sure you have an array as you expect.

Title: PHP saves null to JSON file

Body:
I have a problem with my PHP file. I want to save data from my HTML form to external JSON file "data.json". When I fire button to save it it returns message that everything is fine and data is added. Unfortunetaly, when I check my data.json file, it contains null instead of data from a form. Here is my code:

HTML:

 <form class="form form-group" action="save.php" method="POST">
   Nazwa knajpy
   <input name="name" class="input form-control" id="focusedInput" type="text" value="Wpisz nazwę knajpy">

   Kategoria knajpy
   <input name="category" class="input form-control" id="focusedInput" type="text" value="Bar/restauracja">

   Adres
   <input name="addres" class="input form-control" id="focusedInput" type="text" value="Wpisz adres knajpy">

   Nazwa zdjęcia
   <input name="img" class="input form-control" id="focusedInput" type="text" value="Wpisz nazwę zdjęcia jpg">

   Cena
   <input name="price" class="input form-control" id="focusedInput" type="text" value="Wpisz cenę piwa">

   <input type="submit" class="btn btn-primary" value="Dodaj knajpę">
  </form>

save.php:

<?php

   $myFile = "data/data.json";
   $arr_data = array(); // create empty array

  try
  {
       //Get form data
       $formdata = array(
          'name'=> $_POST['name'],
          'category'=> $_POST['category'],
          'address'=>$_POST['address'],
          'img'=> $_POST['img'],
          'price'=> $_POST['price']
       );

       //Get data from existing json file
       $jsondata = file_get_contents($myFile);

       // converts json data into array
       $arr_data = json_decode($jsondata, true);

       // Push user data to array
       array_push($arr_data,$formdata);

       //Convert updated array to JSON
       $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

       //write json data into data.json file
       if(file_put_contents($myFile, $jsondata)) {
            echo 'Data successfully saved';
        }
       else
            echo "error";

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

?>

Thanks for help!


问:
how to make the selected menu stay selected jquery, css , html
accordian menu , has to make the submenu to stay selected after clicking by js. or css .

not the static solution in html.
need solution comprising jquery and the css
it should appear same as hovering after clicked

check out the fiddle

https://jsfiddle.net/shaswatatripathy/ucgff65k/

$(document).ready(function() {

  $("#accordion > li > div").click(function() {
    $("#submenu li").slideUp();
    if (!$(this).next().is(":visible")) {
      $(this).next().slideDown();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
  display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}</code>```

Menu 2

submenu1

submenu1

submenu1

Menu 3

submenu1

submenu1

submenu1

```

答:
Create an .active class for the  tag inside
 which matches the CSS of the :hover state of , like this:

```<code>a.active {
  background: #b63b4d;
  color: #FFF;
}
</code>```

And then just use the click event listener to add and remove this class when clicked on the submenu:

```<code> $(document).ready(function() {

   $("#accordion > li > div").click(function() {
     if (!$(this).next().is(":visible")) {
       $(this).next().slideDown();
     } else {
       $(this).next().slideUp();
     }
   });

   $(".submenu a").click(function() {
            $(this).toggleClass("active").parent().siblings().find("a").removeClass("active");
   });

 });
</code>```

I also modified to jQuery so that the accordion closes when it is clicked on in the open state.

Here's the working jsfiddle: https://jsfiddle.net/ucgff65k/2/
And the code snippet:

 $(document).ready(function() {

   $("#accordion > li > div").click(function() {
     if (!$(this).next().is(":visible")) {
       $(this).next().slideDown();
     } else {
       $(this).next().slideUp();
     }
   });

   $(".submenu a").click(function() {
       $(this).toggleClass("active").parent().siblings().find("a").removeClass("active");
   });

 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

a.active {
  background: #b63b4d;
  color: #FFF;
}</code>```

Menu 2

submenu1

submenu1

submenu1

Menu 3

submenu1

submenu1

submenu1

```

Body:
accordian menu , has to make the submenu to stay selected after clicking by js. or css .

not the static solution in html.
need solution comprising jquery and the css
it should appear same as hovering after clicked

check out the fiddle

https://jsfiddle.net/shaswatatripathy/ucgff65k/

$(document).ready(function() {

  $("#accordion > li > div").click(function() {
    $("#submenu li").slideUp();
    if (!$(this).next().is(":visible")) {
      $(this).next().slideDown();
    }
  });
});

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
  display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

Menu 2

submenu1

submenu1

submenu1

Menu 3

submenu1

submenu1

submenu1

Body:
Create an .active class for the <a> tag inside <li> which matches the CSS of the :hover state of <a>, like this:

a.active {
  background: #b63b4d;
  color: #FFF;
}

And then just use the click event listener to add and remove this class when clicked on the submenu:

 $(document).ready(function() {

   $("#accordion > li > div").click(function() {
     if (!$(this).next().is(":visible")) {
       $(this).next().slideDown();
     } else {
       $(this).next().slideUp();
     }
   });

   $(".submenu a").click(function() {
            $(this).toggleClass("active").parent().siblings().find("a").removeClass("active");
   });

 });

I also modified to jQuery so that the accordion closes when it is clicked on in the open state.

Here's the working jsfiddle: https://jsfiddle.net/ucgff65k/2/
And the code snippet:

 $(document).ready(function() {

   $("#accordion > li > div").click(function() {
     if (!$(this).next().is(":visible")) {
       $(this).next().slideDown();
     } else {
       $(this).next().slideUp();
     }
   });

   $(".submenu a").click(function() {
       $(this).toggleClass("active").parent().siblings().find("a").removeClass("active");
   });

 });

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

a.active {
  background: #b63b4d;
  color: #FFF;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="accordion" class="accordion">
  <li>
    <div class="link">Menu 2</div>
    <ul class="submenu">
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
    </ul>
  </li>
  <li>
    <div class="link">Menu 3</div>
    <ul class="submenu">
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
    </ul>
  </li>
</ul>


问:
How to correctly syntax a chained promise function
I have a list that I would like it to go through a function and make some fixes on that list, so I can use it later.

Because its function is depended on the result of the previous, I decided to use the chained defer, to wait one another.

```<code>    var $q = Promise;
  $scope.list = function(scan_result) {

  return $q.resolve(scan_result)
    .then(function(scan_result) {
      // Creates an object list with bssid and signal
      const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
        }
      });
      console.log("1st Then:");
      console.log(ap_list);
      return ap_list;
    })

  .then(function(ap_list) {
  //Sort the elements Highest to Lowest Signal Level
  ap_list.sort(function(a, b) {
    return b.signal - a.signal;
  });
  console.log("2nd Then:");
  console.log(ap_list);
  return ap_list;
})

  .then(function(ap_list) {
    //Removes the elements that have signal bellow -50
    for (var i = 0; i < ap_list.length; i++) {
      if (ap_list[i].signal < -50) {
        ap_list.splice(i, 1);
      }
    }
    console.log("3rd Then:");
    console.log(ap_list);
    return ap_list;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    //console.log(ap_list);
    console.log("4th Then:");
    console.log(ap_list.slice(0, 3));
    return ap_list.slice(0, 3);
  })
}

$scope.checkin = function() {
  var scan_result = $scope.getList();
  console.log(scan_result);
  $scope.list(scan_result)
    .then(function(result) {
      //console.log(result);
    })
}
</code>```

When I output the result of the $scope.list() function on the console, it says the promise is pending and the status equals to 0.

So, definitely something is wrong here. Im not a defer guru so I kindly ask for your help.

答:
You are creating a promise that is responsible for resolving itself...after it has been resolved. That's a contradiction, and that's why your promise never resolves. You're also trying to resolve a single promise multiple times, which is not possible. A promise can only be resolved once.

From your example code, I really don't see any reason to use promises, since it's not doing anything asynchronously, but if you really want to use them, the below example should work. You should stop using defer; it's outdated and there is almost always a better way.

// setup mock objects for this example
var $scope = { getList: function () { return ["BSSID: b0:c5:54:dd:e1:20 Signal: -21", "BSSID: c0:05:c2:6d:b1:9f Signal: -34", "BSSID: c0:05:c2:6d:b1:99 Signal: -33", "BSSID: 70:50:af:1f:0b:51 Signal: -80", "BSSID: 76:ea:a8:53:5c:9f Signal: -89", "BSSID: 90:21:06:af:99:65 Signal: -56", "BSSID: d8:fe:e3:e8:51:a6 Signal: -80", "BSSID: 24:de:c6:fb:7c:90 Signal: -89", "BSSID: 6c:c2:17:21:8a:47 Signal: -89", "BSSID: 24:de:c6:fb:7c:91 Signal: -90"]; } };
var $q = Promise;

$scope.list = function(scan_result) {

  return $q.resolve(scan_result)
    .then(function(scan_result) {
      // Creates an object list with bssid and signal
      const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
        }
      });
      console.log(ap_list);
      return ap_list;
    })

  .then(function (ap_list) {
    //Removes the elements that have signal bellow -50
    ap_list = ap_list.filter(el => el.signal >= -50);

    console.log(ap_list);
    return ap_list;
  })

  .then(function (ap_list) {
    //Sort the elements Highest to Lowest Signal Level
    ap_list.sort(function(a, b) {
      return a.signal - b.signal;
    });
    console.log(ap_list);
    return ap_list;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    ap_list = ap_list.slice(0, 3);
    console.log(ap_list);
    return ap_list;
  })
}

$scope.checkin = function() {
  var scan_result = $scope.getList();
  $scope.list(scan_result)
    .then(function(result) {
      console.log(result);
    })
}

$scope.checkin();```

Body:
I have a list that I would like it to go through a function and make some fixes on that list, so I can use it later.

Because its function is depended on the result of the previous, I decided to use the chained defer, to wait one another.

    var $q = Promise;
  $scope.list = function(scan_result) {

  return $q.resolve(scan_result)
    .then(function(scan_result) {
      // Creates an object list with bssid and signal
      const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
        }
      });
      console.log("1st Then:");
      console.log(ap_list);
      return ap_list;
    })

  .then(function(ap_list) {
  //Sort the elements Highest to Lowest Signal Level
  ap_list.sort(function(a, b) {
    return b.signal - a.signal;
  });
  console.log("2nd Then:");
  console.log(ap_list);
  return ap_list;
})

  .then(function(ap_list) {
    //Removes the elements that have signal bellow -50
    for (var i = 0; i < ap_list.length; i++) {
      if (ap_list[i].signal < -50) {
        ap_list.splice(i, 1);
      }
    }
    console.log("3rd Then:");
    console.log(ap_list);
    return ap_list;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    //console.log(ap_list);
    console.log("4th Then:");
    console.log(ap_list.slice(0, 3));
    return ap_list.slice(0, 3);
  })
}

$scope.checkin = function() {
  var scan_result = $scope.getList();
  console.log(scan_result);
  $scope.list(scan_result)
    .then(function(result) {
      //console.log(result);
    })
}

When I output the result of the $scope.list() function on the console, it says the promise is pending and the status equals to 0.

So, definitely something is wrong here. Im not a defer guru so I kindly ask for your help.


问:
Different ways of declaring user defined types in C and C++
Defined here is an enumeration in ANSI C.

```<code>enum Security_Levels
{
    black_ops,
    top_secret,
    secret,
    non_secret
};
</code>```

Now to declare s[4] of type Security_Levels , I wrote this in the main() code

```<code>    Security_Levels s[4];
</code>```

And I get this error:

```<code>file.c: In function ‘main’:
file.c:13:3: error: unknown type name ‘Security_Levels’
Security_Levels s[4];
</code>```

But when I declared it like this

```<code>enum Security_Levels s[4];
</code>```

IT WORKED!

```<code>Security_Levels s[4];
</code>```

This ^Worked in C++ but throws the aforementioned error in C

I have a similar question while using struct in C and C++ as well.

```<code>struct structure_name variable_name; //this is how it works in C
structure_name variable_name; // in  case of C++
</code>```

So, why the difference in declaring vars of user defined types?

答:
Short answer:  because that's the way the two different languages are defined.

Longer answer:  In C, struct and enum names are in separate, distinct namespaces.  That's why you see a lot of typedef struct s s; type things in C code so you don't need to use struct.  In C++, the struct and enum (and class) names are part of the namespace that is defining the struct/enum (usually the global namespace).  So you can reference them without a typedef or keyword.

Body:
Defined here is an enumeration in ANSI C.

enum Security_Levels
{
    black_ops,
    top_secret,
    secret,
    non_secret
};

Now to declare s[4] of type Security_Levels , I wrote this in the main() code

    Security_Levels s[4];

And I get this error:

file.c: In function ‘main’:
file.c:13:3: error: unknown type name ‘Security_Levels’
Security_Levels s[4];

But when I declared it like this

enum Security_Levels s[4];

IT WORKED!

Security_Levels s[4];

This ^Worked in C++ but throws the aforementioned error in C

I have a similar question while using struct in C and C++ as well.

struct structure_name variable_name; //this is how it works in C
structure_name variable_name; // in  case of C++

So, why the difference in declaring vars of user defined types?


问:
Is it possible to use boost accumulators with vectors?
I wanted to use boost accumulators to calculate statistics of a variable that is a vector. Is there a simple way to do this. I think it's not possible to use the dumbest thing:

```<code>  using namespace boost::accumulators;
  //stuff...

  accumulator_set<vector<double>, stats<tag::mean> > acc;
  vector<double> some_vetor;
  //stuff
  some_vector = doStuff();
  acc(some_vector);
</code>```

maybe this is obvious, but I tried anyway. :P

What I wanted was to have an accumulator that would calculate a vector which is the mean of the components of many vectors. Is there an easy way out?

EDIT:

I don't know if I was thoroughly clear. I don't want this:

```<code> for_each(vec.begin(), vec.end(),acc);
</code>```

This would calculate the mean of the entries of a given vector. What I need is different. I have a function that will spit vectors:

```<code> vector<double> doSomething();
 // this is a monte carlo simulation;
</code>```

And I need to run this many times and calculate the vectorial mean of those vectors:

```<code>  for(int i = 0; i < numberOfMCSteps; i++){
  vec = doSomething();
  acc(vec);
  }
  cout << mean(acc);
</code>```

And I want mean(acc) to be a vector itself, whose entry [i] would be the means of the entries [i] of the accumulated vectors.

Theres a hint about this in the docs of Boost, but nothing explicit. And I'm a bit dumb. :P

答: I don't have it set up to try right now, but if all boost::accumulators need is properly defined mathematical operators, then you might be able to get away with a different vector type: http://www.boost.org/doc/libs/1_37_0/libs/numeric/ublas/doc/vector.htm</p>

Body:
I wanted to use boost accumulators to calculate statistics of a variable that is a vector. Is there a simple way to do this. I think it's not possible to use the dumbest thing:

  using namespace boost::accumulators;
  //stuff...

  accumulator_set<vector<double>, stats<tag::mean> > acc;
  vector<double> some_vetor;
  //stuff
  some_vector = doStuff();
  acc(some_vector);

maybe this is obvious, but I tried anyway. :P

What I wanted was to have an accumulator that would calculate a vector which is the mean of the components of many vectors. Is there an easy way out?

EDIT:

I don't know if I was thoroughly clear. I don't want this:

 for_each(vec.begin(), vec.end(),acc);

This would calculate the mean of the entries of a given vector. What I need is different. I have a function that will spit vectors:

 vector<double> doSomething();
 // this is a monte carlo simulation;

And I need to run this many times and calculate the vectorial mean of those vectors:

  for(int i = 0; i < numberOfMCSteps; i++){
  vec = doSomething();
  acc(vec);
  }
  cout << mean(acc);

And I want mean(acc) to be a vector itself, whose entry [i] would be the means of the entries [i] of the accumulated vectors.

Theres a hint about this in the docs of Boost, but nothing explicit. And I'm a bit dumb. :P

ContentLicense: CC BY-SA 2.5


问:
Execute at most N tasks in parallel using JS promises or generators
I want to implement a JS class that executes at most N tasks in parallel using JS promises or generators. Something like

```<code>class Executor {
    constructor(numberOfMaxTasks) {
    ...
    }

    next(task) {
    ...
    }

    done(onDone) {
    ...
    }
}

....
const executor = new Executor(2);
executor.next(task1).next(task2).next(task3).done(onDone);
</code>```

task1 and task 2 should be executed in parallel while task3 should wait until one of the previous tasks finises. When all tasks finish onDone callback is executed.

I was trying to implement it using promises but I failed. I'm new to generators and currently have no idea if they can help here. This is for learning purposes mostly, that's why I don't want to use any third party libraries, just native JS. Any hint would be great, thanks in advance!

答:
Recently I had to solve a quiz for an interview similar to what you want to achieve, but based in Node.js.

  The key is to take control of amount of tasks being executed at the same time with a class property (in my example, this.running). So for an array of tasks, you run them through a while loop and check in every loop if you have any available slot (controlled by this.running and LIMIT) and then run the promise.

  This code might help you.

```<code>    let tasks = [];
    let tasksDone = [];
    const LIMIT = 10;

    class Executor {
        constructor () {
            this.running = 0;
            for (let i = 0; i < 1000; i++) {
                tasks[i] = {
                    id: 'job_' + (i+1),
                    time: ((i % 4) + 1) * 25
                };
            }
        }

        checkConcurrency () {
            if( this.running > LIMIT ){
                throw new Error('Maximum number of tasks ['+LIMIT+'] reached');
            }
        }

        execute (task) {
            return new Promise((resolve, reject)=>{
                this.running ++;
                this.checkConcurrency();
                setTimeout(()=>{
                    this.checkConcurrency();
                    this.running --;
                    resolve({
                ...task,
                        finished: Date.now()
                    });
                }, task.time);
            })

        }

        run () {
          this.startTime = Date.now();
          this.executeTasks(tasks.slice(0));
        }

        executeTasks(tasks) {
          while (this.running < LIMIT && tasks.length > 0) {
            let task = tasks.shift();
            this.execute(task).then( result => {
              tasksDone.push(result);
              if (tasks.length > 0) {
                this.executeTasks(tasks);
              }
            });
          }
        }
    }
</code>```

Body:
I want to implement a JS class that executes at most N tasks in parallel using JS promises or generators. Something like

class Executor {
    constructor(numberOfMaxTasks) {
    ...
    }

    next(task) {
    ...
    }

    done(onDone) {
    ...
    }
}

....
const executor = new Executor(2);
executor.next(task1).next(task2).next(task3).done(onDone);

task1 and task 2 should be executed in parallel while task3 should wait until one of the previous tasks finises. When all tasks finish onDone callback is executed.

I was trying to implement it using promises but I failed. I'm new to generators and currently have no idea if they can help here. This is for learning purposes mostly, that's why I don't want to use any third party libraries, just native JS. Any hint would be great, thanks in advance!

Body:
Recently I had to solve a quiz for an interview similar to what you want to achieve, but based in Node.js.

  The key is to take control of amount of tasks being executed at the same time with a class property (in my example, this.running). So for an array of tasks, you run them through a while loop and check in every loop if you have any available slot (controlled by this.running and LIMIT) and then run the promise.

  This code might help you.

    let tasks = [];
    let tasksDone = [];
    const LIMIT = 10;

    class Executor {
        constructor () {
            this.running = 0;
            for (let i = 0; i < 1000; i++) {
                tasks[i] = {
                    id: 'job_' + (i+1),
                    time: ((i % 4) + 1) * 25
                };
            }
        }

        checkConcurrency () {
            if( this.running > LIMIT ){
                throw new Error('Maximum number of tasks ['+LIMIT+'] reached');
            }
        }

        execute (task) {
            return new Promise((resolve, reject)=>{
                this.running ++;
                this.checkConcurrency();
                setTimeout(()=>{
                    this.checkConcurrency();
                    this.running --;
                    resolve({
                ...task,
                        finished: Date.now()
                    });
                }, task.time);
            })

        }

        run () {
          this.startTime = Date.now();
          this.executeTasks(tasks.slice(0));
        }

        executeTasks(tasks) {
          while (this.running < LIMIT && tasks.length > 0) {
            let task = tasks.shift();
            this.execute(task).then( result => {
              tasksDone.push(result);
              if (tasks.length > 0) {
                this.executeTasks(tasks);
              }
            });
          }
        }
    }


问:
Regex matching and printing string issue

In Perl, I am trying to match three groups. Some groups have two question marks around them, others have one. I need to be able to distinguish between the two.

Sample Input:

The box is ?Red? in colour.
The box is ??green?? in colour.
```

<p><strong>Current Output:</strong></p>

<pre class="lang-none prettyprint-override"><code>The box isRedin colour.

The box is green in colour.
</code>```

Desired Output:

The box is Red in colour.

The box is green in colour.
```

<p>Here is what is almost working perfectly:</p>

<pre class="lang-perl prettyprint-override"><code>my $pattern_q  = '(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)';
my $pattern_qq = '(.*\s?)\?\?(\w.*)\?\?(.*)';

if ( $line =~ /$pattern_q/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
}

if ( $line =~ /$pattern_qq/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
</code>```

When I get a match against $pattern_qq - it handles everything correctly, except for the \n at the end, which I can live with.

When I get a match against $pattern_q - It removes the spaces between the three groups, which I want to retain.

答:
As you said, your code is "almost working perfectly": it is very close to doing exactly what you want.

You can make it do exactly what you want by moving two parentheses in your first pattern to include the [^\?] pattern match in the capture groups.  This will capture the spaces on either side of ?Red? in your sample input.

So

```<code>'(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)'
</code>```

becomes

```<code>'(.*\s?[^\?])\?(\w.*)\?([^\?].*)'
</code>```

Body:
In Perl, I am trying to match three groups. Some groups have two question marks around them, others have one. I need to be able to distinguish between the two.

Sample Input:

The box is ?Red? in colour.
The box is ??green?? in colour.

Current Output:

The box isRedin colour.

The box is green in colour.

Desired Output:

The box is Red in colour.

The box is green in colour.

Here is what is almost working perfectly:

my $pattern_q  = '(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)';
my $pattern_qq = '(.*\s?)\?\?(\w.*)\?\?(.*)';

if ( $line =~ /$pattern_q/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
}

if ( $line =~ /$pattern_qq/ ) {
    print "\n" . $1 . $2 . $3 . "\n";

When I get a match against $pattern_qq - it handles everything correctly, except for the \n at the end, which I can live with.

When I get a match against $pattern_q - It removes the spaces between the three groups, which I want to retain.

Body:
As you said, your code is "almost working perfectly": it is very close to doing exactly what you want.

You can make it do exactly what you want by moving two parentheses in your first pattern to include the [^\?] pattern match in the capture groups.  This will capture the spaces on either side of ?Red? in your sample input.

So

'(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)'

becomes

'(.*\s?[^\?])\?(\w.*)\?([^\?].*)'


问:
Compare SharePoint list forms and Access web apps in SharePoint Office 365
Someone please provide pros and cons,a comparison between SharePoint list and Access web apps since both for the purpose of data collection?</p>

答:
This is a little all over the place since there was 2 different versions of Access Web Applications.  With that said, it is pretty much a moot point now that Access Web Apps have been deprecated:
https://support.office.com/en-us/article/Access-Services-in-SharePoint-Roadmap-497fd86b-e982-43c4-8318-81e6d3e711e8?ui=en-US&rs=en-US&ad=US

While support will last a lot longer in the on premises version of SharePoint I don't think anyone would advise you to start new work using that technology.


问:
C++ simple brute force project password input method
I am trying to create a simple C++ brute forcing program to crack small passwords-maybe like 3-4 characters long, (as a science fair project) just to show people how it works, i.e. my topic is mainly about cyber security and data breach vulnerability and stuff.

So I got the brute forcing part covered, but what I want to change is that instead of asking users to enter their password within my program itself, I was wondering if it was possible to make a, say, an HTML page with a login screen, and the entered password is then saved to a txt file which I can then open from my program for the brute forcing part.

What I am trying to say is that most people trying this out wont be so convinced entering passwords into an output box. They might wonder if I had just printed out the password they entered. I saw other people's programs but all they did was cin>>password and then started the brute forcing part. The user does not know if his password was cracked or the programmer just did cout<< password.

So it would help me a lot by letting me know of methods in which I can achieve this(not just with HTML, anything is fine, as long as its not an output box).

Sorry for the long question! Just wanted to make sure I covered all the info.
Please help me!!!
P.S: I'm just a student (1 and a half years into C++ :)), so please try to keep it as simple as you can. Thanks in advance!!

答: I would simply print out as much internal information in the terminal/outputbox as possible. This way, people get a better understanding of the inner workings of your program. For example, you could print out every password that your program tried. On top of that, show your sourcecode to the people who are also interested in that.</p>


问:
Slow GCC compilation on codeblocks
I always used codeblocks to program in C, now that I have a more powerful computer processing and memory, it's taking like 3~4 seconds to compile and show in the screen a simple console application written

 Hello World!.

Anyone have any idea why is that and how to fix it then go back to normal ? Thanks !

答:
Most of the time it is caused by your Anti-Virus.
Try going to your anti-virus settings and find "exclusions" or something similar.
Then exclude CodeBlocks, turn off any scanning or checking for it.

I use Kaspersky Anti-virus and I had to exlude CodeBlocks, gcc.exe and g++.exe (in the MinGW\bin folder).
The compile time went from 6-7 seconds to almost instant.
Hope that helped!

Title: Slow GCC compilation on codeblocks


问:
How to allow silverlight to read any file on the file system, not just my documents?
I've noticed by default, Silverlight 4 applications only have read access to my documents.

Is there anyway to trust a silverlight application so that it can open a file from any location on the file system.

I can't expect my users to first have to copy files into the my documents folder before upload, is there a way to fully trust a particular silver light app?

答:
Directly no. Silverlight doesn't provide it's own API to access file system outside My Documents. But you can always use COM in elevated trust applications to access any file in the system.

```<code>    dynamic Fso = AutomationFactory.CreateObject("Scripting.FileSystemObject");
    fso.CreateFolder("D:\\SilverFolder");
</code>```

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.automation.automationfactory(VS.95).aspx
http://msdn.microsoft.com/en-us/library/ee721083(VS.96).aspx

Body:
Directly no. Silverlight doesn't provide it's own API to access file system outside My Documents. But you can always use COM in elevated trust applications to access any file in the system.

    dynamic Fso = AutomationFactory.CreateObject("Scripting.FileSystemObject");
    fso.CreateFolder("D:\\SilverFolder");

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.automation.automationfactory(VS.95).aspx
http://msdn.microsoft.com/en-us/library/ee721083(VS.96).aspx


问:
Accessing Variable inside Inner Class
I have a listener and I want to access variable outside the listener method. But even after initializing the variable globally its showing "0" outside scope.

Can anyone explain the reason

```<code>public class MapsActivity{
   double origin_lat;
   //
   @Override
   public void onMapReady(GoogleMap googleMap) {
       //
       srcLat.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double value = (double) dataSnapshot.getValue();
            origin_lat=value;  -- > value shows here
            Log.d("SourceLatitude",Double.toString(value));

        }
       });
   Log.d("OutsideScope",Double.toString(origin_lat)); -- > shows "0"
   }
 }
</code>```

答:
Get yourself familiar with intents. Intents are something very basic in android applications.
Here is the docu: Android Docu

You would then send an intent to your activity.
In the activity you woul register a receiver, that uses the value of the intent.

Title: Accessing Variable inside Inner Class

Body:
I have a listener and I want to access variable outside the listener method. But even after initializing the variable globally its showing "0" outside scope.

Can anyone explain the reason

public class MapsActivity{
   double origin_lat;
   //
   @Override
   public void onMapReady(GoogleMap googleMap) {
       //
       srcLat.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double value = (double) dataSnapshot.getValue();
            origin_lat=value;  -- > value shows here
            Log.d("SourceLatitude",Double.toString(value));

        }
       });
   Log.d("OutsideScope",Double.toString(origin_lat)); -- > shows "0"
   }
 }


问:
How to start a session, and then retrieve the session variable?
First and foremost, I have looked throughout the site and haven't been able to find a solution that works for my program.

Saying this, I am trying to create an authentication page that starts a session, and will save a username from a login page as a session variable. Then, I want my thrid page to retrieve the username session variable.

This is my Form:

```<code><html>
<head>
<title>Form Test</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<h1 align="center">Log in with your username and</h1>
<form class="form-horizontal" method="POST" action="formauth.php">
 <div class="form-group">
          <div class="control-label col-sm-3">
            <label for="card">Username:</label>
          </div>
          <div class="col-sm-5">
            <input type="text" name="username" placeholder="enter username here">
          </div>
        </div>
        <div class="form-group">
 <div class="form-group">
          <div class="control-label col-sm-3">
            <label for="card">Password:</label>
          </div>
          <div class="col-sm-5">
            <input type="text" name="password" placeholder="enter password here">
          </div>
        </div>
        <div class="form-group">
          <div class="control-label col-sm-3">
 <div name="buttons" class="col-sm-offset-3">
          <button type="submit" class="btn btn-primary">Submit</button>
 </div>
</body>
</html>
</code>```

Here is my authentication page. For some reason, I can't get this to save the username that is input into the form as a session variable.

```<code><?php
  session_start();
  $_SESSION['username'] =$user_name;
  if (isset($_POST['username']) &&
      isset($_POST['password']))
  {
    $user = $_POST['username'];
    $pwd = $_POST['password'];
    require_once "login.php";
    $conn = new mysqli($hn, $un, $pwd, $db);
    if ($conn->connect_error) die($conn->connect_error);
    $query = "Select Password from Users where Username = '$user'";
    $result = $conn->query($query);
    if (!$result) {
        $result->close();
        $conn->close();
        header('Location: http://localhost/FormAuth/loginForm.html');

    }
    else {
        $rows = $result->num_rows;
        $result->data_seek(0);
        $p=$result->fetch_assoc()['password'];
        if ($p == $password) {
            header("Location: http://localhost/FormAuth/afterlogin.php");
        }
        else {
            $result->close();
            $conn->close();
            $result->close();
            $conn->close();
            header('Location: http://localhost/loginForm.html');
        }
    }
    $result->close();
    $conn->close();

  }
  else
  {
    $result->close();
    $conn->close();
    header('Location: http://localhost/loginForm.html');
  }
?>
</code>```

Now for my third page, I can't retrieve the username session variable.

```<code>session_start();
if (!isset($_SESSION['username'])) {
echo "Username is: ".$_user_name['username'] . "<br>";
echo "Test, I made it here!";
}else{
echo "You not logged in.";
}

?>
<html>
<head>
</head>
<body>
</body>
</html>
</code>```

This results in:

```<code>Username is:
Test, I made it here!
</code>```

答:
Your problem comes from this line :

```<code><?php
    session_start();
    $_SESSION['username'] = $user_name;

    if (isset($_POST['username']) &&
        isset($_POST['password']))
    {
        $user = $_POST['username'];
</code>```

Do this one instead:

```<code><?php
    session_start();

    if (isset($_POST['username']) && isset($_POST['password'])) {
        $user = $_POST['username'];
        $_SESSION['username'] =  $user;
</code>```

EDIT: The third page:

```<code>session_start();

if (isset($_SESSION['username'])) {
    echo "Username is: ".$_SESSION['username'] . "<br>";
    echo "Test, I made it here!";
} else {
    echo "You not logged in.";
}
?>
</code>```

Good luck.

Body:
First and foremost, I have looked throughout the site and haven't been able to find a solution that works for my program.

Saying this, I am trying to create an authentication page that starts a session, and will save a username from a login page as a session variable. Then, I want my thrid page to retrieve the username session variable.

This is my Form:

<title>Form Test</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Log in with your username and

<form class="form-horizontal" method="POST" action="formauth.php">

            Username:

            <input type="text" name="username" placeholder="enter username here">

            Password:

            <input type="text" name="password" placeholder="enter password here">

          <button type="submit" class="btn btn-primary">Submit</button>

Here is my authentication page. For some reason, I can't get this to save the username that is input into the form as a session variable.

<?php
  session_start();
  $_SESSION['username'] =$user_name;
  if (isset($_POST['username']) &&
      isset($_POST['password']))
  {
    $user = $_POST['username'];
    $pwd = $_POST['password'];
    require_once "login.php";
    $conn = new mysqli($hn, $un, $pwd, $db);
    if ($conn->connect_error) die($conn->connect_error);
    $query = "Select Password from Users where Username = '$user'";
    $result = $conn->query($query);
    if (!$result) {
        $result->close();
        $conn->close();
        header('Location: http://localhost/FormAuth/loginForm.html');

    }
    else {
        $rows = $result->num_rows;
        $result->data_seek(0);
        $p=$result->fetch_assoc()['password'];
        if ($p == $password) {
            header("Location: http://localhost/FormAuth/afterlogin.php");
        }
        else {
            $result->close();
            $conn->close();
            $result->close();
            $conn->close();
            header('Location: http://localhost/loginForm.html');
        }
    }
    $result->close();
    $conn->close();

  }
  else
  {
    $result->close();
    $conn->close();
    header('Location: http://localhost/loginForm.html');
  }
?>

Now for my third page, I can't retrieve the username session variable.

session_start();
if (!isset($_SESSION['username'])) {
echo "Username is: ".$_user_name['username'] . "
";
echo "Test, I made it here!";
}else{
echo "You not logged in.";
}

?>

This results in:

Username is:
Test, I made it here!

Body:
Your problem comes from this line :

<?php
    session_start();
    $_SESSION['username'] = $user_name;

    if (isset($_POST['username']) &&
        isset($_POST['password']))
    {
        $user = $_POST['username'];

Do this one instead:

<?php
    session_start();

    if (isset($_POST['username']) && isset($_POST['password'])) {
        $user = $_POST['username'];
        $_SESSION['username'] =  $user;

EDIT: The third page:

session_start();

if (isset($_SESSION['username'])) {
    echo "Username is: ".$_SESSION['username'] . "<br>";
    echo "Test, I made it here!";
} else {
    echo "You not logged in.";
}
?>

Good luck.

ContentLicense: CC BY-SA 4.0