问:
Navigate to a cell in a DataFrame using a set of criteria
I have a csv table like so:

```<code>a, b, c, d
value, value, value, value
value, value, value, value
</code>```

which I'm loading into a DataFrame. I also have a dictionary that looks like this:

```<code>data = {'a': some_value, 'b' = some_value, 'c' = some_value}
</code>```

I want to navigate to the cell in column d where the row has values a, b and c as specified by this dictionary. I know that there exists exactly one cell that matches these criteria. How can I do this?

答:
Another approach, would be use reduce on boolean conditions

```<code>In [1034]: data[np.logical_and.reduce(pd.DataFrame(data[x] == lookup[x] for x in lookup))]
Out[1034]:
   a  b  c  d
1  2  2  2  2

In [1035]: data[reduce(lambda x, y: x & y, [data[x] == lookup[x] for x in lookup])]
Out[1035]:
   a  b  c  d
1  2  2  2  2
</code>```

Body:
I have a csv table like so:

a, b, c, d
value, value, value, value
value, value, value, value

which I'm loading into a DataFrame. I also have a dictionary that looks like this:

data = {'a': some_value, 'b' = some_value, 'c' = some_value}

I want to navigate to the cell in column d where the row has values a, b and c as specified by this dictionary. I know that there exists exactly one cell that matches these criteria. How can I do this?

Body:
Another approach, would be use reduce on boolean conditions

In [1034]: data[np.logical_and.reduce(pd.DataFrame(data[x] == lookup[x] for x in lookup))]
Out[1034]:
   a  b  c  d
1  2  2  2  2

In [1035]: data[reduce(lambda x, y: x & y, [data[x] == lookup[x] for x in lookup])]
Out[1035]:
   a  b  c  d
1  2  2  2  2


来源: stackexchange

问:
Drawing text with an outer stroke with HTML5's canvas
I'm currently using HTML5's canvas to render a number of strings using the fillText method. This works fine, but I'd also like to give each string a 1px black outer stroke. Unfortunately the strokeText function seems to apply an inner stroke. To counter this, I've written a drawStrokedText function that achieves the effect I'm after. Unfortunately it's horrible slow (for obvious reasons).

Is there a fast, cross-browser way of achieving a 1px outer stroke using native canvas functionality?

```<code>drawStrokedText = function(context, text, x, y)
{
    context.fillStyle = "rgb(0,0,0)";
    context.fillText(text, x-1, y-1);
    context.fillText(text, x+1, y-1);
    context.fillText(text, x-1, y);
    context.fillText(text, x+1, y);
    context.fillText(text, x-1, y+1);
    context.fillText(text, x+1, y+1);

    context.fillStyle = "rgb(255,255,255)";
    context.fillText(text, x, y);
};
</code>```

Here's an example of the effect at work:

答:
For a smooth shadow you can try this</p>

```<code>ctx.beginPath();
ctx.fillStyle = 'white';
ctx.font = "bold 9pt Tahoma";
ctx.shadowBlur = 3;
ctx.textAlign = "center";
ctx.shadowColor = "#000000";
ctx.shadowOffs = 0;
ctx.fillText('www.ifnotpics.com', 100, 50);
ctx.closePath();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently using HTML5's canvas to render a number of strings using the fillText method. This works fine, but I'd also like to give each string a 1px black outer stroke. Unfortunately the strokeText function seems to apply an inner stroke. To counter this, I've written a drawStrokedText function that achieves the effect I'm after. Unfortunately it's horrible slow (for obvious reasons).

Is there a fast, cross-browser way of achieving a 1px outer stroke using native canvas functionality?

drawStrokedText = function(context, text, x, y)
{
    context.fillStyle = "rgb(0,0,0)";
    context.fillText(text, x-1, y-1);
    context.fillText(text, x+1, y-1);
    context.fillText(text, x-1, y);
    context.fillText(text, x+1, y);
    context.fillText(text, x-1, y+1);
    context.fillText(text, x+1, y+1);

    context.fillStyle = "rgb(255,255,255)";
    context.fillText(text, x, y);
};

Here's an example of the effect at work:

Body:
For a smooth shadow you can try this

ctx.beginPath();
ctx.fillStyle = 'white';
ctx.font = "bold 9pt Tahoma";
ctx.shadowBlur = 3;
ctx.textAlign = "center";
ctx.shadowColor = "#000000";
ctx.shadowOffs = 0;
ctx.fillText('www.ifnotpics.com', 100, 50);
ctx.closePath();


问:
Python: Using timer with PyHook
I am attempting to use PyHook to disable keyboard and mouse while running the script, and I am having difficulties setting a timer function so that the keyboard and mouse will only be disabled for a predefined amount of time, e.g. 30 seconds, and then return to normal.

```<code>def windoow(event):
    while True:
        return False
        time.sleep(30)
        break

hm = pyHook.HookManager()
hm.MouseAll = windoow
hm.KeyAll = windoow
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()
</code>```

I am new to programming in general, and I am therefore hoping for an easy solution that I can learn from and understand.

Thank you.

答:
Hmm, This is pretty nefarious but this does work. Your time.sleep() was never executing because it was placed after a return statement</p>

```<code>import pythoncom, pyHook, time
start = time.time()
time.clock()
elapsed = 0

def windoow(event):
    global elapsed
    if elapsed < 30:
       elapsed = time.time() - start
       time.sleep(1)
       return False

    return True

hm = pyHook.HookManager()
hm.MouseAll = windoow
hm.KeyAll = windoow
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()
</code>```

Title: Python: Using timer with PyHook

Body:
I am attempting to use PyHook to disable keyboard and mouse while running the script, and I am having difficulties setting a timer function so that the keyboard and mouse will only be disabled for a predefined amount of time, e.g. 30 seconds, and then return to normal.

def windoow(event):
    while True:
        return False
        time.sleep(30)
        break

hm = pyHook.HookManager()
hm.MouseAll = windoow
hm.KeyAll = windoow
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()

I am new to programming in general, and I am therefore hoping for an easy solution that I can learn from and understand.

Thank you.

Body:
Hmm, This is pretty nefarious but this does work. Your time.sleep() was never executing because it was placed after a return statement

import pythoncom, pyHook, time
start = time.time()
time.clock()
elapsed = 0

def windoow(event):
    global elapsed
    if elapsed < 30:
       elapsed = time.time() - start
       time.sleep(1)
       return False

    return True

hm = pyHook.HookManager()
hm.MouseAll = windoow
hm.KeyAll = windoow
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()


问:
C# Packing multiple signed integers into a single 64-bit value
I need to pack and unpack several values to/from a single 64-bit value. I have 3 signed integers (x,y,z). I would like to pack them into a single 64-bit value (signed or unsigned doesn't matter to me) using 24, 16, and 24 bits for the values respectively. Here are my requirements:

1) I can ensure ahead of times that the values being stored do not exceed the limits of the number of bits I am using to store them into the 64-bit value, so no additional checks need to be made.

2) The initial values are signed, so I'm thinking some kind of bit magic may need to be done in order to ensure that nothing is lost.

3) This conversion is going to take place a LOT, so it needs to be fast. I know in C++ this can pretty easily be done by storing the values in a struct that specifies the integer length, and then establishing a pointer that just points to the first value that can be used for the 64-bit value. With this method, there really isn't any math that needs done, everything is just memory read or right. As far as I can tell, this can't be done quite so simply in C#, but C# is what I have to work with for this project.

4) I don't really care if the 64-bit value is signed or unsigned, so long as I can go both ways with the operation and recover the initial values, and whatever type is used can be used for a Dictionary key.

答:
Masks and shifts are probably your best option. You can create explicit layout structs in C#, but there's no 24-bit primitive, so you'd be tripping over yourself and have to mask anyway. As soon as you're shifting, it is usually best to work unsigned (especially when right-shifting), so:

```<code>ulong val = ((((ulong)x) & 0xFFFFFF) << 40) // 24 bits of x, left-shifted by 40
          | ((((ulong)y) & 0xFFFF) << 24) // 16 bits of y, left-shifted by 24
          | (((ulong)z) & 0xFFFFFF); // 24 bits of z, no left-shift
</code>```

and to reverse that (assuming that we want uint values):

```<code>uint a = (uint)((val >> 40) & 0xFFFFFF),
     b = (uint)((val >> 24) & 0xFFFF),
     c = (uint)(val & 0xFFFFFF);
</code>```

Body:
Masks and shifts are probably your best option. You can create explicit layout structs in C#, but there's no 24-bit primitive, so you'd be tripping over yourself and have to mask anyway. As soon as you're shifting, it is usually best to work unsigned (especially when right-shifting), so:

ulong val = ((((ulong)x) & 0xFFFFFF) << 40) // 24 bits of x, left-shifted by 40
          | ((((ulong)y) & 0xFFFF) << 24) // 16 bits of y, left-shifted by 24
          | (((ulong)z) & 0xFFFFFF); // 24 bits of z, no left-shift

and to reverse that (assuming that we want uint values):

uint a = (uint)((val >> 40) & 0xFFFFFF),
     b = (uint)((val >> 24) & 0xFFFF),
     c = (uint)(val & 0xFFFFFF);


问:
Inter-pod communication in kubernetes
I had previously created a pod with three containers namely - prometheus, blackbox-exporter and python-access-api. The blackbox-exporter runs on port 9115 and scrapes the targets generated by python-access-api container which is alerted in the prometheus for SSL Expiry certificate of the targets. Now I want to move the blackbox- exporter to a different pod. I have tried to establish this via service but I am failing to establish the communication between prometheus and blackbox-exporter now, since they are in a different pod. And as a result of this, I am unable to make probe for    SSL Expiry certificate and hence, cannot see the alerts on prometheus. Below is the yaml file that I have used, can anyone please point out a way out of this problem. Please note that my configuration looks fine for prometheus and also the pods for blackbox and prometheus are running fine individually. Like I said above, I dont see they communicate with each other.

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: blackbox-deployment
  labels:
    app: prometheus
spec:
  replicas: 1
  selector:
    app: blackbox
  template:
    metadata:
      name: blackbox
      labels:
        app: blackbox
    spec:
      containers:
      - name: blackbox
</code>```

