问:
Neo4j scalability and indexing
An argument in favor of graph dbms with native storage over relational dbms made by neo4j (also in the neo4j graph databases book) is that "index-free adjacency" is the most efficient means of processing data in a graph (due to the 'clustering' of the data/nodes in a graph-based model).

Based on some benchmarking I've performed, where 3 nodes are sequentially connected (A->B<-C) and given the id of A I'm querying for C, the scalability is clearly O(n) when testing the same query on databases with 1M, 5M, 10M and 20M nodes - which is reasonable (with my limited understanding) considering I am not limiting my query to 1 node only hence all nodes need to be checked for matching. HOWEVER, when I index the queried node property, the execution time for the same query, is relatively constant.

Figure shows execution time by database node size before and after indexing. Orange plot is O(N) reference line, while the blue plot is the observed execution times.

Based on these results I'm trying to figure out where the advantage of index-free adjacency comes in. Is this advantageous when querying with a limit of 1 for deep(er) links? E.g. depth of 4 in A->B->C->D->E, and querying for E given A. Because in this case we know that there is only one match for A (hence no need to brute force through all the other nodes not part of this sub-network).

As this is highly dependent on the query, I'm listing an example of the Cypher query below for reference (where I'm matching entity labeled node with id of 1, and returning the associated node (B in the above example) and the secondary-linked node (C in the above example)):

```<code>MATCH (:entity{id:1})-[:LINK]->(result_assoc:assoc)<-[:LINK]-(result_entity:entity) RETURN result_entity, result_assoc
</code>```

UPDATE / ADDITIONAL INFORMATION

This source states: "The key message of index-free adjacency is, that the complexity to traverse the whole graph is O(n), where n is the number of nodes. In contrast, using any index will have complexity O(n log n).". This statement explains the O(n) results before indexing. I guess the O(1) performance after indexing is identical to a hash list performance(?). Not sure why using any other index the complexity is O(n log n) if even using a hash list the worst case is O(n).

答:
From my understanding, the index-free aspect is only pertinent for adjacent nodes (that's why it's called index-free adjacency). What your plots are demonstrating, is that when you find A, the additional time to find C is negligible, and the question of whether to use an index or not, is only to find the initial queried node A.

To find A without an index it takes O(n), because it has to scan through all the nodes in the database, but with an index, it's effectively like a hashlist, and  takes O(1) (no clue why the book says O(n log n) either).

Beyond that, finding the adjacent nodes are not that hard for Neo4j, because they are linked to A, whereas in RM the linkage is not as explicit - thus a join, which is expensive, and then scan/filter is required. So to truly see the advantage, one should compare the performance of graph DBs and RM DBs, by varying the depth of the relations/links. It would also be interesting to see how a query would perform when the neighbours of the entity nodes are increased (ie., the graph becomes denser) - does Neo4j rely on the graphs never being too dense? Otherwise the problem of looking through the neighbours to find the right one repeats itself.

Title: Neo4j scalability and indexing

Body:
An argument in favor of graph dbms with native storage over relational dbms made by neo4j (also in the neo4j graph databases book) is that "index-free adjacency" is the most efficient means of processing data in a graph (due to the 'clustering' of the data/nodes in a graph-based model).

Based on some benchmarking I've performed, where 3 nodes are sequentially connected (A->B<-C) and given the id of A I'm querying for C, the scalability is clearly O(n) when testing the same query on databases with 1M, 5M, 10M and 20M nodes - which is reasonable (with my limited understanding) considering I am not limiting my query to 1 node only hence all nodes need to be checked for matching. HOWEVER, when I index the queried node property, the execution time for the same query, is relatively constant.

Figure shows execution time by database node size before and after indexing. Orange plot is O(N) reference line, while the blue plot is the observed execution times.

Based on these results I'm trying to figure out where the advantage of index-free adjacency comes in. Is this advantageous when querying with a limit of 1 for deep(er) links? E.g. depth of 4 in A->B->C->D->E, and querying for E given A. Because in this case we know that there is only one match for A (hence no need to brute force through all the other nodes not part of this sub-network).

As this is highly dependent on the query, I'm listing an example of the Cypher query below for reference (where I'm matching entity labeled node with id of 1, and returning the associated node (B in the above example) and the secondary-linked node (C in the above example)):

MATCH (:entity{id:1})-[:LINK]->(result_assoc:assoc)<-[:LINK]-(result_entity:entity) RETURN result_entity, result_assoc

UPDATE / ADDITIONAL INFORMATION

This source states: "The key message of index-free adjacency is, that the complexity to traverse the whole graph is O(n), where n is the number of nodes. In contrast, using any index will have complexity O(n log n).". This statement explains the O(n) results before indexing. I guess the O(1) performance after indexing is identical to a hash list performance(?). Not sure why using any other index the complexity is O(n log n) if even using a hash list the worst case is O(n).


来源: stackexchange

问:
getting the whole json data instead of paricular string
I'm unable to get data in specific string description in my JSON. Instead of that I'm getting whole JSON data in my webview when clicked on listitem.

JSON file

```<code>{
"status": "ok",
"source": "techcrunch",
"sortBy": "top",
-"articles": [
-{
"author": "Devin Coldewey",
"title": "A mesh network spontaneously erupts in the US and helps connect Puerto Rico",
"description": "When goTenna put out their Mesh device earlier this year, I thought the off-grid gadgets would be great for an emergency kit or back-country hike. But it..",
"url": "https://techcrunch.com/2017/11/14/a-mesh-network-spontaneously-erupts-in-the-us-and-helps-connect-puerto-rico/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/11/gotennapr.png",
"publishedAt": "2017-11-14T18:41:28Z"
},
</code>```

Current code:

```<code>package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);

    }

}
</code>```

this is the main activity
    package com.example.murarilal.volley;

```<code>import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);

            }
        });

    }

    public void home()
    {

        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {

                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);

                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        queue.add(request);
    }

    }
</code>```

答:
Change this :</p>

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Hero hero = heroList.get(i);
                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",hero.getDescription());
                startActivity(intent);

            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm unable to get data in specific string description in my JSON. Instead of that I'm getting whole JSON data in my webview when clicked on listitem.

JSON file

{
"status": "ok",
"source": "techcrunch",
"sortBy": "top",
-"articles": [
-{
"author": "Devin Coldewey",
"title": "A mesh network spontaneously erupts in the US and helps connect Puerto Rico",
"description": "When goTenna put out their Mesh device earlier this year, I thought the off-grid gadgets would be great for an emergency kit or back-country hike. But it..",
"url": "https://techcrunch.com/2017/11/14/a-mesh-network-spontaneously-erupts-in-the-us-and-helps-connect-puerto-rico/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/11/gotennapr.png",
"publishedAt": "2017-11-14T18:41:28Z"
},

Current code:

package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);

    }

}

this is the main activity
    package com.example.murarilal.volley;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);

            }
        });

    }

    public void home()
    {

        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {

                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);

                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        queue.add(request);
    }

    }

Body:
Change this :

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Hero hero = heroList.get(i);
                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",hero.getDescription());
                startActivity(intent);

            }
        });


问:
gnutls_handshake() failure only via jenkins
I have to interact with a GIT repository (bitbucket).
If I try any clone/push/pull command via the bash it works fine.

Anyway, if I try to set my clone uri in jenkins I get:

```<code>fatal: unable to access 'https://myuser@bitbucket.org/myrepo.git/': gnutls_handshake() failed: Error in the push function.
</code>```

Why?

答:
Jenkins is using GnuTLS to handle the TLS portion of the communication with Bitbucket (that is, the "S" in "HTTPS"). In this case, something is keeping GnuTLS from establishing the TLS session appropriately. There isn't really enough information here to say what that something is, but there are a couple things you could try:

Update GnuTLS and/or cURL to a newer version

Use a cURL client compiled against OpenSSL

Use SSH

Body:
I have to interact with a GIT repository (bitbucket).
If I try any clone/push/pull command via the bash it works fine.

Anyway, if I try to set my clone uri in jenkins I get:

fatal: unable to access 'https://myuser@bitbucket.org/myrepo.git/': gnutls_handshake() failed: Error in the push function.

Why?


问:
InterlockedCompareExchange@12 could not be located in DLL SDL2_ttf.dll
I have been having this issue for a little while now but i need to fix it. I am working on a Frogger game using SDL2. To make the score board i am trying to use SDL2_ttf. However i run into this error everytime i try to Initialize SDL_ttf using TTF_Init();

Here is the error i get:

Now i have already looked at the other postings that are similar to this and most suggest that i move the DLL files into the debug folder(Bin\Debug) of my program. This has not worked for me. I have tried re downloading SDL2_ttf.dll from Here.

Im not sure exactly what is causing this error but here are some other screenshots that might prove helpful.

I am running Windows 8.1 and i am using Code::Blocks as the IDE.

I hope someone out there might be able to help me.

If you need any additional information I will happily provide it.

Thanks,
Nathan

答: Put all .dll files into Debug directory, if doesn't work, put in  project folder.</p>


问:
How to async bundles through angular CLI JSON and angular CLI JSON info
Two Angular 2 angular-cli.json questions here:

