问:
Weird Timeout problems on .Net module WebRequests
I've got the following issue:
I'm working on a .Net module which sends requests every ~500ms to a server situated in the same region as the IIS server.
Most of these requests (about 99%) take about 1~3ms to be treated. However, some of these requests are timing out (I've set the WebRequest.Timeout to 150ms, it is important).

There is two weird things:

First the timeout requests would take about ~180ms to execute if I set the timeout to infinite, which is weird as the other requests are quick as lightning

When catching the WebException resulting, I measure ~350ms between the moment I call WebRequest.GetResponse() and the moment the exception is catched whereas I've set the WebRequet.Timeout to 150ms. This gap of performance really is a problem for us and I don't understand why it is happening

This is the legacy code I'm working on:

```<code>ApiResult IApiService.Request(IConnectorRequest request)
{
    long timestamp = 0;
    DebugStream debug = null;

    try
    {
        var dictionary = CollectData(request);

        //TODO:May be include some ServicePoint information.
        //APIConnectionState=Reused

        // Sending request to the API //////////////////////////////////////////////////////
        var http = CreateRequest();

        Stream stream;
        using (stream = http.GetRequestStream())
        {
            if (_Log.IsDebug)
            {
                stream = debug = new DebugStream(stream, _Encoding);
            }

            dictionary.WriteForm(stream, _Encoding);
        }

        if (debug != null)
        {
            _Log.Debug("WebRequestApiService.Request({0:N}): {1}", request.Id, debug.Data);
        }

        // Start request and fix timestamp before execution.
        timestamp = Stopwatch.GetTimestamp();
        var response = http.GetResponse() as HttpWebResponse;
        // (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond => ~2ms

        if (response == null)
        {
            const string message = "Response is not HttpWebResponse";
            _Log.Warning("WebRequestApiService.Request({0:N}): {1}", request.Id, message);

            return ApiResult.Failure(message);
        }
        response.GetRequestHeaders();
        return new ApiResult()
        {
            StatusCode = (int)response.StatusCode,
            Description = response.StatusDescription,
            DataDomeStatus = response.GetStatusHeader(),
            Headers = response.GetHeaders()
        };
    }
    catch (WebException we)
    {
        var errorMessage = string.Empty;
        var response = we.Response as HttpWebResponse;
        Exception e;

        if (response != null)
        {
            errorMessage = response.GetText(out e);

            if (response.StatusCode == HttpStatusCode.Forbidden)
            {
                return new ApiResult()
                {
                    StatusCode = (int)response.StatusCode,
                    Description = response.StatusDescription,
                    DataDomeStatus = response.GetStatusHeader(),
                    Headers = response.GetHeaders(),
                    Content = errorMessage
                };
            }

            if (errorMessage == null)
            {
                _Log.Warning("WebRequestApiService.Request({0}): Problem getting response {1}", request.Id, e);
            }
        }

        // (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond => ~350ms
        _Log.Warning(
            "WebRequestApiService.Request({0}): Message={1}\nTimeout={2}\nError=\n{3}\n\nRequest=\n{4}\n\nAPI=\n{5}\n",
            request.Id,
            errorMessage,
            (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond,
            we,
            request.Dump(),
            debug != null ? debug.Data : "NULL"
        );

        return ApiResult.Failure(errorMessage);
    }
    catch (Exception e)
    {
        _Log.Warning(
            "WebRequestApiService.Request({0}): Timeout={1}\nError=\n{2}\n\nRequest=\n{3}\n\nAPI=\n{4}\n",
            request.Id,
            (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond,
            e,
            request.Dump(),
            debug != null ? debug.Data : "NULL"
        );

        return ApiResult.Failure(e.Message);
    }
}
</code>```

And this is the method used to create our HttpWebRequest:

```<code>private HttpWebRequest CreateRequest()
{
    var http = WebRequest.Create(_uri) as HttpWebRequest;

    if (http == null)
    {
        throw new NotImplementedException();
    }

    // Disable proxy (if node proxy configuration in config file). Otherwise the first
    // request will be slowed down due the proxy auto-detection.
    if (_noProxy)
    {
        http.Proxy = null;
    }

    // Configure timeout. 150ms in our case
    http.Timeout = _timeout;

    // Force connection to be keep-alive.
    http.KeepAlive = true;

    // Disable caching.
    http.CachePolicy = _cachePolicy;

    // Basic request fields
    http.Method = "POST";
    http.ContentType = "application/x-www-form-urlencoded";
    http.UserAgent = null;

    // If auto redirect is allowed, then we can't catch redirect response from API server.
    http.AllowAutoRedirect = false;

    return http;
}
</code>```

Does someone knows the behavior of WebRequest and why it can have some heavy slowdowns as I am experiencing? And why setting timeout to 150ms causes the exception to be catched at 350ms (which is a bad performance heavy problem for us)?

I'd really like some help from someone more experienced in C# and .Net because I'm new to this world and have customer requests constraints

Thank you in advance

答:
The issue is likely DNS query related. The documentation for Timeout states:

A Domain Name System (DNS) query may take up to 15 seconds to return
  or time out. If your request contains a host name that requires
  resolution and you set Timeout to a value less than 15 seconds, it may
  take 15 seconds or more before a WebException is thrown to indicate a
  timeout on your request.

Body:
I've got the following issue:
I'm working on a .Net module which sends requests every ~500ms to a server situated in the same region as the IIS server.
Most of these requests (about 99%) take about 1~3ms to be treated. However, some of these requests are timing out (I've set the WebRequest.Timeout to 150ms, it is important).

There is two weird things:

First the timeout requests would take about ~180ms to execute if I set the timeout to infinite, which is weird as the other requests are quick as lightning

When catching the WebException resulting, I measure ~350ms between the moment I call WebRequest.GetResponse() and the moment the exception is catched whereas I've set the WebRequet.Timeout to 150ms. This gap of performance really is a problem for us and I don't understand why it is happening

This is the legacy code I'm working on:

ApiResult IApiService.Request(IConnectorRequest request)
{
    long timestamp = 0;
    DebugStream debug = null;

    try
    {
        var dictionary = CollectData(request);

        //TODO:May be include some ServicePoint information.
        //APIConnectionState=Reused

        // Sending request to the API //////////////////////////////////////////////////////
        var http = CreateRequest();

        Stream stream;
        using (stream = http.GetRequestStream())
        {
            if (_Log.IsDebug)
            {
                stream = debug = new DebugStream(stream, _Encoding);
            }

            dictionary.WriteForm(stream, _Encoding);
        }

        if (debug != null)
        {
            _Log.Debug("WebRequestApiService.Request({0:N}): {1}", request.Id, debug.Data);
        }

        // Start request and fix timestamp before execution.
        timestamp = Stopwatch.GetTimestamp();
        var response = http.GetResponse() as HttpWebResponse;
        // (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond => ~2ms

        if (response == null)
        {
            const string message = "Response is not HttpWebResponse";
            _Log.Warning("WebRequestApiService.Request({0:N}): {1}", request.Id, message);

            return ApiResult.Failure(message);
        }
        response.GetRequestHeaders();
        return new ApiResult()
        {
            StatusCode = (int)response.StatusCode,
            Description = response.StatusDescription,
            DataDomeStatus = response.GetStatusHeader(),
            Headers = response.GetHeaders()
        };
    }
    catch (WebException we)
    {
        var errorMessage = string.Empty;
        var response = we.Response as HttpWebResponse;
        Exception e;

        if (response != null)
        {
            errorMessage = response.GetText(out e);

            if (response.StatusCode == HttpStatusCode.Forbidden)
            {
                return new ApiResult()
                {
                    StatusCode = (int)response.StatusCode,
                    Description = response.StatusDescription,
                    DataDomeStatus = response.GetStatusHeader(),
                    Headers = response.GetHeaders(),
                    Content = errorMessage
                };
            }

            if (errorMessage == null)
            {
                _Log.Warning("WebRequestApiService.Request({0}): Problem getting response {1}", request.Id, e);
            }
        }

        // (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond => ~350ms
        _Log.Warning(
            "WebRequestApiService.Request({0}): Message={1}\nTimeout={2}\nError=\n{3}\n\nRequest=\n{4}\n\nAPI=\n{5}\n",
            request.Id,
            errorMessage,
            (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond,
            we,
            request.Dump(),
            debug != null ? debug.Data : "NULL"
        );

        return ApiResult.Failure(errorMessage);
    }
    catch (Exception e)
    {
        _Log.Warning(
            "WebRequestApiService.Request({0}): Timeout={1}\nError=\n{2}\n\nRequest=\n{3}\n\nAPI=\n{4}\n",
            request.Id,
            (Stopwatch.GetTimestamp() - timestamp) / TimeSpan.TicksPerMillisecond,
            e,
            request.Dump(),
            debug != null ? debug.Data : "NULL"
        );

        return ApiResult.Failure(e.Message);
    }
}

And this is the method used to create our HttpWebRequest:

private HttpWebRequest CreateRequest()
{
    var http = WebRequest.Create(_uri) as HttpWebRequest;

    if (http == null)
    {
        throw new NotImplementedException();
    }

    // Disable proxy (if node proxy configuration in config file). Otherwise the first
    // request will be slowed down due the proxy auto-detection.
    if (_noProxy)
    {
        http.Proxy = null;
    }

    // Configure timeout. 150ms in our case
    http.Timeout = _timeout;

    // Force connection to be keep-alive.
    http.KeepAlive = true;

    // Disable caching.
    http.CachePolicy = _cachePolicy;

    // Basic request fields
    http.Method = "POST";
    http.ContentType = "application/x-www-form-urlencoded";
    http.UserAgent = null;

    // If auto redirect is allowed, then we can't catch redirect response from API server.
    http.AllowAutoRedirect = false;

    return http;
}

Does someone knows the behavior of WebRequest and why it can have some heavy slowdowns as I am experiencing? And why setting timeout to 150ms causes the exception to be catched at 350ms (which is a bad performance heavy problem for us)?

I'd really like some help from someone more experienced in C# and .Net because I'm new to this world and have customer requests constraints

Thank you in advance


来源: stackexchange

问:
Nginx 403 forbidden with php-fpm
I am trying to install wordpress on CentOS with nginx and php-fpm and MySQL.

After I install nginx and wordpress. Access any path just get 403 forbidden error.

This is nginx config

```<code>user  nginx nginx;
worker_processes  1;

error_log  logs/error.log;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    gzip  on;

    server {
        listen       80;
        server_name  example.com;
        root /home/wordpress;

        location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ \.php$ {
            include fastcgi.conf;
            fastcgi_index index.php;
            fastcgi_pass 127.0.0.1:9000;
        }
    }
}
</code>```

and fastcgi.conf

```<code>fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;
</code>```

My root path is /home/wordpress.

And the namei -om /home/wordpress is:

```<code>f: /home/wordpress/
 dr-xr-xr-x root  root  /
 drwxr-xr-x root  root  home
 drwxrwxrwx nginx nginx wordpress
</code>```

I found if change the location / add index config as

```<code>    location / {
            index index.php;
            try_files $uri $uri/ /index.php?q=$uri&$args;
    }
</code>```

I can access example.com and get the correct content.

Anything else is also 403 forbidden.

答:
Check the nginx error logs. You'll find something like:

```<code> *472430 directory index of "/home/wordpress" is forbidden
</code>```

You should move index declaration to server block:

```<code>server {
   root /home/wordpress;
   index index.php;
}
</code>```

Moreover make sure to set cgi.fix_pathinfo to 0. e.g. by executing

```<code>sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" php.ini
</code>```

You can find your ini files using php --ini.

Restart php-fpm and your site should load normally.

ContentLicense: CC BY-SA 3.0

Title: Nginx 403 forbidden with php-fpm

Body:
I am trying to install wordpress on CentOS with nginx and php-fpm and MySQL.

After I install nginx and wordpress. Access any path just get 403 forbidden error.

This is nginx config

user  nginx nginx;
worker_processes  1;

error_log  logs/error.log;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    gzip  on;

    server {
        listen       80;
        server_name  example.com;
        root /home/wordpress;

        location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ \.php$ {
            include fastcgi.conf;
            fastcgi_index index.php;
            fastcgi_pass 127.0.0.1:9000;
        }
    }
}

and fastcgi.conf

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

My root path is /home/wordpress.

And the namei -om /home/wordpress is:

f: /home/wordpress/
 dr-xr-xr-x root  root  /
 drwxr-xr-x root  root  home
 drwxrwxrwx nginx nginx wordpress

I found if change the location / add index config as

    location / {
            index index.php;
            try_files $uri $uri/ /index.php?q=$uri&$args;
    }

I can access example.com and get the correct content.

Anything else is also 403 forbidden.

Body:
Check the nginx error logs. You'll find something like:

 *472430 directory index of "/home/wordpress" is forbidden

You should move index declaration to server block:

server {
   root /home/wordpress;
   index index.php;
}

Moreover make sure to set cgi.fix_pathinfo to 0. e.g. by executing

sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" php.ini

You can find your ini files using php --ini.

Restart php-fpm and your site should load normally.


问:
How to use Excluding in FluentAssertions to exclude specific KeyValue pair in Dictionary
I'm using FluentAssertions with ShouldBeEquivalentTo to compare two dictionaries of type Dictionary<string, string> but want to exclude one or more specific KeyValue pairs (because they contain timestamps in this case). How to do this?

I tried things like: opt => opt.Excluding(x => x.Single(kv => kv.Key == "MySearchKey")) but this results in errors like: Message: System.ArgumentException : Expression <Convert(x.Single(kv => (kv.Key == "MySearchKey")))> cannot be used to select a member.

Is what I want possible? Or should I maybe exclude the value only and not the pair (that's maybe even better because the existence of the key will be checked then)? Thanks!

答:
Excluding() is meant to exclude members of a type, not excluding a member of a collection, see documentation for more info.

Note: the code below is for the current stable version 4.19.4 of Fluent Assertions.

Example:
You want to compare instances of Person and PersonDTO, but Person contains the AnotherProperty which you want to exclude from the object comparison.

```<code>var person = new Person
{
    FirstName = "John",
    LastName = "McClane",
    AnotherProperty = 42
};

var personDTO = new PersonDTO
{
    FirstName = "John",
    LastName = "McClane"
};
</code>```

This is where you would use Exclude to exclude a member of a type.

```<code>person.ShouldBeEquivalentTo(personDTO, options => options.Excluding(e => e.AnotherProperty));
</code>```

In your concrete case I would not use ShouldBeEquivalentTo.
Consider these two dictionary instances, where you want to omit a member of a collection, here the member with Key == "unknown".

```<code>var actual = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3,
    ["unknown"] = -1,
    ["fail"] = -2
};

var expected = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};
</code>```

You could either just filter out the unwanted key-value pairs:

```<code>IEnumerable<KeyValuePair<string, int>> filtered = actual.Where(e => e.Key != "unknown");
</code>```

Now the assertion will be between two IEnumerable<KeyValuePair<string, int>>s

```<code>filtered.Should().Equal(expected);
</code>```

which will give the following assertion failure message:

```<code>FluentAssertions.Execution.AssertionFailedException: 'Expected collection to be equal to {[one, 1], [two, 2], [three, 3]}, but {[one, 1], [two, 2], [three, 3], [fail, -2]} contains 1 item(s) too many.'
</code>```

Otherwise turn the filtered enumerable back into a dictionary:

```<code>Dictionary<string, int> filteredDict = actual.Where(e => e.Key != "unknown")
    .ToDictionary(e => e.Key, e => e.Value);
</code>```

You will now be comparing Dictionary<string, int>s again:

```<code>filteredDict.Should().Equal(expected);
</code>```

which will give the following assertion failure message:

```<code>FluentAssertions.Execution.AssertionFailedException: 'Expected dictionary to be equal to {[one, 1], [two, 2], [three, 3]}, but found additional keys {"fail"}.'
</code>```

If want to use the second approach and you do this often, you could create extension methods to extract the logic of removing a member from the test method.

```<code>public static class DictionaryExtensions
{
    public static IDictionary<TKey, TValue> ExceptKeys<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, params TKey[] keys)
    {
        if (dictionary == null) throw new ArgumentNullException(nameof(dictionary));
        if (keys == null) throw new ArgumentNullException(nameof(keys));

        return dictionary.Where(e => !keys.Contains(e.Key)).ToDictionary(e => e.Key, e => e.Value);
    }

    public static IDictionary<TKey, TValue> ExceptValues<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, params TValue[] values)
    {
        if (dictionary == null) throw new ArgumentNullException(nameof(dictionary));
        if (values == null) throw new ArgumentNullException(nameof(values));

        return dictionary.Where(e => !values.Contains(e.Value)).ToDictionary(e => e.Key, e => e.Value);
    }
}
</code>```

You can now write an in my opinion more clear and concise test:

```<code>person.ShouldBeEquivalentTo(personDTO, options => options.Excluding(e => e.AnotherProperty));
</code>```0

Body:
Excluding() is meant to exclude members of a type, not excluding a member of a collection, see documentation for more info.

Note: the code below is for the current stable version 4.19.4 of Fluent Assertions.

Example:
You want to compare instances of Person and PersonDTO, but Person contains the AnotherProperty which you want to exclude from the object comparison.

var person = new Person
{
    FirstName = "John",
    LastName = "McClane",
    AnotherProperty = 42
};

var personDTO = new PersonDTO
{
    FirstName = "John",
    LastName = "McClane"
};

This is where you would use Exclude to exclude a member of a type.

person.ShouldBeEquivalentTo(personDTO, options => options.Excluding(e => e.AnotherProperty));

In your concrete case I would not use ShouldBeEquivalentTo.
Consider these two dictionary instances, where you want to omit a member of a collection, here the member with Key == "unknown".

var actual = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3,
    ["unknown"] = -1,
    ["fail"] = -2
};

var expected = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

You could either just filter out the unwanted key-value pairs:

IEnumerable<KeyValuePair<string, int>> filtered = actual.Where(e => e.Key != "unknown");

Now the assertion will be between two IEnumerable<KeyValuePair<string, int>>s

filtered.Should().Equal(expected);

which will give the following assertion failure message:

FluentAssertions.Execution.AssertionFailedException: 'Expected collection to be equal to {[one, 1], [two, 2], [three, 3]}, but {[one, 1], [two, 2], [three, 3], [fail, -2]} contains 1 item(s) too many.'

Otherwise turn the filtered enumerable back into a dictionary:

Dictionary<string, int> filteredDict = actual.Where(e => e.Key != "unknown")
    .ToDictionary(e => e.Key, e => e.Value);

You will now be comparing Dictionary<string, int>s again:

filteredDict.Should().Equal(expected);

which will give the following assertion failure message:

FluentAssertions.Execution.AssertionFailedException: 'Expected dictionary to be equal to {[one, 1], [two, 2], [three, 3]}, but found additional keys {"fail"}.'

If want to use the second approach and you do this often, you could create extension methods to extract the logic of removing a member from the test method.

public static class DictionaryExtensions
{
    public static IDictionary<TKey, TValue> ExceptKeys<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, params TKey[] keys)
    {
        if (dictionary == null) throw new ArgumentNullException(nameof(dictionary));
        if (keys == null) throw new ArgumentNullException(nameof(keys));

        return dictionary.Where(e => !keys.Contains(e.Key)).ToDictionary(e => e.Key, e => e.Value);
    }

    public static IDictionary<TKey, TValue> ExceptValues<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, params TValue[] values)
    {
        if (dictionary == null) throw new ArgumentNullException(nameof(dictionary));
        if (values == null) throw new ArgumentNullException(nameof(values));

        return dictionary.Where(e => !values.Contains(e.Value)).ToDictionary(e => e.Key, e => e.Value);
    }
}