Yaml file for Prometheus deployment

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: python-daemon
  labels:
    app: prometheus-python
spec:
  replicas: 1
  selector:
    app: python
  template:
    metadata:
      name: python
      labels:
        app: python
    spec:
      containers:
</code>```

The service that I have deployed:-

```<code>apiVersion: v1
kind: Service
metadata:
  name: prometheus
spec:
  selector:
    app: prometheus
  ports:
  - name: http
    port: 80
    targetPort: 9115
    protocol: TCP
</code>```

The prometheus config is as follows

```<code>- job_name: blackbox
  params:
    module:
    - http_2xx
  scrape_interval: 1m
  scrape_timeout: 10s
  metrics_path: /probe
  scheme: http
  file_sd_configs:
  - files:
    - /var/suhas/targets.yml
    refresh_interval: 5m
  relabel_configs:
  - source_labels: [__address__]
    separator: ;
    regex: (.*)
    target_label: __param_target
    replacement: $1
    action: replace
  - source_labels: [__param_target]
    separator: ;
    regex: (.*)
    target_label: instance
    replacement: $1
    action: replace
  - source_labels: []
    separator: ;
    regex: (.*)
    target_label: __address__
    replacement: prometheus:9115
    action: replace
</code>```

答:
First of all, you would need to clarify which communications are taking place. Is prometheus accessing blackbox exporter via port 9115, or is blackbox exporter accessing prometheus via port 80? Depending on which is right, the service would be different.

In your service above, you are setting and endpoint which, when accessed via port 80, it will redirect traffic to port 9115 of your blackbox-exporter app. I will assume that prometheus is accessing the blackbox-exporter for the rest of the answer.

Would prometheus access blackbox exporter via port 9115 or port 80. It looks to me that, in your initial set up, the prometheus would use port 9115 to access. Therefore, there is no reason to change the port in the service to 80. Could you try setting port: 9115 in your service file instead?

Plus, make sure you configure prometheus to use the correct address. I assume that it would previously use 127.0.0.1:9115, now it would need to be prometheus:9115 (as you named the service prometheus, which can be bit confusing).

Title: Inter-pod communication in kubernetes

Body:
I had previously created a pod with three containers namely - prometheus, blackbox-exporter and python-access-api. The blackbox-exporter runs on port 9115 and scrapes the targets generated by python-access-api container which is alerted in the prometheus for SSL Expiry certificate of the targets. Now I want to move the blackbox- exporter to a different pod. I have tried to establish this via service but I am failing to establish the communication between prometheus and blackbox-exporter now, since they are in a different pod. And as a result of this, I am unable to make probe for    SSL Expiry certificate and hence, cannot see the alerts on prometheus. Below is the yaml file that I have used, can anyone please point out a way out of this problem. Please note that my configuration looks fine for prometheus and also the pods for blackbox and prometheus are running fine individually. Like I said above, I dont see they communicate with each other.

apiVersion: v1
kind: ReplicationController
metadata:
  name: blackbox-deployment
  labels:
    app: prometheus
spec:
  replicas: 1
  selector:
    app: blackbox
  template:
    metadata:
      name: blackbox
      labels:
        app: blackbox
    spec:
      containers:
      - name: blackbox

Yaml file for Prometheus deployment

apiVersion: v1
kind: ReplicationController
metadata:
  name: python-daemon
  labels:
    app: prometheus-python
spec:
  replicas: 1
  selector:
    app: python
  template:
    metadata:
      name: python
      labels:
        app: python
    spec:
      containers:

The service that I have deployed:-

apiVersion: v1
kind: Service
metadata:
  name: prometheus
spec:
  selector:
    app: prometheus
  ports:
  - name: http
    port: 80
    targetPort: 9115
    protocol: TCP

The prometheus config is as follows

- job_name: blackbox
  params:
    module:
    - http_2xx
  scrape_interval: 1m
  scrape_timeout: 10s
  metrics_path: /probe
  scheme: http
  file_sd_configs:
  - files:
    - /var/suhas/targets.yml
    refresh_interval: 5m
  relabel_configs:
  - source_labels: [__address__]
    separator: ;
    regex: (.*)
    target_label: __param_target
    replacement: $1
    action: replace
  - source_labels: [__param_target]
    separator: ;
    regex: (.*)
    target_label: instance
    replacement: $1
    action: replace
  - source_labels: []
    separator: ;
    regex: (.*)
    target_label: __address__
    replacement: prometheus:9115
    action: replace


问:
Creating a fancy search bar with Swing components
I'm trying to come up with an elegant recreation of the search bar component in Thunderbird. The clear button doesn't appear until there is text in the box, so that screen-shot is a bit inaccurate.

Should I use a layered pane and get some buttons to float above the box? (but then getting the text to not appear below the buttons would be hacky)

Maybe just put buttons at the ends of the search bar and have it somehow blend in?

Any ideas or maybe a style reconsideration is welcome, thank you.

答: What about a white panel with a border and a JTextField without borders inside. Two buttons (or more) in the west and east. Button will appear/hide depending on the text field content.</p>

ContentLicense: CC BY-SA 2.5


问:
UIBezierPath rounded corners in UIButton
I want to draw a tappable bubble shape around text. In order to do that I decided to add a shapelayer to UIButton like this:

```<code>// Button also has this
bubbleButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
bubbleButton.setTitle("Gutp", for: .normal)

// In my subclass of UIButton
override func layoutSubviews() {
    super.layoutSubviews()

    self.bubbleLayer?.removeFromSuperlayer()

    let maskLayer = CAShapeLayer.init()
    let bezierPath = UIBezierPath.init(roundedRect: self.bounds,
                                       byRoundingCorners: [.topRight, .topLeft, .bottomLeft],
                                       cornerRadii: CGSize(width: 20, height: 20))
    maskLayer.path = bezierPath.cgPath
    maskLayer.strokeColor = UIColor.red.cgColor
    maskLayer.lineWidth = 2
    maskLayer.fillColor = UIColor.clear.cgColor
    maskLayer.backgroundColor = UIColor.clear.cgColor
    maskLayer.isOpaque = false

    self.bubbleLayer = maskLayer

    if let layers = self.layer.sublayers {
        self.layer.insertSublayer(self.bubbleLayer!, at: UInt32(layers.count))
    } else {
        self.layer.addSublayer(self.bubbleLayer!)
    }
}
</code>```

Please don't look at the performance at the moment.

I have 2 buttons like this added into a UIStackView.

I get an interesting artefact (a tail if one can say so) in some cases of text (usually when it is short) and a normal bubble in case of longer text:

How can I fix this? And why do I get such behavior?

EDIT: Linking other possibly related questions about broken cornerRadii parameter in bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:. Maybe it will help someone with similar issues.

Why is cornerRadii parameter of CGSize type in -[UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:]?

Crazy rounded rect UIBezierPath behavior on iOS 7. What is the deal?

答:
For using these rounded rect methods you must ensure that the view size is larger then the radius used. In your case both width and height must be larger then 40 (Radii size is 20x20 so max(20*2, 20*2) = 40).

In general I prefer having a custom method to generate such paths. Using lines and arcs usually give you better flexibility. You may try the following:

```<code>    /// Returns a path with rounded corners
    ///
    /// - Parameters:
    ///   - frame: A frame at which the path is drawn. To fit in view "bounds" should be used
    ///   - maximumRadius: A maximum corner radius used. For smaller views radius will be min(width/2, height/2)
    /// - Returns: Returns a new path
    func roundedRectPath(inRect frame: CGRect, radiusConstrainedTo maximumRadius: CGFloat) -> UIBezierPath {

        let radisu = min(maximumRadius, min(frame.size.width*0.5, frame.size.height*0.5))

        let path = UIBezierPath()

        path.move(to: CGPoint(x: frame.origin.x + radisu, y: frame.origin.y)) // Top left
        path.addLine(to: CGPoint(x: frame.origin.x + frame.size.width - radisu, y: frame.origin.y))  // Top right
        path.addQuadCurve(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height - radisu), controlPoint: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y)) // Top right arc
        path.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height - radisu))  // Bottom right
        path.addQuadCurve(to: CGPoint(x: frame.origin.x + frame.size.width - radisu, y: frame.origin.y + frame.size.height), controlPoint: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height)) // Bottom right arc
        path.addLine(to: CGPoint(x: frame.origin.x + radisu, y: frame.origin.y + frame.size.height))  // Bottom left
        path.addQuadCurve(to: CGPoint(x: frame.origin.x, y: frame.origin.y + frame.size.height - radisu), controlPoint: CGPoint(x: frame.origin.x, y: frame.origin.y + frame.size.height)) // Bottom left arc
        path.addLine(to: CGPoint(x: frame.origin.x, y: frame.origin.y + radisu))  // Top left
        path.addQuadCurve(to: CGPoint(x: frame.origin.x + radisu, y: frame.origin.y), controlPoint: CGPoint(x: frame.origin.x, y: frame.origin.y)) // Top left arc
        path.close()

        return path
    }