after running 'ng build --prod' I can go into my index.html file in the newly created dist folder and add the 'async' attribute to the bundled script tags to keep them from being blocking. this helps with website speed but sporadically crashes the site. is there an option in the angular-cli.json that would add this for me during the build in a better way?

i ran my site through google's test my website and the only thing i have left to fix is Eliminate render-blocking JavaScript and CSS in above-the-fold content

below is a the more specific result i get from https://developers.google.com/speed/pagespeed/insights/

Eliminate render-blocking JavaScript and CSS in above-the-fold content

Your page has 4 blocking script resources and 1 blocking CSS
  resources. This causes a delay in rendering your page. None of the
  above-the-fold content on your page could be rendered without waiting
  for the following resources to load. Try to defer or asynchronously
  load blocking resources, or inline the critical portions of those
  resources directly in the HTML. Remove render-blocking JavaScript:

*****.com/inline.e93ce34d30ab58073e62.bundle.js
  *****.com/scripts.68b893062974958fa7b3.bundle.js
  *****.com/vendor.4f05ee5669648be9602e.bundle.js
  *****.com/main.2d50b916b073e7fba148.bundle.js
  Optimize CSS
  Delivery of the following:
  *****.com/styles.c9d2a891e3814f5a5ff6.bundle.css

Where is a resource for explaining every detail of how the angular-cli.json works? I'm having trouble finding good information on it.

答:
You can achieve this by 'ejecting' your app and using HTML WEBPACK PLUGIN and its extension plugin script-ext-html-webpack-plugin:

run ng eject -prod. This command will expose webpack.config.js file in your root directory. (to 'uneject' your app again see my another answer)

Run npm install in order to install webpack loaders

Install two new plugins:

```<code>npm i html-webpack-plugin script-ext-html-webpack-plugin -D
</code>```

In your exposed webpack.config.js file edit plugin entry and add two plugins in this order:

```<code>plugins: [
  new HtmlWebpackPlugin(),
  new ScriptExtHtmlWebpackPlugin({
    defaultAttribute: 'async'
  })
]
</code>```

source

run npm run build since ng build no longer works on ejected apps.
After running above command, you should get all scripts set to async within dist directory.

Body:
You can achieve this by 'ejecting' your app and using HTML WEBPACK PLUGIN and its extension plugin script-ext-html-webpack-plugin:

run ng eject -prod. This command will expose webpack.config.js file in your root directory. (to 'uneject' your app again see my another answer)

Run npm install in order to install webpack loaders

Install two new plugins:

npm i html-webpack-plugin script-ext-html-webpack-plugin -D

In your exposed webpack.config.js file edit plugin entry and add two plugins in this order:

plugins: [
  new HtmlWebpackPlugin(),
  new ScriptExtHtmlWebpackPlugin({
    defaultAttribute: 'async'
  })
]

source

run npm run build since ng build no longer works on ejected apps.
After running above command, you should get all scripts set to async within dist directory.


问:
Enabling Internet Connection Through Proxy in Android in Windows
How to Enable Internet Connection Through Proxy in Android in Windows?</p>

答: Give your Android device a static IP. Ensure both the Windows computer and the Android device are on the same subnet. Set the IP of the android device as the gateway for the Lan connection on the Windows computer.</p>

ContentLicense: CC BY-SA 2.5


问:
Spring 3.1 WebApplicationInitializer & Embedded Jetty 8 AnnotationConfiguration
I'm trying to create a simple webapp without any XML configuration using Spring 3.1 and an embedded Jetty 8 server.

However, I'm struggling to get Jetty to recognise my implementaton of the Spring WebApplicationInitializer interface.

Project structure:

```<code>src
 +- main
     +- java
     |   +- JettyServer.java
     |   +- Initializer.java
     |
     +- webapp
         +- web.xml (objective is to remove this - see below).
</code>```

The Initializer class above is a simple implementation of WebApplicationInitializer:

```<code>import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.WebApplicationInitializer;

public class Initializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("onStartup");
    }
}
</code>```

Likewise JettyServer is a simple implementation of an embedded Jetty server:

```<code>import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyServer {

    public static void main(String[] args) throws Exception {

        Server server = new Server(8080);

        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setResourceBase("src/main/webapp");
        webAppContext.setContextPath("/");
        webAppContext.setConfigurations(new Configuration[] { new AnnotationConfiguration() });
        webAppContext.setParentLoaderPriority(true);

        server.setHandler(webAppContext);
        server.start();
        server.join();
    }
}
</code>```

My understanding is that on startup Jetty will use AnnotationConfiguration to scan for
 annotated implementations of ServletContainerInitializer; it should find Initializer and wire it in...

However, when I start the Jetty server (from within Eclipse) I see the following on the command-line:

```<code>2012-11-04 16:59:04.552:INFO:oejs.Server:jetty-8.1.7.v20120910
2012-11-04 16:59:05.046:INFO:/:No Spring WebApplicationInitializer types detected on classpath
2012-11-04 16:59:05.046:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/Users/duncan/Coding/spring-mvc-embedded-jetty-test/src/main/webapp/}
2012-11-04 16:59:05.117:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080
</code>```

The important bit is this:

```<code>No Spring WebApplicationInitializer types detected on classpath
</code>```

Note that src/main/java is defined as a source folder in Eclipse, so should be on the classpath. Also note that the Dynamic Web Module Facet is set to 3.0.

I'm sure there's a simple explanation, but I'm struggling to see the wood for the trees! I suspect the key is with the following line:

```<code>...
webAppContext.setResourceBase("src/main/webapp");
...
</code>```

This makes sense with a 2.5 servlet using web.xml (see below), but what should it be when using AnnotationConfiguration?

NB: Everything fires up correctly if I change the Configurations to the following:

```<code>...
webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration() });
...
</code>```

In this case it finds the web.xml under src/main/webapp and uses it to wire the servlet using DispatcherServlet and AnnotationConfigWebApplicationContext in the usual way (completely bypassing the WebApplicationInitializer implementation above).

This feels very much like a classpath problem, but I'm struggling to understand quite how Jetty associates itself with implementations of WebApplicationInitializer  - any suggestions would be most appreciated!

For info, I'm using the following:

Spring 3.1.1
  Jetty 8.1.7
  STS 3.1.0

答:
did a simple maven project to demonstrate how it can be done cleanly.

```<code>    public class Console {
    public static void main(String[] args) {
        try {
            Server server = new Server(8080);

            //Set a handler to handle requests.
            server.setHandler(getWebAppContext());

            //starts to listen at 0.0.0.0:8080
            server.start();
            server.join();
        } catch (Exception e) {
            log.error("server exited with exception", e);
        }
    }

    private static WebAppContext getWebAppContext() {
        final WebAppContext webAppContext = new WebAppContext();

        //route all requests via this web-app.
        webAppContext.setContextPath("/");

        /*
         * point to location where the jar into which this class gets packaged into resides.
         * this could very well be the target directory in a maven development build.
         */
        webAppContext.setResourceBase("directory_where_the_application_jar_exists");

        //no web inf for us - so let the scanning know about location of our libraries / classes.
        webAppContext.getMetaData().setWebInfClassesDirs(Arrays.asList(webAppContext.getBaseResource()));

        //Scan for annotations (servlet 3+)
        final AnnotationConfiguration configuration = new AnnotationConfiguration();
        webAppContext.setConfigurations(new Configuration[]{configuration});

        return webAppContext;
    }
}
</code>```

and that's all - the spring WebApplicationInitializer that you use will get detected without explicitly letting jetty server know about the existence of such an app initializer.

Body:
I'm trying to create a simple webapp without any XML configuration using Spring 3.1 and an embedded Jetty 8 server.

However, I'm struggling to get Jetty to recognise my implementaton of the Spring WebApplicationInitializer interface.

Project structure:

src
 +- main
     +- java
     |   +- JettyServer.java
     |   +- Initializer.java
     |
     +- webapp
         +- web.xml (objective is to remove this - see below).

The Initializer class above is a simple implementation of WebApplicationInitializer:

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.WebApplicationInitializer;

public class Initializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("onStartup");
    }
}

Likewise JettyServer is a simple implementation of an embedded Jetty server:

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyServer {

    public static void main(String[] args) throws Exception {

        Server server = new Server(8080);

        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setResourceBase("src/main/webapp");
        webAppContext.setContextPath("/");
        webAppContext.setConfigurations(new Configuration[] { new AnnotationConfiguration() });
        webAppContext.setParentLoaderPriority(true);

        server.setHandler(webAppContext);
        server.start();
        server.join();
    }
}

My understanding is that on startup Jetty will use AnnotationConfiguration to scan for
 annotated implementations of ServletContainerInitializer; it should find Initializer and wire it in...

However, when I start the Jetty server (from within Eclipse) I see the following on the command-line:

2012-11-04 16:59:04.552:INFO:oejs.Server:jetty-8.1.7.v20120910
2012-11-04 16:59:05.046:INFO:/:No Spring WebApplicationInitializer types detected on classpath
2012-11-04 16:59:05.046:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/Users/duncan/Coding/spring-mvc-embedded-jetty-test/src/main/webapp/}
2012-11-04 16:59:05.117:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080

The important bit is this:

No Spring WebApplicationInitializer types detected on classpath