You can now write an in my opinion more clear and concise test:

actual.ExceptKeys("unknown").Should().Equal(expected);


问:
Django-Rest-Auth authentication issue
I have created REST API using Django Rest Framework and used django-rest-auth for auth endpoints. These APIs are used in mobile apps. I've used TokenAuthentication to secure the API.

```<code>REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
)
}
</code>```

The problem arises when using APIDOC. I've added apidoc using coreapi. The documentation needs to be protected too. I get below error when I access /docs/ with above settings:

```<code>'dict' object has no attribute 'data'
</code>```

So I enabled SessionAuthentication.

```<code>REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
)
}
</code>```

This resulted in login endpoint (/rest-auth/login) breaking with CSRF error.

```<code>{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}
</code>```

So how do I protect the endpoints with just TokenAuth and the documentation with SessionAuth separately? Or can I completely bypass security for login endpoint?

答:
Authentication classes can be defined separately while defining the URLs:

```<code>url(r'^docs/', include_docs_urls(title='PeySO API Doc', public=False,
                                 authentication_classes=[SessionAuthentication])),
</code>```

This allows us to enable SessionAuthentication just for docs and use TokenAuthentication for the API endpoints.

Title: Django-Rest-Auth authentication issue

Body:
I have created REST API using Django Rest Framework and used django-rest-auth for auth endpoints. These APIs are used in mobile apps. I've used TokenAuthentication to secure the API.

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
)
}