</code>```

When using this with stroke you need to also inset the frame by half of the line width. This is a snippet from "draw rect" procedure but can be applied anywhere:

```<code>        UIColor.red.setStroke()
        let lineWidth: CGFloat = 5.0
        let path = roundedRectPath(inRect: bounds.insetBy(dx: lineWidth*0.5, dy: lineWidth*0.5), radiusConstrainedTo: 30.0)
        path.lineWidth = lineWidth
        path.stroke()
</code>```

Notice the bounds.insetBy(dx: lineWidth*0.5, dy: lineWidth*0.5).

Body:
I want to draw a tappable bubble shape around text. In order to do that I decided to add a shapelayer to UIButton like this:

// Button also has this
bubbleButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
bubbleButton.setTitle("Gutp", for: .normal)

// In my subclass of UIButton
override func layoutSubviews() {
    super.layoutSubviews()

    self.bubbleLayer?.removeFromSuperlayer()

    let maskLayer = CAShapeLayer.init()
    let bezierPath = UIBezierPath.init(roundedRect: self.bounds,
                                       byRoundingCorners: [.topRight, .topLeft, .bottomLeft],
                                       cornerRadii: CGSize(width: 20, height: 20))
    maskLayer.path = bezierPath.cgPath
    maskLayer.strokeColor = UIColor.red.cgColor
    maskLayer.lineWidth = 2
    maskLayer.fillColor = UIColor.clear.cgColor
    maskLayer.backgroundColor = UIColor.clear.cgColor
    maskLayer.isOpaque = false

    self.bubbleLayer = maskLayer

    if let layers = self.layer.sublayers {
        self.layer.insertSublayer(self.bubbleLayer!, at: UInt32(layers.count))
    } else {
        self.layer.addSublayer(self.bubbleLayer!)
    }
}

Please don't look at the performance at the moment.

I have 2 buttons like this added into a UIStackView.

I get an interesting artefact (a tail if one can say so) in some cases of text (usually when it is short) and a normal bubble in case of longer text:

How can I fix this? And why do I get such behavior?

EDIT: Linking other possibly related questions about broken cornerRadii parameter in bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:. Maybe it will help someone with similar issues.

Why is cornerRadii parameter of CGSize type in -[UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:]?

Crazy rounded rect UIBezierPath behavior on iOS 7. What is the deal?

Body:
For using these rounded rect methods you must ensure that the view size is larger then the radius used. In your case both width and height must be larger then 40 (Radii size is 20x20 so max(20*2, 20*2) = 40).

In general I prefer having a custom method to generate such paths. Using lines and arcs usually give you better flexibility. You may try the following:

    /// Returns a path with rounded corners
    ///
    /// - Parameters:
    ///   - frame: A frame at which the path is drawn. To fit in view "bounds" should be used
    ///   - maximumRadius: A maximum corner radius used. For smaller views radius will be min(width/2, height/2)
    /// - Returns: Returns a new path
    func roundedRectPath(inRect frame: CGRect, radiusConstrainedTo maximumRadius: CGFloat) -> UIBezierPath {

        let radisu = min(maximumRadius, min(frame.size.width*0.5, frame.size.height*0.5))

        let path = UIBezierPath()

        path.move(to: CGPoint(x: frame.origin.x + radisu, y: frame.origin.y)) // Top left
        path.addLine(to: CGPoint(x: frame.origin.x + frame.size.width - radisu, y: frame.origin.y))  // Top right
        path.addQuadCurve(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height - radisu), controlPoint: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y)) // Top right arc
        path.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height - radisu))  // Bottom right
        path.addQuadCurve(to: CGPoint(x: frame.origin.x + frame.size.width - radisu, y: frame.origin.y + frame.size.height), controlPoint: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height)) // Bottom right arc
        path.addLine(to: CGPoint(x: frame.origin.x + radisu, y: frame.origin.y + frame.size.height))  // Bottom left
        path.addQuadCurve(to: CGPoint(x: frame.origin.x, y: frame.origin.y + frame.size.height - radisu), controlPoint: CGPoint(x: frame.origin.x, y: frame.origin.y + frame.size.height)) // Bottom left arc
        path.addLine(to: CGPoint(x: frame.origin.x, y: frame.origin.y + radisu))  // Top left
        path.addQuadCurve(to: CGPoint(x: frame.origin.x + radisu, y: frame.origin.y), controlPoint: CGPoint(x: frame.origin.x, y: frame.origin.y)) // Top left arc
        path.close()

        return path
    }

When using this with stroke you need to also inset the frame by half of the line width. This is a snippet from "draw rect" procedure but can be applied anywhere:

        UIColor.red.setStroke()
        let lineWidth: CGFloat = 5.0
        let path = roundedRectPath(inRect: bounds.insetBy(dx: lineWidth*0.5, dy: lineWidth*0.5), radiusConstrainedTo: 30.0)
        path.lineWidth = lineWidth
        path.stroke()

Notice the bounds.insetBy(dx: lineWidth*0.5, dy: lineWidth*0.5).


问:
RxJS zip not working while forkJoin does
what I'm trying to achieve is this (with Angular 2/Typescript):

Observable A produces stream of events.

For each event of Observable A, make 8 different http calls. (8 switchmaps)

After all of the 8 requests return, do something (subscribe to zip of 8 switchmaps).

Repeat 8 requests for each event of Observable A (taken care of by switchmap and zip)

Code: (full code at https://plnkr.co/edit/44yqw0RYzC7v1TFACMx1)

```<code>let source = Observable
.interval(5000)
.take(100);

let requests = [];

for(let i=0; i<8;i++) {
  let request = source.switchMap(x=> http.get('https://jsonplaceholder.typicode.com/users/'+(i+1))).publish();
  request.subscribe(res => console.log(res.json()));
  requests.push(request);
}

Observable.zip(requests)
.subscribe(console.log("All requests completed"));

requests.forEach(r => r.connect());
</code>```

The problem is my zip never gets called. I console.log'ged the subscription to each of the 8 switchmaps and I'm getting logs showing eight http calls return successfully each time there is an event in Observable/stream A. (also can see the 8 calls returning in the network tab of the debug tools)

But zip never emits anything.

If I try a different (less ideal) approach:

Subscribe to Observable A once (not switchmap)

Within subscription create 8 Observables for each http call, and subscribe to ForkJoin of the 8 Observables

Code: (full code at https://plnkr.co/edit/GqQde1Ae2licBjtL0jcj)

```<code>let source = Observable
.interval(5000)
.take(100);

 source.subscribe(x=> {
   console.log(x);
   let requests = [];

   for(let i=0; i<8;i++) {
     let request = http.get('https://jsonplaceholder.typicode.com/users/'+(i+1)).publish();
     request.subscribe(res => console.log(res.json()));
     requests.push(request);
   }

   Observable.forkJoin(requests)
   .subscribe(console.log("All requests completed"));

   requests.forEach(r => r.connect());

 });
</code>```

This works. But with the obvious pitfall that I'm creating 8+1 nested observables/subscriptions each time Observable A emits.

(In both cases I'm using publish/connect to share/reuse subscriptions, but the problem exists even without it)

答:
You first example would work if you call zip correctly with multiple arguments and pass a function to subscribe (not the result of console.log which is undefined). Demo.

```<code>Observable.zip(...requests) // <-- spread this
    .subscribe(() => console.log("All requests completed")); // <-- pass a function

requests.forEach(r => r.connect());
</code>```

Body:
what I'm trying to achieve is this (with Angular 2/Typescript):

Observable A produces stream of events.

For each event of Observable A, make 8 different http calls. (8 switchmaps)

After all of the 8 requests return, do something (subscribe to zip of 8 switchmaps).

Repeat 8 requests for each event of Observable A (taken care of by switchmap and zip)

Code: (full code at https://plnkr.co/edit/44yqw0RYzC7v1TFACMx1)

let source = Observable
.interval(5000)
.take(100);

let requests = [];

for(let i=0; i<8;i++) {
  let request = source.switchMap(x=> http.get('https://jsonplaceholder.typicode.com/users/'+(i+1))).publish();
  request.subscribe(res => console.log(res.json()));
  requests.push(request);
}

Observable.zip(requests)
.subscribe(console.log("All requests completed"));

requests.forEach(r => r.connect());

The problem is my zip never gets called. I console.log'ged the subscription to each of the 8 switchmaps and I'm getting logs showing eight http calls return successfully each time there is an event in Observable/stream A. (also can see the 8 calls returning in the network tab of the debug tools)

But zip never emits anything.

If I try a different (less ideal) approach:

Subscribe to Observable A once (not switchmap)

Within subscription create 8 Observables for each http call, and subscribe to ForkJoin of the 8 Observables

Code: (full code at https://plnkr.co/edit/GqQde1Ae2licBjtL0jcj)

let source = Observable
.interval(5000)
.take(100);

 source.subscribe(x=> {
   console.log(x);
   let requests = [];

   for(let i=0; i<8;i++) {
     let request = http.get('https://jsonplaceholder.typicode.com/users/'+(i+1)).publish();
     request.subscribe(res => console.log(res.json()));
     requests.push(request);
   }

   Observable.forkJoin(requests)
   .subscribe(console.log("All requests completed"));

   requests.forEach(r => r.connect());

 });

This works. But with the obvious pitfall that I'm creating 8+1 nested observables/subscriptions each time Observable A emits.

(In both cases I'm using publish/connect to share/reuse subscriptions, but the problem exists even without it)

Body:
You first example would work if you call zip correctly with multiple arguments and pass a function to subscribe (not the result of console.log which is undefined). Demo.

Observable.zip(...requests) // <-- spread this
    .subscribe(() => console.log("All requests completed")); // <-- pass a function

requests.forEach(r => r.connect());


问:
Iptables dnat/snat rule internal
I am trying to redirect port 80 to an internal IP (192.168.33.52) with IPtables.
But if a open tcpdump with port 80 i see:

04:36:59.848744 IP 1.2.3.4.59936 > 192.168.33.52.http: Flags [S], seq 2560507980, win 8192, options [mss 1460,nop,wscale 8,nop,nop,sackOK], length 0

How can a rewrite our public IP 1.2.3.4 to our intern IP 192.168.33.200?
And 192.168.33.200 is redirecting the traffic back to the clients?

Network Interface:

eth0 - 1.2.3.4 (public IP)
eth0:0 - 192.168.33.200 (private IP)

Webserver: 192.168.33.52

My iptables rules:

target     prot opt source               destination

DNAT       tcp  --  0.0.0.0/0            1.2.3.4          tcp dpt:80 to:192.168.33.52:80

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)

target     prot opt source               destination

SNAT       tcp  --  0.0.0.0/0            192.168.33.52        to:1.2.3.4

答:
Save the script bellow as script.sh, then make it executable (chmod +x script.sh), then run it with ./script.sh

The iptables rules that you need are as follows:

```<code>#!/bin/bash