Note that src/main/java is defined as a source folder in Eclipse, so should be on the classpath. Also note that the Dynamic Web Module Facet is set to 3.0.

I'm sure there's a simple explanation, but I'm struggling to see the wood for the trees! I suspect the key is with the following line:

...
webAppContext.setResourceBase("src/main/webapp");
...

This makes sense with a 2.5 servlet using web.xml (see below), but what should it be when using AnnotationConfiguration?

NB: Everything fires up correctly if I change the Configurations to the following:

...
webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration() });
...

In this case it finds the web.xml under src/main/webapp and uses it to wire the servlet using DispatcherServlet and AnnotationConfigWebApplicationContext in the usual way (completely bypassing the WebApplicationInitializer implementation above).

This feels very much like a classpath problem, but I'm struggling to understand quite how Jetty associates itself with implementations of WebApplicationInitializer  - any suggestions would be most appreciated!

For info, I'm using the following:

Spring 3.1.1
  Jetty 8.1.7
  STS 3.1.0

Body:
did a simple maven project to demonstrate how it can be done cleanly.

    public class Console {
    public static void main(String[] args) {
        try {
            Server server = new Server(8080);

            //Set a handler to handle requests.
            server.setHandler(getWebAppContext());

            //starts to listen at 0.0.0.0:8080
            server.start();
            server.join();
        } catch (Exception e) {
            log.error("server exited with exception", e);
        }
    }

    private static WebAppContext getWebAppContext() {
        final WebAppContext webAppContext = new WebAppContext();

        //route all requests via this web-app.
        webAppContext.setContextPath("/");

        /*
         * point to location where the jar into which this class gets packaged into resides.
         * this could very well be the target directory in a maven development build.
         */
        webAppContext.setResourceBase("directory_where_the_application_jar_exists");

        //no web inf for us - so let the scanning know about location of our libraries / classes.
        webAppContext.getMetaData().setWebInfClassesDirs(Arrays.asList(webAppContext.getBaseResource()));

        //Scan for annotations (servlet 3+)
        final AnnotationConfiguration configuration = new AnnotationConfiguration();
        webAppContext.setConfigurations(new Configuration[]{configuration});

        return webAppContext;
    }
}

and that's all - the spring WebApplicationInitializer that you use will get detected without explicitly letting jetty server know about the existence of such an app initializer.


问:
What does "VN" optional argument in contour function stand for?
The documentation for it is scarce (in contourc function):

VN is either a scalar denoting the number of lines to compute or a vector containing the values of the lines.  If only one value is wanted, set 'VN = [val, val]'; If VN is omitted it defaults to 10.

I've tried a few examples, it somehow affects the amount of lines around my contour.

Does it denote how smooth my function's slope will be?

What does VN stand for?

答:
Explanation

The contourc function does not change your data. It just plots them. Using the VN argument you can control how many contour lines are created between the highest and lowest point of the topography/function you are plotting.

If you set VN to a scalar integer value, it directly specifies the number of lines. VN=20 will create 20 levels between the highest and lowest point of your topography.

If you specify a vector of values you can exactly control at which values in your data the contour line is produced. You should take care that the values are in between min(data(:)) and max(data(:)). Otherwise the lines will not be drawn. Example VN=linspace(min(data(:)),max(data(:)),10) will create the exact same contour lines as not specifying VN.

Examples

To illustrate the effect of VN parameter I give some examples here. I use the contour function to directly plot the lines instead of just calculating them with contourcbut the effect is the same.

```<code>% Create coordinate grid
[x,y]=meshgrid(-2:0.1:2,-2:0.1:2);
% define a contour function
z=x.^2 + 2*y.^3;
% create a figure
figure();
% plot contour
contour(x,y,z);
% make axis iso scaled
axis equal
</code>```

Example 1

Using the contour command without VN argument produces the following result

```<code>contour(x,y,z);
</code>```

<img src="https://i.stack.imgur.com/O07LZ.png" alt="contour(x,y,z)">

Example 2: VN=50

Setting VN to 50
    contour(x,y,z,50);

<img src="https://i.stack.imgur.com/HHZBw.png" alt="contour(x,y,z,50)">

Example 3: VN= vector

Setting VN explicitly to the contour values vector is used here to limit contour lines to a rather narrow range of z data:

```<code>contour(x,y,z,linspace(-0.5,0.5,10));
</code>```

<img src="https://i.stack.imgur.com/c1vSg.png" alt="contour(x,y,z,linspace(-0.5,0.5,10))">

Body:
Explanation

The contourc function does not change your data. It just plots them. Using the VN argument you can control how many contour lines are created between the highest and lowest point of the topography/function you are plotting.

If you set VN to a scalar integer value, it directly specifies the number of lines. VN=20 will create 20 levels between the highest and lowest point of your topography.

If you specify a vector of values you can exactly control at which values in your data the contour line is produced. You should take care that the values are in between min(data(:)) and max(data(:)). Otherwise the lines will not be drawn. Example VN=linspace(min(data(:)),max(data(:)),10) will create the exact same contour lines as not specifying VN.

Examples

To illustrate the effect of VN parameter I give some examples here. I use the contour function to directly plot the lines instead of just calculating them with contourcbut the effect is the same.

% Create coordinate grid
[x,y]=meshgrid(-2:0.1:2,-2:0.1:2);
% define a contour function
z=x.^2 + 2*y.^3;
% create a figure
figure();
% plot contour
contour(x,y,z);
% make axis iso scaled
axis equal

Example 1

Using the contour command without VN argument produces the following result

contour(x,y,z);

Example 2: VN=50

Setting VN to 50
    contour(x,y,z,50);

Example 3: VN= vector

Setting VN explicitly to the contour values vector is used here to limit contour lines to a rather narrow range of z data:

contour(x,y,z,linspace(-0.5,0.5,10));


问:
Is there a way to check for an exception without using try/catch in Java?
I am fairly new to Java, I have some code that will act on an array in a loop, and the array changes every loop. Sometimes the code will throw a IndexOutOfBoundsException, when the array is too short. Is there a way for me to only execute code if there is no exception thrown? I know in Javascript I could do something like

```<code>var a = arr[index];
if (!a === null) { //do something }
</code>```

How would I achieve the same effect in Java?

答:
You can check before accessing the array item at a certain index</p>

```<code>if (arr != null && index >= 0 && index < arr.length) {
  // arr[i] exists
}
</code>```

Body:
I am fairly new to Java, I have some code that will act on an array in a loop, and the array changes every loop. Sometimes the code will throw a IndexOutOfBoundsException, when the array is too short. Is there a way for me to only execute code if there is no exception thrown? I know in Javascript I could do something like

var a = arr[index];
if (!a === null) { //do something }

How would I achieve the same effect in Java?

Body:
You can check before accessing the array item at a certain index

if (arr != null && index >= 0 && index < arr.length) {
  // arr[i] exists
}


问:
Add Two FirebaseListAdapter in one Recylerview?
Every User in my Firebase Database has created a group and were added in a Group :

```<code>(UserID)z.B(IOPFNV5423890)
      • groups
          • created
              • (groupID)
                    • name (name)
                    • timestamp (usw...)

          • added
              • (groupID)
                    • name (name)
                    • (.....)
</code>```

And now I have only one FirebaseListAdapter :

```<code>final ListUserFirebaseAdapter firebaseAdapter = new ListUserFirebaseAdapter(mFirebaseDatabaseReference.child("users/" + userModel.getId() + "/groups/created"), "", this);

 firebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                int friendlyMessageCount = firebaseAdapter.getItemCount();
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                if (lastVisiblePosition == -1 ||
                        (positionStart >= (friendlyMessageCount - 1) &&
                                lastVisiblePosition == (positionStart - 1))) {
                    rvListMessage.scrollToPosition(positionStart);
                }
            }
        });
</code>```

Here I set the adapter to the RecyclerView :

```<code>rvListMessage.setAdapter(firebaseAdapter);
</code>```

But With this Code I can only can set One Adapter but I want to set this Adapter also :

```<code> final ListUserFirebaseAdapter firebaseAdapter1 = new ListUserFirebaseAdapter(mFirebaseDatabaseReference.child("users/" + userModel.getId() + "/groups/added"), "", this);

   firebaseAdapter1.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                int friendlyMessageCount = firebaseAdapter1.getItemCount();
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                if (lastVisiblePosition == -1 ||
                        (positionStart >= (friendlyMessageCount - 1) &&
                                lastVisiblePosition == (positionStart - 1))) {
                }
            }
        });
</code>```

My Question now : How can i set the two adapter in one RecyclerView or how can i do it , that both childs (created ; added ) were displayed in one RecyclerView ?

答: You can add two RecyclerView in one Activity or Fragment, one about other, and display "created" in one and "added" in another</p>

Body:
Every User in my Firebase Database has created a group and were added in a Group :

(UserID)z.B(IOPFNV5423890)
      • groups
          • created
              • (groupID)
                    • name (name)
                    • timestamp (usw...)

          • added
              • (groupID)
                    • name (name)
                    • (.....)

And now I have only one FirebaseListAdapter :

final ListUserFirebaseAdapter firebaseAdapter = new ListUserFirebaseAdapter(mFirebaseDatabaseReference.child("users/" + userModel.getId() + "/groups/created"), "", this);

 firebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                int friendlyMessageCount = firebaseAdapter.getItemCount();
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                if (lastVisiblePosition == -1 ||
                        (positionStart >= (friendlyMessageCount - 1) &&
                                lastVisiblePosition == (positionStart - 1))) {
                    rvListMessage.scrollToPosition(positionStart);
                }
            }
        });