The problem arises when using APIDOC. I've added apidoc using coreapi. The documentation needs to be protected too. I get below error when I access /docs/ with above settings:

'dict' object has no attribute 'data'

So I enabled SessionAuthentication.

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
)
}

This resulted in login endpoint (/rest-auth/login) breaking with CSRF error.

{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}

So how do I protect the endpoints with just TokenAuth and the documentation with SessionAuth separately? Or can I completely bypass security for login endpoint?

Body:
Authentication classes can be defined separately while defining the URLs:

url(r'^docs/', include_docs_urls(title='PeySO API Doc', public=False,
                                 authentication_classes=[SessionAuthentication])),

This allows us to enable SessionAuthentication just for docs and use TokenAuthentication for the API endpoints.


问:
migrate ksh script from unix to linux
I need to port several hundreds of ksh scripts from SunOS 5.10 to Linux 2.6.18-231.el5.

On SunOS, ksh version is Version M-11/16/88i.
on linux, ksh Version is AJM 93t+ 2010-02-02

It seems there are lots of differnces between ksh on UNIX and Linux...

Is there any doc for the full list of the incompatibility between the ksh on UNIX vs Linux?
Could someone have any advices on this?
Thanks,

答: We have several thousand ksh files that we use to test our components on AIX, HP/UX, Solaris and now RHEL 5 and we found that zsh was the closest in behaviour, on Linux, to the Korn shells on the other platforms.  We installed zsh and symlinked it to /bin/ksh and were pretty happy with the results.

