问:
thread safety of hashtable
I have a HashTable.

Now as hashtable is thread safe, so whenever i add something to list within hashtable also tread safe?

eg

```<code>if hmp is my map

 hmp.get(0).add(something)

 hmp.get(0).remove(0)
</code>```

Are these operations thread safe?

答:
```<code>   package legacyCLasses;
   import java.util.*;
   public class HashTable_With_Enumeration implements Runnable
   {
    Hashtable<Integer,String> htobj=new Hashtable<Integer,String>();
    static int count=1;
    public void run()
    {
            this.htobj.put(10,"ABC");
            this.htobj.put(200,"PQR");
            this.htobj.put(1,"JKL");
            this.dis();
    }
    void dis()
    {
        try
        {
            Enumeration<String> eobj=this.htobj.elements();
            while(eobj.hasMoreElements())
            {
                System.out.print(eobj.nextElement());
                if(count%2!=0)
                {
                    System.out.print("\t\t\t\t");
                    count++;
                }
                else
                {
                    System.out.println();
                    count++;
                }
                Thread.sleep(2000);
            }
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    public static void main(String[] args)
    {
        HashTable_With_Enumeration heobj1=new HashTable_With_Enumeration();
        HashTable_With_Enumeration heobj2=new HashTable_With_Enumeration();
        Thread t=new Thread(heobj1,"HashTable_Thread1");
        Thread t2=new Thread(heobj2,"HashTable_Thread2");
        try
        {
            System.out.print("\n"+t.getName()+" Values \t"+t2.getName()+ "Values
              \n");
            t.start();
            Thread.sleep(500);
            t2.start();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
      }
   }
</code>```

Title: thread safety of hashtable

Body:
I have a HashTable.

Now as hashtable is thread safe, so whenever i add something to list within hashtable also tread safe?

eg

if hmp is my map

 hmp.get(0).add(something)

 hmp.get(0).remove(0)

Are these operations thread safe?


来源: stackexchange

问:
Specify default hosts for a task if no roles/hosts were provided
I would like to define default host(s) for a specific task in case no roles or hosts were explicitly provided from the command line.
I can use env.all_hosts to check the lists of current hosts is empty, but I don't know how to set it to some host.

I also considered using @hosts(), but it seems to override the input from the command line, which is undesirable.

答:
You can override the @hosts decorator from the command line, using the command-line host lists, as described in the first point of Fabric's Order of Precedence:

Order of precedence

We’ve been pointing out which methods of setting host lists trump the others, as we’ve gone along. However, to make things clearer, here’s a quick breakdown:

Per-task, command-line host lists (fab mytask:host=host1) override absolutely everything else.

Per-task, decorator-specified host lists (@hosts('host1')) override the env variables.

Globally specified host lists set in the fabfile (env.hosts = ['host1']) can override such lists set on the command-line, but only if you’re not careful (or want them to.)

Globally specified host lists set on the command-line (--hosts=host1) will initialize the env variables, but that’s it.

Give that first option a try, and let us know if you have any other questions.

ContentLicense: CC BY-SA 3.0


问:
npm ERR! user is not allowed to access package @gulp-sourcemaps/map-sources : @gulp-sourcemaps/map-sources
I am working with nodejs and 'Jenkins' every day now for the past few months.
Without making any changes to my package.json. Building my project at 'jenkins' I get the following error -

```<code>gifsicle@3.0.4 postinstall /var/lib/jenkins/workspace/musichords/public/node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/imagemin-gifsicle/node_modules/gifsicle
> node lib/install.js

module.js:338
    throw err;
          ^
Error: Cannot find module '@gulp-sourcemaps/map-sources'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/var/lib/jenkins/workspace/musichords/public/node_modules/vinyl-fs/node_modules/gulp-sourcemaps/index.js:6:15)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)

npm WARN optional dep failed, continuing imagemin-optipng@4.3.0
npm WARN optional dep failed, continuing imagemin-jpegtran@4.3.2
npm ERR! Linux 3.16.0-4-amd64
npm ERR! argv "/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_0.12.9/bin/node" "/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_0.12.9/bin/npm" "install"
npm ERR! node v0.12.9
npm ERR! npm  v2.14.9
npm ERR! code E403

npm ERR! user developers is not allowed to access package @gulp-sourcemaps/map-sources : @gulp-sourcemaps/map-sources
npm ERR!
</code>```

I've ran npm update, removed and reinstalled npm, installed 'gulp-sourcemaps' and a few more dependencies. Nothing seems to work.

my dependencies at 'package.json'-

```<code>"dependencies": {
    "acorn": "^5.0.0",
    "async": "^1.5.1",
    "aws-sdk": "^2.2.26",
    "blueimp-md5": "^2.1.0",
    "bytes": "^2.2.0",
    "cheerio": "^0.20.0",
    "collections": "^3.0.0",
    "convert-source-map": "^1.5.0",
    "cors": "^2.7.1",
    "csv": "^0.4.6",
    "css": "^2.2.1",
    "extend": "^3.0.0",
    "detect-newline": "^2.1.0",
    "debug-fabulous": "^0.0.4",
    "geoip-lite-youtab": "*",
    "glob": "^7.0.0",
    "grunt-contrib-imagemin": "^1.0.1",
    "gulp": "^3.9.1",
    "gulp-sourcemap": "^1.0.1",
    "imagemin": "^5.2.0",
    "imagemin-gifsicle": "^5.0.0",
    "imagemin-jpegtran":"^5.0.0",
    "imagemin-optipng":"^5.0.0",
    "jade": "^1.11.0",
    "jstransformer-clean-css": "^1.1.0",
    "jstransformer-uglify-js": "^1.1.1",
    "jstransformer-verbatim": "1.0.0",
    "lru-cache": "^4.0.0",
    "moment": "^2.11.0",
    "needle": "^1.0.0",
    "neo4j": "2.0.0-RC2",
    "newrelic": "^1.24.1",
    "node-genres": "*",
    "optipng-bin": "^3.1.2",
    "paypal-rest-sdk": "^1.7.1",
    "source-map": "^0.5.6",
    "string": "^3.3.1",
    "text-encoding": "^0.6.1",
    "underscore": "^1.8.3",
    "underscore.string": "^3.2.2",
    "winston": "^2.1.1",
    "ytf-node-framework": "*",
    "ytf-server": "*",
    "ytf-server-commons": "*"
  },
  "devDependencies": {
    "chai": "^3.4.1",
    "grunt": "^0.4.5",
    "grunt-contrib-clean": "~1.0.0",
    "grunt-contrib-copy": "~0.8.2",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-shell": "^1.1.2",
    "mocha": "^2.3.4",
    "spec-xunit-file": "^0.0.1-3",
    "superagent-no-cache": "^0.1.0",
    "supertest": "^1.1.0",
    "tizi": "*"
  }
</code>```

Appreciate any assistance I can find.

答:
I just ran into the same problem this morning with my own build. It would appear that the authors of gulp-sourcemaps added a scoped dependency to their package.json two days ago. I'm not familiar with scoped dependencies, but it would appear that's what causing npm install to fail. I am on an older version of npm that doesn't have support for scoped dependencies, but it looks like you're on a newer version - it could be that they haven't published the dependency yet, or set it public since scoped dependencies default to private.

As a short-term fix, you can do as I did, and remove the ^ from your version specifier for gulp-sourcemaps in your own package.json, which will avoid pulling the latest version of gulp-sourcemaps that has the new scoped dependency.

Body:
I am working with nodejs and 'Jenkins' every day now for the past few months.
Without making any changes to my package.json. Building my project at 'jenkins' I get the following error -

gifsicle@3.0.4 postinstall /var/lib/jenkins/workspace/musichords/public/node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/imagemin-gifsicle/node_modules/gifsicle
> node lib/install.js

module.js:338
    throw err;
          ^
Error: Cannot find module '@gulp-sourcemaps/map-sources'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/var/lib/jenkins/workspace/musichords/public/node_modules/vinyl-fs/node_modules/gulp-sourcemaps/index.js:6:15)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)

npm WARN optional dep failed, continuing imagemin-optipng@4.3.0
npm WARN optional dep failed, continuing imagemin-jpegtran@4.3.2
npm ERR! Linux 3.16.0-4-amd64
npm ERR! argv "/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_0.12.9/bin/node" "/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_0.12.9/bin/npm" "install"
npm ERR! node v0.12.9
npm ERR! npm  v2.14.9
npm ERR! code E403

npm ERR! user developers is not allowed to access package @gulp-sourcemaps/map-sources : @gulp-sourcemaps/map-sources
npm ERR!

I've ran npm update, removed and reinstalled npm, installed 'gulp-sourcemaps' and a few more dependencies. Nothing seems to work.

my dependencies at 'package.json'-

"dependencies": {
    "acorn": "^5.0.0",
    "async": "^1.5.1",
    "aws-sdk": "^2.2.26",
    "blueimp-md5": "^2.1.0",
    "bytes": "^2.2.0",
    "cheerio": "^0.20.0",
    "collections": "^3.0.0",
    "convert-source-map": "^1.5.0",
    "cors": "^2.7.1",
    "csv": "^0.4.6",
    "css": "^2.2.1",
    "extend": "^3.0.0",
    "detect-newline": "^2.1.0",
    "debug-fabulous": "^0.0.4",
    "geoip-lite-youtab": "*",
    "glob": "^7.0.0",
    "grunt-contrib-imagemin": "^1.0.1",
    "gulp": "^3.9.1",
    "gulp-sourcemap": "^1.0.1",
    "imagemin": "^5.2.0",
    "imagemin-gifsicle": "^5.0.0",
    "imagemin-jpegtran":"^5.0.0",
    "imagemin-optipng":"^5.0.0",
    "jade": "^1.11.0",
    "jstransformer-clean-css": "^1.1.0",
    "jstransformer-uglify-js": "^1.1.1",
    "jstransformer-verbatim": "1.0.0",
    "lru-cache": "^4.0.0",
    "moment": "^2.11.0",
    "needle": "^1.0.0",
    "neo4j": "2.0.0-RC2",
    "newrelic": "^1.24.1",
    "node-genres": "*",
    "optipng-bin": "^3.1.2",
    "paypal-rest-sdk": "^1.7.1",
    "source-map": "^0.5.6",
    "string": "^3.3.1",
    "text-encoding": "^0.6.1",
    "underscore": "^1.8.3",
    "underscore.string": "^3.2.2",
    "winston": "^2.1.1",
    "ytf-node-framework": "*",
    "ytf-server": "*",
    "ytf-server-commons": "*"
  },
  "devDependencies": {
    "chai": "^3.4.1",
    "grunt": "^0.4.5",
    "grunt-contrib-clean": "~1.0.0",
    "grunt-contrib-copy": "~0.8.2",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-shell": "^1.1.2",
    "mocha": "^2.3.4",
    "spec-xunit-file": "^0.0.1-3",
    "superagent-no-cache": "^0.1.0",
    "supertest": "^1.1.0",
    "tizi": "*"
  }

Appreciate any assistance I can find.