Here I set the adapter to the RecyclerView :

rvListMessage.setAdapter(firebaseAdapter);

But With this Code I can only can set One Adapter but I want to set this Adapter also :

 final ListUserFirebaseAdapter firebaseAdapter1 = new ListUserFirebaseAdapter(mFirebaseDatabaseReference.child("users/" + userModel.getId() + "/groups/added"), "", this);

   firebaseAdapter1.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                int friendlyMessageCount = firebaseAdapter1.getItemCount();
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                if (lastVisiblePosition == -1 ||
                        (positionStart >= (friendlyMessageCount - 1) &&
                                lastVisiblePosition == (positionStart - 1))) {
                }
            }
        });

My Question now : How can i set the two adapter in one RecyclerView or how can i do it , that both childs (created ; added ) were displayed in one RecyclerView ?


问:
Null(In C#) Vs Nothing(in vb.net)
How is C# NULL different from vb.net Nothing?

```<code>Console.WriteLine(Nothing = "") => True
</code>```

vs

```<code>Console.WriteLine(null==""); => False
</code>```

My understanding was that both null and Nothing are same. But above code clearly explains it is not.

What is the equivalent of C# null in VB.NET?

答:
The final version of the accepted answer correctly answers the question. However, Fabio added some useful information to his answer, but it has a number of incorrect information and concepts. So this answer is an attempt to merge the two answers in a more complete one with the correct information.

First of all, Nothing in VB is equivalent to null in C#, so your understanding of that is correct, at least partially (because that's only one use of the Nothing keyword). It's been reflected throughout the MSDN literature, although it's been fading recently and being replaced with the word null in many comments. Your confusion arises from the behavior and features of VB which differ from C# and programmers who are coming from other languages and not experienced in VB get confused by the results.

As stated in the accepted answer, the question is considered a string comparison by VB because one of the operands is a string. In string comparisons, VB treats Nothing the same as the empty string "" as per MSDN:

Numeric comparisons treat Nothing as 0. String comparisons treat Nothing as "" (an empty string).

Now, why is that happening in VB? It happens because VB uses the Nothing keyword for two different things (similar to how it uses the = operator for two different things, assignment and comparison). The first usage is equivalent to null in C# as I mentioned above. The second usage is equivalent to the default(T) operator in C#. Like with the = operator, VB knows which way to use Nothing depending on the context. Examples:

In this line, VB uses Nothing as null:

```<code>Console.WriteLine(s Is Nothing) //C#: (s == null)
</code>```

In these lines, VB uses Nothing as default(T) to assign the default value to the variable:

```<code>Dim s As String = Nothing //C#: string s = default(string);
Dim i As Integer = Nothing //C#: int i = default(int);
</code>```

Finally, when comparing variables of different types, both VB and C# convert one operand to match the type of the other operand. For example, if you compare double and integer values. Both VB and C# will return true for this line:

```<code>Console.WriteLine(5.0 = 5) //C#: (5.0 == 5)
</code>```

However, VB and C# differ in what types can be converted to what. Also, the empty string "" and null are treated the same in string comparisons in VB, but not in C#. This makes things easier in most cases, which is something known about VB in general. So you can easily test if your string has no value like this:

```<code>Console.WriteLine(s = Nothing)
Console.WriteLine(s = "")
</code>```

Both lines will return the same result because VB treats Nothing as "" for comparison. In C#, you cannot do that and you have to test for both like this:

```<code>Console.WriteLine(s == null && s == "")
</code>```

Obviously, VB is easier and shorter than C# in this case which is the most common one. However, this comes at the cost of losing some control. In the less common cases when you only want to test for null reference, C# become obviously better because you can still use the == operator:

```<code>Console.WriteLine(s == null)
</code>```

While in VB, you cannot use the = operator and you have to use another one, the Is operator:

```<code>Console.WriteLine(s Is Nothing)
</code>```

Also although VB is easier in the previous point, C# is clearer. That's why from code clarity perspective, this line can be used instead in both languages with the same result:

```<code>Console.WriteLine(string.IsNullOrEmpty(s))
</code>```

Title: Null(In C#) Vs Nothing(in vb.net)

Body:
How is C# NULL different from vb.net Nothing?

Console.WriteLine(Nothing = "") => True

vs

Console.WriteLine(null==""); => False

My understanding was that both null and Nothing are same. But above code clearly explains it is not.

What is the equivalent of C# null in VB.NET?

Body:
The final version of the accepted answer correctly answers the question. However, Fabio added some useful information to his answer, but it has a number of incorrect information and concepts. So this answer is an attempt to merge the two answers in a more complete one with the correct information.

First of all, Nothing in VB is equivalent to null in C#, so your understanding of that is correct, at least partially (because that's only one use of the Nothing keyword). It's been reflected throughout the MSDN literature, although it's been fading recently and being replaced with the word null in many comments. Your confusion arises from the behavior and features of VB which differ from C# and programmers who are coming from other languages and not experienced in VB get confused by the results.

As stated in the accepted answer, the question is considered a string comparison by VB because one of the operands is a string. In string comparisons, VB treats Nothing the same as the empty string "" as per MSDN:

Numeric comparisons treat Nothing as 0. String comparisons treat Nothing as "" (an empty string).

Now, why is that happening in VB? It happens because VB uses the Nothing keyword for two different things (similar to how it uses the = operator for two different things, assignment and comparison). The first usage is equivalent to null in C# as I mentioned above. The second usage is equivalent to the default(T) operator in C#. Like with the = operator, VB knows which way to use Nothing depending on the context. Examples:

In this line, VB uses Nothing as null:

Console.WriteLine(s Is Nothing) //C#: (s == null)

In these lines, VB uses Nothing as default(T) to assign the default value to the variable:

Dim s As String = Nothing //C#: string s = default(string);
Dim i As Integer = Nothing //C#: int i = default(int);

Finally, when comparing variables of different types, both VB and C# convert one operand to match the type of the other operand. For example, if you compare double and integer values. Both VB and C# will return true for this line:

Console.WriteLine(5.0 = 5) //C#: (5.0 == 5)

However, VB and C# differ in what types can be converted to what. Also, the empty string "" and null are treated the same in string comparisons in VB, but not in C#. This makes things easier in most cases, which is something known about VB in general. So you can easily test if your string has no value like this:

Console.WriteLine(s = Nothing)
Console.WriteLine(s = "")

Both lines will return the same result because VB treats Nothing as "" for comparison. In C#, you cannot do that and you have to test for both like this:

Console.WriteLine(s == null && s == "")

Obviously, VB is easier and shorter than C# in this case which is the most common one. However, this comes at the cost of losing some control. In the less common cases when you only want to test for null reference, C# become obviously better because you can still use the == operator:

Console.WriteLine(s == null)

While in VB, you cannot use the = operator and you have to use another one, the Is operator:

Console.WriteLine(s Is Nothing)

Also although VB is easier in the previous point, C# is clearer. That's why from code clarity perspective, this line can be used instead in both languages with the same result:

Console.WriteLine(string.IsNullOrEmpty(s))


问:
Correctly disable AdMob ads
I am integrating AdMob into my app and I wonder how to disable Ads correctly. I want to give the user the ability to disable them. I don't want to get any problems with AdMob because of wrong impressions. Is this way correct or should I consider something?</p>

```<code>AdView ads = (AdView) findViewById(R.id.ad);
ads.setEnabled(false);
</code>```

答:
In your layout file (eg, main.xml) :

```<code><LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/adsContainer">

    <com.admob.android.ads.AdView
        android:id="@+id/admobAds"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:backgroundColor="#000000"
        app:primaryTextColor="#FFFFFF"
        app:secondaryTextColor="#CCCCCC">

</LinearLayout>
</code>```

Then in your code (eg, inside a "if" block)

```<code>(LinearLayout) adscontainer = (LinearLayout) findViewById(R.id.adsContainer);

View admobAds = (View) findViewById(R.id.admobAds);

adscontainer.removeView(admobAds);
</code>```

This will "permanently" (for the lifecycle of the app) remove the ads from the layou, which means that there will not be any ads requested.

Title: Correctly disable AdMob ads

Body:
I am integrating AdMob into my app and I wonder how to disable Ads correctly. I want to give the user the ability to disable them. I don't want to get any problems with AdMob because of wrong impressions. Is this way correct or should I consider something?

AdView ads = (AdView) findViewById(R.id.ad);
ads.setEnabled(false);

Body:
In your layout file (eg, main.xml) :

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/adsContainer">

    <com.admob.android.ads.AdView
        android:id="@+id/admobAds"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:backgroundColor="#000000"
        app:primaryTextColor="#FFFFFF"
        app:secondaryTextColor="#CCCCCC">

</LinearLayout>

Then in your code (eg, inside a "if" block)

(LinearLayout) adscontainer = (LinearLayout) findViewById(R.id.adsContainer);

View admobAds = (View) findViewById(R.id.admobAds);

adscontainer.removeView(admobAds);

This will "permanently" (for the lifecycle of the app) remove the ads from the layou, which means that there will not be any ads requested.


问:
How to decode a json with a variable property type
I have the following JSON:

```<code>{
    "items": [
        {
            "level": 1,
            "displayValue": "das",
            "dataValue": "das"
        },
        {
            "level": 2,
            "displayValue": "das",
            "dataValue": {
                "name": "some name",
                "scope": "some scope"
            }
        }
    ]
}
</code>```

And the following types:

```<code>type alias Item =
    { level: Int
    , displayValue: String
    , dataValue: DataValue
    }

type alias KeyValue =
    { name: String
    , scope: String
    }

type DataValue
    = Value String
    | Key KeyValue
</code>```

How would I write a decoder for the dataValue property since it can be of two completly different types?

答:
You can use oneOf:

import Json.Decode as JD

dataValueDecoder : JD.Decoder DataValue
dataValueDecoder =
    JD.oneOf
        [ JD.map Value JD.string
        , JD.map Key keyValueDecoder
        ]

keyValueDecoder : JD.Decoder KeyValue
keyValueDecoder =
    JD.map2 KeyValue
        (JD.field "name" JD.string)
        (JD.field "scope" JD.string)
```

Body:
I have the following JSON:

{
    "items": [
        {
            "level": 1,
            "displayValue": "das",
            "dataValue": "das"
        },
        {
            "level": 2,
            "displayValue": "das",
            "dataValue": {
                "name": "some name",
                "scope": "some scope"
            }
        }
    ]
}

And the following types:

type alias Item =
    { level: Int
    , displayValue: String
    , dataValue: DataValue
    }

type alias KeyValue =
    { name: String
    , scope: String
    }

type DataValue
    = Value String
    | Key KeyValue

How would I write a decoder for the dataValue property since it can be of two completly different types?


问:
How to apply a filter and mesh to a D3 Choropleth
I'm working with a variation of Bostock's Quantile Choropleth.

I've have successfully scaled the projection and integrated my own data. I am also currently filtering the json counties data to only include county ids starting with the state id of 48.

It all works perfectly, however, I still need to apply the .mesh function to combine the arcs between bordering counties. Otherwise, when I add a hover affect I get strangely uneven borders.

I tried replacing the data call with a datum(mesh) call instead (see the commented out line below) but it did not work.

Here is my working code:

```<code>function ready(error, us) {
  if (error) throw error;

    //define the feature of the states from the topojson file, then filter so only state 48 (texas) shows
  var states = topojson.feature(us, us.objects.states),
  state = states.features.filter(function(d) { return d.id === 48; })[0];

    //define the features for the counties and filter based on number (starting with 48)
  var counties = topojson.feature(us, us.objects.counties),
  mycounties = counties.features.filter(function(d) { if(d.id >= 48000 && d.id <=49000) return d.id; });

    //initiate the class for the state, and add an outline path
  svg.append("path")
      .datum(state)
      .attr("class", "outline")
      .attr("d", path);

    //initiate the g object for the counties
  svg.append("g")
      .attr("class", "counties")
    .selectAll("path")
    //.datum(topojson.mesh(us, us.objects.counties, function(a, b) { return a !== b; }))
    // ^I tried adding this to replace the following line, but it does not work
    .data(mycounties)
    .enter().append("path")
      .attr("fill", function(d) { return color(d.establishments = centralTexas.get(d.id)); })
      .attr("d", path)
    .append("title")
      .text(function(d) { var obj2 = jsonCounties[d.id]; if (typeof obj2 != "undefined") {return obj2.countyName + ": " + d.establishments + " Active Establishments";} });

}
</code>```

How should I be going about this?  Is it possible to do a more complicated filter query inside the .mesh function and totally eliminate the need for my

var counties = topojson.feature(us, us.objects.counties),   mycounties
  = counties.features.filter(function(d) { if(d.id >= 48000 && d.id <=49000) return d.id; });

code?

Or do I need to run the mesh function on that variable with a different syntax?

答:
Assuming I understand your ultimate goal is to get even borders of a hovered feature:

Using datum.append(mesh) won't append areas - a mesh "Returns the GeoJSON MultiLineString geometry object representing the mesh for the specified object in the given topology." API documentation. Also, using .append().datum() would append one feature - hover effects on individual counties would be lost - there are not data bound to features, just one datum bound to one feature. Lastly, the mesh can have odd fill patterns too (see this question). But, a mesh is unnecessary to get modified borders on hover that display as intended.

While the topojson removes identical arcs, every shared arc is represented at least twice in the geojson - but as they are identical they are overlain directly on top of each other. The layering is relative to the order in which the features are imported.

If a boundary is expanded on hover it may fall behind some (or all or none) of the neighboring features because of how the features are layered. This creates odd outline patterns by essentially clipping the feature's outline. This means that only some changes to a county/feature may be visible, depending on feature/element layering.

Try modifying the hover function with d3.select(this).raise() (new in v4) or use
node.parentNode.appendChild(node); (v3, where node is the DOM element, not the d3 selection), these will move a feature to the top of the svg (as though they were appended last) - which will allow you to show a feature with edge styling that is not partly covered by any other feature.

See this example using your referenced block (I've placed the state outlines in the same parent node so that raising the hovered county raises the edge above the state boundary too. On mouse out I lower the feature so that the state boundaries are unaffected.

Body:
I'm working with a variation of Bostock's Quantile Choropleth.

I've have successfully scaled the projection and integrated my own data. I am also currently filtering the json counties data to only include county ids starting with the state id of 48.

It all works perfectly, however, I still need to apply the .mesh function to combine the arcs between bordering counties. Otherwise, when I add a hover affect I get strangely uneven borders.

I tried replacing the data call with a datum(mesh) call instead (see the commented out line below) but it did not work.

Here is my working code:

function ready(error, us) {
  if (error) throw error;

    //define the feature of the states from the topojson file, then filter so only state 48 (texas) shows
  var states = topojson.feature(us, us.objects.states),
  state = states.features.filter(function(d) { return d.id === 48; })[0];

    //define the features for the counties and filter based on number (starting with 48)
  var counties = topojson.feature(us, us.objects.counties),
  mycounties = counties.features.filter(function(d) { if(d.id >= 48000 && d.id <=49000) return d.id; });

    //initiate the class for the state, and add an outline path
  svg.append("path")
      .datum(state)
      .attr("class", "outline")
      .attr("d", path);

    //initiate the g object for the counties
  svg.append("g")
      .attr("class", "counties")
    .selectAll("path")
    //.datum(topojson.mesh(us, us.objects.counties, function(a, b) { return a !== b; }))
    // ^I tried adding this to replace the following line, but it does not work
    .data(mycounties)
    .enter().append("path")
      .attr("fill", function(d) { return color(d.establishments = centralTexas.get(d.id)); })
      .attr("d", path)
    .append("title")
      .text(function(d) { var obj2 = jsonCounties[d.id]; if (typeof obj2 != "undefined") {return obj2.countyName + ": " + d.establishments + " Active Establishments";} });

}

How should I be going about this?  Is it possible to do a more complicated filter query inside the .mesh function and totally eliminate the need for my

var counties = topojson.feature(us, us.objects.counties),   mycounties
  = counties.features.filter(function(d) { if(d.id >= 48000 && d.id <=49000) return d.id; });

code?

Or do I need to run the mesh function on that variable with a different syntax?


问:
woocommerce shipping method with 3.0 api
Hi there, I'm trying to build a very simple plugin for woocommerce to show some information about delivery without taxes. The diference for the other methods is the extra HTML field.

I read a lot of the documentation but I think there is something miss on the configuration. The admin it seems working. But the method didn't appear on checkout screen. The code is below:

```<code><?php
if ( ! defined( 'WPINC' ) ) {
   die('security by preventing any direct access to your plugin file');
}
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {

function shipping_delivery_info() {

    if (!class_exists('shipping_delivery_info')) {

        class shipping_delivery_info extends WC_Shipping_Method {

            public function __construct( $instance_id = 0) {

                $this->id = 'shipping_delivery_info';
                $this->instance_id = absint( $instance_id );
                $this->method_title = __('Shipping Delivery Info', 'shipping_delivery_info');
                $this->method_description = __('A Woocommerce custom shipping method plugin, that shows ' .
                    'some shipping information to costumer, like free shipping but with HTML field.',
                    'shipping_delivery_info');
                $this->supports = array(
                    'shipping-zones',
                    'instance-settings',
                    'instance-settings-modal',
                );

                $this->init();
            }

             /**
              * Load the settings API
              */
             function init() {

                // Load the settings
                $this->init_form_fields();
                $this->init_settings();

                $this->enabled = $this->get_option( 'enabled' );
                $this->title   = $this->get_option( 'title' );
                $this->info   = $this->get_option( 'info' );

                add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
             }

             function init_form_fields() {
                $this->instance_form_fields = array(
                    'enabled' => array(
                        'title'         => __( 'Enable/Disable', 'shipping_delivery_info'),
                        'type'          => 'checkbox',
                        'label'         => __( 'Enable this shipping method', 'shipping_delivery_info'),
                        'default'       => 'yes',
                    ),
                    'title' => array(
                        'title' => __('Title', 'shipping_delivery_info'),
                        'type' => 'text',
                        'description' => __( 'The title to be displayed during checkout.', 'shipping_delivery_info' ),
                        'default' => __('Shipping Information', 'shipping_delivery_info'),
                    ),
                    'info' => array(
                        'title' => __('Information', 'shipping_delivery_info'),
                        'type' => 'text',
                        'description' => __( 'Information about delivery and its taxes.', 'shipping_delivery_info' ),
                        'default' => __('Insert here some HTML.'),
                    ),
                );
             }
        }
    }
}
add_action('woocommerce_shipping_init', 'shipping_delivery_info');

function add_shipping_delivery_info($methods)
{
    $methods['shipping_delivery_info'] = 'shipping_delivery_info';
    return $methods;
}
add_filter('woocommerce_shipping_methods', 'add_shipping_delivery_info');

function shipping_delivery_info_message($posted)
{
    $packages = WC()->shipping->get_packages();
    $chosen_methods = WC()->session->get('chosen_shipping_methods');
    if (is_array($chosen_methods) && in_array('shipping_delivery_info', $chosen_methods)) {
        foreach ($packages as $i => $package) {
            if ($chosen_methods[$i] != "shipping_delivery_info") {
                continue;
            }
            $shipping_delivery_info = new shipping_delivery_info();

            $message = $shipping_delivery_info->settings['info'];
            return $message;
            /*$messageType = "info";
            wc_add_notice($message, $messageType);*/
        }
    }
}

add_action('woocommerce_review_order_before_cart_contents', 'shipping_delivery_info_message', 10);
add_action('woocommerce_after_checkout_validation', 'shipping_delivery_info_message', 10);
}
</code>```

答:
You need to add the calculate_shipping function to your class

```<code>       /**
         * function calculate_shipping.
         *
         * @access public
         * @param mixed $package
         * @return void
         */
        public function calculate_shipping( $package = array() ) {
                $rate = array(
                   'id' => 'My Method id',
                   'label' => 'New method',
                   'cost' => 0,
                   'calc_tax' => 'per_item'
                 );
                $this->add_rate( $rate );

            }
        }
</code>```

Anyway, i think you don't need to add a new shipping method just to show some info at the cart, instead you can use these actions:

```<code>add_action( 'woocommerce_review_order_before_submit', 'add_tracking_notification', 12 );
add_action('woocommerce_proceed_to_checkout', 'add_tracking_notification');

function add_tracking_notification() {
        echo '<h5 style="margin-bottom:10px">This is a custom message</h5>';
}
</code>```

Body:
Hi there, I'm trying to build a very simple plugin for woocommerce to show some information about delivery without taxes. The diference for the other methods is the extra HTML field.

I read a lot of the documentation but I think there is something miss on the configuration. The admin it seems working. But the method didn't appear on checkout screen. The code is below:

<?php
if ( ! defined( 'WPINC' ) ) {
   die('security by preventing any direct access to your plugin file');
}
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {

function shipping_delivery_info() {

    if (!class_exists('shipping_delivery_info')) {

        class shipping_delivery_info extends WC_Shipping_Method {

            public function __construct( $instance_id = 0) {

                $this->id = 'shipping_delivery_info';
                $this->instance_id = absint( $instance_id );
                $this->method_title = __('Shipping Delivery Info', 'shipping_delivery_info');
                $this->method_description = __('A Woocommerce custom shipping method plugin, that shows ' .
                    'some shipping information to costumer, like free shipping but with HTML field.',
                    'shipping_delivery_info');
                $this->supports = array(
                    'shipping-zones',
                    'instance-settings',
                    'instance-settings-modal',
                );

                $this->init();
            }

             /**
              * Load the settings API
              */
             function init() {

                // Load the settings
                $this->init_form_fields();
                $this->init_settings();

                $this->enabled = $this->get_option( 'enabled' );
                $this->title   = $this->get_option( 'title' );
                $this->info   = $this->get_option( 'info' );

                add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
             }

             function init_form_fields() {
                $this->instance_form_fields = array(
                    'enabled' => array(
                        'title'         => __( 'Enable/Disable', 'shipping_delivery_info'),
                        'type'          => 'checkbox',
                        'label'         => __( 'Enable this shipping method', 'shipping_delivery_info'),
                        'default'       => 'yes',
                    ),
                    'title' => array(
                        'title' => __('Title', 'shipping_delivery_info'),
                        'type' => 'text',
                        'description' => __( 'The title to be displayed during checkout.', 'shipping_delivery_info' ),
                        'default' => __('Shipping Information', 'shipping_delivery_info'),
                    ),
                    'info' => array(
                        'title' => __('Information', 'shipping_delivery_info'),
                        'type' => 'text',
                        'description' => __( 'Information about delivery and its taxes.', 'shipping_delivery_info' ),
                        'default' => __('Insert here some HTML.'),
                    ),
                );
             }
        }
    }
}
add_action('woocommerce_shipping_init', 'shipping_delivery_info');

function add_shipping_delivery_info($methods)
{
    $methods['shipping_delivery_info'] = 'shipping_delivery_info';
    return $methods;
}
add_filter('woocommerce_shipping_methods', 'add_shipping_delivery_info');

function shipping_delivery_info_message($posted)
{
    $packages = WC()->shipping->get_packages();
    $chosen_methods = WC()->session->get('chosen_shipping_methods');
    if (is_array($chosen_methods) && in_array('shipping_delivery_info', $chosen_methods)) {
        foreach ($packages as $i => $package) {
            if ($chosen_methods[$i] != "shipping_delivery_info") {
                continue;
            }
            $shipping_delivery_info = new shipping_delivery_info();

            $message = $shipping_delivery_info->settings['info'];
            return $message;
            /*$messageType = "info";
            wc_add_notice($message, $messageType);*/
        }
    }
}

add_action('woocommerce_review_order_before_cart_contents', 'shipping_delivery_info_message', 10);
add_action('woocommerce_after_checkout_validation', 'shipping_delivery_info_message', 10);
}

Body:
You need to add the calculate_shipping function to your class

       /**
         * function calculate_shipping.
         *
         * @access public
         * @param mixed $package
         * @return void
         */
        public function calculate_shipping( $package = array() ) {
                $rate = array(
                   'id' => 'My Method id',
                   'label' => 'New method',
                   'cost' => 0,
                   'calc_tax' => 'per_item'
                 );
                $this->add_rate( $rate );

            }
        }

Anyway, i think you don't need to add a new shipping method just to show some info at the cart, instead you can use these actions:

add_action( 'woocommerce_review_order_before_submit', 'add_tracking_notification', 12 );
add_action('woocommerce_proceed_to_checkout', 'add_tracking_notification');

function add_tracking_notification() {
        echo '<h5 style="margin-bottom:10px">This is a custom message</h5>';
}


问:
How to toggle to no sort in angularjs for columns
```<code><a href="#/" ng-click="sortType = 'name'; sortReverse = !sortReverse">
        Project
        <span ng-show="sortType == 'name' && !sortReverse" class="fa fa-caret-down"></span>
        <span ng-show="sortType == 'name' && sortReverse" class="fa fa-caret-up"></span>
      </a>
</code>```

<p>The above column when clicked sorts in ascending and descending. I need to add no-sort as well to the above toggle click. </p>

答:
you need logic to detect a third state somehow:

```<code><a href="#/" ng-click="sortBy('name')">

function sortBy(prop) {
    if (sortType === prop) { // already sorted by this property
      if (!sortReverse) { // second click
         sortReverse = true;
      } else { // 3rd click
        sortType = null;
      }
    } else {
       // initial sort set for this type
       sortType = prop;
       sortReverse = false;
    }
}
</code>```

side note: too much logic in template is bad practice and leads to hard to maintain projects. Always minimize template logic in favor of code.

Body:
        Project

The above column when clicked sorts in ascending and descending. I need to add no-sort as well to the above toggle click.

Body:
you need logic to detect a third state somehow:

<a href="#/" ng-click="sortBy('name')">

function sortBy(prop) {
    if (sortType === prop) { // already sorted by this property
      if (!sortReverse) { // second click
         sortReverse = true;
      } else { // 3rd click
        sortType = null;
      }
    } else {
       // initial sort set for this type
       sortType = prop;
       sortReverse = false;
    }
}

side note: too much logic in template is bad practice and leads to hard to maintain projects. Always minimize template logic in favor of code.


问:
Is it possible to make this PHP code shorter?
I need a help with this code. How can I make it shorter ? I think How can I create an array with name for example errors a modify code without so many If statements. I still can't solve it. I'm a beginner in PHP.

```<code>$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
  $error1 = "fill in fname";
}
if (empty($_POST["lname"])) {
  $error2 = "fill in lname";
}
if (empty($_POST["street"])) {
  $error3 = "fill in street";
}
if (empty($_POST["city"])) {
  $error4 = "fill in city";
}
if (empty($_POST["postcode"])) {
  $error5 = "fill in postcode";
}
if (empty($_POST["country"])) {
  $error6 = "fill in country";
}
if (empty($_POST["email"])) {
  $error7 = "fill in email";
}
if (empty($_POST["phone"])) {
  $error8 = "fill in phone";
}
if (empty($_POST["fname"]) ||
    empty($_POST["lname"]) ||
    empty($_POST["street"]) ||
    empty($_POST["city"]) ||
    empty($_POST["postcode"]) ||
    empty($_POST["country"]) ||
    empty($_POST["email"]) ||
    empty($_POST["phone"])) {
} else {
  $form_items = $_POST;
    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml'))
    {
        $document->load("form_data.xml");
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    else
    {
        $xmlko = $document->createElement("xml");
        $document->appendChild($xmlko);
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
            $form = $document->createElement("form");
                $new_user = $document->createElement("user");
                foreach ($form_items as $ite => $val) {
                    $this_user = $document->createElement($ite, $val);
                    $new_user->appendChild($this_user);
                }
               $form->appendChild($new_user);
           $xmlko->appendChild($form);
    $document->save("form_data.xml");

  }
}

?>
</code>```

Here is HTML code. Everything is in one php file.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>form</title>
    <link rel="stylesheet" href="CSS/styly.css">
  </head>
  <body>
    <h1>FORM</h1>
    <form action="" method="post">
      <p>FName:</p>
      <input type="text" name="fname"/><span class="error"><?php echo $error1?></span>
      <p>LName:</p>
      <input type="text" name="lname"/><span class="error"><?php echo $error2?></span>
      <p>Street:</p>
      <input type="text" name="street"/><span class="error"><?php echo $error3?></span>
      <p>City:</p>
      <input type="text" name="city"/><span class="error"><?php echo $error4?></span>
      <p>Postcode:</p>
      <input type="text" name="postcode"/><span class="error"><?php echo $error5?></span>
      <p>Country:</p>
      <input type="text" name="country"/><span class="error"><?php echo $error6?></span>
      <p>E-mail:</p>
      <input type="text" name="email"/><span class="error"><?php echo $error7?></span>
      <p>Phone:</p>
      <input type="text" name="phone"/><span class="error"><?php echo $error8?></span>
      <input type="submit" value="SUBMIT"/>
    </form>

   <?php

      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml')) {
        $document->load("form_data.xml");
        $users = $document->getElementsByTagName("user");

        echo "<table>";

            echo '<tr>';
            foreach($users->item(0)->childNodes as $data) {
                echo '<th>'.$data->nodeName."</th>";
            }
            echo '</tr>';

            foreach($users as $user){
                echo '<tr>';
                foreach($user->childNodes as $data) {
                    echo '<td>'.$data->nodeValue."</td>";
                }
                echo '</tr>';
            }

        echo "</table>";
      }

   ?>

  </body>
</html>
</code>```

All data from html form are inserted into the table below the form.
Thanks in advance!

答:
How about this code?</p>

```<code>$requiredFields = ['fname', 'lname', 'street', 'city', 'postcode', 'country', 'email', 'phone'];

$errors = [];

foreach ($_POST as $key => $val) {
    if (!in_array($key, $requiredFields)) {
        continue;
    }

    $errors[$key] = 'fill in '.$key;
}

if (empty($errors)) {
    $form_items = $_POST;
    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml'))
    {
        $document->load("form_data.xml");
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    else
    {
        $xmlko = $document->createElement("xml");
        $document->appendChild($xmlko);
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
            $form = $document->createElement("form");
                $new_user = $document->createElement("user");
                foreach ($form_items as $ite => $val) {
                    $this_user = $document->createElement($ite, $val);
                    $new_user->appendChild($this_user);
                }
               $form->appendChild($new_user);
           $xmlko->appendChild($form);
    $document->save("form_data.xml");

  }
}
</code>```

Body:
I need a help with this code. How can I make it shorter ? I think How can I create an array with name for example errors a modify code without so many If statements. I still can't solve it. I'm a beginner in PHP.

$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
  $error1 = "fill in fname";
}
if (empty($_POST["lname"])) {
  $error2 = "fill in lname";
}
if (empty($_POST["street"])) {
  $error3 = "fill in street";
}
if (empty($_POST["city"])) {
  $error4 = "fill in city";
}
if (empty($_POST["postcode"])) {
  $error5 = "fill in postcode";
}
if (empty($_POST["country"])) {
  $error6 = "fill in country";
}
if (empty($_POST["email"])) {
  $error7 = "fill in email";
}
if (empty($_POST["phone"])) {
  $error8 = "fill in phone";
}
if (empty($_POST["fname"]) ||
    empty($_POST["lname"]) ||
    empty($_POST["street"]) ||
    empty($_POST["city"]) ||
    empty($_POST["postcode"]) ||
    empty($_POST["country"]) ||
    empty($_POST["email"]) ||
    empty($_POST["phone"])) {
} else {
  $form_items = $_POST;
    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml'))
    {
        $document->load("form_data.xml");
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    else
    {
        $xmlko = $document->createElement("xml");
        $document->appendChild($xmlko);
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
            $form = $document->createElement("form");
                $new_user = $document->createElement("user");
                foreach ($form_items as $ite => $val) {
                    $this_user = $document->createElement($ite, $val);
                    $new_user->appendChild($this_user);
                }
               $form->appendChild($new_user);
           $xmlko->appendChild($form);
    $document->save("form_data.xml");

  }
}

?>

Here is HTML code. Everything is in one php file.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>form</title>
    <link rel="stylesheet" href="CSS/styly.css">

FORM

    <form action="" method="post">

FName:

      <input type="text" name="fname"/><?php echo $error1?>

LName:

      <input type="text" name="lname"/><?php echo $error2?>

Street:

      <input type="text" name="street"/><?php echo $error3?>

City:

      <input type="text" name="city"/><?php echo $error4?>

Postcode:

      <input type="text" name="postcode"/><?php echo $error5?>

Country:

      <input type="text" name="country"/><?php echo $error6?>

E-mail:

      <input type="text" name="email"/><?php echo $error7?>

Phone:

      <input type="text" name="phone"/><?php echo $error8?>
      <input type="submit" value="SUBMIT"/>
    </form>

   <?php

      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml')) {
        $document->load("form_data.xml");
        $users = $document->getElementsByTagName("user");

        echo "
";

            echo '
';
            foreach($users->item(0)->childNodes as $data) {
                echo ''.$data->nodeName."	";
            }
            echo '
';

            foreach($users as $user){
                echo '
';
                foreach($user->childNodes as $data) {
                    echo ''.$data->nodeValue."	";
                }
                echo '
';
            }

        echo "
";
      }

   ?>