# enable ip forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# define vars
LOCALNET="192.168.33.0/24"
WAN="eth0"
WANIP="PUBLIC_IP"
WEBSERVER="192.168.33.52"

# enable traffic from the local network to the internet
iptables -t nat -A POSTROUTING -s $LOCALNET -o $WAN -j MASQUERADE

# HTTP to the local web server from the outside world
iptables -t nat -A PREROUTING -d $WANIP -p tcp --dport 80 -j DNAT --to-destination $WEBSERVER:80
iptables -t nat -A POSTROUTING -d $WEBSERVER -p tcp --dport 80 -j MASQUERADE
</code>```

Title: Iptables dnat/snat rule internal

Body:
Save the script bellow as script.sh, then make it executable (chmod +x script.sh), then run it with ./script.sh

The iptables rules that you need are as follows:

#!/bin/bash

# enable ip forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# define vars
LOCALNET="192.168.33.0/24"
WAN="eth0"
WANIP="PUBLIC_IP"
WEBSERVER="192.168.33.52"

# enable traffic from the local network to the internet
iptables -t nat -A POSTROUTING -s $LOCALNET -o $WAN -j MASQUERADE

# HTTP to the local web server from the outside world
iptables -t nat -A PREROUTING -d $WANIP -p tcp --dport 80 -j DNAT --to-destination $WEBSERVER:80
iptables -t nat -A POSTROUTING -d $WEBSERVER -p tcp --dport 80 -j MASQUERADE


问:
Cannot convert input to Timestamp, bday_range(...) - Pandas/Python
Looking to generate a number for the days in business days between current date and the end of the month of a pandas dataframe.
E.g. 26/06/2017 - 4, 23/06/2017 - 5

I'm having trouble as I keep getting a Type Error:

```<code>TypeError: Cannot convert input to Timestamp
</code>```

From line:

```<code>result['bdaterange'] = pd.bdate_range(pd.to_datetime(result['dte'], unit='ns').values, pd.to_datetime(result['bdate'], unit='ns').values)
</code>```

I have a Data Frame result with the column dte in a date format and I'm trying to create a new column (bdaterange) as a simple integer/float that I can use to see how far from month end in business days it has.

```<code>Sample data:
           bid   ask  spread         dte        day      bdate
01:49:00  2.17  3.83    1.66  2016-12-20  20.858333 2016-12-30
02:38:00   2.2   3.8    1.60  2016-12-20  20.716667 2016-12-30
22:15:00  2.63  3.12    0.49  2016-12-20  21.166667 2016-12-30
03:16:00  1.63  2.38    0.75  2016-12-21  21.391667 2016-12-30
07:11:00  1.46  2.54    1.08  2016-12-21  21.475000 2016-12-30
</code>```

I've tried BDay() and using that the day cannot be 6 & 7 in the calculation but have not got anywhere. I came across bdate_range which I believe will be exactly what I'm looking for, but the closest I've got gives me the error Cannot convert input to Timestamp.

My attempt is:

```<code>result['bdate'] = pd.to_datetime(result['dte']) + BMonthEnd(0)

result['bdaterange'] = pd.bdate_range(pd.to_datetime(result['dte'], unit='ns').values, pd.to_datetime(result['bdate'], unit='ns').values)

