问:
Why is PHP not taking over system default locale settings?
```<code>root@35395c2d434a:/var/www/project# locale -a
C
C.UTF-8
POSIX
en_GB.utf8
root@35395c2d434a:/var/www/project# echo $LC_MONETARY
en_GB.UTF-8
root@35395c2d434a:/var/www/project#  php -r "echo setlocale(LC_MONETARY, 0).\"\n\";"
C
root@35395c2d434a:/var/www/project#
</code>```

As you can see, I have en_GB.UTF-8 both installed and set in LC_MONETARY environmental variable. But PHP doesn't care and sets it to C anyway. Is there a php configuration so PHP takes this system setting over, so I don't have to set it manually in each PHP script via setlocale(LC_MONETARY, 'en_GB.UTF-8')?

答:
This seems to be limitation of C programs. PHP's setlocale function just returns whatever output returns C's setlocale. From http://php.net/manual/en/function.setlocale.php:

The return value of setlocale() depends on the system that PHP is
  running. It returns exactly what the system setlocale function
  returns.

And from http://www.cplusplus.com/reference/clocale/setlocale/:

Most running environments have certain locale information set
  according to the user preferences or localization. But, independently
  of this system locale, on start, all C programs have the "C" locale
  set, which is a rather neutral locale with minimal locale information
  that allows the result of programs to be predictable. In order to use
  the default locale set in the environment, this function can be called
  with "" as argument locale.

On program startup, the locale selected is the "C" locale, which is
  the same as would be set by calling setlocale(LC_ALL,"C").

The locale settings selected in the environment can be selected by
  calling setlocale(LC_ALL,"").

So as far as I see, there is no way to set this by default for all C programs, nor for PHP.

If someone figures out how to do this for all PHP scripts, I'll accept that answer.

Body:
root@35395c2d434a:/var/www/project# locale -a
C
C.UTF-8
POSIX
en_GB.utf8
root@35395c2d434a:/var/www/project# echo $LC_MONETARY
en_GB.UTF-8
root@35395c2d434a:/var/www/project#  php -r "echo setlocale(LC_MONETARY, 0).\"\n\";"
C
root@35395c2d434a:/var/www/project#

As you can see, I have en_GB.UTF-8 both installed and set in LC_MONETARY environmental variable. But PHP doesn't care and sets it to C anyway. Is there a php configuration so PHP takes this system setting over, so I don't have to set it manually in each PHP script via setlocale(LC_MONETARY, 'en_GB.UTF-8')?


来源: stackexchange

问:
Informix: using stored procedures in Java
how can I find the parameters(function declaration) of stored procedures in Informix?
whether "{ call sp_csq_activity }" or "{ call sp_csq_activity(?,? ..) }" and their types? And also is there any definitions list of this stored functions? How can I use these functions to retrieve any columns of a table in db?</p>

```<code>public void callSP() throws SQLException {

        CallableStatement proc = null;

        proc = conn.prepareCall("{ call sp_csq_activity }");
        proc.execute();

    }
</code>```

答:
You can also use DatabaseMetaData to get the information you want.

A simple program that gets all stored procedures and their parameters is this:

```<code>import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {

    public static void main(String[] args) {

        try {
            Class.forName ("com.informix.jdbc.IfxDriver");
        } catch (ClassNotFoundException e) {
            System.out.println(e);
            return;
        }

        try {
            Connection conn = DriverManager.getConnection("jdbc:informix-sqli://.........");

            ResultSet rsProcs;

            DatabaseMetaData dbMeta = conn.getMetaData();

            rsProcs = dbMeta.getProcedures(null, null, null);

            while (rsProcs.next()) {
                String procName = rsProcs.getString("PROCEDURE_NAME");
                System.out.println(procName);

                ResultSet rsParams = dbMeta.getProcedureColumns(null, null, procName, null);

                while (rsParams.next()) {
                    System.out.println("Param " + rsParams.getString("ORDINAL_POSITION") + " :" +
                            " Name: " + rsParams.getString("COLUMN_NAME") +
                            " Type: " + rsParams.getString("COLUMN_TYPE") +
                            " Data Type: " + rsParams.getString("DATA_TYPE"));
                }
                System.out.println("");

                rsParams.close();
            }
            rsProcs.close();
            conn.close();

        } catch (SQLException e) {
            System.out.println(e);
        }

    }

}
</code>```

Check the java.sql.Types section at Constant Field Values for the SQL data type values.

ContentLicense: CC BY-SA 3.0

Body:
how can I find the parameters(function declaration) of stored procedures in Informix?
whether "{ call sp_csq_activity }" or "{ call sp_csq_activity(?,? ..) }" and their types? And also is there any definitions list of this stored functions? How can I use these functions to retrieve any columns of a table in db?

public void callSP() throws SQLException {

        CallableStatement proc = null;

        proc = conn.prepareCall("{ call sp_csq_activity }");
        proc.execute();

    }

Body:
You can also use DatabaseMetaData to get the information you want.

A simple program that gets all stored procedures and their parameters is this:

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {

    public static void main(String[] args) {

        try {
            Class.forName ("com.informix.jdbc.IfxDriver");
        } catch (ClassNotFoundException e) {
            System.out.println(e);
            return;
        }

        try {
            Connection conn = DriverManager.getConnection("jdbc:informix-sqli://.........");

            ResultSet rsProcs;

            DatabaseMetaData dbMeta = conn.getMetaData();

            rsProcs = dbMeta.getProcedures(null, null, null);

            while (rsProcs.next()) {
                String procName = rsProcs.getString("PROCEDURE_NAME");
                System.out.println(procName);

                ResultSet rsParams = dbMeta.getProcedureColumns(null, null, procName, null);

                while (rsParams.next()) {
                    System.out.println("Param " + rsParams.getString("ORDINAL_POSITION") + " :" +
                            " Name: " + rsParams.getString("COLUMN_NAME") +
                            " Type: " + rsParams.getString("COLUMN_TYPE") +
                            " Data Type: " + rsParams.getString("DATA_TYPE"));
                }
                System.out.println("");

                rsParams.close();
            }
            rsProcs.close();
            conn.close();

        } catch (SQLException e) {
            System.out.println(e);
        }

    }

}

Check the java.sql.Types section at Constant Field Values for the SQL data type values.


问:
Build path using google map
I have a small function to get a route on Google Maps. It works fine when I have English addresses (I mean between two streets in England or other EU\NA countries). But I have a problem when I have Russian addresses which were written on English. Like Example:

from = 'Belarus, Minsk, Russianova, 1'

to = 'Belarus, Minsk, Nikiforova, 1'.

I can find these addresses on Google Maps but I can not build a route and the status results in NOT_FOUND.

It's not a problem when I use a library to translate from English to Russian, but that doesn't solve all problems. For example:

Belarussia => Minsk and Belarus => Brest do not work

Belarus => Minsk and Belarussia, Brest do work

Also it doesn't work with marks at all.

Could you help me to build routes using addresses without having to guess what form of one city works with another?

The function I'm using now is this:

function getRout(from, to) {
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer;
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 53.9,
      lng: 27.6
    }
  });
  directionsDisplay.setMap(map);
  directionsService.route({
    origin: from,
    destination: to,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      window.alert(status);
    }
  });
}```

答: Try spelling it differently: 'Belarus, Minsk, Rusijanava, 1'</p>

Title: Build path using google map


问:
TCP Sockets not working on iPhone 7 running iOS 10.3.2
I am creating an app that communicates with an external service via a TCP Socket (NSStream).

I am running into an issue on an iPhone 7 running iOS 10.3.2 whereby the NSStream is congested and messages can't send fast enough for my app to react. There is no issue with this on an iPhone 6s running iOS 10.3.2 or an iPhone 6 running iOS 9. I have tried this on two iPhone 7's running iOS 10.3.2 and both have the same issue.

So in essence, I'm sending multiple request messages to my external device every second.

For example: If I send 3 messages to the external service every second, only one of the messages sends the response. I have written a callback method that only fires when I get an ACK back from the external device. I have used NSLogs and I have identified that the requests are never actually sent over the socket, leading me to believe this is an iOS issue (Stream is blocked from sending additional messages while waiting for a response maybe?)

Here is my code for my TCPSocketManager class, where the socket connection is managed (I'm sending the requests on a background thread, then once the response comes back, I send the callback out on the main thread):

```<code>@interface TCPSocketManager ()
@property (weak, nonatomic)NSMutableArray *jsonObject;
@property (weak, nonatomic)NSMutableArray *dataQueue;
@property (nonatomic)bool sentNotif;
@end

static NSString *hostIP;
static int hostPORT;
@implementation TCPSocketManager {
    BOOL flag_canSendDirectly;
}

-(instancetype)initWithSocketHost:(NSString *)host withPort:(int)port{
    hostIP = host;
    hostPORT = port;

    _completionDict = [NSMutableDictionary new];
    _dataQueue = [NSMutableArray new];

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)(host), port, &readStream, &writeStream);

    _inputStream = (__bridge NSInputStream *)readStream;
    _outputStream = (__bridge NSOutputStream *)writeStream;

    [self openStreams];
    return self;
}