All data from html form are inserted into the table below the form.
Thanks in advance!

Body:
How about this code?

$requiredFields = ['fname', 'lname', 'street', 'city', 'postcode', 'country', 'email', 'phone'];

$errors = [];

foreach ($_POST as $key => $val) {
    if (!in_array($key, $requiredFields)) {
        continue;
    }

    $errors[$key] = 'fill in '.$key;
}

if (empty($errors)) {
    $form_items = $_POST;
    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml'))
    {
        $document->load("form_data.xml");
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    else
    {
        $xmlko = $document->createElement("xml");
        $document->appendChild($xmlko);
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
            $form = $document->createElement("form");
                $new_user = $document->createElement("user");
                foreach ($form_items as $ite => $val) {
                    $this_user = $document->createElement($ite, $val);
                    $new_user->appendChild($this_user);
                }
               $form->appendChild($new_user);
           $xmlko->appendChild($form);
    $document->save("form_data.xml");

  }
}


问:
Accurev SCM
Does anyone use Accurev for Source Control Management? We are switching (eventually) from StarTeam to Accurev.

My initial impression is that the GUI tool is severely lacking, however the underlying engine, and the branches as streams concept is incredible.

The biggest difficulty we are facing is assessing our own DIY tools that interfaced with starteam, and either replacing them with DIY new tools, or finding and purchasing appropriate replacements.

Additionally, is anyone using the AccuWork component for Issue management? Starteam had a very nice change request system, and AccuWork does not come close to matching it. We are evaluating either using Accuwork, or buying a 3rd party package such as JIRA.

Opinions?

答:
Accurev has some great concepts; but suffers from:

1) many many inconsistencies in the command-line interface.