ContentLicense: CC BY-SA 2.5

Title: migrate ksh script from unix to linux


问:
CDI doesn't see an interceptor
I don't understand why interceptor is not found. I get the following error: the class is not found, or not annotated with @Interceptor and still not registered through a portable extension, or not annotated with @Dependent inside an implicit bean archive
Interceptor itself:

```<code>    @Interceptor
    @Loggable
    public class LoggingInterceptor {

    @Inject
    private Logger logger;

    @AroundConstruct
    public void init(InvocationContext ic) throws Exception {
        logger.fine("Entering constructor");
        try {
            ic.proceed();
        } finally {
            logger.fine("Exiting constructor");
        }
    }

    @AroundInvoke
    public Object logMethod(InvocationContext ic) throws Exception {
        logger.entering(ic.getTarget().toString(),ic.getMethod().getName());
        try {
            return ic.proceed();
        } finally {
            logger.exiting(ic.getTarget().toString(),ic.getMethod().getName());
        }
     }
   }
</code>```

Here is a beans.xml where it is specified:

```<code> <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
        bean-discovery-mode="all">
    <alternatives>
        <class>org.abondar.experimental.javaeedemo.basiccdi.test.MockGenerator</class>
    </alternatives>
    <interceptors>
        <class>org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor</class>
    </interceptors>
</beans>
</code>```

log producer:

```<code>public class LoggingProducer {

    @Produces
    private Logger createLogger(InjectionPoint injectionPoint){
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }
}
</code>```

And loggable annotation:

```<code>@InterceptorBinding
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Loggable {
}
</code>```

For running the app I am using Weld Se.Here is Main.class

```<code>public class Main {
    public static void main(String[] args) {

        Weld weld = new Weld();
        WeldContainer container = weld.initialize();

        BookService service = container.select(BookService.class).get();

        Book book = service.createBook("Salo",5.0f,"A book of salo");
        System.out.println(book);

        weld.shutdown();
    }
}
</code>```

There is another weird problem which I believe causes the one I am asking about:  Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Main because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Main not found.

I see this message related to all classes in my example.

So an entire stack trace:

```<code>Nov 16, 2017 1:24:42 PM org.jboss.weld.bootstrap.WeldStartup <clinit>
INFO: WELD-000900: 3.0.1 (Final)
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.WeldStartup startContainer
INFO: WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Main because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Main not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.test.MockGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.test.MockGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.BookService because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.BookService not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.ThirteenDigits because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.ThirteenDigits not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.IsbnGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.IsbnGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.NumberGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.NumberGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Book because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Book not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Loggable because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Loggable not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.LoggingProducer because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.LoggingProducer not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.IssnGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.IssnGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.EightDigits because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.EightDigits not found.  If this is unexpected, enable DEBUG logging to see the full error.
[WARNING]
org.jboss.weld.exceptions.DeploymentException: WELD-001417: Enabled interceptor class org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor (<class>org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor</class> in file:/home/abondar/IdeaProjects/JavaEEDemo/BasicCDI/target/classes/META-INF/beans.xml@12) does not match an interceptor bean: the class is not found, or not annotated with @Interceptor and still not registered through a portable extension, or not annotated with @Dependent inside an implicit bean archive
    at org.jboss.weld.bootstrap.Validator.validateEnabledInterceptorClasses(Validator.java:661)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:481)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:480)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at org.jboss.weld.environment.se.Weld.initialize(Weld.java:790)
    at org.abondar.experimental.javaeedemo.basiccdi.Main.main(Main.java:10)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:282)
    at java.base/java.lang.Thread.run(Thread.java:844)
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-9,5,org.abondar.experimental.javaeedemo.basiccdi.Main] was interrupted but is still alive after waiting at least 15000msecs
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-9,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-2,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-11,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-4,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-13,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-6,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-15,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] NOTE: 7 thread(s) did not finish despite being asked to  via interruption. This is not a problem with exec:java, it is a problem with the running code. Although not serious, it should be remedied.
[WARNING] Couldn't destroy threadgroup org.codehaus.mojo.exec.ExecJavaMojo$IsolatedThreadGroup[name=org.abondar.experimental.javaeedemo.basiccdi.Main,maxpri=10]
java.lang.IllegalThreadStateException
    at java.base/java.lang.ThreadGroup.destroy(ThreadGroup.java:776)
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:321)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
</code>```

答:
Ok, thanks for the clarifying content.

The problem is that since you're using Weld SE, your beans.xml may not be used the way you're expecting.  Specifically, bean discovery works differently in SE mode.  The error you get is pretty clear - you're missing @Dependent on the interceptor class.

Another way to do what you're trying to do is to use SeContainerInitializer from CDI:

```<code>SeContainer container = SeContainerInitializer.newInstance()
        .enableInterceptors(LoggingInterceptor.class)
        .selectAlternatives(MockGenerator.class).initialize();
</code>```

But I believe you actually found a bug in Weld, since you're using all, all beans should have been discovered.

Title: CDI doesn't see an interceptor