问:
Bash: run service if not already running (Centos, Apache, Clam)
Wrote a simple bash script which is to be run in order to check if httpd (apache) or clamd (antivirus) is running on my Centos server, and if not it will restart them.

```<code>#!/bin/bash
if [[ ! "$(/sbin/service httpd status)" =~ "running" ]]
then
    service httpd start
elif [[ ! "$(/sbin/service clamd status)" =~ "running" ]]
then
    service clamd start
fi
</code>```

tested it via the command line so it works, but is there any way to optimize this further?

答:
```<code>#!/usr/bin/env bash

# First parameter is a comma-delimited string i.e. service1,service2,service3
SERVICES=$1

if [ $EUID -ne 0 ]; then
  if [ "$(id -u)" != "0" ]; then
    echo "root privileges are required" 1>&2
    exit 1
  fi
  exit 1
fi

for service in ${SERVICES//,/ }
do
    STATUS=$(service ${service} status | awk '{print $2}')

    if [ "${STATUS}" != "started" ]; then
        echo "${service} not started"

        #DO STUFF TO SERVICE HERE
    fi
done
</code>```

Body:
Wrote a simple bash script which is to be run in order to check if httpd (apache) or clamd (antivirus) is running on my Centos server, and if not it will restart them.

#!/bin/bash
if [[ ! "$(/sbin/service httpd status)" =~ "running" ]]
then
    service httpd start
elif [[ ! "$(/sbin/service clamd status)" =~ "running" ]]
then
    service clamd start
fi

tested it via the command line so it works, but is there any way to optimize this further?


问:
Launch image doesn't update
I'm using Xcode 4.3.1. Adding launch image is pretty simple -- just drag the image to the Project->Summary->Launch Images window.

So I set a launch image before and it worked. But when I dragged a different image and run the app on my iPhone again, the launch image still remain the same as the old one. Even after I delete the launch image from the Launch Images window, the old image still shows up upon launching.

I've tried clearing the build as well. Didn't work.

Help please. Very much appreciated!

答:
What worked for me on iOS 10.2.1, iPhone 5s hardware test device, Xcode 8.2.1

I think it has nothing to do with Xcode. The test device appears to be caching the LaunchScreen.storyboard image. I needed to reboot my device by holding home + top button. Then I rebuilt, low and behold, the image updated.

Title: Launch image doesn't update


问:
Spring Boot & OAuth2: Getting ResourceAccessException: I/O error on POST request for "http://localhost:5555/oauth/token": Connection refused: connect
based on this example https://github.com/royclarkson/spring-rest-service-oauth I have modified the source code adding repositories and other rest controllers.  The resource and authorization servers are running/configured in the same application.

I have added an endpoint "/api/login" (POST) with request body:

```<code>{"usernamme":"foo", "password":"bar"}
</code>```

I want to get an access token for this user in the service called by the controller. This implementation looks as follows:

Controller

```<code>public ResponseEntity<OAuth2AccessToken> login(@RequestBody @Valid final LoginCommand credentials)
        throws LoginFailedException, UnexpectedErrorException {
    try {
        final OAuth2AccessToken token = securityService.authenticate(credentials.getUsername(), credentials.getPassword());
        return ResponseEntity.ok(token);
    } catch (final InvalidGrantException badCredentialExeption) {
        throw new LoginFailedException(badCredentialExeption.getMessage());
    } catch (final Exception e) {
        throw new UnexpectedErrorException(e.getMessage());
    }
}
</code>```

Service

```<code>@Autowired
@Qualifier("OAuth2RestOperations")
private OAuth2RestOperations client;

@Override
public OAuth2AccessToken authenticate(final String username, final String password) {
    final ResourceOwnerPasswordResourceDetails resourceDetails = (ResourceOwnerPasswordResourceDetails) client.getResource();
    resourceDetails.setUsername(username);
    resourceDetails.setPassword(password);
    return client.getAccessToken();
}
</code>```

Rest client config

```<code>@Configuration
@Import({ OauthProperties2.class })
@EnableOAuth2Client
public class RestClientConfig {

    @Autowired
    private OauthProperties2 oauth;

    @Bean(name = "OAuth2RestOperations")
    public OAuth2RestOperations restTemplate(final OAuth2ClientContext oauth2ClientContext) {
       return new OAuth2RestTemplate(resource(), oauth2ClientContext);
    }

    @Bean
    public OAuth2ProtectedResourceDetails resource() {
       final ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
       resource.setAccessTokenUri(oauth.getClient().getAccessTokenUri());
       resource.setClientId(oauth.getClient().getClientId());
       resource.setClientSecret(oauth.getClient().getClientSecret());
       resource.setGrantType(oauth.getClient().getGrantType());
       resource.setScope(oauth.getClient().getScope());
       return resource;
    }

}
</code>```

The Test

```<code>public class SecurityApiControllerTest extends TestBase {

    @InjectMocks
    private SecurityApiController controller;

    @Test
    public void loginOK() throws Exception {
       final String credentials = FileUtils.readContent("requests/loginOK.json");
    // @formatter:off
        mvc.perform(post("/api/login")
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .content(credentials))
            .andExpect(status().isOk());
    // @formatter:on
    }

}
</code>```

TestBase

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class TestBase {

    @Autowired
    protected WebApplicationContext context;

    @Autowired
    protected FilterChainProxy springSecurityFilterChain;

    protected MockMvc mvc;

    @Before
    public void setUp() {
    MockitoAnnotations.initMocks(this);
        mvc = MockMvcBuilders.webAppContextSetup(context).addFilter(springSecurityFilterChain).build();
    }
 }