2) many bugs and nuisances in the application/interface. E.g. their time-safe property is not actually time-safe at all because of several bugs that affect snapshots and pass-through streams.

3) major bugs in critically important features... As above; time-safe bugs; bugs in merging by issues.
3) they are a year behind where they should be, because they wasted a whole year on trying to move their backend to a database - this will be version 5 which may never see the light of day.

4) The marketing is excellent; but the product does not live up to the marketing hype

5) every release has had major critical bugs that has required them to release immediate hotfixes. This has been a major disruption for us.  And these aren't minor bugs.

6) doesn't scale well... takes up a huge amount of disk space and gets slower over time

Having said all that; it's still a good product; but if I were to do it all again I'd consider git instead.

OwnerDisplayName: Jonathan Holland

Title: Accurev SCM


问:
mechanicalsoup - How to input single text box
The site that I'm trying to parse only has a single input box with no form. I'm having trouble just defining the single input box, passing it an address and then submitting.

What I'd like to do is input an address, submit, grab the info under id="A18" title="Click to get bulk trash pick up info" and load into JSON.

Python:

```<code>import mechanicalsoup

# URL that we authenticate against
map_url = "http://mapservices.phoenix.gov/gis/imap/iMap.html"
address = "<address>"
json_file = "/home/pi/bulk_pickup.json"

# Setup browser
browser = mechanicalsoup.StatefulBrowser(
    soup_config={'features': 'lxml'},
    user_agent='Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13',
)

# Open the login URL
map_page = browser.get(map_url)

# Similar to assert login_page.ok but with full status code in case of failure.
map_page.raise_for_status()

search_form = mechanicalsoup.Form(map_page.soup.select_one('input[id="search_input"]'))

search_form.input({'search_input': address})
</code>```