Body:
I don't understand why interceptor is not found. I get the following error: the class is not found, or not annotated with @Interceptor and still not registered through a portable extension, or not annotated with @Dependent inside an implicit bean archive
Interceptor itself:

    @Interceptor
    @Loggable
    public class LoggingInterceptor {

    @Inject
    private Logger logger;

    @AroundConstruct
    public void init(InvocationContext ic) throws Exception {
        logger.fine("Entering constructor");
        try {
            ic.proceed();
        } finally {
            logger.fine("Exiting constructor");
        }
    }

    @AroundInvoke
    public Object logMethod(InvocationContext ic) throws Exception {
        logger.entering(ic.getTarget().toString(),ic.getMethod().getName());
        try {
            return ic.proceed();
        } finally {
            logger.exiting(ic.getTarget().toString(),ic.getMethod().getName());
        }
     }
   }

Here is a beans.xml where it is specified:

 <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
        bean-discovery-mode="all">
    <alternatives>
        <class>org.abondar.experimental.javaeedemo.basiccdi.test.MockGenerator</class>
    </alternatives>
    <interceptors>
        <class>org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor</class>
    </interceptors>
</beans>

log producer:

public class LoggingProducer {

    @Produces
    private Logger createLogger(InjectionPoint injectionPoint){
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }
}

And loggable annotation:

@InterceptorBinding
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Loggable {
}

For running the app I am using Weld Se.Here is Main.class

public class Main {
    public static void main(String[] args) {

        Weld weld = new Weld();
        WeldContainer container = weld.initialize();

        BookService service = container.select(BookService.class).get();

        Book book = service.createBook("Salo",5.0f,"A book of salo");
        System.out.println(book);

        weld.shutdown();
    }
}

There is another weird problem which I believe causes the one I am asking about:  Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Main because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Main not found.

I see this message related to all classes in my example.

So an entire stack trace:

Nov 16, 2017 1:24:42 PM org.jboss.weld.bootstrap.WeldStartup <clinit>
INFO: WELD-000900: 3.0.1 (Final)
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.WeldStartup startContainer
INFO: WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Main because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Main not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.test.MockGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.test.MockGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.BookService because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.BookService not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.ThirteenDigits because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.ThirteenDigits not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.IsbnGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.IsbnGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.NumberGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.NumberGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Book because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Book not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.Loggable because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.Loggable not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.LoggingProducer because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.LoggingProducer not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.IssnGenerator because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.IssnGenerator not found.  If this is unexpected, enable DEBUG logging to see the full error.
Nov 16, 2017 1:24:43 PM org.jboss.weld.bootstrap.MissingDependenciesRegistry handleResourceLoadingException
INFO: WELD-000119: Not generating any bean definitions from org.abondar.experimental.javaeedemo.basiccdi.EightDigits because of underlying class loading error: Type org.abondar.experimental.javaeedemo.basiccdi.EightDigits not found.  If this is unexpected, enable DEBUG logging to see the full error.
[WARNING]
org.jboss.weld.exceptions.DeploymentException: WELD-001417: Enabled interceptor class org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor (<class>org.abondar.experimental.javaeedemo.basiccdi.LoggingInterceptor</class> in file:/home/abondar/IdeaProjects/JavaEEDemo/BasicCDI/target/classes/META-INF/beans.xml@12) does not match an interceptor bean: the class is not found, or not annotated with @Interceptor and still not registered through a portable extension, or not annotated with @Dependent inside an implicit bean archive
    at org.jboss.weld.bootstrap.Validator.validateEnabledInterceptorClasses(Validator.java:661)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:481)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:480)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at org.jboss.weld.environment.se.Weld.initialize(Weld.java:790)
    at org.abondar.experimental.javaeedemo.basiccdi.Main.main(Main.java:10)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:282)
    at java.base/java.lang.Thread.run(Thread.java:844)
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-9,5,org.abondar.experimental.javaeedemo.basiccdi.Main] was interrupted but is still alive after waiting at least 15000msecs
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-9,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-2,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-11,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-4,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-13,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-6,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] thread Thread[ForkJoinPool.commonPool-worker-15,5,org.abondar.experimental.javaeedemo.basiccdi.Main] will linger despite being asked to die via interruption
[WARNING] NOTE: 7 thread(s) did not finish despite being asked to  via interruption. This is not a problem with exec:java, it is a problem with the running code. Although not serious, it should be remedied.
[WARNING] Couldn't destroy threadgroup org.codehaus.mojo.exec.ExecJavaMojo$IsolatedThreadGroup[name=org.abondar.experimental.javaeedemo.basiccdi.Main,maxpri=10]
java.lang.IllegalThreadStateException
    at java.base/java.lang.ThreadGroup.destroy(ThreadGroup.java:776)
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:321)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)

Body:
Ok, thanks for the clarifying content.

The problem is that since you're using Weld SE, your beans.xml may not be used the way you're expecting.  Specifically, bean discovery works differently in SE mode.  The error you get is pretty clear - you're missing @Dependent on the interceptor class.

Another way to do what you're trying to do is to use SeContainerInitializer from CDI:

SeContainer container = SeContainerInitializer.newInstance()
        .enableInterceptors(LoggingInterceptor.class)
        .selectAlternatives(MockGenerator.class).initialize();

But I believe you actually found a bug in Weld, since you're using all, all beans should have been discovered.


问:
Does WebStorm Node.js Remote Debug work with Node.js v8 in Docker container?
Using chrome://inspect I can access 0.0.0.0:56745 to do debugging,

But I find debugging in WebStorm a far better experience. I try to create a Node.js Remote Debug configuration like this to see if WebStorm supports it:

There's no response to any breakpoints in the js files.

Can you tell me whether WebStorm supports debugging Docker node inside WebStorm (not via Chrome developer tool) in the latest 2017.2.5 version?

docker-compose.yml

```<code>version: '3'
services:
  web:
    build:
      context: .
      dockerfile: docker/DockerfileDev.df
    image: web:dev
    ports:
      - "3000:3000"
      - "0.0.0.0:56745:56745"
    expose:
      - "56745"
    entrypoint: ["npm", "run","nodemon" ]
</code>```

package.json:

```<code>  "scripts": {
    "nodemon": "./node_modules/nodemon/bin/nodemon.js --inspect=0.0.0.0:56745 --debug-brk index.js"
  },
</code>```

DockerfileDev.df

```<code>  FROM node:8
  # some other stuff
</code>```

UPDATE

The Remote debugger shows it's connecting, but there's nothing in the console, and doesn't pause at breakpoints:

答:
Node.js Remote run configuration can only be used when debugging with TCP-based Protocol (Node.js < 7.x).

To remotely debug application with Chrome Debugging Protocol (with --inspect/--inspect-brk, Node.js 7+), you need using Chromium Remote run configuration

Body:
Using chrome://inspect I can access 0.0.0.0:56745 to do debugging,

But I find debugging in WebStorm a far better experience. I try to create a Node.js Remote Debug configuration like this to see if WebStorm supports it:

There's no response to any breakpoints in the js files.

Can you tell me whether WebStorm supports debugging Docker node inside WebStorm (not via Chrome developer tool) in the latest 2017.2.5 version?