</code>```

When running the application, I can call the endpoint for example with POSTMAN. During the test I get a connection refused as described in question header. I have tried to figure out the reason why the test is not working. Can anybody give me a hint to solve this issue?

答:
It is so weird. It works since I have changed the TestBase class to:</p>

```<code>@RunWith(SpringJUnit4ClassRunner.class)
// @WebAppConfiguration
@ContextConfiguration(classes = Application.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
</code>```

Body:
based on this example https://github.com/royclarkson/spring-rest-service-oauth I have modified the source code adding repositories and other rest controllers.  The resource and authorization servers are running/configured in the same application.

I have added an endpoint "/api/login" (POST) with request body:

{"usernamme":"foo", "password":"bar"}

I want to get an access token for this user in the service called by the controller. This implementation looks as follows:

Controller

public ResponseEntity<OAuth2AccessToken> login(@RequestBody @Valid final LoginCommand credentials)
        throws LoginFailedException, UnexpectedErrorException {
    try {
        final OAuth2AccessToken token = securityService.authenticate(credentials.getUsername(), credentials.getPassword());
        return ResponseEntity.ok(token);
    } catch (final InvalidGrantException badCredentialExeption) {
        throw new LoginFailedException(badCredentialExeption.getMessage());
    } catch (final Exception e) {
        throw new UnexpectedErrorException(e.getMessage());
    }
}

Service

@Autowired
@Qualifier("OAuth2RestOperations")
private OAuth2RestOperations client;

@Override
public OAuth2AccessToken authenticate(final String username, final String password) {
    final ResourceOwnerPasswordResourceDetails resourceDetails = (ResourceOwnerPasswordResourceDetails) client.getResource();
    resourceDetails.setUsername(username);
    resourceDetails.setPassword(password);
    return client.getAccessToken();
}

Rest client config

@Configuration
@Import({ OauthProperties2.class })
@EnableOAuth2Client
public class RestClientConfig {

    @Autowired
    private OauthProperties2 oauth;

    @Bean(name = "OAuth2RestOperations")
    public OAuth2RestOperations restTemplate(final OAuth2ClientContext oauth2ClientContext) {
       return new OAuth2RestTemplate(resource(), oauth2ClientContext);
    }

    @Bean
    public OAuth2ProtectedResourceDetails resource() {
       final ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
       resource.setAccessTokenUri(oauth.getClient().getAccessTokenUri());
       resource.setClientId(oauth.getClient().getClientId());
       resource.setClientSecret(oauth.getClient().getClientSecret());
       resource.setGrantType(oauth.getClient().getGrantType());
       resource.setScope(oauth.getClient().getScope());
       return resource;
    }

}

The Test

public class SecurityApiControllerTest extends TestBase {

    @InjectMocks
    private SecurityApiController controller;

    @Test
    public void loginOK() throws Exception {
       final String credentials = FileUtils.readContent("requests/loginOK.json");
    // @formatter:off
        mvc.perform(post("/api/login")
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .content(credentials))
            .andExpect(status().isOk());
    // @formatter:on
    }

}

TestBase

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class TestBase {

    @Autowired
    protected WebApplicationContext context;

    @Autowired
    protected FilterChainProxy springSecurityFilterChain;

    protected MockMvc mvc;

    @Before
    public void setUp() {
    MockitoAnnotations.initMocks(this);
        mvc = MockMvcBuilders.webAppContextSetup(context).addFilter(springSecurityFilterChain).build();
    }
 }

When running the application, I can call the endpoint for example with POSTMAN. During the test I get a connection refused as described in question header. I have tried to figure out the reason why the test is not working. Can anybody give me a hint to solve this issue?

Body:
It is so weird. It works since I have changed the TestBase class to:

@RunWith(SpringJUnit4ClassRunner.class)
// @WebAppConfiguration
@ContextConfiguration(classes = Application.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)


问:
How to force MySQL out of TRADITIONAL mode?
I have an old application that started failing after an upgrade from MySQL 5.0 to 5.1.

A bit of research indicated this is due to "strict mode" which prevents inserting certain types of "invalid" values which previously were just automatically converted to something reasonable.

I tried SET @@SESSION.sql_mode = '' and SET @@GLOBAL.sql_mode = '' but I still get the error.

Also tried commenting out sql_mode in the my.ini.

Is there a stronger, sort of "nuclear" option to fix this?

答:
In my application I usually make sure that the MySQL connection is using traditional mode by issuing

```<code>SET SESSION sql_mode = 'ANSI_QUOTES,TRADITIONAL'
</code>```

on each new connection. I presume that if you just issue

```<code>SET SESSION sql_mode = ''
</code>```

on each new connection, you will have solved the problem.

You should be able to change the default SQL mode for new connections by issuing

```<code>SET GLOBAL sql_mode = ''
</code>```

but you must use an account with sufficient privileges to do this or it won't work.

I think that if you want to make sure a particular SQL mode is in operation for your application, the most robust way to do so is to set it for each and every new connection.

ContentLicense: CC BY-SA 2.5

Body:
In my application I usually make sure that the MySQL connection is using traditional mode by issuing

SET SESSION sql_mode = 'ANSI_QUOTES,TRADITIONAL'

on each new connection. I presume that if you just issue

SET SESSION sql_mode = ''

on each new connection, you will have solved the problem.

You should be able to change the default SQL mode for new connections by issuing

SET GLOBAL sql_mode = ''

but you must use an account with sufficient privileges to do this or it won't work.

I think that if you want to make sure a particular SQL mode is in operation for your application, the most robust way to do so is to set it for each and every new connection.


问:
Boost asio GET with client certificate sslv3 hand shake failed
I want to do a simple C++ web get similar to what is done by this curl command. I can use asio from boost. I must use boost 1.49

curl https://mysite.dev/api/v1/search?q=test -k --cert
  C:\work\testCert.pem

The server is requiring the client certificate.

I started by using this as an example http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/example/ssl/client.cpp

and I added modifications by adding calls to the context like

```<code>ctx.set_options(boost::asio::ssl::context::default_workarounds);
ctx.use_certificate_file("C:\\work\\testCert.pem", boost::asio::ssl::context_base::pem);
ctx.use_private_key_file("C:\\work\\testKey.pem", boost::asio::ssl::context_base::pem);
</code>```

My Request Looks like this:

GET /api/v1/search?q=test HTTP/1.0

  Host: mysite.dev

  Accept: */*

but I keep getting messages like this

Error: sslv3 alert handshake failure

clearly there is a step I am missing in the handshake process

答:
The solution was to disable SSLv3 support, appartently most servers disable this because of design flaws.</p>

```<code>ctx.set_options(boost::asio::ssl::context::default_workarounds |
                boost::asio::ssl::context::no_sslv2 |
                boost::asio::ssl::context::no_sslv3);
</code>```

Body:
I want to do a simple C++ web get similar to what is done by this curl command. I can use asio from boost. I must use boost 1.49

curl https://mysite.dev/api/v1/search?q=test -k --cert
  C:\work\testCert.pem

The server is requiring the client certificate.

I started by using this as an example http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/example/ssl/client.cpp

and I added modifications by adding calls to the context like

ctx.set_options(boost::asio::ssl::context::default_workarounds);
ctx.use_certificate_file("C:\\work\\testCert.pem", boost::asio::ssl::context_base::pem);
ctx.use_private_key_file("C:\\work\\testKey.pem", boost::asio::ssl::context_base::pem);

My Request Looks like this:

GET /api/v1/search?q=test HTTP/1.0

  Host: mysite.dev

  Accept: */*

but I keep getting messages like this

Error: sslv3 alert handshake failure

clearly there is a step I am missing in the handshake process

Body:
The solution was to disable SSLv3 support, appartently most servers disable this because of design flaws.

ctx.set_options(boost::asio::ssl::context::default_workarounds |
                boost::asio::ssl::context::no_sslv2 |
                boost::asio::ssl::context::no_sslv3);


问:
Mvvm-light / Serilog design time error: Could not load file or assembly [VS2017]
I'm getting the error below in DesignTime when I have a view open which has a viewmodel with references to SeriLog.

Could not load file or assembly 'Serilog, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=24c2f752a8e58a10' or one of its
  dependencies. Het systeem kan het opgegeven bestand niet vinden. myapp
  C:\snip\Projects\snip\myapp\myapp\Views\MyViews\MyView.xaml

The dutch string translated to English: "The system can't find the file"

The project compiles and runs fine, but I'd like an error-free design-time experience. Right now this error breaks my design-time project code in VS2017.
What can I do to fix this error?

Already tried:

Removing the serilog folder from %userprofile%.nuget and rebuilding

Cleaning the project folder bin\ and obj\ folder

Rebuilding the project

Restarting VS2017

Rebooting computer

Another workstation shows the same error

Compiling serilog and sink myself on netcore1.6 target

I'm building an UWP app targeting the anniversary edition 14393 framework.

project.json serilog references:

```<code> "Serilog": "2.4.0",
 "Serilog.Sinks.RollingFile": "3.3.0",
</code>```

Sample VS project which replicates the issue

I have created a blank Template10 project with mvvm-light viewmodel on DetailPage.xaml for which the serilog error is shown.

Download location:

https://www.dropbox.com/s/uocjx0kuc1dknwt/Template10_Serilog_Sample.zip?dl=0

Screenshot of error

答:
Try to use the Package Manager to update.

Go to: Tools > Nuget Package Manager > Package Manager Console

And type it:

```<code>Update-Package Serilog
</code>```

Body:
I'm getting the error below in DesignTime when I have a view open which has a viewmodel with references to SeriLog.

Could not load file or assembly 'Serilog, Version=2.0.0.0,
  Culture=neutral, PublicKeyToken=24c2f752a8e58a10' or one of its
  dependencies. Het systeem kan het opgegeven bestand niet vinden. myapp
  C:\snip\Projects\snip\myapp\myapp\Views\MyViews\MyView.xaml

The dutch string translated to English: "The system can't find the file"

The project compiles and runs fine, but I'd like an error-free design-time experience. Right now this error breaks my design-time project code in VS2017.
What can I do to fix this error?

Already tried:

Removing the serilog folder from %userprofile%.nuget and rebuilding

Cleaning the project folder bin\ and obj\ folder

Rebuilding the project

Restarting VS2017

Rebooting computer

Another workstation shows the same error

Compiling serilog and sink myself on netcore1.6 target

I'm building an UWP app targeting the anniversary edition 14393 framework.

project.json serilog references:

 "Serilog": "2.4.0",
 "Serilog.Sinks.RollingFile": "3.3.0",

Sample VS project which replicates the issue

I have created a blank Template10 project with mvvm-light viewmodel on DetailPage.xaml for which the serilog error is shown.

Download location:

https://www.dropbox.com/s/uocjx0kuc1dknwt/Template10_Serilog_Sample.zip?dl=0

Screenshot of error

Body:
Try to use the Package Manager to update.

Go to: Tools > Nuget Package Manager > Package Manager Console

And type it:

Update-Package Serilog


问:
How to stop Camel Context immediately?
I have a camel application where I create below structure

```<code>main thread
        create Camel Context
          addRoute(routeBuilder1)
          addRoute(routeBuilder2)
        context.start
</code>```

RouteBuilder1

```<code>    R11
    R12
    R13
    R14
</code>```

RouteBuilder2

```<code>    R21
    R22
</code>```

In very specific situation, I need to stop the context(stop all processing right now). When I use context.shutdown,I noticed that if a route processing is in progress, camel is not able to stop it(called as gracefull shutdown), and that route continue processing. Whereas,in my case I need to hard stop everything immediately.

How can we achieve that?

答:
Set the timeout field of DefaultShutdownStrategy.

Example:

```<code>context.getShutdownStrategy().setTimeout(0);
context.getShutdownStrategy().setShutdownNowOnTimeout(true);
</code>```

UPDATE:

I'm not sure, but maybe it should work with 1 millisec timeout (you can set the TimeUnit on the shutdownStrategy)

```<code>context.getShutdownStrategy().setTimeUnit(TimeUnit.MILLISECONDS);
context.getShutdownStrategy().setTimeout(1);
context.getShutdownStrategy().setShutdownNowOnTimeout(true)
</code>```

Title: How to stop Camel Context immediately?

Body:
I have a camel application where I create below structure

main thread
        create Camel Context
          addRoute(routeBuilder1)
          addRoute(routeBuilder2)
        context.start

RouteBuilder1

    R11
    R12
    R13
    R14

RouteBuilder2

    R21
    R22

In very specific situation, I need to stop the context(stop all processing right now). When I use context.shutdown,I noticed that if a route processing is in progress, camel is not able to stop it(called as gracefull shutdown), and that route continue processing. Whereas,in my case I need to hard stop everything immediately.

How can we achieve that?

Body:
Set the timeout field of DefaultShutdownStrategy.

Example:

context.getShutdownStrategy().setTimeout(0);
context.getShutdownStrategy().setShutdownNowOnTimeout(true);

UPDATE:

I'm not sure, but maybe it should work with 1 millisec timeout (you can set the TimeUnit on the shutdownStrategy)

context.getShutdownStrategy().setTimeUnit(TimeUnit.MILLISECONDS);
context.getShutdownStrategy().setTimeout(1);
context.getShutdownStrategy().setShutdownNowOnTimeout(true)


问:
django check if the uploaded file is a zip file
I have a handler for a POST method in Django which receives an uploaded file. What I would like to do is verify that the file is a valid zip file before proceeding.

So, I have:

```<code>@login_required(login_url="login/")
def upload(request):
    if request.method == 'POST' and request.FILES['upload_file']:
        uploaded_file = request.FILES['upload_file']
        print type(uploaded_file)

    return render(request, 'upload.html', {'context': RequestContext(request)})
</code>```

Now at this point uploaded_file is of type <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>. My question is what would be the best way to verify that this is a valid archive? Do I need to save it to the disk and then use the zipfile module or is there some way to do it without writing to the disk?

Note: I am not using the Django model with a FileField and the corresponding Form for various unrelated reasons.

答:
Save the filename of the pbject

```<code>Name = request.FILES['filename'].name
</code>```

Then check if is a zip file

```<code>If Name.endswith('.zip'):
     print(True)
</code>```

Body:
I have a handler for a POST method in Django which receives an uploaded file. What I would like to do is verify that the file is a valid zip file before proceeding.

So, I have:

@login_required(login_url="login/")
def upload(request):
    if request.method == 'POST' and request.FILES['upload_file']:
        uploaded_file = request.FILES['upload_file']
        print type(uploaded_file)

    return render(request, 'upload.html', {'context': RequestContext(request)})

Now at this point uploaded_file is of type <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>. My question is what would be the best way to verify that this is a valid archive? Do I need to save it to the disk and then use the zipfile module or is there some way to do it without writing to the disk?

Note: I am not using the Django model with a FileField and the corresponding Form for various unrelated reasons.

Body:
Save the filename of the pbject

Name = request.FILES['filename'].name

Then check if is a zip file

If Name.endswith('.zip'):
     print(True)


问:
invalid argument supplied for foreach
I am parsing XML in PHP code and getting a warning "invalid argument supplied for foreach".
Below is the XML:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<BookStore>
    <book>
        <title>Computer Concepts</title>
        <auther>Goerge Arthar</auther>
        <category>Computer Science</category>
        <price>24.00</price>
    </book>
    <book>
        <title>Algebra</title>
        <auther>Mike</auther>
        <category>Mathematics</category>
        <price>34.00</price>
    </book>
</BookStore>
</code>```

and using the following code:

```<code><?php
$xmlDOM = new DOMDocument();
$xmlDOM->load("Books.xml");
$document = $xmlDOM->documentElement;
foreach ($document->childNodes as $node) {
    foreach($node->childNodes as $temp) {
        echo $temp->nodeName."=".$temp->nodeValue."<br />";
    }
}
?>
</code>```

NOTE: I get the output that I require but with a warning. It shows that array is not empty.
Please see output also:

```<code>Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Computer Concepts
#text=
auther=Goerge Arthar
#text=
category=Computer Science
#text=
price=24.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Algebra
#text=
auther=Mike
#text=
category=Mathematics
#text=
price=34.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
</code>```

答: Unsure of how the xml works, but this error is class for the first $variable in your foreach not being an array. As the function can only break down an array.</p>

Title: invalid argument supplied for foreach

Body:
I am parsing XML in PHP code and getting a warning "invalid argument supplied for foreach".
Below is the XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<BookStore>
    <book>
        <title>Computer Concepts</title>
        <auther>Goerge Arthar</auther>
        <category>Computer Science</category>
        <price>24.00</price>
    </book>
    <book>
        <title>Algebra</title>
        <auther>Mike</auther>
        <category>Mathematics</category>
        <price>34.00</price>
    </book>
</BookStore>

and using the following code:

<?php
$xmlDOM = new DOMDocument();
$xmlDOM->load("Books.xml");
$document = $xmlDOM->documentElement;
foreach ($document->childNodes as $node) {
    foreach($node->childNodes as $temp) {
        echo $temp->nodeName."=".$temp->nodeValue."
";
    }
}
?>

NOTE: I get the output that I require but with a warning. It shows that array is not empty.
Please see output also:

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Computer Concepts
#text=
auther=Goerge Arthar
#text=
category=Computer Science
#text=
price=24.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Algebra
#text=
auther=Mike
#text=
category=Mathematics
#text=
price=34.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8


问:
How to dynamically build and store complex linq queries against a list of hierarchical objects?
I have a list of objects in a hierarchical structure. I want to build complex LINQ queries against that object list based on "conditions" a client company sets and are stored in the database. So I need to build these at run time, but because they will be run repeatedly whenever the client's users update or refresh their data I would like to store the LINQ queries in objects rather than rebuild them each time.

I have looked at ScottGu's Blog about Dynamic LINQ.

Also this article about using expression trees.

Neither of these appear to provide an adequate solution, but I may not be understanding them adequately. I'm afraid that I'm trying to use LINQ when I should consider other options.

My object hierarchy:

```<code>WorkOrder[]
    Field[]
    Task[]
        Field[]
</code>```

Here is an example of a LINQ query that I would like to store and execute. I can reasonably build this format based on the database records that define the conditions.

```<code>var query =
from wo in WorkOrders
from woF in wo.Fields
from task in wo.Tasks
from taskF in task.Fields
from taskF2 in task.Fields
where woF.Name == "System Status"
    && woF.Value.Contains("SETC")
    && taskF.Name == "Material"
    && taskF.Value == "Y"
    && taskF2.Name == "Planner"
    && taskF2.Value == "GR5259"
select new
{
    wo_id = wo.ID,
    task_id = task.ID
};
</code>```

A few considerations.

Depending on the complexity of the user defined conditions I may or may not need to pull from the different object lists: the "froms" are dynamic.

Note that in this example I pulled twice from the task.fields[] so I aliased it two times.

The example LINQ structure allows me to have complex ANDs, ORs, parenthesis, etc. that I don't believe is practical with Dynamic Chaining or Expression Trees.

In my code I envision:

```<code>//1) Retrieve business rules from DB. I can do this.

//2) Iterate through the business rules to build the linq queries.
foreach (BusinessRule br in BusinessRules) {
    //Grab the criteria for the rule from the DB.

    //Create a linq to object query based on the criteria just built.
    //Add this query to a list for later use.
}

...Elsewhere in application.

//Iterate through and execute the linq queries in order to apply business rules to data cached in the application.
foreach (LinqQuery q in LinqQueries) {
    //Execute the query

    //Apply business rule to the results.
}
</code>```

Thank you very much for your thoughts, effort and ideas.

答:
You can technically achieve what you need using only LINQ, but the PredicateBuilder is a nice utility class:

```<code>public enum AndOr
{
    And,
    Or
}

public enum QueryableObjects
{
    WorkOrderField,
    TaskField
}

public class ClientCondition
{
    public AndOr AndOr;
    public QueryableObjects QueryableObject;
    public string PropertyName;
    public string PropertyValue;
}

public void PredicateBuilderExample()
{
    var conditions = new List<ClientCondition> {
    {
        new ClientCondition { AndOr = LINQ.AndOr.And,
            QueryableObject = QueryableObjects.WorkOrderField,
            PropertyName = "System Status",
            PropertyValue = "SETC"
        }
    },
    {
        new ClientCondition{AndOr = AndOr.And,
            QueryableObject = QueryableObjects.TaskField,
            PropertyName = "Material",
            PropertyValue = "Y"
        }
    },
    {
        new ClientCondition{AndOr = AndOr.Or,
            QueryableObject = QueryableObjects.TaskField,
            PropertyName = "Planner",
            PropertyValue = "GR5259"
        }
    }
    };

    //Obviously this WorkOrder object is empty so it will always return empty lists when queried.
    //Populate this yourself.
    var WorkOrders = new List<WorkOrder>();

    var wofPredicateBuilder = PredicateBuilder.True<WorkOrderField>();
    var tfPredicateBuilder = PredicateBuilder.True<TaskField>();

    foreach (var condition in conditions)
    {
        if (condition.AndOr == AndOr.And)
        {
            if (condition.QueryableObject == QueryableObjects.WorkOrderField)
            {
                wofPredicateBuilder = wofPredicateBuilder.And(
                    wof => wof.Name == condition.PropertyName &&
                        wof.Value.Contains(condition.PropertyValue));
            }
        }
        if (condition.AndOr == AndOr.Or)
        {
            if (condition.QueryableObject == QueryableObjects.TaskField)
            {
                tfPredicateBuilder = tfPredicateBuilder.Or(
                    tf => tf.Name = condition.PropertyName &&
                        tf.Value.Contains(condition.PropertyValue));
            }
        }
        //And so on for each condition type.
    }

    var query = from wo in WorkOrders
                from woF in wo.Fields.AsQueryable().Where(wofPredicateBuilder)
                from task in wo.Tasks
                from taskF in task.Fields.AsQueryable().Where(tfPredicateBuilder)
                select new
                {
                    wo_id = wo.ID,
                    task_id = task.ID
                };
}
</code>```

Note that I use the enums to limit the possible conditions your clients can send you. To have a truly dynamic queryable engine, you will need to use Reflection to ensure the object names you receive are valid. That seems like a rather large scope, and at that point I would recommend researching a different approach, such as ElasticSearch.

Also note that the order of And and Ors matters significantly. Essentially you are allowing your customers to build SQL queries against your data, and that usually ends in tears. It's your job to limit them to the proper set of conditions they should be querying.

Body:
I have a list of objects in a hierarchical structure. I want to build complex LINQ queries against that object list based on "conditions" a client company sets and are stored in the database. So I need to build these at run time, but because they will be run repeatedly whenever the client's users update or refresh their data I would like to store the LINQ queries in objects rather than rebuild them each time.

I have looked at ScottGu's Blog about Dynamic LINQ.

Also this article about using expression trees.

Neither of these appear to provide an adequate solution, but I may not be understanding them adequately. I'm afraid that I'm trying to use LINQ when I should consider other options.

My object hierarchy:

WorkOrder[]
    Field[]
    Task[]
        Field[]

Here is an example of a LINQ query that I would like to store and execute. I can reasonably build this format based on the database records that define the conditions.

var query =
from wo in WorkOrders
from woF in wo.Fields
from task in wo.Tasks
from taskF in task.Fields
from taskF2 in task.Fields
where woF.Name == "System Status"
    && woF.Value.Contains("SETC")
    && taskF.Name == "Material"
    && taskF.Value == "Y"
    && taskF2.Name == "Planner"
    && taskF2.Value == "GR5259"
select new
{
    wo_id = wo.ID,
    task_id = task.ID
};

A few considerations.

Depending on the complexity of the user defined conditions I may or may not need to pull from the different object lists: the "froms" are dynamic.

Note that in this example I pulled twice from the task.fields[] so I aliased it two times.

The example LINQ structure allows me to have complex ANDs, ORs, parenthesis, etc. that I don't believe is practical with Dynamic Chaining or Expression Trees.

In my code I envision:

//1) Retrieve business rules from DB. I can do this.

//2) Iterate through the business rules to build the linq queries.
foreach (BusinessRule br in BusinessRules) {
    //Grab the criteria for the rule from the DB.

    //Create a linq to object query based on the criteria just built.
    //Add this query to a list for later use.
}

...Elsewhere in application.

//Iterate through and execute the linq queries in order to apply business rules to data cached in the application.
foreach (LinqQuery q in LinqQueries) {
    //Execute the query

    //Apply business rule to the results.
}

Thank you very much for your thoughts, effort and ideas.

Body:
You can technically achieve what you need using only LINQ, but the PredicateBuilder is a nice utility class:

public enum AndOr
{
    And,
    Or
}

public enum QueryableObjects
{
    WorkOrderField,
    TaskField
}

public class ClientCondition
{
    public AndOr AndOr;
    public QueryableObjects QueryableObject;
    public string PropertyName;
    public string PropertyValue;
}

public void PredicateBuilderExample()
{
    var conditions = new List<ClientCondition> {
    {
        new ClientCondition { AndOr = LINQ.AndOr.And,
            QueryableObject = QueryableObjects.WorkOrderField,
            PropertyName = "System Status",
            PropertyValue = "SETC"
        }
    },
    {
        new ClientCondition{AndOr = AndOr.And,
            QueryableObject = QueryableObjects.TaskField,
            PropertyName = "Material",
            PropertyValue = "Y"
        }
    },
    {
        new ClientCondition{AndOr = AndOr.Or,
            QueryableObject = QueryableObjects.TaskField,
            PropertyName = "Planner",
            PropertyValue = "GR5259"
        }
    }
    };

    //Obviously this WorkOrder object is empty so it will always return empty lists when queried.
    //Populate this yourself.
    var WorkOrders = new List<WorkOrder>();

    var wofPredicateBuilder = PredicateBuilder.True<WorkOrderField>();
    var tfPredicateBuilder = PredicateBuilder.True<TaskField>();

    foreach (var condition in conditions)
    {
        if (condition.AndOr == AndOr.And)
        {
            if (condition.QueryableObject == QueryableObjects.WorkOrderField)
            {
                wofPredicateBuilder = wofPredicateBuilder.And(
                    wof => wof.Name == condition.PropertyName &&
                        wof.Value.Contains(condition.PropertyValue));
            }
        }
        if (condition.AndOr == AndOr.Or)
        {
            if (condition.QueryableObject == QueryableObjects.TaskField)
            {
                tfPredicateBuilder = tfPredicateBuilder.Or(
                    tf => tf.Name = condition.PropertyName &&
                        tf.Value.Contains(condition.PropertyValue));
            }
        }
        //And so on for each condition type.
    }

    var query = from wo in WorkOrders
                from woF in wo.Fields.AsQueryable().Where(wofPredicateBuilder)
                from task in wo.Tasks
                from taskF in task.Fields.AsQueryable().Where(tfPredicateBuilder)
                select new
                {
                    wo_id = wo.ID,
                    task_id = task.ID
                };
}

Note that I use the enums to limit the possible conditions your clients can send you. To have a truly dynamic queryable engine, you will need to use Reflection to ensure the object names you receive are valid. That seems like a rather large scope, and at that point I would recommend researching a different approach, such as ElasticSearch.

Also note that the order of And and Ors matters significantly. Essentially you are allowing your customers to build SQL queries against your data, and that usually ends in tears. It's your job to limit them to the proper set of conditions they should be querying.


问:
How to truncate float values?
I want to remove digits from a float to have a fixed number of digits after the dot, like:

```<code>1.923328437452 → 1.923
</code>```

I need to output as a string to another function, not print.

Also I want to ignore the lost digits, not round them.

答:
>>> from math import floor
>>> floor((1.23658945) * 10**4) / 10**4
1.2365
```

# divide and multiply by 10**number of desired digits

ContentLicense: CC BY-SA 4.0

Title: How to truncate float values?

Body:
I want to remove digits from a float to have a fixed number of digits after the dot, like:

1.923328437452 → 1.923

I need to output as a string to another function, not print.

Also I want to ignore the lost digits, not round them.

Body:
>>> from math import floor
>>> floor((1.23658945) * 10**4) / 10**4
1.2365

# divide and multiply by 10**number of desired digits


问:
Split string at every Nth occurrence of character
I need to split a string like the following after every fourth pipe -

Input -

userid456|userid457|userid458|userid459|userid460|userid461|userid462|userid463|userid464|userid465|userid466|userid467|userid468|userid469|userid470|userid471|userid472|userid473|userid474|userid475|userid476|userid477|userid478|userid479|userid480|userid481|userid482|userid483

Output -

```<code>userid456|userid457|userid458|userid459

userid460|userid461|userid462|userid463

userid464|userid465|userid466|userid467

userid468|userid469|userid470|userid471
</code>```

etc.

Was trying to figure out if there is an easy way using regexp and String.split()

答:
You would be better off matching instead of splitting.

It's the same effect, but with more control.

((?:[^|]*?\|){3}[^|]*?)\||([\S\s]+)

Explained

```<code>     (                             # (1 start)
          (?:                           # Group - 3 pipes
               [^|]*?                        # Optional non-pipe chars
               \|                            # Pipe
          ){3}                          # End group
          [^|]*?                        # Optional non-pipe chars
     )                             # (1 end)
     \|                            # 4th pipe, consume but do not capture

  |
     ( [\S\s]+ )                   # (2), Final text less than 4 pipes
</code>```

Body:
I need to split a string like the following after every fourth pipe -

Input -

userid456|userid457|userid458|userid459|userid460|userid461|userid462|userid463|userid464|userid465|userid466|userid467|userid468|userid469|userid470|userid471|userid472|userid473|userid474|userid475|userid476|userid477|userid478|userid479|userid480|userid481|userid482|userid483

Output -

userid456|userid457|userid458|userid459

userid460|userid461|userid462|userid463

userid464|userid465|userid466|userid467

userid468|userid469|userid470|userid471

etc.

Was trying to figure out if there is an easy way using regexp and String.split()

Body:
You would be better off matching instead of splitting.

It's the same effect, but with more control.

((?:[^|]*?\|){3}[^|]*?)\||([\S\s]+)

Explained

     (                             # (1 start)
          (?:                           # Group - 3 pipes
               [^|]*?                        # Optional non-pipe chars
               \|                            # Pipe
          ){3}                          # End group
          [^|]*?                        # Optional non-pipe chars
     )                             # (1 end)
     \|                            # 4th pipe, consume but do not capture

  |
     ( [\S\s]+ )                   # (2), Final text less than 4 pipes


问:
Tags not showing for Wagtail under posts or /tag page
I'm following this guide > http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html#tagging-posts

As far as I can tell, I followed the guide exactly as it's written but tags won't load while viewing individual blog posts and the tag page doesn't show a list of tags. I'm not getting any errors, they just don't show up.

They are showing when searching via link e.g. http://0.0.0.0:8000/tags/?tag=lorem.

Thanks.

答:
I keep figuring things out on my own. Wagtail needs to update their docs to be more specific but here's the code that worked for me in blog/blog_page.html:

```<code>{% extends "base.html" %}

{% load wagtailcore_tags wagtailimages_tags %}

{% block body_class %}template-blogpage{% endblock %}

{% block content %}
    <h1>{{ page.title }}</h1>
    <p class="meta">{{ page.date }}</p>

{% with categories=page.categories.all %}
    {% if categories %}
        <h3>Posted in:</h3>
        <ul>
            {% for category in categories %}
                <li style="display: inline">
                    {% image category.icon fill-32x32 style="vertical-align: middle" %}
                    {{ category.name }}
                </li>
            {% endfor %}
        </ul>
    {% endif %}
{% endwith %}

{% if page.tags.all.count %}
    <div class="tags">
        <h3>Tags</h3>
        {% for tag in page.tags.all %}
            <a href="{% slugurl 'tags' %}?tag={{ tag }}"><button type="button">{{ tag }}<$
        {% endfor %}
    </div>
{% endif %}

    <div class="intro">{{ page.intro }}</div>

    {{ page.body|richtext }}

    {% for item in page.gallery_images.all %}
        <div style="float: left; margin: 10px">
            {% image item.image fill-320x240 %}
            <p>{{ item.caption }}</p>
        </div>
    {% endfor %}

    <p><a href="{{ page.get_parent.url }}">Return to blog</a></p>

{% endblock %}
</code>```

Body:
I keep figuring things out on my own. Wagtail needs to update their docs to be more specific but here's the code that worked for me in blog/blog_page.html:

{% extends "base.html" %}

{% load wagtailcore_tags wagtailimages_tags %}

{% block body_class %}template-blogpage{% endblock %}

{% block content %}
    <h1>{{ page.title }}</h1>
    <p class="meta">{{ page.date }}</p>

{% with categories=page.categories.all %}
    {% if categories %}
        <h3>Posted in:</h3>
        <ul>
            {% for category in categories %}
                <li style="display: inline">
                    {% image category.icon fill-32x32 style="vertical-align: middle" %}
                    {{ category.name }}
                </li>
            {% endfor %}
        </ul>
    {% endif %}
{% endwith %}

{% if page.tags.all.count %}
    <div class="tags">
        <h3>Tags</h3>
        {% for tag in page.tags.all %}
            <a href="{% slugurl 'tags' %}?tag={{ tag }}"><button type="button">{{ tag }}<$
        {% endfor %}
    </div>
{% endif %}

    <div class="intro">{{ page.intro }}</div>

    {{ page.body|richtext }}

    {% for item in page.gallery_images.all %}
        <div style="float: left; margin: 10px">
            {% image item.image fill-320x240 %}
            <p>{{ item.caption }}</p>
        </div>
    {% endfor %}

    <p><a href="{{ page.get_parent.url }}">Return to blog</a></p>

{% endblock %}


问:
React + Semantic-UI: Using Forms inside UI MODAL
In the plain old Semantic-UI WITHOUT React, I have been able to put a form inside a Modal without a problem at all.

With the Semantic-UI + React version, I am able to display the form inside the modal, but it doesn't work the way I would expect it to.

For example, after the modal shows and the form inside the modal also is displayed.  If I start inputting in the input field, I would get this error displayed:

```<code>Error: Invariant Violation: findComponentRoot(..., .1.1.1.0.4.0.0.1): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID ``.
</code>```

And due to this error, the other react code that I use the input for do not work as expected.

This is the most simple version of the code that demonstrates the problem:

```<code>ConfirmEdit = React.createClass({

    render(){
        return (
            <div className="ui modal editform">
                <form className="ui form">
                    <div className="field">
                        <label>Name</label>
                        <input name="name" type="text" placeholder="Name">
                        </input>
                    </div>
                </form>
            </div>
        );
    }
});
</code>```

Inside the component where i add the above the component I made sure to trigger it:

```<code>$('.ui.modal.editform').modal('show');
</code>```

As mentioned above.  It displays fine, but it doesn't work fine due to the Invariant Violation.

How do I work around this and make it work?

答:
The updated solution is to use semantic-ui-react:

https://github.com/Semantic-Org/Semantic-UI-React

http://react.semantic-ui.com/modules/modal

Body:
In the plain old Semantic-UI WITHOUT React, I have been able to put a form inside a Modal without a problem at all.

With the Semantic-UI + React version, I am able to display the form inside the modal, but it doesn't work the way I would expect it to.

For example, after the modal shows and the form inside the modal also is displayed.  If I start inputting in the input field, I would get this error displayed:

Error: Invariant Violation: findComponentRoot(..., .1.1.1.0.4.0.0.1): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a
 when using tables, nesting tags like <form>,
, or , or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID ``.

And due to this error, the other react code that I use the input for do not work as expected.

This is the most simple version of the code that demonstrates the problem:

ConfirmEdit = React.createClass({

    render(){
        return (

                <form className="ui form">

                        Name
                        <input name="name" type="text" placeholder="Name">
                        </input>

                </form>

        );
    }
});

Inside the component where i add the above the component I made sure to trigger it:

$('.ui.modal.editform').modal('show');

As mentioned above.  It displays fine, but it doesn't work fine due to the Invariant Violation.

How do I work around this and make it work?


问:
Javascript strings and objects
In js can I call a function in an object from a string? Hm, I show you with an example:

```<code>var Object = {
    callMe : function() { }
}

Object.callMe();
</code>```

This I can do, but what if I want to do this:

```<code>var string = 'callMe';
Object.string();
</code>```

Can I somehow do this? Maybe I'm just thinking wrong here

答:
For this use bracket notation, like this:

```<code>var string = 'callMe';
Object[string]();
</code>```

You can test it out here.

In JavaScript obj.thing (dot notation) is accessing the same thing as obj["thing"] (bracket notation).

Title: Javascript strings and objects

Body:
In js can I call a function in an object from a string? Hm, I show you with an example:

var Object = {
    callMe : function() { }
}

Object.callMe();

This I can do, but what if I want to do this:

var string = 'callMe';
Object.string();

Can I somehow do this? Maybe I'm just thinking wrong here

Body:
For this use bracket notation, like this:

var string = 'callMe';
Object[string]();

You can test it out here.

In JavaScript obj.thing (dot notation) is accessing the same thing as obj["thing"] (bracket notation).


问:
Excel: Group values from rows based on common cell value
I have an Excel file that contains a list of groups and the users that belong to them. I need to generate a list of users that belong to each group. Key point: while this is a trivial task in perl, python, or any other programming language, I'd like to do the whole thing in Excel so I don't have to export to csv, re-import the results, and re-do the formatting every time there's a change.

The file format (when exported to csv) is akin to:

```<code>Group, username, email
Perl Jam, evedder, evedder@pj.com
Perl Jam, mcameron, mcameron@soundgarden.com
Perl Jam, jament, jament@pj.com
Perl Jam, sgossard, sgossard@pj.com
Perl Jam, mmccready, mmccready@pj.com
Soundgarden, mcameron, mcameron@soundgarden.com
Soundgarden, ccornell, ccornell@soundgarden.com
Soundgarden, kthayill, kthayill@pj.com
Soundgarden, bshepherd, bshepherd@pj.com
Temple of the Dog, evedder, evedder@pj.com
Temple of the Dog, ccornell, ccornell@soundgarden.com
Temple of the Dog, jament, jament@pj.com
Temple of the Dog, sgossard, sgossard@pj.com
Temple of the Dog, mmccready, mmccready@pj.com
Temple of the Dog, mcameron, mcameron@soundgarden.com
</code>```

What I'd like to end up with is:

```<code>Group, usernames
Perl Jam, evedder, mcameron, jament, sgossard, mmccready
Soundgarden, mcameron, ccornell, kthayill, bshepherd
Temple of the Dog, evedder, mcameron, ccornell, jament, sgossard, mmccready
</code>```

答:
To get your unique list use this array formula:

```<code>=IFERROR(INDEX($A$2:$A$16,MATCH(0,COUNTIF($E$1:E1,$A$2:$A$16),0)),"")
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

Put in first cell, hit Ctrl-Shift-Enter, then copy down till you get blanks.

To get the username:

```<code>=IFERROR(INDEX($B:$B,AGGREGATE(15,6,ROW($A$2:$A$16)/($A$2:$A$16=$E2),COLUMN(A:A))),"")
</code>```

Where $E2 is the cell in which the other formula is.

Then copy across and down.

Body:
I have an Excel file that contains a list of groups and the users that belong to them. I need to generate a list of users that belong to each group. Key point: while this is a trivial task in perl, python, or any other programming language, I'd like to do the whole thing in Excel so I don't have to export to csv, re-import the results, and re-do the formatting every time there's a change.

The file format (when exported to csv) is akin to:

Group, username, email
Perl Jam, evedder, evedder@pj.com
Perl Jam, mcameron, mcameron@soundgarden.com
Perl Jam, jament, jament@pj.com
Perl Jam, sgossard, sgossard@pj.com
Perl Jam, mmccready, mmccready@pj.com
Soundgarden, mcameron, mcameron@soundgarden.com
Soundgarden, ccornell, ccornell@soundgarden.com
Soundgarden, kthayill, kthayill@pj.com
Soundgarden, bshepherd, bshepherd@pj.com
Temple of the Dog, evedder, evedder@pj.com
Temple of the Dog, ccornell, ccornell@soundgarden.com
Temple of the Dog, jament, jament@pj.com
Temple of the Dog, sgossard, sgossard@pj.com
Temple of the Dog, mmccready, mmccready@pj.com
Temple of the Dog, mcameron, mcameron@soundgarden.com

What I'd like to end up with is:

Group, usernames
Perl Jam, evedder, mcameron, jament, sgossard, mmccready
Soundgarden, mcameron, ccornell, kthayill, bshepherd
Temple of the Dog, evedder, mcameron, ccornell, jament, sgossard, mmccready

Body:
To get your unique list use this array formula:

=IFERROR(INDEX($A$2:$A$16,MATCH(0,COUNTIF($E$1:E1,$A$2:$A$16),0)),"")

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

Put in first cell, hit Ctrl-Shift-Enter, then copy down till you get blanks.

To get the username:

=IFERROR(INDEX($B:$B,AGGREGATE(15,6,ROW($A$2:$A$16)/($A$2:$A$16=$E2),COLUMN(A:A))),"")

Where $E2 is the cell in which the other formula is.

Then copy across and down.


问:
chef spawn a background ruby process on windows
Is it possible using chef to spawn a new ruby process using its own ruby interpreter? Alternatively, is it possible to run ruby code asynchronously? My use case is an install file that I want to automate but it does not have a silent install option. I have an automate helper that uses win32ole to automate the install instead.

My current recipe uses a custom resource that looks like

```<code>action :install do
  # calling automate here happens too soon
  windows_package 'ESP' do
    # calling automate here won't happen until after the setup
    action :install
    source repo_from_version('sw', new_resource.version)
    installer_type :custom
    only_if { registry_data_exists?(csreg(node), :name => 'Version', :type => :string, :data => '6.0.0') }
  end
end

action_class do
  include MyModule::Helpers # defines automate
end
</code>```

I thought I might place the automate code in its own file and use spawn to create a new ruby process before calling windows_package and have that process sleep for 3 seconds before trying to automate. But this server will not have ruby installed, except for the built-in chef interpreter.

答: In general, no. Or more specifically Chef has no handling for async actions overall.</p>

Body:
Is it possible using chef to spawn a new ruby process using its own ruby interpreter? Alternatively, is it possible to run ruby code asynchronously? My use case is an install file that I want to automate but it does not have a silent install option. I have an automate helper that uses win32ole to automate the install instead.

My current recipe uses a custom resource that looks like

action :install do
  # calling automate here happens too soon
  windows_package 'ESP' do
    # calling automate here won't happen until after the setup
    action :install
    source repo_from_version('sw', new_resource.version)
    installer_type :custom
    only_if { registry_data_exists?(csreg(node), :name => 'Version', :type => :string, :data => '6.0.0') }
  end
end

action_class do
  include MyModule::Helpers # defines automate
end

I thought I might place the automate code in its own file and use spawn to create a new ruby process before calling windows_package and have that process sleep for 3 seconds before trying to automate. But this server will not have ruby installed, except for the built-in chef interpreter.


问:
How to add watermark to all files in folder?
I am use method, in which openfiledialog and savefiledialog for second method for add  watermark on one picture, press button-call method
How to realize this for all pictures in folder?
I think,neccesary used folderbrowserdialog  like this:

```<code>AddWatermarkOnAllPictures_Click ()
{
folderbrowser.Dialog.ShowDialog();
{
}
}
</code>```

I am right? May be, i must call method, which adds watermark and this methods  work  with ALL  pictures in folder?

答:
Assuming "folderbrowser" is your FolderBrowserDialog

Iterate over the selected directory:

```<code>if (folderbrowser.ShowDialog() != DialogResult.OK) return;

foreach(string file in System.IO.Directory.GetFiles(folderbrowser.SelectedPath))
{
 // Do something
}
</code>```

Body:
I am use method, in which openfiledialog and savefiledialog for second method for add  watermark on one picture, press button-call method
How to realize this for all pictures in folder?
I think,neccesary used folderbrowserdialog  like this:

AddWatermarkOnAllPictures_Click ()
{
folderbrowser.Dialog.ShowDialog();
{
}
}

I am right? May be, i must call method, which adds watermark and this methods  work  with ALL  pictures in folder?

Body:
Assuming "folderbrowser" is your FolderBrowserDialog

Iterate over the selected directory:

if (folderbrowser.ShowDialog() != DialogResult.OK) return;

foreach(string file in System.IO.Directory.GetFiles(folderbrowser.SelectedPath))
{
 // Do something
}


问:
Get SUM of values in a column after query is ran
This is my SQL statement which pulls back all the fills I've had in a certain time frame.  Is there a way to get the list to come up and also pull the SUM of all of them?</p>

```<code>SELECT customerName, date, gallons
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )
ORDER BY CONVERT(DATE, date) ASC
</code>```

答:
First, I would write your query as:

```<code>SELECT customerName, date, gallons
FROM addFill
WHERE date >= '2015-03-03'
ORDER BY date ASC;
</code>```

I see no value in ordering by the date and not the date/time component.  Also, you might as well just use a recognizable date format for the comparison.

If you want the sum as well, then that is tricky.  One method uses rollup:

```<code>SELECT customerName, date, SUM(gallons) as gallons
FROM addFill
WHERE date >= '2015-03-03'
GROUP BY customerName, date with rollup
</code>```

Body:
This is my SQL statement which pulls back all the fills I've had in a certain time frame.  Is there a way to get the list to come up and also pull the SUM of all of them?

SELECT customerName, date, gallons
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )
ORDER BY CONVERT(DATE, date) ASC