答:
Unfortunately, the page http://mapservices.phoenix.gov/gis/imap/iMap.html seems to do a heavy use of JavaScript. The <input ...> tag you're seeing is not even part of a <form>, and MechanicalSoup needs the action= attribute of the form to know where to submit it. Either you'll need to hack the low-level stuff yourself (but MechanicalSoup won't be very helpful compared to using the bare request library), or you'll need a more advanced solution like Selenium.

See http://mechanicalsoup.readthedocs.io/en/stable/faq.html#when-to-use-mechanicalsoup for more information.

Had the page been more "HTMLy" and less "JavaScripty", you could have written

```<code>browser.open(map_url)
browser.select_form(...)
browser["search_input"] = ...
browser.submit_selected()
</code>```

Body:
The site that I'm trying to parse only has a single input box with no form. I'm having trouble just defining the single input box, passing it an address and then submitting.

What I'd like to do is input an address, submit, grab the info under id="A18" title="Click to get bulk trash pick up info" and load into JSON.

Python:

import mechanicalsoup

# URL that we authenticate against
map_url = "http://mapservices.phoenix.gov/gis/imap/iMap.html"
address = "<address>"
json_file = "/home/pi/bulk_pickup.json"

# Setup browser
browser = mechanicalsoup.StatefulBrowser(
    soup_config={'features': 'lxml'},
    user_agent='Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13',
)