docker-compose.yml

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: docker/DockerfileDev.df
    image: web:dev
    ports:
      - "3000:3000"
      - "0.0.0.0:56745:56745"
    expose:
      - "56745"
    entrypoint: ["npm", "run","nodemon" ]

package.json:

  "scripts": {
    "nodemon": "./node_modules/nodemon/bin/nodemon.js --inspect=0.0.0.0:56745 --debug-brk index.js"
  },

DockerfileDev.df

  FROM node:8
  # some other stuff

UPDATE

The Remote debugger shows it's connecting, but there's nothing in the console, and doesn't pause at breakpoints:


问:
send a local email with codeIgniter
I try to send a local email with codeIgniter.

```<code>// envoi du mail
 public function envoiMail(){
    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    );
    $sujet = $this->input->post('sujet');
    $message = $this->input->post('message');
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('xxxx@gmail.com', 'Name');
    $this->email->to('xxxx@yahoo.fr');
    $this->email->subject($sujet);
    $this->email->message($message);
    $this->email->send();
  if($this->email->send()){
      // mail transmis
       echo "ok";
  }else{
      // erreur de transmission
      echo"erreur d'envoi";
  }
 }
</code>```

when I test I get this error:  Message: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.

答:
try to update your config to something like this:</p>

```<code> $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'smtp.googlemail.com',
        'smtp_port' => '587',
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    )
</code>```

Title: send a local email with codeIgniter

Body:
I try to send a local email with codeIgniter.

// envoi du mail
 public function envoiMail(){
    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    );
    $sujet = $this->input->post('sujet');
    $message = $this->input->post('message');
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('xxxx@gmail.com', 'Name');
    $this->email->to('xxxx@yahoo.fr');
    $this->email->subject($sujet);
    $this->email->message($message);
    $this->email->send();
  if($this->email->send()){
      // mail transmis
       echo "ok";
  }else{
      // erreur de transmission
      echo"erreur d'envoi";
  }
 }

when I test I get this error:  Message: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed.

Body:
try to update your config to something like this:

 $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'smtp.googlemail.com',
        'smtp_port' => '587',
        'smtp_user' => 'xxxxxxx@gmail.cm',
        'smtp_pass' => 'XXXXXX',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1',
        'crlf'   => '\r\n',
        'newline'   => '\r\n',
    )


问:
AVPlayer UITapGestureRecognizer not working
I have this code for my AVPlayerViewController.

```<code>UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAvPlayer)];
[self.avPlayerViewController.view addGestureRecognizer:tap];
</code>```

but this is not working.. :S, I tried setting

```<code>[self.avPlayerViewController.view setUserInteractionEnabled:YES];
</code>```

still no good..

The only working solution is to use UIGestureRecognizer and implement it's shouldReceiveTouch delegate and check if the av player is touched.. but the issue is, we wan't to capture the "tap release" event.. because if the av player view is just touched, it immediately executes the code and that is not what we wanted...

Please help us with this issue..

Thanks!

答:
The easy solution is add a gesture view on the same movie holder view after adding the movie player.
No need to add the gesture recognizer directly to the movie player.

```<code>  [self.movieHolderView addSubview:self.moviePlayer.view];

  [self.movieHolderView addSubview:self.gestureView];
  [self.movieHolderView bringSubviewToFront:self.gestureView];
</code>```

Now we can add our Gesture recognizer on the gesture view like this

```<code>self.fullScreenTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandler:)];
self.fullScreenTapGesture.numberOfTapsRequired = 1;
[self.gestureView addGestureRecognizer:self.fullScreenTapGesture];
</code>```

Body:
I have this code for my AVPlayerViewController.

UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAvPlayer)];
[self.avPlayerViewController.view addGestureRecognizer:tap];

but this is not working.. :S, I tried setting

[self.avPlayerViewController.view setUserInteractionEnabled:YES];

still no good..

The only working solution is to use UIGestureRecognizer and implement it's shouldReceiveTouch delegate and check if the av player is touched.. but the issue is, we wan't to capture the "tap release" event.. because if the av player view is just touched, it immediately executes the code and that is not what we wanted...

Please help us with this issue..

Thanks!

Body:
The easy solution is add a gesture view on the same movie holder view after adding the movie player.
No need to add the gesture recognizer directly to the movie player.

  [self.movieHolderView addSubview:self.moviePlayer.view];

  [self.movieHolderView addSubview:self.gestureView];
  [self.movieHolderView bringSubviewToFront:self.gestureView];

Now we can add our Gesture recognizer on the gesture view like this

self.fullScreenTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandler:)];
self.fullScreenTapGesture.numberOfTapsRequired = 1;
[self.gestureView addGestureRecognizer:self.fullScreenTapGesture];


问:
use routerLink inside external html template
I am learning routing in angular 2 , In my root app component I am using template configuration property to show navigation links in the view.

app.component.cs

```<code>import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `
              <div style="padding:5px">
              <ul class="nav nav-tabs">
                <li routerLinkActive="active">
                 <a routerLink="home">Home</a>
                </li>

                 <li routerLinkActive="active">
                  <a routerLink="employees">Employees</a>
                 </li>

              </ul>
               <br/>
              <router-outlet></router-outlet>
             </div>
              `
})
export class AppComponent {
}
</code>```

If I have more links the above doesn't look clean and maintainable, So Can I use templateUrl property instead and have all router navigation links in separate html file ? As shown below.

```<code>import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl:'/app/home/navigation_template.html'
})
export class AppComponent {
}
</code>```

navigation_template.html

```<code><div style="padding:5px">
 <ul class="nav nav-tabs">
   <li routerLinkActive="active">
    <a routerLink="home">Home</a>
   </li>

   <li routerLinkActive="active">
      <a routerLink="employees">Employees</a>
   </li>

  </ul>
   <br/>
   <router-outlet></router-outlet>
</div>
</code>```

I have tried that but it doesn't work , I get error saying:

InternalError: too much recursion Stack trace:

答:
For angular 2 and more, the best way to do this is to create a specific routing configuration file.

I created app-routing.module.ts

```<code>import { RouterModule, Routes }     from '@angular/router';

/ Redirection route
const routes: Routes = [
    {
        path: '',
        redirectTo: '/homePage',
        pathMatch: 'full'
    },
    {
        path: 'employees',
        component: EmployeesComponent,
    }];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})

export class AppRoutingModule {}
</code>```

You can then import your AppRoutingModule and when you click on

```<code><a routerLink="employees">Employees</a>
</code>```

you will navigate to the right page.

Don't forget to put

```<code><base href="/">
</code>```

in your index.html file in the head for telling your router that this is the base URL

Body:
I am learning routing in angular 2 , In my root app component I am using template configuration property to show navigation links in the view.

app.component.cs

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `

                 Home

                  Employees

              <router-outlet></router-outlet>

              `
})
export class AppComponent {
}

If I have more links the above doesn't look clean and maintainable, So Can I use templateUrl property instead and have all router navigation links in separate html file ? As shown below.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl:'/app/home/navigation_template.html'
})
export class AppComponent {
}