Body:
First, I would write your query as:

SELECT customerName, date, gallons
FROM addFill
WHERE date >= '2015-03-03'
ORDER BY date ASC;

I see no value in ordering by the date and not the date/time component.  Also, you might as well just use a recognizable date format for the comparison.

If you want the sum as well, then that is tricky.  One method uses rollup:

SELECT customerName, date, SUM(gallons) as gallons
FROM addFill
WHERE date >= '2015-03-03'
GROUP BY customerName, date with rollup


问:
Why didn't 'npm install canvas' create a javascript file?
I am new to node packages. I attempted to install canvas to my project using:

```<code>npm install canvas
</code>```

Before I could get this to work I needed to install gtk and cairo following the instructions here: https://github.com/Automattic/node-canvas/issues/619

After following the above instructions npm install canvas generated no errors and here is the full output (I don't see any errors):

```<code>canvas@1.6.5 install
C:\Users\user\Desktop\latest\myproject\node_modules\canvas
> node-gyp rebuild

C:\Users\user\Desktop\latest\myproject\node_modules\canvas>if not
defined npm_config_node_gyp (node
"C:\Users\user\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js"
rebuild )  else (node "" rebuild )  Building the projects in this
solution one at a time. To enable parallel build, please add the "/m"
switch.   Canvas.cc   CanvasGradient.cc   CanvasPattern.cc
CanvasRenderingContext2d.cc ..\src\CanvasRenderingContext2d.cc(801):
warning C4458: declaration of 'constructor' hides class member
[C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\canvas.vcxproj]
c:\users\user\desktop\latest\myproject\node_modules\canvas\src\CanvasRenderingContext2d.h(72):
note: see declaration of 'Context2d::constructor' (compiling source
file ..\src\CanvasRenderingContext2d.cc) ..\src\Canvas.cc(154):
warning C4457: declaration of 'data' hides function parameter
[C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\canvas.vcxproj]
..\src\Canvas.cc(150): note: see declaration of 'data'   color.cc
Image.cc   ImageData.cc   init.cc   win_delay_load_hook.cc
     Creating library C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas.lib
and object
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas.exp
Generating code   Finished generating code   canvas.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\canvas.node
canvas.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas.pdb
(Full PDB)   Copying C:/GTK/bin/libcairo-2.dll to
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libcairo-2.dll
          1 file(s) copied.   Copying C:/GTK/bin/libfontconfig-1.dll to
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libfontconfig-1.dll
          1 file(s) copied.   Copying C:/GTK/bin/libexpat-1.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libexpat-1.dll
          1 file(s) copied.   Copying C:/GTK/bin/libfreetype-6.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libfreetype-6.dll
          1 file(s) copied.   Copying C:/GTK/bin/libpng14-14.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libpng14-14.dll
          1 file(s) copied.   Copying C:/GTK/bin/zlib1.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\zlib1.dll
          1 file(s) copied.   win_delay_load_hook.cc   Generating code   Finished generating code   canvas-postbuild.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\canvas-postbuild.node
canvas-postbuild.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas-postbuild.pdb
(Full PDB) myproject@0.1.15 C:\Users\user\Desktop\latest\myproject `--
canvas@1.6.5
</code>```

I don't see any errors however when I perform npm start I see:

```<code>ERROR in ./~/canvas/lib/bindings.js Module not found: Error: Can't
resolve '../build/Release/canvas' in
'C:\Users\me\myapp\node_modules\canvas\lib' @
./~/canvas/lib/bindings.js 3:17-51 @ ./~/canvas/lib/canvas.js @
./app/app.js @ ./app/components/base/base.spec.js
</code>```

I look in the bindings.js file and the only code is:

```<code>module.exports = require('../build/Release/canvas');
</code>```

I navigate to the ../build/Release/canvas folder and find 5 files named canvas with different extensions:

```<code>canvas.exp
canvas.lib
canvas.map
canvas.node
canvas.pdb
</code>```

However there is no canvas.js or other file. None of the files in the 'Release' folder are even javascript. What did I do wrong? What do I need to do right?

答:
It doesn't generate a .js file because it uses a .node file, which is the extension used for native Node Addons, and Node.js will load it just fine.

From Node.js - File Modules:

If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node.

Node is perfectly happy with a .node file, so you can just import it without explicitly adding the extension.

Webpack on the other hand does not look for .node by default. As show in resolve.extensions, the default is:

```<code>extensions: [".js", ".json"]
</code>```

You can change that in your webpack config to:

```<code>resolve: {
  extensions: [".js", ".json", "node"]
}
</code>```

As .node files are loaded differently by Node, you'll probably also need node-loader to make it work in webpack.

Note: Native Node Addons won't work in the browser and for them to work with webpack you'll likely need to set target: 'node' and you might also need to tell webpack to defer the require to run-time by defining it as an external.

Body:
I am new to node packages. I attempted to install canvas to my project using:

npm install canvas

Before I could get this to work I needed to install gtk and cairo following the instructions here: https://github.com/Automattic/node-canvas/issues/619

After following the above instructions npm install canvas generated no errors and here is the full output (I don't see any errors):

canvas@1.6.5 install
C:\Users\user\Desktop\latest\myproject\node_modules\canvas
> node-gyp rebuild

C:\Users\user\Desktop\latest\myproject\node_modules\canvas>if not
defined npm_config_node_gyp (node
"C:\Users\user\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js"
rebuild )  else (node "" rebuild )  Building the projects in this
solution one at a time. To enable parallel build, please add the "/m"
switch.   Canvas.cc   CanvasGradient.cc   CanvasPattern.cc
CanvasRenderingContext2d.cc ..\src\CanvasRenderingContext2d.cc(801):
warning C4458: declaration of 'constructor' hides class member
[C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\canvas.vcxproj]
c:\users\user\desktop\latest\myproject\node_modules\canvas\src\CanvasRenderingContext2d.h(72):
note: see declaration of 'Context2d::constructor' (compiling source
file ..\src\CanvasRenderingContext2d.cc) ..\src\Canvas.cc(154):
warning C4457: declaration of 'data' hides function parameter
[C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\canvas.vcxproj]
..\src\Canvas.cc(150): note: see declaration of 'data'   color.cc
Image.cc   ImageData.cc   init.cc   win_delay_load_hook.cc
     Creating library C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas.lib
and object
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas.exp
Generating code   Finished generating code   canvas.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\canvas.node
canvas.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas.pdb
(Full PDB)   Copying C:/GTK/bin/libcairo-2.dll to
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libcairo-2.dll
          1 file(s) copied.   Copying C:/GTK/bin/libfontconfig-1.dll to
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libfontconfig-1.dll
          1 file(s) copied.   Copying C:/GTK/bin/libexpat-1.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libexpat-1.dll
          1 file(s) copied.   Copying C:/GTK/bin/libfreetype-6.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libfreetype-6.dll
          1 file(s) copied.   Copying C:/GTK/bin/libpng14-14.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\libpng14-14.dll
          1 file(s) copied.   Copying C:/GTK/bin/zlib1.dll to C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\zlib1.dll
          1 file(s) copied.   win_delay_load_hook.cc   Generating code   Finished generating code   canvas-postbuild.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\\canvas-postbuild.node
canvas-postbuild.vcxproj ->
C:\Users\user\Desktop\latest\myproject\node_modules\canvas\build\Release\canvas-postbuild.pdb
(Full PDB) myproject@0.1.15 C:\Users\user\Desktop\latest\myproject `--
canvas@1.6.5

I don't see any errors however when I perform npm start I see:

ERROR in ./~/canvas/lib/bindings.js Module not found: Error: Can't
resolve '../build/Release/canvas' in
'C:\Users\me\myapp\node_modules\canvas\lib' @
./~/canvas/lib/bindings.js 3:17-51 @ ./~/canvas/lib/canvas.js @
./app/app.js @ ./app/components/base/base.spec.js

I look in the bindings.js file and the only code is:

module.exports = require('../build/Release/canvas');

I navigate to the ../build/Release/canvas folder and find 5 files named canvas with different extensions:

canvas.exp
canvas.lib
canvas.map
canvas.node
canvas.pdb

However there is no canvas.js or other file. None of the files in the 'Release' folder are even javascript. What did I do wrong? What do I need to do right?

Body:
It doesn't generate a .js file because it uses a .node file, which is the extension used for native Node Addons, and Node.js will load it just fine.

From Node.js - File Modules:

If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node.

Node is perfectly happy with a .node file, so you can just import it without explicitly adding the extension.

Webpack on the other hand does not look for .node by default. As show in resolve.extensions, the default is:

extensions: [".js", ".json"]

You can change that in your webpack config to:

resolve: {
  extensions: [".js", ".json", "node"]
}

As .node files are loaded differently by Node, you'll probably also need node-loader to make it work in webpack.

Note: Native Node Addons won't work in the browser and for them to work with webpack you'll likely need to set target: 'node' and you might also need to tell webpack to defer the require to run-time by defining it as an external.


问:
Why is my canvas line so small and disoriented?
In my very simple code example below, I am trying to draw a box, 10 pixels in from the margin all the way around the outside of a canvas. Despite getting what seem like legit values from the screen extends of the browser window, I am only getting an L-shaped line, which seems really odd. My code seems very straight forward. So 2 questions:

Why is it so small (eg not going across the whole browser window?

Why isn't it a box like the code suggests it should be?

X:

Y:

<canvas id="DemoCanvas" width=100% height=100%></canvas>

```

Here's the result which you can clearly see is both way too small and not a box at all:

答:
Because you are using window / document width & height,
e.g. the entire webpage, so the lines goes outside of the canvas.

you should instead use the canvas element's width & height.

var canvas = document.getElementById('DemoCanvas');
var xoutput = document.getElementById('X');
var youtput = document.getElementById('Y');

// Always check for properties and methods, to make sure your code doesn't break in other browsers.
if (canvas.getContext)
 {
  var margin = 10;

  var startx = margin;
  var starty = margin;

  var endx = canvas.clientWidth - margin;
 var endy = canvas.clientHeight - margin;

 xoutput.innerHTML = endx;
 youtput.innerHTML = endy-margin;

  var context = canvas.getContext('2d');

   context.beginPath();

   context.moveTo(startx,starty);
   context.lineTo(endx,starty);
 context.lineTo(endx,endy);
  context.lineTo(startx,endy);
   context.lineTo(startx,starty);

  context.stroke();
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="X">X:</p>
<p id="Y">Y:</p>
<!--<form>
Timeline Item: <input type="text" name="item"><br>
Timeline Date: <input type="date" name="date"><br>
</form>-->
<canvas id="DemoCanvas" width=100 height=100></canvas>  </code>```

To achieve "fullscreen", something you can do is to use a parent element or the body tag and then "copy" it's width & height to the canvas afterwards.
Note that i use vh & vw instead of % to avoid any stretching issues, etc.

var canvas = document.getElementById('DemoCanvas');
var xoutput = document.getElementById('X');
var youtput = document.getElementById('Y');

updateCanvasSize();

function updateCanvasSize(){
  canvas.width = bodySim.clientWidth;
  canvas.height = bodySim.clientHeight;

  draw();
  }

function draw(){
 if (canvas.getContext)
 {
  var margin = 10;

  var startx = margin;
  var starty = margin;

  var endx = canvas.clientWidth - margin;
 var endy = canvas.clientHeight - margin;

 xoutput.innerHTML = endx;
 youtput.innerHTML = endy-margin;

  var context = canvas.getContext('2d');

   context.beginPath();

   context.moveTo(startx,starty);
   context.lineTo(endx,starty);
 context.lineTo(endx,endy);
  context.lineTo(startx,endy);
   context.lineTo(startx,starty);

  context.stroke();
 }
} //end of draw```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#bodySim {
  width: 100vw;
  height: 100vh;
}</code>```

X:

Y:

<canvas id="DemoCanvas" ></canvas>

```

Body:
In my very simple code example below, I am trying to draw a box, 10 pixels in from the margin all the way around the outside of a canvas. Despite getting what seem like legit values from the screen extends of the browser window, I am only getting an L-shaped line, which seems really odd. My code seems very straight forward. So 2 questions:

Why is it so small (eg not going across the whole browser window?

Why isn't it a box like the code suggests it should be?

X:

Y:

<canvas id="DemoCanvas" width=100% height=100%></canvas>

Here's the result which you can clearly see is both way too small and not a box at all:

Body:
Because you are using window / document width & height,
e.g. the entire webpage, so the lines goes outside of the canvas.

you should instead use the canvas element's width & height.

var canvas = document.getElementById('DemoCanvas');
var xoutput = document.getElementById('X');
var youtput = document.getElementById('Y');

// Always check for properties and methods, to make sure your code doesn't break in other browsers.
if (canvas.getContext)
 {
  var margin = 10;

  var startx = margin;
  var starty = margin;

  var endx = canvas.clientWidth - margin;
 var endy = canvas.clientHeight - margin;

 xoutput.innerHTML = endx;
 youtput.innerHTML = endy-margin;

  var context = canvas.getContext('2d');

   context.beginPath();

   context.moveTo(startx,starty);
   context.lineTo(endx,starty);
 context.lineTo(endx,endy);
  context.lineTo(startx,endy);
   context.lineTo(startx,starty);

  context.stroke();
 }

<p id="X">X:</p>
<p id="Y">Y:</p>
<!--<form>
Timeline Item: <input type="text" name="item"><br>
Timeline Date: <input type="date" name="date"><br>
</form>-->
<canvas id="DemoCanvas" width=100 height=100></canvas>

To achieve "fullscreen", something you can do is to use a parent element or the body tag and then "copy" it's width & height to the canvas afterwards.
Note that i use vh & vw instead of % to avoid any stretching issues, etc.

var canvas = document.getElementById('DemoCanvas');
var xoutput = document.getElementById('X');
var youtput = document.getElementById('Y');

updateCanvasSize();

function updateCanvasSize(){
  canvas.width = bodySim.clientWidth;
  canvas.height = bodySim.clientHeight;

  draw();
  }

function draw(){
 if (canvas.getContext)
 {
  var margin = 10;

  var startx = margin;
  var starty = margin;

  var endx = canvas.clientWidth - margin;
 var endy = canvas.clientHeight - margin;

 xoutput.innerHTML = endx;
 youtput.innerHTML = endy-margin;

  var context = canvas.getContext('2d');

   context.beginPath();

   context.moveTo(startx,starty);
   context.lineTo(endx,starty);
 context.lineTo(endx,endy);
  context.lineTo(startx,endy);
   context.lineTo(startx,starty);

  context.stroke();
 }
} //end of draw

#bodySim {
  width: 100vw;
  height: 100vh;
}

<p id="X">X:</p>
<p id="Y">Y:</p>
<!--<form>
Timeline Item: <input type="text" name="item"><br>
Timeline Date: <input type="date" name="date"><br>
</form>-->
<div id="bodySim">
<canvas id="DemoCanvas" ></canvas>
</div>


问:
JavaScript regular expression for two-letter tokens separated by commas
I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.

Here i included the acceptable sting

```<code>string = ab,ca,ls,gz,tv......
</code>```

I tried:

```<code>/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/
</code>```

but it is not working as expected.

答:
If I'm understanding you correctly, then you're trying to get (capture) the 2 characters, with the condition that they're within the bounds of a comma or at the start or end of a line:

```<code>(?:^|,)([a-zA-Z]{2})(?=,|$)
</code>```

Live preview

var string = "ab,ca,ls,gz,tv";

const regex = /(?:^|,)([a-zA-Z]{2})(?=,|$)/g;

match = regex.exec(string);

while (match != null) {
    console.log(match[1]);
    match = regex.exec(string);
}```

The above outputs:

ab

ca

ls

gz

tv

Body:
I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.

Here i included the acceptable sting

string = ab,ca,ls,gz,tv......

I tried:

/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/

but it is not working as expected.

Body:
If I'm understanding you correctly, then you're trying to get (capture) the 2 characters, with the condition that they're within the bounds of a comma or at the start or end of a line:

(?:^|,)([a-zA-Z]{2})(?=,|$)

Live preview

var string = "ab,ca,ls,gz,tv";

const regex = /(?:^|,)([a-zA-Z]{2})(?=,|$)/g;

match = regex.exec(string);

while (match != null) {
    console.log(match[1]);
    match = regex.exec(string);
}

The above outputs:

ab

ca

ls

gz

tv


问:
Skype Bot responding with empty body
I'm trying to get a Skype bot up and running based off of the echo example but I'm struggling to make a successful POST to my app. When I send a post to /v1/chat I get back a status of 201 (successful creation), and nothing in the body. My console.log does not print anything either, which leads me to believe that the botService.on('personalMessage', ...) function is not being run. Does anyone have any insight into how these POST requests should be formatted? I cannot seem to find anything in the documentation.

My code:

```<code>const fs = require('fs');
const restify = require('restify');
const skype = require('skype-sdk');

const botService = new skype.BotService({
    messaging: {
        botId: '28:<bot’s id="ID176db9ab-e313-4d76-a60c-bc2a280e9825">',
        serverUrl : "https://apis.skype.com",
        requestTimeout : 15000,
        appId: process.env.APP_ID,
        appSecret: process.env.APP_SECRET
    }
});

botService.on('contactAdded', (bot, data) => {
    console.log('contact added');
    bot.reply('Hello ${data.fromDisplayName}!', true);
});

botService.on('personalMessage', (bot, data) => {
    console.log('message incoming');
    console.log(data);
    bot.reply('Hey ${data.from}. Thank you for your message: "${data.content}".', true);
});

const server = restify.createServer();
server.post('/v1/chat', skype.messagingHandler(botService));
const port = process.env.PORT || 8080;
server.listen(port);
console.log('Listening for incoming requests on port ' + port);
</code>```

答:
Make sure that Procfile and worker processes are setup.

My bot is working fine on heroku itself

Title: Skype Bot responding with empty body

Body:
I'm trying to get a Skype bot up and running based off of the echo example but I'm struggling to make a successful POST to my app. When I send a post to /v1/chat I get back a status of 201 (successful creation), and nothing in the body. My console.log does not print anything either, which leads me to believe that the botService.on('personalMessage', ...) function is not being run. Does anyone have any insight into how these POST requests should be formatted? I cannot seem to find anything in the documentation.

My code:

const fs = require('fs');
const restify = require('restify');
const skype = require('skype-sdk');

const botService = new skype.BotService({
    messaging: {
        botId: '28:<bot’s id="ID176db9ab-e313-4d76-a60c-bc2a280e9825">',
        serverUrl : "https://apis.skype.com",
        requestTimeout : 15000,
        appId: process.env.APP_ID,
        appSecret: process.env.APP_SECRET
    }
});

botService.on('contactAdded', (bot, data) => {
    console.log('contact added');
    bot.reply('Hello ${data.fromDisplayName}!', true);
});

botService.on('personalMessage', (bot, data) => {
    console.log('message incoming');
    console.log(data);
    bot.reply('Hey ${data.from}. Thank you for your message: "${data.content}".', true);
});

const server = restify.createServer();
server.post('/v1/chat', skype.messagingHandler(botService));
const port = process.env.PORT || 8080;
server.listen(port);
console.log('Listening for incoming requests on port ' + port);


问:
Website with a database questions
i'm creating a website connected to a database that pulls information for a team. It should be able to hold and process information without pushing it back into the database.
How do I approach this? What is a good technology to use for this. I know some sort of SQL will be needed for the database. What sort of technology should I use for developing this? I've heard of ASP.NET, AngularJS. What language what should I use with what technology? Also, are there any references or tutorials I could look at that could really help me get this job done? I was hoping to get this done in under a week!
Any help will be very appreciated.
Thank you</p>

答: This question is so general. I hardly hold my emotions into play here. You want to create a web site in under a week without any experience what so ever (that's what I understand from your question, otherwise you won't ask for what technology to use). You can achieve this with any of the mentioned technologies, but you got to have a little bit of knowledge here. In my opinion you have to learn the basics of the field you are targeting and then go for that kind of challenges.</p>

Title: Website with a database questions


问:
Hide div if value is undefined or blank (Angularjs)
I have the following. If i do a console.log($scope.variable), i get 2 values of it at different times on the console.

It shows undefined and '' at the console.

I want to hide a div on basis of this value. I do the following

```<code><div ng-hide="$scope.variable== undefined || $scope.variable = ''>
  Hide this section
</div>
</code>```

It should be able to hide the section since the values are either undefined and '' at all cases. However the div still shows at the UI. Am i missing any constraint or not putting the condition check properly ?

答:
Ng-show should never be used.It will load view in value and just hides it by setting css property display:none.  Instead use ng-if

```<code><div ng-if="variable != null"></div>
or

<div ng-if="variable === null>
  Hide this section
</div>
</code>```

Body:
I have the following. If i do a console.log($scope.variable), i get 2 values of it at different times on the console.

It shows undefined and '' at the console.

I want to hide a div on basis of this value. I do the following

  Hide this section

It should be able to hide the section since the values are either undefined and '' at all cases. However the div still shows at the UI. Am i missing any constraint or not putting the condition check properly ?

Body:
Ng-show should never be used.It will load view in value and just hides it by setting css property display:none.  Instead use ng-if

<div ng-if="variable != null"></div>
or

<div ng-if="variable === null>
  Hide this section
</div>


问:
Destructor causes corruption of the heap.
I'm playing around with destructors and I don't understand why I get an error for this code when the main function terminates.

```<code>#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;

class RGBA {
    uint8_t _red, _blue, _green, _alpha;
    int *_arr;
    int _length;
public:
    RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255):
      _red (r), _blue (b), _green (g), _alpha (a) {
      _arr = arr;
      _length = length;
      }
      ~RGBA() {
          cout << "Destroying object" << endl;
          delete[] _arr;
      }

    void print() {
        for (int i = 0; i < _length; ++i) {
            cout << _arr[i] << endl;
        }
        cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
    }
};