# Open the login URL
map_page = browser.get(map_url)

# Similar to assert login_page.ok but with full status code in case of failure.
map_page.raise_for_status()

search_form = mechanicalsoup.Form(map_page.soup.select_one('input[id="search_input"]'))

search_form.input({'search_input': address})

Body:
Unfortunately, the page http://mapservices.phoenix.gov/gis/imap/iMap.html seems to do a heavy use of JavaScript. The <input ...> tag you're seeing is not even part of a <form>, and MechanicalSoup needs the action= attribute of the form to know where to submit it. Either you'll need to hack the low-level stuff yourself (but MechanicalSoup won't be very helpful compared to using the bare request library), or you'll need a more advanced solution like Selenium.

See http://mechanicalsoup.readthedocs.io/en/stable/faq.html#when-to-use-mechanicalsoup for more information.

Had the page been more "HTMLy" and less "JavaScripty", you could have written

browser.open(map_url)
browser.select_form(...)
browser["search_input"] = ...
browser.submit_selected()


问:
How to convert strings with even or odd numbers to 0 or 1?
Starting with the data of this form:

```<code>    col_1   col_2
0   a1      a6
1   a3      a7
2   a4      a2
3   a5      a8
</code>```

Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to data frame:

```<code>    col_1   col_2
0   1       0
1   1       1
2   0       0
3   1       0
</code>```

How I can approach this?

答:
I am not sure about the context of this, but here you go :

First step: extract the numbers you want to apply check.
I think the best aproach is using regex, something like

/.*(\d+)/

Second step is check if the number is odd or even:

result = number % 2

I hope it helps

Body:
Starting with the data of this form:

    col_1   col_2
0   a1      a6
1   a3      a7
2   a4      a2
3   a5      a8

Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to data frame:

    col_1   col_2
0   1       0
1   1       1
2   0       0
3   1       0

How I can approach this?


问:
Possible to use Math.min to get second smallest number from array?
I am using Math.min to get the smallest number out of an array of numbers. However, I also need to get the second smallest number as well. Wondering if there is a way to do this using Math.min as well, otherwise looking for the best way to get this number.

Here's what I have:

var arr = [15, 37, 9, 21, 55];
var min = Math.min.apply(null, arr.filter(Boolean));
var secondMin; // Get second smallest number from array here

console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);```

答:
I see you are using Array.filter (but why?) on your first min.  So, if we are using ES6 features you can find the second lowest value by first removing min from the array.

```<code>var secondMin = Math.min.apply(null, arr.filter(n => n != min));
</code>```

edit:  for clarity, unless you are doing something very clever with Array.filter(Boolean) while calculating the first min, you should just pass it the array without filtering:

```<code>var min = Math.min.apply(null, arr);
</code>```

Body:
I see you are using Array.filter (but why?) on your first min.  So, if we are using ES6 features you can find the second lowest value by first removing min from the array.

var secondMin = Math.min.apply(null, arr.filter(n => n != min));

edit:  for clarity, unless you are doing something very clever with Array.filter(Boolean) while calculating the first min, you should just pass it the array without filtering:

var min = Math.min.apply(null, arr);


问:
Limit how many emails/second that ColdFusion sends to AWS SES
I'm currently seeing a bunch of the same errors in our mail.log in ColdFusion 11:

com.sun.mail.smtp.SMTPSendFailedException: 454 Throttling failure: Maximum sending rate exceeded.

There's 200 or so at the exact same datetime, and then another batch of 200 or so at another random time (presumably a different email several hours later).

We're using Amazon SES, and the max send rate on our account is "14 emails/second." Based on those errors we're seeing in mail.log, we assume this rate is being exceeded by ColdFusion trying to send too many at once. Does that assumption sound correct?

Looking around the CF 11 Admin, I'm unsure about what adjustments we need to make to ensure CF doesn't exceed the 14/s rate. Here are some of our current settings (under CF Admin > Server Settings > Mail) which may or may not apply:

[x] Maintain connection to mail server
 Connection Timeout (in seconds): 60
 [ ] Enable SSL socket connections to mail server
 [x] Enable TLS connection to mail server

Spool Interval (in seconds): 15
 Mail Delivery Threads: 10
 [x] Spool mail messages for delivery to: Disk
 Maximum number of messages spooled to memory: 50000

答:
When messages transport is rejected by the SMTP server, the ACF server will respool those items for future delivery, which will retry at regular intervals.  As such, you probably don't need to add additional code to handle them, unless you're dealing with emails in the hundreds or thousands.

If either of the latter are the true, request a rate limit increase from AWS, or look in to another transactional email provider which provides a higher rate ( e.g. - SendGrid ).

Another option is to connect directly to the SES API and and use its multi-send options to bypass eliminate the throttling of individual SMTP requests.  If the emails being sent are error reports, I would suggest using a separate bug tracking application like Rollbar or BugLogHQ, to eliminate redundant transactional bug report mail - thus freeing up the throttle for true application transactional messages.


问:
How do I store a custom user selected CSS template style (like wordpress visual editor)?
I am making a diary app. I want users to be able to customize/style the skin of their journal e.g. covers/backgrounds/fonts/colors etc.

I want to create something like the wordpress theme editor that allows users to update the background color in real time:

Here is how style editor would look.

For example if a user wants to set the writing area of the diary to a light yellow, how do I save that color into a custom CSS template and then render it again? Would I need to create a MySQL table just for style templates and have a row for color, background-color, etc... ?

答:
In Framework7 you can change the theme of the page with a function. I am not entirely sure what you are asking but from my understanding of your question: you can create a function that stores the user theme in LocalStorage. On page load you can read LocalStorage and apply the theme.

Another option would be, as you said in your question, storing this in a database.

If this is not what you are asking please correct me and I will edit or remove my answer.


问:
Jekyll IF statement for 'IF index (home) and NOT paged'?
As you may know Jekyll uses Liquid tags, and the Liquid templating engine has support for If / Else / Unless statements. Does anyone know how to show a specific content only on the 'homepage` (& NOT paged)?

答:
The best way to to is :</p>

```<code>{% if paginator.page==1 %}
  // Do something here
{% endif %}
</code>```

Body:
The best way to to is :

{% if paginator.page==1 %}
  // Do something here
{% endif %}


问:
which files are need to create .ipa for my application which is done in xcode
I am creating a simple application in xcode

Now i need to create ipa for that file.

By google i found some info regarding this.

create a folder named Payload and copy the app file,Zip the fine and rename zip to .ipa.

But i have a doubt in the this path users/username/library/application support/iphone simulator/4.1/Applications

i found a folder named with random alphabets and numbers.

In that i found documents,library,tmp folders along with my application.app.

is i need to copy all the 3 folders into payload or just my application.app is enough.

And i did n't get my icon in over the .ipa.

How can i get it.

can any one pls help me.

Thank u in advance.

答:
If you go to Build and Archive in Xcode, it will package your app into an .ipa for you.

When in Organizer, click on your app, then click on the Share... button, then choose Save to Disk...

Also, I wouldnt suggest manually creating your .ipa files.