navigation_template.html

    Home

      Employees

   <router-outlet></router-outlet>

I have tried that but it doesn't work , I get error saying:

InternalError: too much recursion Stack trace:

Body:
For angular 2 and more, the best way to do this is to create a specific routing configuration file.

I created app-routing.module.ts

import { RouterModule, Routes }     from '@angular/router';

/ Redirection route
const routes: Routes = [
    {
        path: '',
        redirectTo: '/homePage',
        pathMatch: 'full'
    },
    {
        path: 'employees',
        component: EmployeesComponent,
    }];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})

export class AppRoutingModule {}

You can then import your AppRoutingModule and when you click on

<a routerLink="employees">Employees</a>

you will navigate to the right page.

Don't forget to put

<base href="/">

in your index.html file in the head for telling your router that this is the base URL


问:
Any way to achieve fulltext-like search on InnoDB
I have a very simple query:

```<code>SELECT ... WHERE row LIKE '%some%' OR row LIKE '%search%' OR  row LIKE '%string%'
</code>```

to search for some search string, but as you can see, it searches for each string individually and it's also not good for performance.

Is there a way to recreate a fulltext-like search using LIKE on an InnoDB table. Of course, I know I can use something like Sphinx to achieve this but I'm looking for a pure MySQL solution.

答:
use a myisam fulltext table to index back into your innodb tables for example:

Build your system using innodb:

```<code>create table users (...) engine=innodb;

create table forums (...) engine=innodb;

create table threads
(
forum_id smallint unsigned not null,
thread_id int unsigned not null default 0,
user_id int unsigned not null,
subject varchar(255) not null, -- gonna want to search this... !!
created_date datetime not null,
next_reply_id int unsigned not null default 0,
view_count int unsigned not null default 0,
primary key (forum_id, thread_id) -- composite clustered PK index
)
engine=innodb;
</code>```

Now the fulltext search table which we will use just to index back into our innodb tables. You can maintain rows in this table either by using a trigger or nightly batch updates etc.

```<code>create table threads_ft
(
forum_id smallint unsigned not null,
thread_id int unsigned not null default 0,
subject varchar(255) not null,
fulltext (subject), -- fulltext index on subject
primary key (forum_id, thread_id) -- composite non-clustered index
)
engine=myisam;
</code>```

Finally the search stored procedure which you call from your php/application:

```<code>drop procedure if exists ft_search_threads;
delimiter #

create procedure ft_search_threads
(
in p_search varchar(255)
)
begin

select
 t.*,
 f.title as forum_title,
 u.username,
 match(tft.subject) against (p_search in boolean mode) as rank
from
 threads_ft tft
inner join threads t on tft.forum_id = t.forum_id and tft.thread_id = t.thread_id
inner join forums f on t.forum_id = f.forum_id
inner join users u on t.user_id = u.user_id
where
 match(tft.subject) against (p_search in boolean mode)
order by
 rank desc
limit 100;

end;

call ft_search_threads('+innodb +clustered +index');
</code>```

Hope this helps :)

Body:
I have a very simple query:

SELECT ... WHERE row LIKE '%some%' OR row LIKE '%search%' OR  row LIKE '%string%'

to search for some search string, but as you can see, it searches for each string individually and it's also not good for performance.

Is there a way to recreate a fulltext-like search using LIKE on an InnoDB table. Of course, I know I can use something like Sphinx to achieve this but I'm looking for a pure MySQL solution.

Body:
use a myisam fulltext table to index back into your innodb tables for example:

Build your system using innodb:

create table users (...) engine=innodb;

create table forums (...) engine=innodb;

create table threads
(
forum_id smallint unsigned not null,
thread_id int unsigned not null default 0,
user_id int unsigned not null,
subject varchar(255) not null, -- gonna want to search this... !!
created_date datetime not null,
next_reply_id int unsigned not null default 0,
view_count int unsigned not null default 0,
primary key (forum_id, thread_id) -- composite clustered PK index
)
engine=innodb;

Now the fulltext search table which we will use just to index back into our innodb tables. You can maintain rows in this table either by using a trigger or nightly batch updates etc.

create table threads_ft
(
forum_id smallint unsigned not null,
thread_id int unsigned not null default 0,
subject varchar(255) not null,
fulltext (subject), -- fulltext index on subject
primary key (forum_id, thread_id) -- composite non-clustered index
)
engine=myisam;

Finally the search stored procedure which you call from your php/application:

drop procedure if exists ft_search_threads;
delimiter #

create procedure ft_search_threads
(
in p_search varchar(255)
)
begin

select
 t.*,
 f.title as forum_title,
 u.username,
 match(tft.subject) against (p_search in boolean mode) as rank
from
 threads_ft tft
inner join threads t on tft.forum_id = t.forum_id and tft.thread_id = t.thread_id
inner join forums f on t.forum_id = f.forum_id
inner join users u on t.user_id = u.user_id
where
 match(tft.subject) against (p_search in boolean mode)
order by
 rank desc
limit 100;

end;

call ft_search_threads('+innodb +clustered +index');

Hope this helps :)


问:
Android adb:opendir failed permission denied
I try to use adb to connect my android device:

```<code>C:\Users\vince>adb shell
shell@M3s:/ $ su root
enter main
start command :am start -a android.intent.action.MAIN -n com.android.settings/com.meizu.settings.root.FlymeRootRequestActivity --ei uid 2000 --ei pid 3472 > /dev/null
shell@M3s:/ # cd data
shell@M3s:/data # ls
opendir failed, Permission denied
255|shell@M3s:/data #
</code>```

I got the #,but the permission is denied

答:
In past it was easy for anyone to ROOT the mobile device for any purpose. But now for user's security, Android has made it really tough to ROOT the android device. There are still some ways and 3rd party software available that can help you in ROOTing the device. But doing so may harm your device or data.

A Workaround for Developers
If you are an android developer and want to test your app using ADB like accessing your app's SQLite DB, then I'll suggest you to use android's emulators. They are purpose built emulators and I think they are ROOTED by default. Currently connecting to those emulators through ADB is really easy and requires no SU access.

NOTE
If you are not an Android developer and want to get ROOT access for cracking / unlocking your device then you may need to play with your device's kernel and any mistake can lead to a non-recoverable damage to your device or to your data.

Body:
I try to use adb to connect my android device:

C:\Users\vince>adb shell
shell@M3s:/ $ su root
enter main
start command :am start -a android.intent.action.MAIN -n com.android.settings/com.meizu.settings.root.FlymeRootRequestActivity --ei uid 2000 --ei pid 3472 > /dev/null
shell@M3s:/ # cd data
shell@M3s:/data # ls
opendir failed, Permission denied
255|shell@M3s:/data #

I got the #,but the permission is denied


问:
Using a select box to trigger JS event to make another select box become passive/active? HTML/JS
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

```<code>function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>
</code>```

Thanks!

答:
I think this is just a simple attribute mix-up. That second select box has an id of icd, but you're trying to change it with document.getElementById('test').

EDIT: Another problem is that you're not sending any variable to toggle2, so the if-then will always fail, and it will always set the visibility to hidden. I think.