int main() {
    int arr[3] = {1,2,3};
    RGBA rgba(arr, 3);
    rgba.print();

    cin.get();
    return 0;
}
</code>```

It outputs, but then when I press Enter, it prints 'Destroying object' with the following error "This may be due to a corruption of the heap, which indicates a bug in testcpp.exe or any of the DLLs it has loaded.".

```<code>1
2
3
0 0 0 255
</code>```

I use VS2010 on Win7.

答:
```<code>~RGBA() {
    cout << "Destroying object" << endl;
    delete[] _arr;
}
</code>```

Here was your problem because delete didn't work on static array, It always work for dynamic array. delete only work for new

```<code>int *arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
</code>```

this will work perfectly.

Body:
I'm playing around with destructors and I don't understand why I get an error for this code when the main function terminates.

#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;

class RGBA {
    uint8_t _red, _blue, _green, _alpha;
    int *_arr;
    int _length;
public:
    RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255):
      _red (r), _blue (b), _green (g), _alpha (a) {
      _arr = arr;
      _length = length;
      }
      ~RGBA() {
          cout << "Destroying object" << endl;
          delete[] _arr;
      }

    void print() {
        for (int i = 0; i < _length; ++i) {
            cout << _arr[i] << endl;
        }
        cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
    }
};

int main() {
    int arr[3] = {1,2,3};
    RGBA rgba(arr, 3);
    rgba.print();

    cin.get();
    return 0;
}

It outputs, but then when I press Enter, it prints 'Destroying object' with the following error "This may be due to a corruption of the heap, which indicates a bug in testcpp.exe or any of the DLLs it has loaded.".

1
2
3
0 0 0 255

I use VS2010 on Win7.

Body:
~RGBA() {
    cout << "Destroying object" << endl;
    delete[] _arr;
}

Here was your problem because delete didn't work on static array, It always work for dynamic array. delete only work for new

int *arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

this will work perfectly.


问:
How to make wx.Frame modal in wxPython (Phoenix)
There used to be in wxPython 2

```<code>self.MakeModal(True)
</code>```

But not in Phoenix.
How do I show it Modal?
I do not want to use wx.Dialog because i need to add status bar.

答:
a good work-around that I've used is to add the style flag wx.FRAME_FLOAT_ON_PARENT to the frame and disable the parent window via frame.GetParent().Disable(). Then bind the modal-like frame to EVT_CLOSE and re-enable the parent window via frame.GetParent().Enable().

------ Update -----

Robin Dunn's suggestion is a more appropriate way to Modalize a frame.
From the wx phoenix migration guide, add this to your Frame class

```<code>def MakeModal(self, modal=True):
    if modal and not hasattr(self, '_disabler'):
        self._disabler = wx.WindowDisabler(self)
    if not modal and hasattr(self, '_disabler'):
        del self._disabler
</code>```

Body:
There used to be in wxPython 2

self.MakeModal(True)

But not in Phoenix.
How do I show it Modal?
I do not want to use wx.Dialog because i need to add status bar.

Body:
a good work-around that I've used is to add the style flag wx.FRAME_FLOAT_ON_PARENT to the frame and disable the parent window via frame.GetParent().Disable(). Then bind the modal-like frame to EVT_CLOSE and re-enable the parent window via frame.GetParent().Enable().

------ Update -----

Robin Dunn's suggestion is a more appropriate way to Modalize a frame.
From the wx phoenix migration guide, add this to your Frame class

def MakeModal(self, modal=True):
    if modal and not hasattr(self, '_disabler'):
        self._disabler = wx.WindowDisabler(self)
    if not modal and hasattr(self, '_disabler'):
        del self._disabler