-(void)openStreams {
    [_outputStream setDelegate:self];
    [_inputStream setDelegate:self];

    [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [_outputStream open];
    [_inputStream open];
}

-(void)closeStreams{
    [_outputStream close];
    [_outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [_inputStream close];
    [_inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void) messageReceived:(NSString *)message {
    [message enumerateLinesUsingBlock:^(NSString * _Nonnull msg, BOOL * _Nonnull stop) {
        [_messages addObject:msg];

        NSError *error;
        NSMutableArray *copyJsonObject = [NSJSONSerialization JSONObjectWithData:[msg dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
        _jsonObject = [copyJsonObject copy];

        NSDictionary *rsp_type = [_jsonObject valueForKey:@"rsp"];
        NSString *typeKey = rsp_type[@"type”];
        CompleteMsgRsp response = _completionDict[typeKey];
        //assign the response to the block

         if (response){
             dispatch_async(dispatch_get_main_queue(), ^{
                  response(rsp_type);
             });
         }

         [_completionDict removeObjectForKey:typeKey]
   }];
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    switch (streamEvent) {
        case NSStreamEventOpenCompleted:
            break;

        case NSStreamEventHasBytesAvailable:
            if (theStream == _inputStream){
                uint8_t buffer[1024];
                NSInteger len;

                while ([_inputStream hasBytesAvailable])
                {
                    len = [_inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0)
                    {
                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
                        if (nil != output)
                        {
                            [self messageReceived:output];
               //Do Something with the message
                        }
                    }
                }
            }
            break;

        case NSStreamEventHasSpaceAvailable:{
            //send data over stream now that we know the stream is ready to send/ receive
            [self _sendData];
            break;
        }
        case NSStreamEventErrorOccurred:
            [self initWithSocketHost:hostIP withPort:hostPORT];
            break;

        case NSStreamEventEndEncountered:
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

            break;
        default:
            DLog(@"Unknown Stream Event");
    }

}

- (void)sendData:(NSData *)data {
    //insert the request to the head of a queue
    [_dataQueue insertObject:data atIndex:0];

    //if able to send directly, send it. This flag is set in _sendData if the array is empty
    //Message is sent when the stream has space available.
    if (flag_canSendDirectly) [self _sendData];
}

-(void)_sendData {
    flag_canSendDirectly = NO;

    //get the last object of the array.
    NSData *data = [_dataQueue lastObject];

    //if data is empty, set the send direct flag
    if (data == nil){
        flag_canSendDirectly = YES;
        return;
    }
    //send request out over stream, store the amount of bytes written to stream
    NSInteger bytesWritten = [_outputStream write:[data bytes] maxLength:[data length]];

    //if bytes written is more than 0, we know something was output over the stream
    if (bytesWritten >0) {
        //remove the request from the queue.
        [self.dataQueue removeLastObject];
    }
}

- (void)sendRequest:(NSString*)request withCompletion:(void (^)(NSDictionary *rsp_dict))finishBlock{
    self.uuid = [[NSUUID UUID] UUIDString];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            //Convert the request string to NSData.
            NSData *data = [[NSData alloc] initWithData:[request dataUsingEncoding:NSASCIIStringEncoding]];

            //method to send the data over stream with a queue
            [self sendData:data];

            //Completion Handler for Messages
            NSString *typeKey = reqType;
            [_completionDict setObject:[finishBlock copy] forKey:typeKey];
    });
}
@end
</code>```

Here is a sample request and the definition of the TCPSocketManager class:

```<code>-(void)connectToSocket{
        _socketMan = [[TCPSocketManager alloc] initWithSocketHost:@"192.168.1.10" withPort:50505];
}

-(void)sendSomeRequest:(NSString *)request {
        [_socketMan sendRequest:request withCompletion:^(NSDictionary *rsp_dict) {
              NSString *result =[rsp_dict objectForKey:@"result"];
              if ([result length] < 3 && [result isEqualToString:@"OK"]){
                  //Successful request with a response
              }else{
                  //Request has failed with no/ bad response
              }
        }];
}
</code>```

Since this problem only appears on iPhone 7 devices. I'm wondering if this is an NSStream bug? Has anyone come across any similar issues. Would I be better off using a library such as CocoaAsyncSocket? Is there any way to fix the issue without using an external library?

I have set up CocoaAsyncSocket before and it didn't help me as it was breaking messages requests and responses. It would send multiple responses back in the same message, adding more complexity when parsing the messages.

答:
After a lot of trial and error, I came to the conclusion that TCP Packets were being coalesced on the kernel level due to me rapidly sending relatively small byte message. I came across Nagles Algorithm` when looking up this issue.

Nagle's algorithm works by combining a number of small outgoing messages, and sending them all at once. Specifically, as long as there is a sent packet for which the sender has received no acknowledgment, the sender should keep buffering its output until it has a full packet's worth of output, thus allowing output to be sent all at once.

The solution to my problem was found on this question.

Basically, In order to fix my problem, I needed to disable Nagles algorithm like so:

```<code>#import <arpa/inet.h>       // for IPPROTO_TCP
#include <netinet/tcp.h>    // for TCP_NODELAY

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    switch (streamEvent) {
      case NSStreamEventOpenCompleted:
        [self disableNaglesAlgorithmForStream:theStream];
        break;
    ...
}

//from tar500's answer in the linked question.
-(void)disableNaglesAlgorithmForStream:(NSStream *)stream {
    CFDataRef socketData;

    // Get socket data
    if ([stream isKindOfClass:[NSOutputStream class]]) {
        socketData = CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)((NSOutputStream *)stream), kCFStreamPropertySocketNativeHandle);
    } else if ([stream isKindOfClass:[NSInputStream class]]) {
        socketData = CFReadStreamCopyProperty((__bridge CFReadStreamRef)((NSInputStream *)stream), kCFStreamPropertySocketNativeHandle);
    }

    // get a handle to the native socket
    CFSocketNativeHandle rawsock;

    CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&rawsock);
    CFRelease(socketData);

    // Disable Nagle's algorythm

    // Debug info
    BOOL isInput = [stream isKindOfClass:[NSInputStream class]];
    NSString * streamType = isInput ? @"INPUT" : @"OUTPUT";

    int err;
    static const int kOne = 1;
    err = setsockopt(rawsock, IPPROTO_TCP, TCP_NODELAY, &kOne, sizeof(kOne));
    if (err < 0) {
        err = errno;
        NSLog(@"Could Not Disable Nagle for %@ stream", streamType);
    } else {
        NSLog(@"Nagle Is Disabled for %@ stream", streamType);
    }
}
</code>```

After disabling Nagles, my socket messages appeared to be more responsive and I'm not experiencing the packet coalescing any more.

Body:
I am creating an app that communicates with an external service via a TCP Socket (NSStream).

I am running into an issue on an iPhone 7 running iOS 10.3.2 whereby the NSStream is congested and messages can't send fast enough for my app to react. There is no issue with this on an iPhone 6s running iOS 10.3.2 or an iPhone 6 running iOS 9. I have tried this on two iPhone 7's running iOS 10.3.2 and both have the same issue.

So in essence, I'm sending multiple request messages to my external device every second.

For example: If I send 3 messages to the external service every second, only one of the messages sends the response. I have written a callback method that only fires when I get an ACK back from the external device. I have used NSLogs and I have identified that the requests are never actually sent over the socket, leading me to believe this is an iOS issue (Stream is blocked from sending additional messages while waiting for a response maybe?)

Here is my code for my TCPSocketManager class, where the socket connection is managed (I'm sending the requests on a background thread, then once the response comes back, I send the callback out on the main thread):

@interface TCPSocketManager ()
@property (weak, nonatomic)NSMutableArray *jsonObject;
@property (weak, nonatomic)NSMutableArray *dataQueue;
@property (nonatomic)bool sentNotif;
@end

static NSString *hostIP;
static int hostPORT;
@implementation TCPSocketManager {
    BOOL flag_canSendDirectly;
}

-(instancetype)initWithSocketHost:(NSString *)host withPort:(int)port{
    hostIP = host;
    hostPORT = port;

    _completionDict = [NSMutableDictionary new];
    _dataQueue = [NSMutableArray new];

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)(host), port, &readStream, &writeStream);

    _inputStream = (__bridge NSInputStream *)readStream;
    _outputStream = (__bridge NSOutputStream *)writeStream;

    [self openStreams];
    return self;
}

-(void)openStreams {
    [_outputStream setDelegate:self];
    [_inputStream setDelegate:self];

    [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [_outputStream open];
    [_inputStream open];
}

-(void)closeStreams{
    [_outputStream close];
    [_outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [_inputStream close];
    [_inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void) messageReceived:(NSString *)message {
    [message enumerateLinesUsingBlock:^(NSString * _Nonnull msg, BOOL * _Nonnull stop) {
        [_messages addObject:msg];

        NSError *error;
        NSMutableArray *copyJsonObject = [NSJSONSerialization JSONObjectWithData:[msg dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
        _jsonObject = [copyJsonObject copy];

        NSDictionary *rsp_type = [_jsonObject valueForKey:@"rsp"];
        NSString *typeKey = rsp_type[@"type”];
        CompleteMsgRsp response = _completionDict[typeKey];
        //assign the response to the block

         if (response){
             dispatch_async(dispatch_get_main_queue(), ^{
                  response(rsp_type);
             });
         }

         [_completionDict removeObjectForKey:typeKey]
   }];
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    switch (streamEvent) {
        case NSStreamEventOpenCompleted:
            break;

        case NSStreamEventHasBytesAvailable:
            if (theStream == _inputStream){
                uint8_t buffer[1024];
                NSInteger len;

                while ([_inputStream hasBytesAvailable])
                {
                    len = [_inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0)
                    {
                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
                        if (nil != output)
                        {
                            [self messageReceived:output];
               //Do Something with the message
                        }
                    }
                }
            }
            break;

        case NSStreamEventHasSpaceAvailable:{
            //send data over stream now that we know the stream is ready to send/ receive
            [self _sendData];
            break;
        }
        case NSStreamEventErrorOccurred:
            [self initWithSocketHost:hostIP withPort:hostPORT];
            break;

        case NSStreamEventEndEncountered:
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

            break;
        default:
            DLog(@"Unknown Stream Event");
    }

}

- (void)sendData:(NSData *)data {
    //insert the request to the head of a queue
    [_dataQueue insertObject:data atIndex:0];

    //if able to send directly, send it. This flag is set in _sendData if the array is empty
    //Message is sent when the stream has space available.
    if (flag_canSendDirectly) [self _sendData];
}

-(void)_sendData {
    flag_canSendDirectly = NO;

    //get the last object of the array.
    NSData *data = [_dataQueue lastObject];

    //if data is empty, set the send direct flag
    if (data == nil){
        flag_canSendDirectly = YES;
        return;
    }
    //send request out over stream, store the amount of bytes written to stream
    NSInteger bytesWritten = [_outputStream write:[data bytes] maxLength:[data length]];

    //if bytes written is more than 0, we know something was output over the stream
    if (bytesWritten >0) {
        //remove the request from the queue.
        [self.dataQueue removeLastObject];
    }
}

- (void)sendRequest:(NSString*)request withCompletion:(void (^)(NSDictionary *rsp_dict))finishBlock{
    self.uuid = [[NSUUID UUID] UUIDString];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            //Convert the request string to NSData.
            NSData *data = [[NSData alloc] initWithData:[request dataUsingEncoding:NSASCIIStringEncoding]];

            //method to send the data over stream with a queue
            [self sendData:data];

            //Completion Handler for Messages
            NSString *typeKey = reqType;
            [_completionDict setObject:[finishBlock copy] forKey:typeKey];
    });
}
@end

Here is a sample request and the definition of the TCPSocketManager class:

-(void)connectToSocket{
        _socketMan = [[TCPSocketManager alloc] initWithSocketHost:@"192.168.1.10" withPort:50505];
}

-(void)sendSomeRequest:(NSString *)request {
        [_socketMan sendRequest:request withCompletion:^(NSDictionary *rsp_dict) {
              NSString *result =[rsp_dict objectForKey:@"result"];
              if ([result length] < 3 && [result isEqualToString:@"OK"]){
                  //Successful request with a response
              }else{
                  //Request has failed with no/ bad response
              }
        }];
}

Since this problem only appears on iPhone 7 devices. I'm wondering if this is an NSStream bug? Has anyone come across any similar issues. Would I be better off using a library such as CocoaAsyncSocket? Is there any way to fix the issue without using an external library?

I have set up CocoaAsyncSocket before and it didn't help me as it was breaking messages requests and responses. It would send multiple responses back in the same message, adding more complexity when parsing the messages.

Body:
After a lot of trial and error, I came to the conclusion that TCP Packets were being coalesced on the kernel level due to me rapidly sending relatively small byte message. I came across Nagles Algorithm` when looking up this issue.

Nagle's algorithm works by combining a number of small outgoing messages, and sending them all at once. Specifically, as long as there is a sent packet for which the sender has received no acknowledgment, the sender should keep buffering its output until it has a full packet's worth of output, thus allowing output to be sent all at once.

The solution to my problem was found on this question.

Basically, In order to fix my problem, I needed to disable Nagles algorithm like so:

#import <arpa/inet.h>       // for IPPROTO_TCP
#include <netinet/tcp.h>    // for TCP_NODELAY

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    switch (streamEvent) {
      case NSStreamEventOpenCompleted:
        [self disableNaglesAlgorithmForStream:theStream];
        break;
    ...
}

//from tar500's answer in the linked question.
-(void)disableNaglesAlgorithmForStream:(NSStream *)stream {
    CFDataRef socketData;

    // Get socket data
    if ([stream isKindOfClass:[NSOutputStream class]]) {
        socketData = CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)((NSOutputStream *)stream), kCFStreamPropertySocketNativeHandle);
    } else if ([stream isKindOfClass:[NSInputStream class]]) {
        socketData = CFReadStreamCopyProperty((__bridge CFReadStreamRef)((NSInputStream *)stream), kCFStreamPropertySocketNativeHandle);
    }

    // get a handle to the native socket
    CFSocketNativeHandle rawsock;

    CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&rawsock);
    CFRelease(socketData);

    // Disable Nagle's algorythm

    // Debug info
    BOOL isInput = [stream isKindOfClass:[NSInputStream class]];
    NSString * streamType = isInput ? @"INPUT" : @"OUTPUT";

    int err;
    static const int kOne = 1;
    err = setsockopt(rawsock, IPPROTO_TCP, TCP_NODELAY, &kOne, sizeof(kOne));
    if (err < 0) {
        err = errno;
        NSLog(@"Could Not Disable Nagle for %@ stream", streamType);
    } else {
        NSLog(@"Nagle Is Disabled for %@ stream", streamType);
    }
}

After disabling Nagles, my socket messages appeared to be more responsive and I'm not experiencing the packet coalescing any more.


问:
How to get all keys from the cache in Apache Ignite C++
There is a function specified to get the values based on the keys. </p>

```<code>std::map<K, V> GetAll(const std::set<K>& keys)
</code>```

<p>How can I retrieve all the keys that are present in all the nodes for a cache? </p>

答:
You can use ScanQuery for this:

```<code>ScanQuery qry;
QueryCursor<int, QueryPerson> cursor = cache.Query(qry);
while (cursor.HasNext())
{
    CacheEntry<int, QueryPerson> entry = cursor.GetNext();

    std::cout << entry.GetKey() << std::endl;
}
</code>```

Body:
There is a function specified to get the values based on the keys.

std::map<K, V> GetAll(const std::set<K>& keys)

How can I retrieve all the keys that are present in all the nodes for a cache?

Body:
You can use ScanQuery for this:

ScanQuery qry;
QueryCursor<int, QueryPerson> cursor = cache.Query(qry);
while (cursor.HasNext())
{
    CacheEntry<int, QueryPerson> entry = cursor.GetNext();

    std::cout << entry.GetKey() << std::endl;
}


问:
JMeter can I run it locally?
In my opinion, load tests should be performed from several different IP addresses simultaneously(because of restrictions on http). Am I right?

I will do load tests for:
Number of Threads (users):  2000
Ramp-Up Period (in seconds): 10

答:
Yes you can run JMeter locally, it can be run anywhere that has a Java Virtual Machine.

Another alternative if you are interested is Gatling http://gatling.io/

Title: JMeter can I run it locally?


问:
how to set the Caps Lock warning balloon in meanstack
I want to set the caps lock warning balloon message in meanstack.

is it possible to do in mean stack. if yes mean can anybody give some example.

thanks

vinoth

答:
I think this code will help you for your requirement.

```<code>$('input').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
    alert('caps is on');
}
});
</code>```

Fiddle

Body:
I think this code will help you for your requirement.

$('input').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
    alert('caps is on');
}
});

Fiddle


问:
InternalFrameListener "interrupts" the loading of JFrame
I have a Jframe that extends ModalJInternalFrame. In the constructor of one class, I'm putting the title and size of the frame:

```<code>public class ApplicInternalFrame extends ModalJInternalFrame {
private static final long serialVersionUID = 1L;

public ApplicInternalFrame(Component parent) throws CommonException {
    super(parent, "Applic", false, false);
    this.setSize(200, 200);
}
</code>```

In another class I'm creating the GUI in it:

```<code>public class ApplicabilityChooserPanel extends CdmPanel implements ActionListener, ComponentListener, Runnable {
public ApplicabilityChooserPanel(Component parent, [...]) throws CommonException {
parentFrame = new FrameWrapper(parent);

JInternalFrame test = FrameUtils.getParentInternalFrame(parentFrame.getContentPane());
[...]
buildGUI();

test.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter() {
        public void internalFrameClosing(InternalFrameEvent e) {
            System.out.println("Hello World");
        }
    });
</code>```

"test" perfectly gets the frame-object, and I can among other see the "Applic" title of the frame through "test". My issue comes on the line with "test.addInternalFrameListener(...)". If I use those last lines of code, Eclipse goes into an "invisible" break point in ClassLoader.class, and the frame does not open at all.
I need help to get an action to happen when I click the "X" in the window.

Any suggestions are much appreciated.

答: I found the solution. I didn't realize that it was created inner clases. Found solution from Exception in thread "main" java.lang.NoClassDefFoundError: Main$1 java?</p>

Body:
I have a Jframe that extends ModalJInternalFrame. In the constructor of one class, I'm putting the title and size of the frame:

public class ApplicInternalFrame extends ModalJInternalFrame {
private static final long serialVersionUID = 1L;

public ApplicInternalFrame(Component parent) throws CommonException {
    super(parent, "Applic", false, false);
    this.setSize(200, 200);
}

In another class I'm creating the GUI in it:

public class ApplicabilityChooserPanel extends CdmPanel implements ActionListener, ComponentListener, Runnable {
public ApplicabilityChooserPanel(Component parent, [...]) throws CommonException {
parentFrame = new FrameWrapper(parent);

JInternalFrame test = FrameUtils.getParentInternalFrame(parentFrame.getContentPane());
[...]
buildGUI();

test.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter() {
        public void internalFrameClosing(InternalFrameEvent e) {
            System.out.println("Hello World");
        }
    });

"test" perfectly gets the frame-object, and I can among other see the "Applic" title of the frame through "test". My issue comes on the line with "test.addInternalFrameListener(...)". If I use those last lines of code, Eclipse goes into an "invisible" break point in ClassLoader.class, and the frame does not open at all.
I need help to get an action to happen when I click the "X" in the window.

Any suggestions are much appreciated.


问:
How to monitor more than 20 regions?
I'm working on an app in which there are 66 annotations. These annotations are centers of regions and whenever user enters a region, a notification appears, but that works only for first 20 of them because there's a limited number on monitoring regoins. My problem is that I don't know how to monitor more than 20 regions. Could anyone help?</p>

答:
There is no way to monitor more than 20 regions using Apples API.

You have to update the actively monitored regions to the nearest 20 regions.

Whenever you enter/leave a region:

Check entered location

Stop monitoring all regions

Start monitoring the nearest 19 regions (distance to entered location) plus the entered one.

If the result is not satisfying, you might also want to monitor significant location changes to have the chance to update the monitored regions every ~500 meters while not draining too much battery.

ContentLicense: CC BY-SA 4.0

Title: How to monitor more than 20 regions?


问:
Check if object is not colliding with anything
Is there a way to detect if the collider on the player (with a rigidbody) object is not colliding with any other collider in a 2D environment?</p>

答:
/edit - actually piojo's idea with counters is better, just use int instead of bool.
One way would be to add an int to your script called collisions and set it to 0. Then if at any point the collider fires OnCollisionEnter just increment it, and in OnCollisionExit decrement it.
Something like this should work for 3D:

```<code>public int collisions = 0;

void OnCollisionEnter(Collision collision)
{
    collisions++;
}

void OnCollisionExit(Collision collision)
{
    collisions--;
}
</code>```

https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html

https://docs.unity3d.com/ScriptReference/Collider.OnCollisionExit.html

Body:
/edit - actually piojo's idea with counters is better, just use int instead of bool.
One way would be to add an int to your script called collisions and set it to 0. Then if at any point the collider fires OnCollisionEnter just increment it, and in OnCollisionExit decrement it.
Something like this should work for 3D:

public int collisions = 0;

void OnCollisionEnter(Collision collision)
{
    collisions++;
}

void OnCollisionExit(Collision collision)
{
    collisions--;
}

https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html

https://docs.unity3d.com/ScriptReference/Collider.OnCollisionExit.html


问:
imacros , java script / datasource .csv number of rows = loop value

```<code>date.csv  like this

    day,month,year
    15,04,2016
    22,06,2017
    29,06,2017
    23,06,2017
</code>```

Example there is 4 rows  in date.csv file.

```<code>var accounts = 7;
for(k= 1; k<= accounts; k++){
iimDisplay("first_loop: "+ k);
var extract;
extract =  "CODE:";
extract +=  "SET !REPLAYSPEED fast" + "\n";
extract +=  "SET !DATASOURCE date.csv" + "\n";
extract +=  "SET !DATASOURCE_LINE {{CSV}}" + "\n";
extract +=  "URL GOTO=http://www.tcmb.gov.tr/wps/wcm/connect/tcmb+tr/tcmb+tr" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";
extract +=  "TAG POS=1 TYPE=A ATTR=TXT:ARŞİV" + "\n";
extract +=  "FRAME F=1" + "\n";

extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:gun CONTENT=%{{!COL1}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:ay CONTENT=%{{!COL2}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:yil CONTENT=%{{!COL3}}" + "\n";
extract +=  "TAG POS=1 TYPE=INPUT:BUTTON FORM=NAME:doviz ATTR=NAME:chk" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";

iimSet("CSV", k);
iimPlay(extract);
}
</code>```

accounts is a variable set 7 times,   this code work fine .. but i need  change loop value

could you tell me . how can i do to change "account" variable value  as a date.csv rows count..

regards,
thank you so much

答:
Try it like this:

```<code>var accounts = 7;
var extract;

extract =  "CODE:";
extract +=  "SET !REPLAYSPEED fast" + "\n";
extract +=  "SET !DATASOURCE date.csv" + "\n";
extract +=  "SET !DATASOURCE_LINE {{CSV}}" + "\n";
extract +=  "URL GOTO=http://www.tcmb.gov.tr/wps/wcm/connect/tcmb+tr/tcmb+tr" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";
extract +=  "TAG POS=1 TYPE=A ATTR=TXT:ARŞİV" + "\n";
extract +=  "FRAME F=1" + "\n";

extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:gun CONTENT=%{{!COL1}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:ay CONTENT=%{{!COL2}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:yil CONTENT=%{{!COL3}}" + "\n";
extract +=  "TAG POS=1 TYPE=INPUT:BUTTON FORM=NAME:doviz ATTR=NAME:chk" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";

for(k= 1; k<= accounts; k++){
iimDisplay("first_loop: "+ k);
iimSet("CSV", k);
iimPlay(extract);
}
</code>```

The macro code should all be outside the loop, see?
Also, you don't need the var accounts = 7; variable set. You can initiate the loop with for(k= 1; k<=7; k++) directly.
One last advice, if you don't mind: don't post links of live sites here.

Edit:
added link to iMacros forum on how to count the number of rows in a csv:
http://forum.imacros.net/viewtopic.php?f=11&t=13610&p=40923&hilit=count+number+rows+csv#p40964

Body:
date.csv  like this

    day,month,year
    15,04,2016
    22,06,2017
    29,06,2017
    23,06,2017

Example there is 4 rows  in date.csv file.

var accounts = 7;
for(k= 1; k<= accounts; k++){
iimDisplay("first_loop: "+ k);
var extract;
extract =  "CODE:";
extract +=  "SET !REPLAYSPEED fast" + "\n";
extract +=  "SET !DATASOURCE date.csv" + "\n";
extract +=  "SET !DATASOURCE_LINE {{CSV}}" + "\n";
extract +=  "URL GOTO=http://www.tcmb.gov.tr/wps/wcm/connect/tcmb+tr/tcmb+tr" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";
extract +=  "TAG POS=1 TYPE=A ATTR=TXT:ARŞİV" + "\n";
extract +=  "FRAME F=1" + "\n";

extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:gun CONTENT=%{{!COL1}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:ay CONTENT=%{{!COL2}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:yil CONTENT=%{{!COL3}}" + "\n";
extract +=  "TAG POS=1 TYPE=INPUT:BUTTON FORM=NAME:doviz ATTR=NAME:chk" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";

iimSet("CSV", k);
iimPlay(extract);
}

accounts is a variable set 7 times,   this code work fine .. but i need  change loop value

could you tell me . how can i do to change "account" variable value  as a date.csv rows count..

regards,
thank you so much

Body:
Try it like this:

var accounts = 7;
var extract;

extract =  "CODE:";
extract +=  "SET !REPLAYSPEED fast" + "\n";
extract +=  "SET !DATASOURCE date.csv" + "\n";
extract +=  "SET !DATASOURCE_LINE {{CSV}}" + "\n";
extract +=  "URL GOTO=http://www.tcmb.gov.tr/wps/wcm/connect/tcmb+tr/tcmb+tr" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";
extract +=  "TAG POS=1 TYPE=A ATTR=TXT:ARŞİV" + "\n";
extract +=  "FRAME F=1" + "\n";

extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:gun CONTENT=%{{!COL1}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:ay CONTENT=%{{!COL2}}" + "\n";
extract +=  "TAG POS=1 TYPE=SELECT FORM=NAME:doviz ATTR=NAME:yil CONTENT=%{{!COL3}}" + "\n";
extract +=  "TAG POS=1 TYPE=INPUT:BUTTON FORM=NAME:doviz ATTR=NAME:chk" + "\n";
extract +=  "WAIT SECONDS=2" + "\n";

for(k= 1; k<= accounts; k++){
iimDisplay("first_loop: "+ k);
iimSet("CSV", k);
iimPlay(extract);
}

The macro code should all be outside the loop, see?
Also, you don't need the var accounts = 7; variable set. You can initiate the loop with for(k= 1; k<=7; k++) directly.
One last advice, if you don't mind: don't post links of live sites here.

Edit:
added link to iMacros forum on how to count the number of rows in a csv:
http://forum.imacros.net/viewtopic.php?f=11&t=13610&p=40923&hilit=count+number+rows+csv#p40964


问:
How To call An Action In Umbraco Controller?
I created an Umbraco DocumentType with the alias Personal and created a controller that inherits

Umbraco.Web.Mvc.RenderMvcController

I added two Actions, one is the default action and the other is called Test.

How can I fire the Test Action from the Personal controller?

```<code>public class PersonalController : Umbraco.Web.Mvc.RenderMvcController
{
    // GET: Personal
    public override ActionResult Index(RenderModel model)
    {
        return base.Index(model);
    }

    public String Test(RenderModel model)
    {
        return "fff";
    }
}
</code>```

When I put the url like this: localHost/personal/test it shows:

No umbraco document matches the url '/test'.

Which is right, so how can I call it?

答:
I would do it like this

```<code>[HttpPost]
public ActionResult SubmitSearchForm(SearchViewModel model)
{
    if (ModelState.IsValid)
    {
        if (!string.IsNullOrEmpty(model.SearchTerm))
        {
            model.SearchTerm = model.SearchTerm;
            model.SearchGroups = GetSearchGroups(model);
            model.SearchResults = _searchHelper.GetSearchResults(model, Request.Form.AllKeys);
        }
        return RenderSearchResults(model.SearchResults);
    }
    return null;
}

public ActionResult RenderSearchResults(SearchResultsModel model)
{
    return PartialView(PartialViewPath("_SearchResults"), model);
}
</code>```

See this blog post for the full context behind where this code snippet came from.

http://www.codeshare.co.uk/blog/how-to-search-by-document-type-and-property-in-umbraco/

Body:
I created an Umbraco DocumentType with the alias Personal and created a controller that inherits

Umbraco.Web.Mvc.RenderMvcController

I added two Actions, one is the default action and the other is called Test.

How can I fire the Test Action from the Personal controller?

public class PersonalController : Umbraco.Web.Mvc.RenderMvcController
{
    // GET: Personal
    public override ActionResult Index(RenderModel model)
    {
        return base.Index(model);
    }

    public String Test(RenderModel model)
    {
        return "fff";
    }
}

When I put the url like this: localHost/personal/test it shows:

No umbraco document matches the url '/test'.

Which is right, so how can I call it?

Body:
I would do it like this

[HttpPost]
public ActionResult SubmitSearchForm(SearchViewModel model)
{
    if (ModelState.IsValid)
    {
        if (!string.IsNullOrEmpty(model.SearchTerm))
        {
            model.SearchTerm = model.SearchTerm;
            model.SearchGroups = GetSearchGroups(model);
            model.SearchResults = _searchHelper.GetSearchResults(model, Request.Form.AllKeys);
        }
        return RenderSearchResults(model.SearchResults);
    }
    return null;
}

public ActionResult RenderSearchResults(SearchResultsModel model)
{
    return PartialView(PartialViewPath("_SearchResults"), model);
}

See this blog post for the full context behind where this code snippet came from.

http://www.codeshare.co.uk/blog/how-to-search-by-document-type-and-property-in-umbraco/


问:
What are some valid use cases for using stack and queue in Java?
I am studying this part of collections in Java, but I'm still confused about when I should use them?  What are some valid use cases where they are the best option to use?</p>

答:
Queues and Stacks can be used when you need to work with data in a first-in-first-out / last-in-first-out (respectively) order and you want to be able discard every item you polled out of the queue / popped out of the stack after processing it.

Of course you can also use an ArrayList, but then you will have to maintain it and delete every item you processed it yourself

Example of logic questions you can solve with these structures:

Queue - Level order traversal on a tree ( see: http://www.geeksforgeeks.org/print-level-order-traversal-line-line/)

Stack - Post order traversal on a tree ( see: http://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/)

Stack - check if an expression is balanced - {[()]}:
Java balanced expressions check {[()]}

Also see this nice answer here:
https://stackoverflow.com/a/17436821/2940903


问:
Why is a trait needed in order to constrain the type parameter?
Why is the trait needed in the following code? The commented variant without a trait does not compile, even if it looks as if it has the same information available.

```<code>trait ReliabilityConstructor<T> {
    fn new(a: T) -> Reliability;
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

//impl<T> Reliability
impl<T> ReliabilityConstructor<T> for Reliability
where
    f64: std::convert::From<T>,
{
    fn new(a: T) -> Reliability {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}
</code>```

When the commented line is uncommented:

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:10:6
   |
10 | impl<T> Reliability
   |      ^ unconstrained type parameter
```

答:
It's because you have the type parameter defined on the trait definition, not the struct definition. To get rid of the trait, you'll need to move T onto the struct itself:

```<code>#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability<T> {
    alpha: i8,
}

impl<T> Reliability<T>
where
    f64: std::convert::From<T>,
{
    fn new(a: T) -> Reliability<T> {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}
</code>```

That said, this raises a different issue - Reliability doesn't actually use T anywhere in the definition or implementation, so it'll fall over with this error:

error[E0392]: parameter `T` is never used
 --> src/main.rs:2:20
  |
2 | struct Reliability<T> {
  |                    ^ unused type parameter
  |
  = help: consider removing `T` or using a marker such as `std::marker::PhantomData`
```

<p>Your issue is that you're not trying to constrain the struct, you're just trying to constrain the method. In which case, it's much easier!</p>

```#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

impl Reliability {
    fn new<T>(a: T) -> Reliability
    where
        f64: std::convert::From<T>,
    {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}
```

Body:
Why is the trait needed in the following code? The commented variant without a trait does not compile, even if it looks as if it has the same information available.

trait ReliabilityConstructor<T> {
    fn new(a: T) -> Reliability;
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

//impl<T> Reliability
impl<T> ReliabilityConstructor<T> for Reliability
where
    f64: std::convert::From<T>,
{
    fn new(a: T) -> Reliability {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}

When the commented line is uncommented:

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:10:6
   |
10 | impl<T> Reliability
   |      ^ unconstrained type parameter

Body:
It's because you have the type parameter defined on the trait definition, not the struct definition. To get rid of the trait, you'll need to move T onto the struct itself:

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability<T> {
    alpha: i8,
}

impl<T> Reliability<T>
where
    f64: std::convert::From<T>,
{
    fn new(a: T) -> Reliability<T> {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}

That said, this raises a different issue - Reliability doesn't actually use T anywhere in the definition or implementation, so it'll fall over with this error:

error[E0392]: parameter `T` is never used
 --> src/main.rs:2:20
  |
2 | struct Reliability<T> {
  |                    ^ unused type parameter
  |
  = help: consider removing `T` or using a marker such as `std::marker::PhantomData`

Your issue is that you're not trying to constrain the struct, you're just trying to constrain the method. In which case, it's much easier!

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

impl Reliability {
    fn new<T>(a: T) -> Reliability
    where
        f64: std::convert::From<T>,
    {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}


问:
VagrantFile execution on vagrant destroy
Every time you call vagrant up or vagrant destroy VagrantFile gets executed?

It's because I'm having the following problem. On vagrant up I configure the machine with the following parameters:

```<code>config.vm.provision "chef_client" do |chef|
    chef.node_name = 'living-dev-'+Time.new.strftime("%H%M%S")
    config.vm.hostname = chef.node_name
end
</code>```

When I execute vagrant destroy the following code executes:

```<code>config.trigger.after :destroy do
    info "Attempting to remove node #{config.vm.hostname}"
    run "knife node show #{config.vm.hostname} -c c:/chef/knife.rb"
    if $?.to_i == 0
        info "Removing node #{config.vm.hostname}"
        "knife node delete #{config.vm.hostname} -y -c c:/chef/knife.rb"
    end
end
</code>```

The config.vm.hostname that I obtain here is diferent that the one defined on chef, so I'm not able to remove the vm machine on chef server.

How I can solve it?

答:
Yes, when you execute the vagrant command, it reads the whole Vagrantfile and puts in memory to know how to work with the machine. so in your case even the provisioning block is read (and executed), and then when you'll reboot the VM, the hostname will change

I believe you can find on SO questions about handling dynamic hostname, but basically you need to persist this information, so you'll need to write the hostname once it is defined in a file and then reads from this file

```<code>If File.exist?(".vagrant/machines/default/virtualbox/hostname")
  File.open(".vagrant/machines/default/virtualbox/hostname", "rb")
  hostname = File.read
else
  hostname = 'living-dev-'+Time.new.strftime("%H%M%S")
  File.open(".vagrant/machines/default/virtualbox/hostname" ,'w') do |f|
    f.write "#{hostname}]"
  end
end
</code>```

Body:
Every time you call vagrant up or vagrant destroy VagrantFile gets executed?

It's because I'm having the following problem. On vagrant up I configure the machine with the following parameters:

config.vm.provision "chef_client" do |chef|
    chef.node_name = 'living-dev-'+Time.new.strftime("%H%M%S")
    config.vm.hostname = chef.node_name
end

When I execute vagrant destroy the following code executes:

config.trigger.after :destroy do
    info "Attempting to remove node #{config.vm.hostname}"
    run "knife node show #{config.vm.hostname} -c c:/chef/knife.rb"
    if $?.to_i == 0
        info "Removing node #{config.vm.hostname}"
        "knife node delete #{config.vm.hostname} -y -c c:/chef/knife.rb"
    end
end

The config.vm.hostname that I obtain here is diferent that the one defined on chef, so I'm not able to remove the vm machine on chef server.

How I can solve it?

Body:
Yes, when you execute the vagrant command, it reads the whole Vagrantfile and puts in memory to know how to work with the machine. so in your case even the provisioning block is read (and executed), and then when you'll reboot the VM, the hostname will change

I believe you can find on SO questions about handling dynamic hostname, but basically you need to persist this information, so you'll need to write the hostname once it is defined in a file and then reads from this file

If File.exist?(".vagrant/machines/default/virtualbox/hostname")
  File.open(".vagrant/machines/default/virtualbox/hostname", "rb")
  hostname = File.read
else
  hostname = 'living-dev-'+Time.new.strftime("%H%M%S")
  File.open(".vagrant/machines/default/virtualbox/hostname" ,'w') do |f|
    f.write "#{hostname}]"
  end
end


问:
Add custom html after the last child of my list using javascript
I'm trying to use javascript to add a custom div after my last child of a unordered list, the result should basically look like this.

```<code><ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <div>custom div</div>
<ul>
</code>```

I am getting this far, but don't know if it's close to be the right solution.
I cant get it to work

```<code>$( document ).ready(function() {
document.getElementByClassName("myList").lastChild.innerHTML = "<h1>test</h1>";
}
</code>```

答:
Native DOM implementation using querySelector and insertAdjacentHTML methods

document.querySelector('.mylist > li:last-child')
        .insertAdjacentHTML('afterend', '

Test

')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
</ul> </code>```

Body:
I'm trying to use javascript to add a custom div after my last child of a unordered list, the result should basically look like this.

 content

 content

 content

 content

custom div

I am getting this far, but don't know if it's close to be the right solution.
I cant get it to work

$( document ).ready(function() {
document.getElementByClassName("myList").lastChild.innerHTML = "
test
";
}

Body:
Native DOM implementation using querySelector and insertAdjacentHTML methods

document.querySelector('.mylist > li:last-child')
        .insertAdjacentHTML('afterend', '<li><h1>Test</h1></li>')

<ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
</ul>


问:
Adding condition to data-bind="with"
I have a Users table, each user is clickable, once you click on it- a modal popups with the user's information.

the div of the modal:

```<code><div class="infoForm" data-bind="with: $root.selectedItem">
      <input id="companyName" placeholder="Company Name" data-bind="value: name" />
      <div class="cont">
      <label for="address">ADDRESS</label>
      <input class="contField" placeholder="Address 1" id="address" data-bind="value: address1" />
      <input class="contField" placeholder="Address 2" id="address2" data-bind="value: address2" />
      <input class="contField" id="city" placeholder="City" data-bind="value: city" />
      <input class="contField" id="state" placeholder="State" data-bind="value: state" />
      <input class="contField" id="zip" placeholder="Zip" data-bind="value: zip" />
...
</div>
</code>```

The problem is that if selectedItem is empty, the modal popups blank, without any content.

I wanted to add a condition to the data-bind to happen only if $root.selectedItem is not null becasue when I take out the data-bind at all it does work.

I tried that:

```<code><div class="infoForm" data-bind="with: $root.selectedItem ? $root.selectedItem : ''">
    .....
</div>
</code>```

But it doesn't work, it just doesn't happen, in other types of binding (text, value it does work).

The selectedItem is being set when one of the users on the table is being clicked:

```<code> <td class="name n" data-bind="text: name, click: $root.setSelectedItems.bind($data)"></td>
</code>```

The View Model:

```<code>var UsersViewModel = function () {
    var self = this;
    self.selectedItem = ko.observable();
    ...

    self.setSelectedItems = function (selectedUser) {
    if (selectedUser) {
        self.selectedItem(selectedUser);
    }
}
}
</code>```

Any idea on how to achieve that?

答:
I solve it by setting the selectedItem with an empty user:

```<code>self.selectedItem = ko.observable(new User(""));
</code>```

Title: Adding condition to data-bind="with"

Body:
I have a Users table, each user is clickable, once you click on it- a modal popups with the user's information.

the div of the modal:

      <input id="companyName" placeholder="Company Name" data-bind="value: name" />

      ADDRESS
      <input class="contField" placeholder="Address 1" id="address" data-bind="value: address1" />
      <input class="contField" placeholder="Address 2" id="address2" data-bind="value: address2" />
      <input class="contField" id="city" placeholder="City" data-bind="value: city" />
      <input class="contField" id="state" placeholder="State" data-bind="value: state" />
      <input class="contField" id="zip" placeholder="Zip" data-bind="value: zip" />
...

The problem is that if selectedItem is empty, the modal popups blank, without any content.

I wanted to add a condition to the data-bind to happen only if $root.selectedItem is not null becasue when I take out the data-bind at all it does work.

I tried that:

    .....

But it doesn't work, it just doesn't happen, in other types of binding (text, value it does work).

The selectedItem is being set when one of the users on the table is being clicked:

The View Model:

var UsersViewModel = function () {
    var self = this;
    self.selectedItem = ko.observable();
    ...

    self.setSelectedItems = function (selectedUser) {
    if (selectedUser) {
        self.selectedItem(selectedUser);
    }
}
}

Any idea on how to achieve that?

Body:
I solve it by setting the selectedItem with an empty user:

self.selectedItem = ko.observable(new User(""));


问:
Google Maps API Error: “"Position Error: Only secure origins are allowed"”
I have tried to integrate google map in ionic 3 android project. It works fine when run as 'ionic serve', but not in 'ionic cordova run android'. I see only a blank page on emulator.

答:
Have a look at the following document:

https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only

Starting with Chrome 50, Chrome no longer supports obtaining the user's location using the HTML5 Geolocation API from pages delivered by non-secure connections. This means that the page that's making the Geolocation API call must be served from a secure context such as HTTPS.

As I can see in the screenshot you are not using HTTPS.


问:
How to modify python module content?
I have file named config.py, content like below:

```<code>logindata = [
  {'user': '18320967034', 'password': '123456'}
]
</code>```

I wanna modify the logindata and write it back,

```<code>import config
config.logindata[0]['password'] = 'xxxx'
</code>```

How can I write it back to config.py?

Please don't tell me to use .ini/configparser

答:
Unless you don't think about your security. Than you can go this way.</p>

```<code>import config
config.logindata[0]['password'] = 'xxxx'
#print(config.logindata)
config_string = "".join(('logindata = [',str(config.logindata[0]),"]"))
file = open("config.py", 'w')
file.write(config_string)
file.close()
</code>```

Title: How to modify python module content?

Body:
I have file named config.py, content like below:

logindata = [
  {'user': '18320967034', 'password': '123456'}
]

I wanna modify the logindata and write it back,

import config
config.logindata[0]['password'] = 'xxxx'

How can I write it back to config.py?

Please don't tell me to use .ini/configparser

Body:
Unless you don't think about your security. Than you can go this way.

import config
config.logindata[0]['password'] = 'xxxx'
#print(config.logindata)
config_string = "".join(('logindata = [',str(config.logindata[0]),"]"))
file = open("config.py", 'w')
file.write(config_string)
file.close()


问:
Admob & ActionScript 3
I saw that Admob just released an SDK for Flash Lite (Action Script 2). I'm working on an AS3
project, and could not find anywhere on the internet an AS3 version of the SDK.

Does anyone have any knowledge of such an SDK for AS3 or using the AS2 SDK in AS3.

Thanks

Can

答:
You could try to use the AS2 SDK in an AS2 file that has some methods exposed or reads some URL variables and then try to load that AS2 SWF file into an AS3 container. More info on loading AS2 files in AS3 containers can be found here:

Load AS2 SWF Into AS3 SWF and pass vars in URL

and here:

http://www.kirupa.com/forum/showpost.php?p=1964550&postcount=249

It's a total pain, but it beats having to write the SDK all over again in AS3.

ContentLicense: CC BY-SA 2.5

Title: Admob & ActionScript 3


问:
How to fix border color on mouse click
I have one color box, so when I am hovering on the box the border color is getting appear. Now I want to click on the box then the border color should be remain as it is. It should not get remove when you will remove the mouse from box.

My Scss:

.fill-color1{
    background:$workspace-fill-color2;
    &:hover{
        border:2px solid $work-border-color2;
    }
}
```
<pre class="lang-js prettyprint-override"><code>$(`.fill-color${i}`).click(function () {
    $(this).css('border-color', 'red');
});
</code>```

in the above code, after click the color is getting set but when I am removing the mouse from the box border is also getting remove.

答:
You are adding a border-color to a box which have no border. It only have a border if you hover it.

Change this:

```<code>$(this).css('border-color', 'red');
</code>```

to this:

```<code>$(this).css('border', '2px solid red');
</code>```

Example here:

$(`#test`).click(function() {
  $(this).css('border', '2px solid red');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test:hover {
  border: 2px solid blue;
}</code>```

  Hover and click me!

```

Title: How to fix border color on mouse click

Body:
I have one color box, so when I am hovering on the box the border color is getting appear. Now I want to click on the box then the border color should be remain as it is. It should not get remove when you will remove the mouse from box.

My Scss:

.fill-color1{
    background:$workspace-fill-color2;
    &:hover{
        border:2px solid $work-border-color2;
    }
}

$(`.fill-color${i}`).click(function () {
    $(this).css('border-color', 'red');
});

in the above code, after click the color is getting set but when I am removing the mouse from the box border is also getting remove.

Body:
You are adding a border-color to a box which have no border. It only have a border if you hover it.

Change this:

$(this).css('border-color', 'red');

to this:

$(this).css('border', '2px solid red');

Example here:

$(`#test`).click(function() {
  $(this).css('border', '2px solid red');
});

#test:hover {
  border: 2px solid blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  Hover and click me!
</div>


问:
How can I add a filter class in Spring Boot?
Is there any annotation for a Filter class (for web applications) in Spring Boot? Perhaps @Filter?

I want to add a custom filter in my project.

The Spring Boot Reference Guide mentioned about
FilterRegistrationBean, but I am not sure how to use it.

答:
If you use Spring Boot + Spring Security, you can do that in the security configuration.

In the below example, I'm adding a custom filter before the UsernamePasswordAuthenticationFilter (see all the default Spring Security filters and their order).

```<code>@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired FilterDependency filterDependency;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(
                new MyFilter(filterDependency),
                UsernamePasswordAuthenticationFilter.class);
    }
}
</code>```

And the filter class

```<code>class MyFilter extends OncePerRequestFilter  {
    private final FilterDependency filterDependency;

    public MyFilter(FilterDependency filterDependency) {
        this.filterDependency = filterDependency;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain)
        throws ServletException, IOException {

        // Filter
        filterChain.doFilter(request, response);
    }
}
</code>```

Body:
If you use Spring Boot + Spring Security, you can do that in the security configuration.

In the below example, I'm adding a custom filter before the UsernamePasswordAuthenticationFilter (see all the default Spring Security filters and their order).

@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired FilterDependency filterDependency;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(
                new MyFilter(filterDependency),
                UsernamePasswordAuthenticationFilter.class);
    }
}

And the filter class

class MyFilter extends OncePerRequestFilter  {
    private final FilterDependency filterDependency;

    public MyFilter(FilterDependency filterDependency) {
        this.filterDependency = filterDependency;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain)
        throws ServletException, IOException {

        // Filter
        filterChain.doFilter(request, response);
    }
}


问:
ngFor from object?
I'm using Ionic 2 / Angular, but I realized that the ngFor function can't read objects. Also, I need it to be shown only if the cart is not empty.

Object:

```<code>{
    "48131": {
        "code":"D40905",
        "name":"ДАМСКА ПЛЕТЕНА БЛУЗА КЪС РЪКАВ ЩАМПА REASON",
        "price":"18.99",
        "size":"STANDART",
        "qty":"1"
    },
    "49410": {
        "code":"D41821",
        "name":"ДАМСКА БЛУЗА ТРИКО",
        "price":"44.99",
        "size":"M",
        "qty":"4"
    }
}
</code>```

HTML:

```<code><ion-row *ngFor="let p of cart">
    <ion-col col-3>
        <div><img src="http://example.com/products/small/{{p.code}}-1.jpg" /></div>
    </ion-col>
    <ion-col col-9>
        <ion-row>
            <ion-col col-12>
                <div>{{p.name}}</div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div>{{p.qty}} бр ({{p.size}} размер) x <b>{{p.price}} лв</b></div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div (click)="deleteCart({{p.id}})">Изтрий <ion-icon name='trash' item-start color="danger"></ion-icon></div>
            </ion-col>
        </ion-row>
    </ion-col>
</ion-row>
</code>```

Can someone help me with this? I've tried so many things...

答:
Convert your json object to an array based on this link

https://stackoverflow.com/a/37667589/2013245

Then you should be fine.

Title: ngFor from object?

Body:
I'm using Ionic 2 / Angular, but I realized that the ngFor function can't read objects. Also, I need it to be shown only if the cart is not empty.

Object:

{
    "48131": {
        "code":"D40905",
        "name":"ДАМСКА ПЛЕТЕНА БЛУЗА КЪС РЪКАВ ЩАМПА REASON",
        "price":"18.99",
        "size":"STANDART",
        "qty":"1"
    },
    "49410": {
        "code":"D41821",
        "name":"ДАМСКА БЛУЗА ТРИКО",
        "price":"44.99",
        "size":"M",
        "qty":"4"
    }
}

HTML:

<ion-row *ngFor="let p of cart">
    <ion-col col-3>

    </ion-col>
    <ion-col col-9>
        <ion-row>
            <ion-col col-12>

{{p.name}}

            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>

{{p.qty}} бр ({{p.size}} размер) x {{p.price}} лв

            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>

Изтрий <ion-icon name='trash' item-start color="danger"></ion-icon>

            </ion-col>
        </ion-row>
    </ion-col>
</ion-row>

Can someone help me with this? I've tried so many things...


问:
numpy, pandas modules not found when deploying flask app behind apache with pyenv and virtualenv
I built a flask frontend for a rather detailed app and it runs perfectly locally after a lot of coding. So now I want to make it visible to the public, so have read that it needs an apache or nginx frontend. I worked out the size of instance I needed and switched it on on AWS, and ran through these two tutorials which prove that the base case is working. Once the Apache setup is done, the Apache welcome page shows when I navigate to the IP of the AWS instance. Then when I temporarily substitute the "Hello World" code for my flask app and refresh the browser with the IP, the hello world appears rendered. Also, if I substitute the flasskapp.py code from here it perfectly serves across apache to the IP typed into the browser a list of modules found by pip including Numpy and Pandas which it otherwise complains about not finding! This script, could however easily be killed by adding import numpy at the top, but it gives me the following error messages:

```<code>ImportError: cannot import name 'multiarray'
</code>```

and

```<code>Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
If you're working with a numpy git repo, try `git clean -xdf`
(removes all files not under version control).
Otherwise reinstall numpy.
</code>```

both in the apache log.

The trouble happens when I put my app back in instead of hello world. It just refuses to import pandas here is the last section of the Apache log:

```<code>Mon Jul 03 19:42:14.691081 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560] Traceback (most recent call last):
[Mon Jul 03 19:42:14.691126 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/var/www/html/flaskapp/flaskapp.wsgi", line 30, in <module>
[Mon Jul 03 19:42:14.691130 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     from similar_items_frontend import app as application
[Mon Jul 03 19:42:14.691137 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/var/www/html/flaskapp/similar_items_frontend.py", line 4, in <module>
[Mon Jul 03 19:42:14.691140 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     from item_similar_to_doc import similar_to_doc
[Mon Jul 03 19:42:14.691145 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/home/ubuntu/find-similar/frontend/../item_similar_to_doc.py", line 1, in <module>
[Mon Jul 03 19:42:14.691148 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     from PullVectors import p
[Mon Jul 03 19:42:14.691153 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/home/ubuntu/find-similar/frontend/../RunSimilarity.py", line 5, in <module>
[Mon Jul 03 19:42:14.691156 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     import pandas as pd
[Mon Jul 03 19:42:14.691161 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/home/ubuntu/.pyenv/versions/miniconda3-latest/envs/find_similarProject/lib/python3.6/site-packages/pandas/__init__.py", line 19, in <module>
[Mon Jul 03 19:42:14.691164 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     "Missing required dependencies {0}".format(missing_dependencies))
[Mon Jul 03 19:42:14.691180 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560] ImportError: Missing required dependencies ['numpy']
</code>```

I feel like I've tried everything it's been many painful hours, hair pulling time..

Here is 000-default.conf :

```<code>WSGIPythonPath /home/ubuntu/.pyenv/versions/miniconda3-latest/envs/vtenv4YTproject/lib/python3.6/site-packages/

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        WSGIDaemonProcess flaskapp threads=5
        WSGIScriptAlias / /var/www/html/flaskapp/flaskapp.wsgi

        <Directory flaskapp>
              WSGIScriptReloading On
              WSGIProcessGroup %{GLOBAL}
              WSGIApplicationGroup %{GLOBAL}
              Order allow,deny
              Allow from all
        </Directory>

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
</code>```

I should mention that my flask app runs perfectly (to the point of flask serving the page) in its virtualenv when I am on ssh into the AWS instance, of course was a bit of tinkering to get that to work, but it finds all its dependencies, not crashing at the pandas import.

To try and fix it I looked here, here, added some code from here, went through the extensive docs here, my flaskapp.wsgi file looks like this:

```<code>import sys
import logging
import os.path
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import config
import site

prev_sys_path = list(sys.path)

site.addsitedir('/home/ubuntu/.pyenv/versions/miniconda3-latest/envs/find_similarProject/lib/python3.6/site-packages')

new_sys_path = []

for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path

logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, "/var/www/html/flaskapp")

from similar_vids_frontend import app as application
application.secret_key = config.WSGI_KEY
</code>```

There is just no reason I can find why pandas / numpy imports are failing with apache but working fine when just run in the virtualenv. I wonder if there's something to do with permissions and groups, as per the docs:

Do be aware that the user that Apache runs your code as will need to be able to access the Python virtual environment. On some Linux distributions, the home directory of a user account is not accessible to other users. Rather than change the permissions on your home directory, it might be better to consider locating your WSGI application code and any Python virtual environment outside of your home directory.

But is Ubuntu one of those distributions, and what then, install the virtual environments and project into the / folder?

Grateful for any tips or a solution.

答:
This now works, mainly thanks to Graham's recipe here and also this answer about loading modules into apache. The proof that it works is that the following variation of the hello world app:

```<code>from flask import Flask
import numpy
app = Flask(__name__)

@app.route('/')
def hello_from_np():
  a = numpy.array([4,5,6])
  return str(a)

if __name__ == '__main__':
  app.run()
</code>```

gives you this in the browser when you go to the IP:

...rather than a bunch of errors in the apache log about numpy.
It's all set up for Python 3.6:

```<code>AH00489: Apache/2.4.7 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured
</code>```

Wanted to record a few details as a note to self and in case anyone is having trouble and trying to reproduce this, maybe save you from days of barking up the wrong tree..

So I switched from Ubuntu Server 16.04 to 14.04.5 LTS in case that was part of the issue but also because pyenv was performing poorly, crashing half way through the installation of many older Python versions I was testing. Also chose to leave out pyenv-virtualenv as there were no multiple projects planned for this instance and it was one less thing to go wrong.

From the clean install of Ubuntu, in addition to installing apache2, pyenv, libapache2-mod-wsgi, activating it with a2enmod, I deliberately ran the following lines before installing the requirements with pip, which included numpy, so it doesn't complain:

```<code>sudo apt-get install gcc
sudo apt-get install g++
</code>```

This is also needed:

```<code>sudo apt-get install apache2-dev
</code>```

Then inside the environment, after the requirements,

```<code>pip install mod_wsgi
mod_wsgi-express module-config
</code>```

The second line returned:

```<code>LoadModule wsgi_module "/home/ubuntu/.pyenv/versions/miniconda3-latest/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"
WSGIPythonHome "/home/ubuntu/.pyenv/versions/miniconda3-latest"
</code>```

Then with loading the module, the docs encourages you to paste into a file httpd.conf which at least in my version of apache and ubuntu does not exist. After a lot of reading, I avoided creating one and also avoided pasting it into apache2.conf which seems to be related. Rather, following the instructions for ubuntu linked to at the top,

edit this file:

```<code>sudo vi /etc/apache2/mods-available/wsgi.load
</code>```

paste this line into it and save:

```<code>LoadModule wsgi_module /path/to/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
</code>```

then run this and restart the apache server if necessary:

```<code>sudo a2enmod wsgi
</code>```

000-default.conf looks like this:

```<code>WSGIPythonHome "/home/ubuntu/.pyenv/versions/miniconda3-latest"

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
        WSGIDaemonProcess helloapp threads=5 python-path=/var/www/html/frontend/
        WSGIScriptAlias / /var/www/html/frontend/helloapp.wsgi

        <Directory flaskapp>
        WSGIProcessGroup helloapp
        WSGIApplicationGroup %{GLOBAL}
        Order allow,deny
        Allow from all
        </Directory>

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>
</code>```

Body:
I built a flask frontend for a rather detailed app and it runs perfectly locally after a lot of coding. So now I want to make it visible to the public, so have read that it needs an apache or nginx frontend. I worked out the size of instance I needed and switched it on on AWS, and ran through these two tutorials which prove that the base case is working. Once the Apache setup is done, the Apache welcome page shows when I navigate to the IP of the AWS instance. Then when I temporarily substitute the "Hello World" code for my flask app and refresh the browser with the IP, the hello world appears rendered. Also, if I substitute the flasskapp.py code from here it perfectly serves across apache to the IP typed into the browser a list of modules found by pip including Numpy and Pandas which it otherwise complains about not finding! This script, could however easily be killed by adding import numpy at the top, but it gives me the following error messages:

ImportError: cannot import name 'multiarray'

and

Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
If you're working with a numpy git repo, try `git clean -xdf`
(removes all files not under version control).
Otherwise reinstall numpy.

both in the apache log.

The trouble happens when I put my app back in instead of hello world. It just refuses to import pandas here is the last section of the Apache log:

Mon Jul 03 19:42:14.691081 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560] Traceback (most recent call last):
[Mon Jul 03 19:42:14.691126 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/var/www/html/flaskapp/flaskapp.wsgi", line 30, in <module>
[Mon Jul 03 19:42:14.691130 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     from similar_items_frontend import app as application
[Mon Jul 03 19:42:14.691137 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/var/www/html/flaskapp/similar_items_frontend.py", line 4, in <module>
[Mon Jul 03 19:42:14.691140 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     from item_similar_to_doc import similar_to_doc
[Mon Jul 03 19:42:14.691145 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/home/ubuntu/find-similar/frontend/../item_similar_to_doc.py", line 1, in <module>
[Mon Jul 03 19:42:14.691148 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     from PullVectors import p
[Mon Jul 03 19:42:14.691153 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/home/ubuntu/find-similar/frontend/../RunSimilarity.py", line 5, in <module>
[Mon Jul 03 19:42:14.691156 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     import pandas as pd
[Mon Jul 03 19:42:14.691161 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]   File "/home/ubuntu/.pyenv/versions/miniconda3-latest/envs/find_similarProject/lib/python3.6/site-packages/pandas/__init__.py", line 19, in <module>
[Mon Jul 03 19:42:14.691164 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560]     "Missing required dependencies {0}".format(missing_dependencies))
[Mon Jul 03 19:42:14.691180 2017] [wsgi:error] [pid 12300:tid 140131159766784] [client 93.21.05.132:52560] ImportError: Missing required dependencies ['numpy']

I feel like I've tried everything it's been many painful hours, hair pulling time..

Here is 000-default.conf :

WSGIPythonPath /home/ubuntu/.pyenv/versions/miniconda3-latest/envs/vtenv4YTproject/lib/python3.6/site-packages/

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        WSGIDaemonProcess flaskapp threads=5
        WSGIScriptAlias / /var/www/html/flaskapp/flaskapp.wsgi

        <Directory flaskapp>
              WSGIScriptReloading On
              WSGIProcessGroup %{GLOBAL}
              WSGIApplicationGroup %{GLOBAL}
              Order allow,deny
              Allow from all
        </Directory>

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

I should mention that my flask app runs perfectly (to the point of flask serving the page) in its virtualenv when I am on ssh into the AWS instance, of course was a bit of tinkering to get that to work, but it finds all its dependencies, not crashing at the pandas import.

To try and fix it I looked here, here, added some code from here, went through the extensive docs here, my flaskapp.wsgi file looks like this:

import sys
import logging
import os.path
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import config
import site

prev_sys_path = list(sys.path)

site.addsitedir('/home/ubuntu/.pyenv/versions/miniconda3-latest/envs/find_similarProject/lib/python3.6/site-packages')

new_sys_path = []

for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path

logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, "/var/www/html/flaskapp")

from similar_vids_frontend import app as application
application.secret_key = config.WSGI_KEY

There is just no reason I can find why pandas / numpy imports are failing with apache but working fine when just run in the virtualenv. I wonder if there's something to do with permissions and groups, as per the docs:

Do be aware that the user that Apache runs your code as will need to be able to access the Python virtual environment. On some Linux distributions, the home directory of a user account is not accessible to other users. Rather than change the permissions on your home directory, it might be better to consider locating your WSGI application code and any Python virtual environment outside of your home directory.

But is Ubuntu one of those distributions, and what then, install the virtual environments and project into the / folder?

Grateful for any tips or a solution.

Body:
This now works, mainly thanks to Graham's recipe here and also this answer about loading modules into apache. The proof that it works is that the following variation of the hello world app:

from flask import Flask
import numpy
app = Flask(__name__)

@app.route('/')
def hello_from_np():
  a = numpy.array([4,5,6])
  return str(a)

if __name__ == '__main__':
  app.run()

gives you this in the browser when you go to the IP:

...rather than a bunch of errors in the apache log about numpy.
It's all set up for Python 3.6:

AH00489: Apache/2.4.7 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured

Wanted to record a few details as a note to self and in case anyone is having trouble and trying to reproduce this, maybe save you from days of barking up the wrong tree..

So I switched from Ubuntu Server 16.04 to 14.04.5 LTS in case that was part of the issue but also because pyenv was performing poorly, crashing half way through the installation of many older Python versions I was testing. Also chose to leave out pyenv-virtualenv as there were no multiple projects planned for this instance and it was one less thing to go wrong.

From the clean install of Ubuntu, in addition to installing apache2, pyenv, libapache2-mod-wsgi, activating it with a2enmod, I deliberately ran the following lines before installing the requirements with pip, which included numpy, so it doesn't complain:

sudo apt-get install gcc
sudo apt-get install g++

This is also needed:

sudo apt-get install apache2-dev

Then inside the environment, after the requirements,

pip install mod_wsgi
mod_wsgi-express module-config

The second line returned:

LoadModule wsgi_module "/home/ubuntu/.pyenv/versions/miniconda3-latest/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"
WSGIPythonHome "/home/ubuntu/.pyenv/versions/miniconda3-latest"

Then with loading the module, the docs encourages you to paste into a file httpd.conf which at least in my version of apache and ubuntu does not exist. After a lot of reading, I avoided creating one and also avoided pasting it into apache2.conf which seems to be related. Rather, following the instructions for ubuntu linked to at the top,

edit this file:

sudo vi /etc/apache2/mods-available/wsgi.load

paste this line into it and save:

LoadModule wsgi_module /path/to/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so

then run this and restart the apache server if necessary:

sudo a2enmod wsgi

000-default.conf looks like this:

WSGIPythonHome "/home/ubuntu/.pyenv/versions/miniconda3-latest"

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
        WSGIDaemonProcess helloapp threads=5 python-path=/var/www/html/frontend/
        WSGIScriptAlias / /var/www/html/frontend/helloapp.wsgi

        <Directory flaskapp>
        WSGIProcessGroup helloapp
        WSGIApplicationGroup %{GLOBAL}
        Order allow,deny
        Allow from all
        </Directory>

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>


问:
Passing IDs of table rows
I am new to JavaScript and not long ago I ask the following question:

I have a normal HTML table where each row has its own id. What I want to achieve is that each time I click a link in a row the id for that row should be stored in a variable and later passed to a function. Let's say I click row#1 then id#1 should be passed and so on... How can I achieve this?

I got a very good answer. This example works in jsFiddle

http://jsfiddle.net/andrewwhitaker/9HEQk/

But if I copy the JavaScript and the table exactly like it is into a HTML file the whole thing just doesn't work and I can't find the answer. Could someone help me again please?

Thank you very much!

答:
If all you need is the row id so why not using a simple code like this:

HTML:

```<code><table id="table-one">
    <tr id="row-one">
        <td><a href="JavaScript: void(0)" id="one" onClick="saveRow( 1 )">one</a></td>
    </tr>
    <tr id="row-two">
        <td><a href="JavaScript: void(0)" id="two" onClick="saveRow( 2 )">two</a></td>
    </tr>
</table>
</code>```

JS:

```<code>var lastRowId = -1;

function saveRow( id )
{
   lastRowId = id;
}
</code>```

Maybe I didn't fully understand what you asked?

Rotem

Title: Passing IDs of table rows

Body:
If all you need is the row id so why not using a simple code like this:

HTML:

<table id="table-one">
    <tr id="row-one">
        <td><a href="JavaScript: void(0)" id="one" onClick="saveRow( 1 )">one</a></td>
    </tr>
    <tr id="row-two">
        <td><a href="JavaScript: void(0)" id="two" onClick="saveRow( 2 )">two</a></td>
    </tr>
</table>

JS:

var lastRowId = -1;

function saveRow( id )
{
   lastRowId = id;
}

Maybe I didn't fully understand what you asked?

Rotem