Body:
I want select box B to become visible when option 2 is selected in select box A, otherwise it should remain hidden.  It's not working.  Here's my code: [EDIT: I actually want it to be passive instead of hidden.]

The JavaScript first:

function toggle2(value){
if(value=='confirm')
 document.getElementById('test').style.visibility='visible';
else
 document.getElementById('test').style.visibility='hidden';
}

 <select class="select3" name="CaseType" onchange="toggle2()">
  <option value="select" selected="selected">- Select Case Type -</option>
  <option value="suspect">Suspected</option>
  <option value="confirm">Confirmed</option>
  </select>

  <select id="test" class="select4" name="test" style="visibility: hidden;">
  <option selected="selected">- Select test -</option>
  </select>

Thanks!


问:
Elasticsearch results limit issue
I have a python script that should print all the ID's of people in my JSON files stored in elasticsearch. But I only get ten results(truncated), as I know that by default only 10 results are shown.

```<code>from elasticsearch import Elasticsearch
import sys
es = Elasticsearch()
res = es.search(index="my_docs", body={"query": {"match_all": {}}})
print("%d documents found" % res['hits']['total'])
for doc in res['hits']['hits']:
        print (" Doc ID: %s" % (doc['_id']))
</code>```

It says 5000 Documents found but returns 10 ID's only.

What is the way to get all documents' Doc ID's printed from my collection in Elasticsearch?

答:
Use Scroll api if Number of documents exceeds 10000.

Use Search api with limit to get specified count.

Title: Elasticsearch results limit issue

Body:
I have a python script that should print all the ID's of people in my JSON files stored in elasticsearch. But I only get ten results(truncated), as I know that by default only 10 results are shown.

from elasticsearch import Elasticsearch
import sys
es = Elasticsearch()
res = es.search(index="my_docs", body={"query": {"match_all": {}}})
print("%d documents found" % res['hits']['total'])
for doc in res['hits']['hits']:
        print (" Doc ID: %s" % (doc['_id']))

It says 5000 Documents found but returns 10 ID's only.

What is the way to get all documents' Doc ID's printed from my collection in Elasticsearch?


问:
Xcode Swift 4 Facebook & Twitter sharing no longer working?
i am using Facebook & Twitter sharing in my app , after upgrade xCode to 9.0.1 Swift 4, both are not working , the method saying i have no FB or Tw account on my device but they're already there and was working fine with Swift 3.

Log :

```<code>2017-10-25 09:53:41.619676+0300 jack[2428:926750] [core] isAvailableForServiceType: for com.apple.social.facebook returning NO
</code>```

and here is the Code :

```<code>if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)
            {

                let shareText = "xxx"

                let facebookShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
                    //facebookShare.add(imageView.image!)
                    facebookShare.add(URL(string:self.track.share_url))
                    facebookShare.setInitialText(shareText)

                self.present(facebookShare, animated: true, completion: nil)

            }

if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter)
            {
                let shareText = "xxx"
                let twitterSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
                    twitterSheet.add(URL(string : self.track.share_url))
                    twitterSheet.setInitialText( shareText )

                self.present(twitterSheet, animated: true, completion: nil)

            }
</code>```

答:
You have to use Facebook's SDK to share: FBSDKShareKit

You can install it using cocoa pods:

```<code>pod 'FBSDKShareKit'
</code>```

Example

```<code>#import <FBSDKShareKit/FBSDKShareKit.h>

-(IBAction)sharingOnFacebook:(id)sender {
     FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
     content.contentURL = [NSURL URLWithString:@"https://myPageWeb/"];

    [FBSDKShareDialog showFromViewController:self withContent:content delegate:nil];
}
</code>```

And for Twitter the steps are similar: TwitterKit

```<code>pod 'TwitterKit'
</code>```

Example:

```<code>-(IBAction)sharingOnTwitter:(id)sender {
    TWTRComposer *composer = [[TWTRComposer alloc] init];
    [composer setURL:[NSURL URLWithString:@"https://https://myPageWeb/"]];
    [composer showFromViewController:self completion:^(TWTRComposerResult result) {
        /*if (result == TWTRComposerResultCancelled) {
            NSLog(@"Tweet composition cancelled");
        } else {
            NSLog(@"Sending Tweet!");
        }*/
    }];
}
</code>```

NOTE: Read Facebook and Twitter documentation because you need to do some steps for your app previously. Register the app, get the AppID...

Facebook iOS Developers

Twitter iOS Developers page

Body:
i am using Facebook & Twitter sharing in my app , after upgrade xCode to 9.0.1 Swift 4, both are not working , the method saying i have no FB or Tw account on my device but they're already there and was working fine with Swift 3.

Log :

2017-10-25 09:53:41.619676+0300 jack[2428:926750] [core] isAvailableForServiceType: for com.apple.social.facebook returning NO

and here is the Code :

if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)
            {

                let shareText = "xxx"

                let facebookShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
                    //facebookShare.add(imageView.image!)
                    facebookShare.add(URL(string:self.track.share_url))
                    facebookShare.setInitialText(shareText)

                self.present(facebookShare, animated: true, completion: nil)

            }

if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter)
            {
                let shareText = "xxx"
                let twitterSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
                    twitterSheet.add(URL(string : self.track.share_url))
                    twitterSheet.setInitialText( shareText )

                self.present(twitterSheet, animated: true, completion: nil)

            }

Body:
You have to use Facebook's SDK to share: FBSDKShareKit

You can install it using cocoa pods:

pod 'FBSDKShareKit'

Example

#import <FBSDKShareKit/FBSDKShareKit.h>

-(IBAction)sharingOnFacebook:(id)sender {
     FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
     content.contentURL = [NSURL URLWithString:@"https://myPageWeb/"];

    [FBSDKShareDialog showFromViewController:self withContent:content delegate:nil];
}

And for Twitter the steps are similar: TwitterKit

pod 'TwitterKit'

Example:

-(IBAction)sharingOnTwitter:(id)sender {
    TWTRComposer *composer = [[TWTRComposer alloc] init];
    [composer setURL:[NSURL URLWithString:@"https://https://myPageWeb/"]];
    [composer showFromViewController:self completion:^(TWTRComposerResult result) {
        /*if (result == TWTRComposerResultCancelled) {
            NSLog(@"Tweet composition cancelled");
        } else {
            NSLog(@"Sending Tweet!");
        }*/
    }];
}

NOTE: Read Facebook and Twitter documentation because you need to do some steps for your app previously. Register the app, get the AppID...

Facebook iOS Developers

Twitter iOS Developers page


问:
eclipse RCP UI through java code
Can I implement Eclipse RCP UI using java code only and not plugin.xml?

答:
While it might be possible in theory (eclipse plugins are OSGi bundle which are read by the extension registry), I don't think it is practical (unless you re-implement the extension registry lifecycle).

Eclipse Equinox precisely extends the concept of bundles with the concept of extension points, hence the mandatory presence of plugin.xml.

Title: eclipse RCP UI through java code