print(result['bdaterange'])
</code>```

Not sure how to solve the error though.

Body:
Looking to generate a number for the days in business days between current date and the end of the month of a pandas dataframe.
E.g. 26/06/2017 - 4, 23/06/2017 - 5

I'm having trouble as I keep getting a Type Error:

TypeError: Cannot convert input to Timestamp

From line:

result['bdaterange'] = pd.bdate_range(pd.to_datetime(result['dte'], unit='ns').values, pd.to_datetime(result['bdate'], unit='ns').values)

I have a Data Frame result with the column dte in a date format and I'm trying to create a new column (bdaterange) as a simple integer/float that I can use to see how far from month end in business days it has.

Sample data:
           bid   ask  spread         dte        day      bdate
01:49:00  2.17  3.83    1.66  2016-12-20  20.858333 2016-12-30
02:38:00   2.2   3.8    1.60  2016-12-20  20.716667 2016-12-30
22:15:00  2.63  3.12    0.49  2016-12-20  21.166667 2016-12-30
03:16:00  1.63  2.38    0.75  2016-12-21  21.391667 2016-12-30
07:11:00  1.46  2.54    1.08  2016-12-21  21.475000 2016-12-30

I've tried BDay() and using that the day cannot be 6 & 7 in the calculation but have not got anywhere. I came across bdate_range which I believe will be exactly what I'm looking for, but the closest I've got gives me the error Cannot convert input to Timestamp.

My attempt is:

result['bdate'] = pd.to_datetime(result['dte']) + BMonthEnd(0)

result['bdaterange'] = pd.bdate_range(pd.to_datetime(result['dte'], unit='ns').values, pd.to_datetime(result['bdate'], unit='ns').values)

print(result['bdaterange'])

Not sure how to solve the error though.

Body:
I think you need length of bdate_range for each row, so need custom function with apply:

#convert only once to datetime
result['dte'] = pd.to_datetime(result['dte'])

f = lambda x: len(pd.bdate_range(x['dte'], x['dte'] + pd.offsets.BMonthEnd(0)))
result['bdaterange'] = result.apply(f, axis=1)
print (result)
           bid   ask  spread        dte        day  bdaterange
01:49:00  2.17  3.83    1.66 2016-12-20  20.858333           9
02:38:00  2.20  3.80    1.60 2016-12-20  20.716667           9
22:15:00  2.63  3.12    0.49 2016-12-20  21.166667           9
03:16:00  1.63  2.38    0.75 2016-12-21  21.391667           8
07:11:00  1.46  2.54    1.08 2016-12-21  21.475000           8


问:
How to manage more than 1000 custom markers in google map with bounding box limitation to avoid Out of memory exception?
I am using google map with custom markers in my project ,
where each markers needed to set with custom view , for different purposes like waypoints with polylines and markers to identify them, polygon with markers etc.
Now when these markers are more than 1000 , the bitmap is failed to load into the Map and OOM is thrown .

I have used vector drawables as the marker identity and normal text view for levelling them, creating bitmap is taking 180*210 image ,

How can i efficiency manage it without lagging and OOM problem?

here is the code :
This is to read location from allGlobalPoints  Array and differentiate them and plotting them.

```<code>mMap.clear();
    allpointPlotterThreadRunning = true;
    switchTospecific = true;
    final String POINTS = "points";
    final String POIS = "pois";
    final String FAILSAFE = "failsafe";
    final String POLYGON = "polygon";
    final String LASTPOLYGON = "lastpolygon";

    allMapPointPlotter = new AsyncTask<Void, Object, Void>() {
        ProgressDialog pgbarLoading;
        PolylineOptions polyline;
        PolygonOptions plogon;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            final View tiltleView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.progress_dialog_title_background, null);
            OpenSansRegularTextView tiltle = (OpenSansRegularTextView) tiltleView.findViewById(R.id.title_text);
            tiltle.setText("UAV Editor");

            pgbarLoading = new ProgressDialog(getActivity());
            pgbarLoading.setCancelable(false);
            pgbarLoading.setMessage("" + getActivity().getString(R.string.please_wait));
            pgbarLoading.setCustomTitle(tiltleView);
            pgbarLoading.show();
            markerPlottedList = new ArrayList<>();
            markerOnQueue = new ArrayList<>();

            ((DashboardActivity) getActivity()).setZoomOut();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            allpointPlotterThreadRunning = false;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                if (allpointPlotterThreadRunning) {
                    if (allGlobalPoints.size() > 0) {

                        for (int global = 0; global < allGlobalPoints.size(); global++) {
                            if (allpointPlotterThreadRunning) {
                                //getting first object containing all points data
                                AllGlobalPointsArrayData globalDataObject = allGlobalPoints.get(global);  //This is the object of the position that contains all 5 data

                                if (globalDataObject.getPointsDataArray() != null && globalDataObject.getPointsDataArray().size() > 0) {

                                    ArrayList<RoutePointCoordinatesDataType> innerarraylist = globalDataObject.getPointsDataArray();

                                    for (int i = 0; i < innerarraylist.size(); i++) {
                                        if (allpointPlotterThreadRunning) {

                                            if (i == (innerarraylist.size() - 1)) {
                                                publishProgress(
                                                        POINTS,
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerarraylist.get(i).getTag(),
                                                        innerarraylist.get(i).getHeadingAngle(),
                                                        true
                                                );
                                            } else {
                                                publishProgress(
                                                        POINTS,
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerarraylist.get(i).getTag(),
                                                        innerarraylist.get(i).getHeadingAngle(),
                                                        false
                                                );
                                            }

                                        } else {
                                            break;
                                        }

                                    }
                                }
                                if (globalDataObject.getPoiDataArray() != null && globalDataObject.getPoiDataArray().size() > 0) {
                                    ArrayList<RoutePointCoordinatesDataType> innerList = globalDataObject.getPoiDataArray();

                                    if (innerList != null && innerList.size() > 0) {

                                        for (int i = 0; i < innerList.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                publishProgress(
                                                        POIS,
                                                        Double.parseDouble(innerList.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerList.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerList.get(i).getTag()
                                                );

                                            } else {
                                                break;
                                            }

                                        }
                                    }
                                }

                                if (globalDataObject.getFailsafeDataArray() != null && globalDataObject.getFailsafeDataArray().size() > 0) {

                                    ArrayList<RoutePointCoordinatesDataType> innerArray = globalDataObject.getFailsafeDataArray();
                                    if (innerArray != null && innerArray.size() > 0) {
                                        for (int i = 0; i < innerArray.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                publishProgress(
                                                        FAILSAFE,
                                                        Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerArray.get(i).getTag()
                                                );

                                            } else {
                                                break;
                                            }

                                        }
                                    }
                                }

                                if (globalDataObject.getPolygonLastUsedDataArray() != null && globalDataObject.getPolygonLastUsedDataArray().size() > 0) {
                                    ArrayList<RoutePointCoordinatesDataType> innerArray = globalDataObject.getPolygonLastUsedDataArray();
                                    if (innerArray != null && innerArray.size() > 0) {

                                        for (int i = 0; i < innerArray.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                if (i == (innerArray.size() - 1)) {
                                                    publishProgress(
                                                            LASTPOLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            true
                                                    );
                                                } else {
                                                    publishProgress(
                                                            LASTPOLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            false
                                                    );
                                                }

                                            } else {
                                                break;
                                            }

                                        }
                                    }
                                }

                                if (globalDataObject.getPolygonLastUsedDataArray() == null || globalDataObject.getPolygonLastUsedDataArray().size() == 0) {
                                    ArrayList<RoutePointCoordinatesDataType> innerArray = globalDataObject.getPolygonDataArray();
                                    if (innerArray != null && innerArray.size() > 0) {

                                        for (int i = 0; i < innerArray.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                if (i == (innerArray.size() - 1)) {
                                                    publishProgress(
                                                            POLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            true
                                                    );
                                                } else {
                                                    publishProgress(
                                                            POLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            false
                                                    );
                                                }

                                            } else {
                                                break;
                                            }

                                        }

                                    }
                                }
                            } else {
                                break;
                            }
                        }

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object... values) {
            super.onProgressUpdate(values);
            if (allpointPlotterThreadRunning) {
                String tagmarker = (String) values[0];
                int innerCounter = (Integer) values[3];

                if (tagmarker.equalsIgnoreCase(POINTS)) {
                    if (innerCounter == 0) {
                        polyline = new PolylineOptions();
                        polyline.width(4);
                        polyline.color(Color.parseColor("#425fa9"));
                        polyline.geodesic(true);
                    }

                    polyline.add(
                            new LatLng(
                                    (Double) values[1],
                                    (Double) values[2]
                            )
                    );
                    if ((Double) values[5] != 400) {
                        createMarker(
                                mMap,
                                (Double) values[1],
                                (Double) values[2],
                                innerCounter,
                                (String) values[4],
                                (Double) values[5]

                        );

                    } else {
                        createMarker(
                                mMap,
                                (Double) values[1],
                                (Double) values[2],
                                innerCounter,
                                (String) values[4],
                                400
                        );
                    }

                    if ((Boolean) values[6]) {
                        mMap.addPolyline(polyline);
                    }

                } else if (tagmarker.equalsIgnoreCase(POIS)) {

                    createMarkerPoi(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                } else if (tagmarker.equalsIgnoreCase(FAILSAFE)) {

                    createMarkerFailsafe(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                } else if (tagmarker.equalsIgnoreCase(POLYGON)) {
                    if (innerCounter == 0) {
                        plogon = new PolygonOptions();
                        plogon.fillColor(Color.parseColor("#20ff1a1a"));

                        plogon.strokeWidth((float) 5.1)
                                .strokeColor(Color.parseColor("#30ff1a1a"));
                    }
                    createMarkerPolygon(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                    plogon.add(new LatLng(
                            (Double) values[1],
                            (Double) values[2]
                    ));
                    if ((Boolean) values[5]) {
                        mMap.addPolygon(plogon);
                    }

                } else if (tagmarker.equalsIgnoreCase(LASTPOLYGON)) {
                    if (innerCounter == 0) {
                        plogon = new PolygonOptions();
                        plogon.fillColor(Color.parseColor("#20ff1a1a"));

                        plogon.strokeWidth((float) 5.1)
                                .strokeColor(Color.parseColor("#30ff1a1a"));
                    }

                    createMarkerPolygon(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                    plogon.add(new LatLng(
                            (Double) values[1],
                            (Double) values[2]
                    ));
                    if ((Boolean) values[5]) {
                        mMap.addPolygon(plogon);
                    }
                }
            }

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pgbarLoading.dismiss();
            allpointPlotterThreadRunning = false;

        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
</code>```

For creating markers
and bitmaps the functions are used follows:->
memoryCacheData is used as lrucache list for quick access to bitmap

```<code>    protected void createMarker(GoogleMap map, double latitude, double longitude, int inner, String outer, double angle) {
    try {
        Bitmap resultantBitmap = null;
        if (((DashboardActivity) getActivity()).memoryCacheData != null && ((DashboardActivity) getActivity()).memoryCacheData.size() > 0) {
            resultantBitmap = ((DashboardActivity) getActivity()).memoryCacheData.get(latitude + "/" + longitude + "-OwnTab-" + inner + "|" + outer);
            if (resultantBitmap == null) {
                resultantBitmap = getMarkerBitmapFromView("P" + (inner + 1), "P", angle);
                ((DashboardActivity) getActivity()).memoryCacheData.put(latitude + "/" + longitude + "-OwnTabMarker-" + inner + "|" + outer, resultantBitmap);
            }
        } else {
            resultantBitmap = getMarkerBitmapFromView("P" + (inner + 1), "P", angle);
            ((DashboardActivity) getActivity()).memoryCacheData.put(latitude + "/" + longitude + "-OwnTabMarker-" + inner + "|" + outer, resultantBitmap);
        }

        map.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title("" + outer)
                .icon(BitmapDescriptorFactory.fromBitmap(resultantBitmap))
        );

    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

Please help me how to manage the bitmap without freezing the application and avoiding the Out of memory exception , and how can i manage that much of markers with custom view .

答:
I know it is too late to answer on this but you can use ClusterManager in order to display 1000 marker efficiently. First put all the lat long in the ArrayList and then add the list to ClusterManager at once by using mClusterManager.addItems(ArrayList<..>);, mClusterManager.cluster();.

Doing this will eliminate UI freezing problem and Out of memory problem.

In Order to implement the ClusterManager please refer this link: https://github.com/googlemaps/android-maps-utils/blob/master/demo/src/com/google/maps/android/utils/demo/CustomMarkerClusteringDemoActivity.java

Body:
I am using google map with custom markers in my project ,
where each markers needed to set with custom view , for different purposes like waypoints with polylines and markers to identify them, polygon with markers etc.
Now when these markers are more than 1000 , the bitmap is failed to load into the Map and OOM is thrown .

I have used vector drawables as the marker identity and normal text view for levelling them, creating bitmap is taking 180*210 image ,

How can i efficiency manage it without lagging and OOM problem?

here is the code :
This is to read location from allGlobalPoints  Array and differentiate them and plotting them.

mMap.clear();
    allpointPlotterThreadRunning = true;
    switchTospecific = true;
    final String POINTS = "points";
    final String POIS = "pois";
    final String FAILSAFE = "failsafe";
    final String POLYGON = "polygon";
    final String LASTPOLYGON = "lastpolygon";

    allMapPointPlotter = new AsyncTask<Void, Object, Void>() {
        ProgressDialog pgbarLoading;
        PolylineOptions polyline;
        PolygonOptions plogon;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            final View tiltleView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.progress_dialog_title_background, null);
            OpenSansRegularTextView tiltle = (OpenSansRegularTextView) tiltleView.findViewById(R.id.title_text);
            tiltle.setText("UAV Editor");

            pgbarLoading = new ProgressDialog(getActivity());
            pgbarLoading.setCancelable(false);
            pgbarLoading.setMessage("" + getActivity().getString(R.string.please_wait));
            pgbarLoading.setCustomTitle(tiltleView);
            pgbarLoading.show();
            markerPlottedList = new ArrayList<>();
            markerOnQueue = new ArrayList<>();

            ((DashboardActivity) getActivity()).setZoomOut();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            allpointPlotterThreadRunning = false;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                if (allpointPlotterThreadRunning) {
                    if (allGlobalPoints.size() > 0) {

                        for (int global = 0; global < allGlobalPoints.size(); global++) {
                            if (allpointPlotterThreadRunning) {
                                //getting first object containing all points data
                                AllGlobalPointsArrayData globalDataObject = allGlobalPoints.get(global);  //This is the object of the position that contains all 5 data

                                if (globalDataObject.getPointsDataArray() != null && globalDataObject.getPointsDataArray().size() > 0) {

                                    ArrayList<RoutePointCoordinatesDataType> innerarraylist = globalDataObject.getPointsDataArray();

                                    for (int i = 0; i < innerarraylist.size(); i++) {
                                        if (allpointPlotterThreadRunning) {

                                            if (i == (innerarraylist.size() - 1)) {
                                                publishProgress(
                                                        POINTS,
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerarraylist.get(i).getTag(),
                                                        innerarraylist.get(i).getHeadingAngle(),
                                                        true
                                                );
                                            } else {
                                                publishProgress(
                                                        POINTS,
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerarraylist.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerarraylist.get(i).getTag(),
                                                        innerarraylist.get(i).getHeadingAngle(),
                                                        false
                                                );
                                            }

                                        } else {
                                            break;
                                        }

                                    }
                                }
                                if (globalDataObject.getPoiDataArray() != null && globalDataObject.getPoiDataArray().size() > 0) {
                                    ArrayList<RoutePointCoordinatesDataType> innerList = globalDataObject.getPoiDataArray();

                                    if (innerList != null && innerList.size() > 0) {

                                        for (int i = 0; i < innerList.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                publishProgress(
                                                        POIS,
                                                        Double.parseDouble(innerList.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerList.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerList.get(i).getTag()
                                                );

                                            } else {
                                                break;
                                            }

                                        }
                                    }
                                }

                                if (globalDataObject.getFailsafeDataArray() != null && globalDataObject.getFailsafeDataArray().size() > 0) {

                                    ArrayList<RoutePointCoordinatesDataType> innerArray = globalDataObject.getFailsafeDataArray();
                                    if (innerArray != null && innerArray.size() > 0) {
                                        for (int i = 0; i < innerArray.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                publishProgress(
                                                        FAILSAFE,
                                                        Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                        Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                        i,
                                                        "" + innerArray.get(i).getTag()
                                                );

                                            } else {
                                                break;
                                            }

                                        }
                                    }
                                }

                                if (globalDataObject.getPolygonLastUsedDataArray() != null && globalDataObject.getPolygonLastUsedDataArray().size() > 0) {
                                    ArrayList<RoutePointCoordinatesDataType> innerArray = globalDataObject.getPolygonLastUsedDataArray();
                                    if (innerArray != null && innerArray.size() > 0) {

                                        for (int i = 0; i < innerArray.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                if (i == (innerArray.size() - 1)) {
                                                    publishProgress(
                                                            LASTPOLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            true
                                                    );
                                                } else {
                                                    publishProgress(
                                                            LASTPOLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            false
                                                    );
                                                }

                                            } else {
                                                break;
                                            }

                                        }
                                    }
                                }

                                if (globalDataObject.getPolygonLastUsedDataArray() == null || globalDataObject.getPolygonLastUsedDataArray().size() == 0) {
                                    ArrayList<RoutePointCoordinatesDataType> innerArray = globalDataObject.getPolygonDataArray();
                                    if (innerArray != null && innerArray.size() > 0) {

                                        for (int i = 0; i < innerArray.size(); i++) {
                                            if (allpointPlotterThreadRunning) {

                                                if (i == (innerArray.size() - 1)) {
                                                    publishProgress(
                                                            POLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            true
                                                    );
                                                } else {
                                                    publishProgress(
                                                            POLYGON,
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLatitude()),
                                                            Double.parseDouble(innerArray.get(i).getCoordinatesLongitude()),
                                                            i,
                                                            "" + innerArray.get(i).getTag(),
                                                            false
                                                    );
                                                }

                                            } else {
                                                break;
                                            }

                                        }

                                    }
                                }
                            } else {
                                break;
                            }
                        }

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object... values) {
            super.onProgressUpdate(values);
            if (allpointPlotterThreadRunning) {
                String tagmarker = (String) values[0];
                int innerCounter = (Integer) values[3];

                if (tagmarker.equalsIgnoreCase(POINTS)) {
                    if (innerCounter == 0) {
                        polyline = new PolylineOptions();
                        polyline.width(4);
                        polyline.color(Color.parseColor("#425fa9"));
                        polyline.geodesic(true);
                    }

                    polyline.add(
                            new LatLng(
                                    (Double) values[1],
                                    (Double) values[2]
                            )
                    );
                    if ((Double) values[5] != 400) {
                        createMarker(
                                mMap,
                                (Double) values[1],
                                (Double) values[2],
                                innerCounter,
                                (String) values[4],
                                (Double) values[5]

                        );

                    } else {
                        createMarker(
                                mMap,
                                (Double) values[1],
                                (Double) values[2],
                                innerCounter,
                                (String) values[4],
                                400
                        );
                    }

                    if ((Boolean) values[6]) {
                        mMap.addPolyline(polyline);
                    }

                } else if (tagmarker.equalsIgnoreCase(POIS)) {

                    createMarkerPoi(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                } else if (tagmarker.equalsIgnoreCase(FAILSAFE)) {

                    createMarkerFailsafe(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                } else if (tagmarker.equalsIgnoreCase(POLYGON)) {
                    if (innerCounter == 0) {
                        plogon = new PolygonOptions();
                        plogon.fillColor(Color.parseColor("#20ff1a1a"));

                        plogon.strokeWidth((float) 5.1)
                                .strokeColor(Color.parseColor("#30ff1a1a"));
                    }
                    createMarkerPolygon(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                    plogon.add(new LatLng(
                            (Double) values[1],
                            (Double) values[2]
                    ));
                    if ((Boolean) values[5]) {
                        mMap.addPolygon(plogon);
                    }

                } else if (tagmarker.equalsIgnoreCase(LASTPOLYGON)) {
                    if (innerCounter == 0) {
                        plogon = new PolygonOptions();
                        plogon.fillColor(Color.parseColor("#20ff1a1a"));

                        plogon.strokeWidth((float) 5.1)
                                .strokeColor(Color.parseColor("#30ff1a1a"));
                    }

                    createMarkerPolygon(
                            mMap,
                            (Double) values[1],
                            (Double) values[2],
                            innerCounter,
                            (String) values[4]
                    );

                    plogon.add(new LatLng(
                            (Double) values[1],
                            (Double) values[2]
                    ));
                    if ((Boolean) values[5]) {
                        mMap.addPolygon(plogon);
                    }
                }
            }

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pgbarLoading.dismiss();
            allpointPlotterThreadRunning = false;

        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

For creating markers
and bitmaps the functions are used follows:->
memoryCacheData is used as lrucache list for quick access to bitmap

    protected void createMarker(GoogleMap map, double latitude, double longitude, int inner, String outer, double angle) {
    try {
        Bitmap resultantBitmap = null;
        if (((DashboardActivity) getActivity()).memoryCacheData != null && ((DashboardActivity) getActivity()).memoryCacheData.size() > 0) {
            resultantBitmap = ((DashboardActivity) getActivity()).memoryCacheData.get(latitude + "/" + longitude + "-OwnTab-" + inner + "|" + outer);
            if (resultantBitmap == null) {
                resultantBitmap = getMarkerBitmapFromView("P" + (inner + 1), "P", angle);
                ((DashboardActivity) getActivity()).memoryCacheData.put(latitude + "/" + longitude + "-OwnTabMarker-" + inner + "|" + outer, resultantBitmap);
            }
        } else {
            resultantBitmap = getMarkerBitmapFromView("P" + (inner + 1), "P", angle);
            ((DashboardActivity) getActivity()).memoryCacheData.put(latitude + "/" + longitude + "-OwnTabMarker-" + inner + "|" + outer, resultantBitmap);
        }

        map.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title("" + outer)
                .icon(BitmapDescriptorFactory.fromBitmap(resultantBitmap))
        );

    } catch (Exception e) {
        e.printStackTrace();
    }

}

Please help me how to manage the bitmap without freezing the application and avoiding the Out of memory exception , and how can i manage that much of markers with custom view .


问:
Howto map a unknown complex type within wsimport
Currently I try to generate a web service client for a wsdl vis wsimport which works quite fine excepting one complex type:

```<code>...
<element name="response">
 <complexType>
  <sequence>
   <element name="methodReturn" type="apachesoap:Document"/>
  </sequence>
 </complexType>
</element>
...
</code>```

When I try to generate the client via wsimport I get:

```<code>org.xml.sax.SAXParseException; systemId: file:/D:/dev/src/java/prj/src/wsdl/service.wsdl; lineNumber: 21; columnNumber: 80; undefined simple or complex type 'apachesoap:Document'
    at com.sun.xml.xsom.impl.parser.ParserContext$1.reportError(ParserContext.java:180)
    at com.sun.xml.xsom.impl.parser.NGCCRuntimeEx.reportError(NGCCRuntimeEx.java:175)
    at com.sun.xml.xsom.impl.parser.DelayedRef.resolve(DelayedRef.java:110)
    at com.sun.xml.xsom.impl.parser.DelayedRef.run(DelayedRef.java:85)
    at com.sun.xml.xsom.impl.parser.ParserContext.getResult(ParserContext.java:135)
    at com.sun.xml.xsom.parser.XSOMParser.getResult(XSOMParser.java:211)
    at com.sun.tools.xjc.ModelLoader.createXSOM(ModelLoader.java:538)
    at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:269)
    at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:95)
    at com.sun.tools.ws.processor.modeler.wsdl.JAXBModelBuilder.bind(JAXBModelBuilder.java:142)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildJAXBModel(WSDLModeler.java:2298)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.internalBuildModel(WSDLModeler.java:198)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildModel(WSDLModeler.java:141)
    at com.sun.tools.ws.wscompile.WsimportTool.buildWsdlModel(WsimportTool.java:444)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:205)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:183)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.mojo.jaxws.Invoker.main(Invoker.java:78)
undefined simple or complex type 'apachesoap:Document'
  line 21 of file:/D:/dev/src/java/prj/src/wsdl/service.wsdl

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.mojo.jaxws.Invoker.main(Invoker.java:78)
Caused by: com.sun.tools.ws.wscompile.AbortException
    at com.sun.tools.ws.processor.modeler.wsdl.JAXBModelBuilder.bind(JAXBModelBuilder.java:144)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildJAXBModel(WSDLModeler.java:2298)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.internalBuildModel(WSDLModeler.java:198)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildModel(WSDLModeler.java:141)
    at com.sun.tools.ws.wscompile.WsimportTool.buildWsdlModel(WsimportTool.java:444)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:205)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:183)
    ... 5 more
</code>```

When I change the type to
<element name="methodReturn" type="xsd:anySimpleType"/>

The client can be generated. So the generation just hangs on the unknown complex type.

So the question: Is it possible to provide a custom mapper to wsimport so that the client could be generated withing the "apachesoap:Document" type?

答:
In the WSDL you have to

provide namespace for apachesoap prefix

import or include XSD schema for that namespace with Document type defined there. (either in WSDL or into any XSD schema used in WSDL)

then client will be properly generated.

Without it wsimport (or any other tools) has no idea what type apachesoap:Document actually means.

Body:
Currently I try to generate a web service client for a wsdl vis wsimport which works quite fine excepting one complex type:

...
<element name="response">
 <complexType>
  <sequence>
   <element name="methodReturn" type="apachesoap:Document"/>
  </sequence>
 </complexType>
</element>
...

When I try to generate the client via wsimport I get:

org.xml.sax.SAXParseException; systemId: file:/D:/dev/src/java/prj/src/wsdl/service.wsdl; lineNumber: 21; columnNumber: 80; undefined simple or complex type 'apachesoap:Document'
    at com.sun.xml.xsom.impl.parser.ParserContext$1.reportError(ParserContext.java:180)
    at com.sun.xml.xsom.impl.parser.NGCCRuntimeEx.reportError(NGCCRuntimeEx.java:175)
    at com.sun.xml.xsom.impl.parser.DelayedRef.resolve(DelayedRef.java:110)
    at com.sun.xml.xsom.impl.parser.DelayedRef.run(DelayedRef.java:85)
    at com.sun.xml.xsom.impl.parser.ParserContext.getResult(ParserContext.java:135)
    at com.sun.xml.xsom.parser.XSOMParser.getResult(XSOMParser.java:211)
    at com.sun.tools.xjc.ModelLoader.createXSOM(ModelLoader.java:538)
    at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:269)
    at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:95)
    at com.sun.tools.ws.processor.modeler.wsdl.JAXBModelBuilder.bind(JAXBModelBuilder.java:142)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildJAXBModel(WSDLModeler.java:2298)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.internalBuildModel(WSDLModeler.java:198)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildModel(WSDLModeler.java:141)
    at com.sun.tools.ws.wscompile.WsimportTool.buildWsdlModel(WsimportTool.java:444)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:205)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:183)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.mojo.jaxws.Invoker.main(Invoker.java:78)
undefined simple or complex type 'apachesoap:Document'
  line 21 of file:/D:/dev/src/java/prj/src/wsdl/service.wsdl

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.mojo.jaxws.Invoker.main(Invoker.java:78)
Caused by: com.sun.tools.ws.wscompile.AbortException
    at com.sun.tools.ws.processor.modeler.wsdl.JAXBModelBuilder.bind(JAXBModelBuilder.java:144)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildJAXBModel(WSDLModeler.java:2298)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.internalBuildModel(WSDLModeler.java:198)
    at com.sun.tools.ws.processor.modeler.wsdl.WSDLModeler.buildModel(WSDLModeler.java:141)
    at com.sun.tools.ws.wscompile.WsimportTool.buildWsdlModel(WsimportTool.java:444)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:205)
    at com.sun.tools.ws.wscompile.WsimportTool.run(WsimportTool.java:183)
    ... 5 more

When I change the type to
<element name="methodReturn" type="xsd:anySimpleType"/>

The client can be generated. So the generation just hangs on the unknown complex type.

So the question: Is it possible to provide a custom mapper to wsimport so that the client could be generated withing the "apachesoap:Document" type?


问:
How to split a string after specific character in SQL Server and update this value to specific column
I have table with data 1/1 to 1/20 in one column. I want the value 1 to 20 i.e value after '/'(front slash) is updated into other column in same table in SQL Server.

Example:

Column has value 1/1,1/2,1/3...1/20

new Column value 1,2,3,..20

That is, I want to update this new column.

答: I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int) function.

ContentLicense: CC BY-SA 4.0


问:
PostgreSQL: how to format date without using to_char()?
I have this PHP-script which I'd like to keep unchanged:

```<code>$display = array(
    'QDATETIME',
    'ID',
    'NAME',
    'CATEGORY',
    'APPSVERSION',
    'OSVERSION',
);

$sql = sprintf("
    select %s from quincytrack
    where qdatetime > (now() - interval '2 day') and
    qdatetime <= now()",
    join(', ', $display));
$sth = $pg->prepare($sql);
$sth->execute($args);
</code>```

My problem is that QDATETIME is printed as 2010-12-18 15:51:37 while I need it as 2010-12-18. I know I could call to_char(QDATETIME, 'YYYY-MM-DD') as QDATETIME, but would prefer to find some other way to affect the date output format...

Using PostgreSQL 8.4.5 under CentOS 5.5 Linux / 64 bit.

Thank you!
Alex

答:
Just CAST to datatype DATE:</p>

```<code>SELECT
    CAST('2010-12-18 15:51:37' AS DATE);
</code>```

Body:
I have this PHP-script which I'd like to keep unchanged:

$display = array(
    'QDATETIME',
    'ID',
    'NAME',
    'CATEGORY',
    'APPSVERSION',
    'OSVERSION',
);

$sql = sprintf("
    select %s from quincytrack
    where qdatetime > (now() - interval '2 day') and
    qdatetime <= now()",
    join(', ', $display));
$sth = $pg->prepare($sql);
$sth->execute($args);

My problem is that QDATETIME is printed as 2010-12-18 15:51:37 while I need it as 2010-12-18. I know I could call to_char(QDATETIME, 'YYYY-MM-DD') as QDATETIME, but would prefer to find some other way to affect the date output format...

Using PostgreSQL 8.4.5 under CentOS 5.5 Linux / 64 bit.

Thank you!
Alex

Body:
Just CAST to datatype DATE:

SELECT
    CAST('2010-12-18 15:51:37' AS DATE);


问:
Use _.chain .groupBy .filter .map in lodash to get grouping based on different filters
Data Set:

```<code>[
  {
    "created_by": "5750790484393984",
    "patient_dateofbirth": "02/05/1990",
    "patient_aadhaar": "1234567890",
    "patient_area": "wert",
    "patient_state": "Arunachal Pradesh",
    "patient_gender": "Male",
    "patient_pincode": "123456",
    "location": "Guwahati",
    "patient_name": "Rakesh",
    "isVisited": 2,
    "new_repeat": "Repeat",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-04T04:41:59.261Z",
    "CreatedAt": "2017-07-03T18:48:25.773Z",
    "patient_bloodgroup": "B+",
    "patient_country": "India"
  },
  {
    "created_by": "5750790484393984",
    "patient_dateofbirth": "07/30/2006",
    "patient_aadhaar": "2343524361731",
    "patient_area": "begusarai",
    "patient_state": "Bihar",
    "patient_gender": "Male",
    "patient_pincode": "110016",
    "patient_name": "gyguy yuguy",
    "registration_number": "2",
    "ip_address": "43.225.248.20, 162.158.155.110",
    "CreatedAt": "2017-06-28T09:41:47.188Z",
    "patient_bloodgroup": "A+",
    "patient_country": "India"
  },
  {
    "ip_address": "103.83.148.161, 141.101.99.35",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-04T09:56:51.588Z",
    "CreatedAt": "2017-07-02T23:37:29.512Z",
    "patient_bloodgroup": "A+",
    "patient_country": "India",
    "created_by": "5750790484393984",
    "patient_dateofbirth": "06/24/1964",
    "patient_aadhaar": "",
    "patient_area": "Chattarpur",
    "patient_state": "Uttar Pradesh",
    "patient_gender": "Female",
    "patient_pincode": "201005",
    "patient_name": "Sudha Ambastha",
    "isVisited": 2,
    "new_repeat": "Repeat"
  },
  {
    "patient_area": "ajsdh",
    "patient_state": "Delhi",
    "patient_gender": "Male",
    "patient_pincode": "110074",
    "patient_name": "prashant",
    "registration_number": "283423472834",
    "isVisited": 1,
    "new_repeat": "New",
    "ip_address": "43.225.248.20, 162.158.155.110",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-03T18:41:55.777Z",
    "CreatedAt": "2017-06-28T11:18:55.792Z",
    "patient_bloodgroup": "B+",
    "patient_country": "India",
    "created_by": "5750790484393984",
    "patient_dateofbirth": "06/13/1990",
    "patient_aadhaar": "2131231238"
  },
  {
    "created_by": "5750790484393984",
    "patient_dateofbirth": "06/07/1990",
    "patient_aadhaar": "1278292020029",
    "patient_area": "Bhubneshwar",
    "patient_state": "Orissa",
    "patient_gender": "Male",
    "patient_pincode": "112218",
    "location": "Haldia",
    "patient_name": "Rajesh Mishra",
    "isVisited": 2,
    "new_repeat": "Repeat",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-04T04:40:26.724Z",
    "CreatedAt": "2017-07-03T04:21:35.647Z",
    "patient_bloodgroup": "B-",
    "patient_country": "India"
  }
]
</code>```

I want to group the above data based on CreatedAt column and filter data on the basis of new_repeat column in the data set. I have already written a function for this, which is using _.chain and grouping the data but I am not able to filter it. Check the function below:

```<code>const formatDataCount = (data, group_by) => {
  return  _.chain(data)
    .sortBy('CreatedAt')
    .groupBy(datum => moment(datum.CreatedAt).format(group_by) )
    .map((value, key) => {
      return {
        label: key,
        value:  _.size(value)
      }
    })
    .value();
};
</code>```

group_by is the date format and can be "DD-MM-YYYY" or "MMM"
So, above is the function.How do filter parameter and value to it.

Please suggest changes:

```<code>const formatDataCount = (data, group_by) => {
  return  _.chain(data)
    .sortBy('CreatedAt')
    .groupBy(datum => moment(datum.CreatedAt).format(group_by) )
    .filter(filter_by => filter_by.new_repeat == "New")
    .map((value, key) => {
      return {
        label: key,
        value:  _.size(value)
      }
    })
    .value();
};
</code>```

First one is working, 2nd one isn't.

答:
The filter line - .filter(filter_by => filter_by.new_repeat == "New") should be before the groupBy. I would also move it before the sortBy, because you don't need to sort data that you are removing.

```<code>const formatDataCount = (data, group_by) => {
  return  _.chain(data)
    .filter(filter_by => filter_by.new_repeat == "New")
    .sortBy('CreatedAt')
    .groupBy(datum => moment(datum.CreatedAt).format(group_by) )
    .map((value, key) => {
      return {
        label: key,
        value:  _.size(value)
      }
    })
    .value();
};
</code>```

Body:
Data Set:

[
  {
    "created_by": "5750790484393984",
    "patient_dateofbirth": "02/05/1990",
    "patient_aadhaar": "1234567890",
    "patient_area": "wert",
    "patient_state": "Arunachal Pradesh",
    "patient_gender": "Male",
    "patient_pincode": "123456",
    "location": "Guwahati",
    "patient_name": "Rakesh",
    "isVisited": 2,
    "new_repeat": "Repeat",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-04T04:41:59.261Z",
    "CreatedAt": "2017-07-03T18:48:25.773Z",
    "patient_bloodgroup": "B+",
    "patient_country": "India"
  },
  {
    "created_by": "5750790484393984",
    "patient_dateofbirth": "07/30/2006",
    "patient_aadhaar": "2343524361731",
    "patient_area": "begusarai",
    "patient_state": "Bihar",
    "patient_gender": "Male",
    "patient_pincode": "110016",
    "patient_name": "gyguy yuguy",
    "registration_number": "2",
    "ip_address": "43.225.248.20, 162.158.155.110",
    "CreatedAt": "2017-06-28T09:41:47.188Z",
    "patient_bloodgroup": "A+",
    "patient_country": "India"
  },
  {
    "ip_address": "103.83.148.161, 141.101.99.35",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-04T09:56:51.588Z",
    "CreatedAt": "2017-07-02T23:37:29.512Z",
    "patient_bloodgroup": "A+",
    "patient_country": "India",
    "created_by": "5750790484393984",
    "patient_dateofbirth": "06/24/1964",
    "patient_aadhaar": "",
    "patient_area": "Chattarpur",
    "patient_state": "Uttar Pradesh",
    "patient_gender": "Female",
    "patient_pincode": "201005",
    "patient_name": "Sudha Ambastha",
    "isVisited": 2,
    "new_repeat": "Repeat"
  },
  {
    "patient_area": "ajsdh",
    "patient_state": "Delhi",
    "patient_gender": "Male",
    "patient_pincode": "110074",
    "patient_name": "prashant",
    "registration_number": "283423472834",
    "isVisited": 1,
    "new_repeat": "New",
    "ip_address": "43.225.248.20, 162.158.155.110",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-03T18:41:55.777Z",
    "CreatedAt": "2017-06-28T11:18:55.792Z",
    "patient_bloodgroup": "B+",
    "patient_country": "India",
    "created_by": "5750790484393984",
    "patient_dateofbirth": "06/13/1990",
    "patient_aadhaar": "2131231238"
  },
  {
    "created_by": "5750790484393984",
    "patient_dateofbirth": "06/07/1990",
    "patient_aadhaar": "1278292020029",
    "patient_area": "Bhubneshwar",
    "patient_state": "Orissa",
    "patient_gender": "Male",
    "patient_pincode": "112218",
    "location": "Haldia",
    "patient_name": "Rajesh Mishra",
    "isVisited": 2,
    "new_repeat": "Repeat",
    "lastVisitDate": "2017-07-04",
    "updatedAt": "2017-07-04T04:40:26.724Z",
    "CreatedAt": "2017-07-03T04:21:35.647Z",
    "patient_bloodgroup": "B-",
    "patient_country": "India"
  }
]

I want to group the above data based on CreatedAt column and filter data on the basis of new_repeat column in the data set. I have already written a function for this, which is using _.chain and grouping the data but I am not able to filter it. Check the function below:

const formatDataCount = (data, group_by) => {
  return  _.chain(data)
    .sortBy('CreatedAt')
    .groupBy(datum => moment(datum.CreatedAt).format(group_by) )
    .map((value, key) => {
      return {
        label: key,
        value:  _.size(value)
      }
    })
    .value();
};

group_by is the date format and can be "DD-MM-YYYY" or "MMM"
So, above is the function.How do filter parameter and value to it.

Please suggest changes:

const formatDataCount = (data, group_by) => {
  return  _.chain(data)
    .sortBy('CreatedAt')
    .groupBy(datum => moment(datum.CreatedAt).format(group_by) )
    .filter(filter_by => filter_by.new_repeat == "New")
    .map((value, key) => {
      return {
        label: key,
        value:  _.size(value)
      }
    })
    .value();
};

First one is working, 2nd one isn't.

Body:
The filter line - .filter(filter_by => filter_by.new_repeat == "New") should be before the groupBy. I would also move it before the sortBy, because you don't need to sort data that you are removing.

const formatDataCount = (data, group_by) => {
  return  _.chain(data)
    .filter(filter_by => filter_by.new_repeat == "New")
    .sortBy('CreatedAt')
    .groupBy(datum => moment(datum.CreatedAt).format(group_by) )
    .map((value, key) => {
      return {
        label: key,
        value:  _.size(value)
      }
    })
    .value();
};


问:
Does each server (EC2 Node) behind a load balancer need their own SSL certificate?
I have 2 EC2 nodes behind a load balancer.
I need to setup SSL certificate for use with Amazon Web Services.
Does each server behind a load balancer need their own SSL certificate?
Or only the load balancer need the SSL certificate?</p>

答:
You can associate the SSL certificate with the load balancer, and then use either normal HTTP between the Load Balancer and the server, or another form of authentication that is less resource-intensive than SSL.

See:

HTTPS Listeners for Your Classic Load Balancer

HTTPS Listeners for Your Application Load Balancer


问:
Nodejs dynamically add HTML content when documents are inserted in collection
When a document is added to the MongoDB Collection, I want to add a new HTML element (div,p,img,etc..) to my homepage.html . The homepage.html has to be dynamically updated by the server, by 'Detecting' the changes in the MongoDB database Collection.  I'm using Express.js to respond to client requests.</p>

答:
Your task cannot be done by only using those technologies. You have to use some kind of socket programming framework like socket.io.

I recommend you to refer this real time chat app creating blog post to get some sort of idea of your case. here is the link

Thanks. Hope you will understand me.


问:
Create a bat file for git-bash script
Hi all. I gave a git-bash installed and want some automatisation. I've got a .bat file, which I want to run as

```<code>some.bat param | iconv -cp1251 > l.log | tail -f l.log
</code>```

And I want to run it not in WinCMD but in git-bash shell - tell me plz how to do it?

答:
Git bash on windows uses BASH. You can use bash to create a quick script that can take in parameters and echo them so that you can pipe them to your next utility.

It could look something like this

File: some.sh

```<code> #!/bin/bash

 #Lots of fun bash scripting here...

 echo $1
 # $1 here is the first parameter sent to this script.
 # $2 is the second... etc. $0 is the script name
</code>```

then by setting some.sh as executable

```<code>$ chmod +x some.sh
</code>```

You'll then be able to execute it in the git-bash shell

```<code>./some.sh param | cat ... etc | etc...
</code>```

You can read about bash programming

I'd reccomend looking at some bash scripting tutorials such as this one

Title: Create a bat file for git-bash script

Body:
Hi all. I gave a git-bash installed and want some automatisation. I've got a .bat file, which I want to run as

some.bat param | iconv -cp1251 > l.log | tail -f l.log

And I want to run it not in WinCMD but in git-bash shell - tell me plz how to do it?

Body:
Git bash on windows uses BASH. You can use bash to create a quick script that can take in parameters and echo them so that you can pipe them to your next utility.

It could look something like this

File: some.sh

 #!/bin/bash

 #Lots of fun bash scripting here...

 echo $1
 # $1 here is the first parameter sent to this script.
 # $2 is the second... etc. $0 is the script name

then by setting some.sh as executable

$ chmod +x some.sh

You'll then be able to execute it in the git-bash shell

./some.sh param | cat ... etc | etc...

You can read about bash programming

I'd reccomend looking at some bash scripting tutorials such as this one