问:
Does stringstream initializing with big length buffer doubles memory usage
Suppose I have a buffer with length 100MB char[100*1024*1024]. I would like to use stringstream facilities on this buffer like format read so I defined a new stringstream ss(arr) using this array. So I would like to learn if my program uses 200MB in total at runtime or not? I am working on big data and memory usage is critical. Actually I defined a char buffer and initialize my custom istream with this buffer and solved my memory issue. But I am still in confusion whether my second way is redundant or not.

答:
So I would like to learn if my program uses 200MB in total at runtime
  or not?

If you construct a stringstream from a char array it will at least double the memory usage. From the reference of std::basic_stringstream constructor:

Uses a copy of str as initial contents of the underlying string
  device.

You could write your own stream buffer to create a non-owning stringstream, but the boost::iostreams library already provides that via array devices.

```<code>namespace io = boost::iostreams;

char str[100*1024*1024];

// No copy of str is made here! The stream just stores pointer and size of array.
io::stream<io::array_source> strm( str, sizeof(str) );

// Do something with the stream as usual. It is fully compatible with standard streams.
int x;
strm >> x;
</code>```

There is a nice online compiler that shows peak memory usage.
In the following examples I'm creating a stream from a 10 MiB array.

Live example using std::stringstream. Peaks at 31(!) MiB.

Live example using boost::array_source. Peaks at only 11 MiB.

Why there is a peak memory usage of even 3x the char array size when using std::stringstream? Because we must create a temporary string from the char array first as std::stringstream doesn't have a constructor that takes a char pointer.

Body:
So I would like to learn if my program uses 200MB in total at runtime
  or not?

If you construct a stringstream from a char array it will at least double the memory usage. From the reference of std::basic_stringstream constructor:

Uses a copy of str as initial contents of the underlying string
  device.

You could write your own stream buffer to create a non-owning stringstream, but the boost::iostreams library already provides that via array devices.

namespace io = boost::iostreams;

char str[100*1024*1024];

// No copy of str is made here! The stream just stores pointer and size of array.
io::stream<io::array_source> strm( str, sizeof(str) );

// Do something with the stream as usual. It is fully compatible with standard streams.
int x;
strm >> x;

There is a nice online compiler that shows peak memory usage.
In the following examples I'm creating a stream from a 10 MiB array.

Live example using std::stringstream. Peaks at 31(!) MiB.

Live example using boost::array_source. Peaks at only 11 MiB.

Why there is a peak memory usage of even 3x the char array size when using std::stringstream? Because we must create a temporary string from the char array first as std::stringstream doesn't have a constructor that takes a char pointer.


来源: stackexchange

问:
Best Practice: 301 Redirect HTTP to HTTPS (Standard Domain)
I have been searching for the perfect 301 redirect. But I am finding so many solutions and do not know what’s best.

Here is what I want to do

http://domain.tld/ → https://domain.tld/

http://www.domain.tld/ → https://domain.tld/

https://www.domain.tld/ → https://domain.tld/

Best practice .htacess?

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
</IfModule>
</code>```

This is my preferred code. At least unil now.

Alternative ways

I also found a lot of other ways to redirect from HTTP to HTTPS. For example:

1.

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</code>```

Missing one step? And no [R=301,L] here?

2.

```<code>RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Is a different order generally better?

Should I use

```<code>RewriteRule ^(.*)$
</code>```

instead of

```<code>RewriteRule (.*)
</code>```

?

3.

```<code>RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]
</code>```

Does using the full domain name have any performance advantages? Do I really need NE? ([R=301,L,NE] vs. [L,R=301])

So, my question to all experts: What's the best (performing) way to redirect both from HTTP to HTTPS and from  to HTTPS:// ?

答:
So, condensing, this becomes;

```<code>RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]
</code>```

Let me know if you see any bugs

ContentLicense: CC BY-SA 3.0

Body:
I have been searching for the perfect 301 redirect. But I am finding so many solutions and do not know what’s best.

Here is what I want to do

http://domain.tld/ → https://domain.tld/

http://www.domain.tld/ → https://domain.tld/

https://www.domain.tld/ → https://domain.tld/

Best practice .htacess?

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
</IfModule>

This is my preferred code. At least unil now.

Alternative ways

I also found a lot of other ways to redirect from HTTP to HTTPS. For example:

1.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Missing one step? And no [R=301,L] here?

2.

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Is a different order generally better?

Should I use

RewriteRule ^(.*)$

instead of

RewriteRule (.*)

?

3.

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]

Does using the full domain name have any performance advantages? Do I really need NE? ([R=301,L,NE] vs. [L,R=301])

So, my question to all experts: What's the best (performing) way to redirect both from HTTP to HTTPS and from  to HTTPS:// ?

Body:
So, condensing, this becomes;

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]

Let me know if you see any bugs


问:
How to make check-outs be unreserved by default using ClearCase command line tools
Is there a way to make cleartool checkouts unreserved by default?  Perhaps a ~/.cleartool file or some environment variable?  I understand the default can be set on the VOB (or all VOBs), but that option is beyond my control.

The ClearCase version I'm using is:

```<code>$ ct -version ClearCase version 7.0.1 (Wed May 30 17:04:58 EDT 2007)
7.0.1.0-RATL-RCC-IFIX01 (Wed Sep 19 16:08:10 EDT 2007) @(#) MVFS version
7.0.1.0-IFIX01 (Thu Sep  6 20:09:08 2007) built at $Date: 2009-12-08.14:59:16 (UTC) $ cleartool
7.0.1.0-IFIX01 (Thu Aug  9 20:20:45 EDT 2007) db_server
7.0.1.0-IFIX01 (Fri Sep 14 20:23:09 EDT 2007) VOB database schema version:    54
</code>```

You may ask "why in world would the default ever be set to -reserved?"  A fair question.  However, the matter is beyond my control.

Update: I neglected to mention the environment is Linux.

答:
I know this is an old post, but in case anyone in the future comes along with the same question, here's my answer.

If you want to set up a trigger so that everyone performs UNRESERVED checkouts then use the following command:

```<code>cleartool mktrtype -element -all -post checkout -exec '/opt/rational/clearcase/bin/cleartool unreserve -nc '$CLEARCASE_PN' TRIGGERNAME
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to make cleartool checkouts unreserved by default?  Perhaps a ~/.cleartool file or some environment variable?  I understand the default can be set on the VOB (or all VOBs), but that option is beyond my control.

The ClearCase version I'm using is:

$ ct -version ClearCase version 7.0.1 (Wed May 30 17:04:58 EDT 2007)
7.0.1.0-RATL-RCC-IFIX01 (Wed Sep 19 16:08:10 EDT 2007) @(#) MVFS version
7.0.1.0-IFIX01 (Thu Sep  6 20:09:08 2007) built at $Date: 2009-12-08.14:59:16 (UTC) $ cleartool
7.0.1.0-IFIX01 (Thu Aug  9 20:20:45 EDT 2007) db_server
7.0.1.0-IFIX01 (Fri Sep 14 20:23:09 EDT 2007) VOB database schema version:    54

You may ask "why in world would the default ever be set to -reserved?"  A fair question.  However, the matter is beyond my control.

Update: I neglected to mention the environment is Linux.

Body:
I know this is an old post, but in case anyone in the future comes along with the same question, here's my answer.

If you want to set up a trigger so that everyone performs UNRESERVED checkouts then use the following command:

cleartool mktrtype -element -all -post checkout -exec '/opt/rational/clearcase/bin/cleartool unreserve -nc '$CLEARCASE_PN' TRIGGERNAME


问:
Neo4j Passing distinct nodes through WITH in Cypher
I have the following query, where there are 3 MATCHES, connected with WITH, searching through 3 paths.

```<code>MATCH (:File {name: 'A'})-[:FILE_OF]->(:Fun {name: 'B'})-->(ent:CFGEntry)-[:Flows*]->()-->(expr:CallExpr {name: 'C'})-->()-[:IS_PARENT]->(Callee {name: 'd'})
WITH expr, ent

MATCH (expr)-->(:Arg {chNum: '1'})-->(id:Id)
WITH id, ent

MATCH (entry)-[:Flows*]->(:IdDecl)-[:Def]->(sym:Sym)
WHERE id.name = sym.name
RETURN id.name
</code>```

The query returns two distinct id and one distinct entry, and 7 distinct sym.

The problem is that since in the second MATCH I pass "WITH id, entry", and two distinct id were found, two instances of entry is passed to the third match instead of 1, and the run time of the third match unnecessarily gets doubled at least.

I am wondering if anyone know how I should write this query to just make use of one single instance of entry.

答:
Your best bet will be to aggregate id, but then you'll need to adjust your logic in the third part of your query accordingly:</p>

```<code>MATCH (:File {name: 'A'})-[:FILE_OF]->(:Fun {name: 'B'})-->(ent:CFGEntry)-[:Flows*]->()-->(expr:CallExpr {name: 'C'})-->()-[:IS_PARENT]->(Callee {name: 'd'})
WITH expr, ent

MATCH (expr)-->(:Arg {chNum: '1'})-->(id:Id)
WITH collect(id.name) as names, ent

MATCH (entry)-[:Flows*]->(:IdDecl)-[:Def]->(sym:Sym)
WHERE sym.name in names
RETURN sym.name
</code>```

Body:
I have the following query, where there are 3 MATCHES, connected with WITH, searching through 3 paths.

MATCH (:File {name: 'A'})-[:FILE_OF]->(:Fun {name: 'B'})-->(ent:CFGEntry)-[:Flows*]->()-->(expr:CallExpr {name: 'C'})-->()-[:IS_PARENT]->(Callee {name: 'd'})
WITH expr, ent

MATCH (expr)-->(:Arg {chNum: '1'})-->(id:Id)
WITH id, ent

MATCH (entry)-[:Flows*]->(:IdDecl)-[:Def]->(sym:Sym)
WHERE id.name = sym.name
RETURN id.name

The query returns two distinct id and one distinct entry, and 7 distinct sym.

The problem is that since in the second MATCH I pass "WITH id, entry", and two distinct id were found, two instances of entry is passed to the third match instead of 1, and the run time of the third match unnecessarily gets doubled at least.

I am wondering if anyone know how I should write this query to just make use of one single instance of entry.

Body:
Your best bet will be to aggregate id, but then you'll need to adjust your logic in the third part of your query accordingly:

MATCH (:File {name: 'A'})-[:FILE_OF]->(:Fun {name: 'B'})-->(ent:CFGEntry)-[:Flows*]->()-->(expr:CallExpr {name: 'C'})-->()-[:IS_PARENT]->(Callee {name: 'd'})
WITH expr, ent

MATCH (expr)-->(:Arg {chNum: '1'})-->(id:Id)
WITH collect(id.name) as names, ent

MATCH (entry)-[:Flows*]->(:IdDecl)-[:Def]->(sym:Sym)
WHERE sym.name in names
RETURN sym.name


问:
find a substring and then replace it with something else probably with regex
I need some help on regex. I'm working on some twitter data and there are a lot of tweets that contain text like this: #something1@something2 . I'm trying to find a way to find substrings like that and replace it with #something1 @something2. I use python 3.
How can i do this? Thanks!</p>

答:
Use look-behind to check there is a non-space:

```<code>s = re.sub(r'(?<=\S)@', ' @', s)
</code>```

To only do this if there is a "connected" #:

```<code>s = re.sub(r'(#\S+)@', r'\1 @', s)
</code>```

Body:
Use look-behind to check there is a non-space:

s = re.sub(r'(?<=\S)@', ' @', s)

To only do this if there is a "connected" #:

s = re.sub(r'(#\S+)@', r'\1 @', s)


问:
ZSH loops only over first item of the array
```<code>#/bin/zsh
servers=('10.138.0.8' '10.138.0.91')

for srv in $servers; do
   echo "Checking health for " $srv
   echo "=========================================="
   echo mntr | nc $srv 2181
done
</code>```

when I execute, I don't get loop over 2nd value 10.138.0.91, as shown below

```<code>[devops@devops]~% ./healthcheck/zookeeper.sh
Checking health for  10.138.0.8
==========================================
zk_version      3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
zk_avg_latency  0
zk_max_latency  0
zk_min_latency  0
zk_packets_received     9
zk_packets_sent 8
zk_num_alive_connections        1
zk_outstanding_requests 0
zk_server_state follower
zk_znode_count  4
zk_watch_count  0
zk_ephemerals_count     0
zk_approximate_data_size        27
zk_open_file_descriptor_count   28
zk_max_file_descriptor_count    4096
</code>```

why?

答:
Because your script isn't being executed by zsh. Fix the shebang line: #!/bin/zsh

Why does your script get executed anyway, even without a shebang line? Because:

The kernel doesn't recognize an executable format, and gives up (the execve system call returns ENOEXEC).

The shell that tried to execute the file ./healthcheck/zookeeper.sh responds by opening the file and noticing that it looks like text that might be a script. Out of tradition, it calls /bin/sh to execute the script. For /bin/sh, the first line is just an ordinary comment.

Apparently /bin/sh is bash or ksh on your machine. The array assignment works with the same syntax as zsh, but the reference to the array doesn't — in ksh/bash syntax, you'd have to write "${servers[@]}" (modeled after "$@") to enumerate the elements of an array.

Body:
#/bin/zsh
servers=('10.138.0.8' '10.138.0.91')

for srv in $servers; do
   echo "Checking health for " $srv
   echo "=========================================="
   echo mntr | nc $srv 2181
done

when I execute, I don't get loop over 2nd value 10.138.0.91, as shown below

[devops@devops]~% ./healthcheck/zookeeper.sh
Checking health for  10.138.0.8
==========================================
zk_version      3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
zk_avg_latency  0
zk_max_latency  0
zk_min_latency  0
zk_packets_received     9
zk_packets_sent 8
zk_num_alive_connections        1
zk_outstanding_requests 0
zk_server_state follower
zk_znode_count  4
zk_watch_count  0
zk_ephemerals_count     0
zk_approximate_data_size        27
zk_open_file_descriptor_count   28
zk_max_file_descriptor_count    4096

why?


问:
What is the difference between libsqlite3.dylib and libsqlite3.0.dylib?
I'm getting started with SQLite databases in an app I'm working on.  I've not run into issues yet but one of the early steps from this tutorial is linking the SQLite3 framework.  The tutorial calls for libsqlite3.0.dylib but I noticed another one libsqlite3.dylib.  Is the latter just a symlink to the latest v3 library like the convention for package managers on UNIX or is there a difference?

Adam

答:
Is the latter just a symlink to the latest v3 library like the convention for package managers on UNIX?

That’s it exactly.


问:
recursively restructure object javascript
So this is my method for getting all posts related to their corresponding topics.

```<code>const moment = require('moment');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const Post = require('../models/Post');

let posts = {
    getPosts: function(req, res) {
        return Post.find({ topicId: req.params._id })
            .then(function(result) {

                console.log('------------------------------------');
                console.log('Headed to the Client: ', result);
                console.log('------------------------------------');

                res.json(result);

            })
            .catch(function(error) {
                console.log('Nope! Nerd!');
                return Promise.reject(error);
            })
    }
}
</code>```

the result comes out like so:

```<code>[ { _id: 58deac2223b5b92ce45bdfac,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: null,
    content: '1 Post',
    author: 'Bob',
    createdAt: 2017-03-31T19:21:06.698Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: true },

  { _id: 58deac2c23b5b92ce45bdfad,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: null,
    content: '2 Post',
    author: 'Bob',
    createdAt: 2017-03-31T19:21:16.622Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: true },

  { _id: 58deac3c23b5b92ce45bdfae,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: null,
    content: '3 Post',
    author: 'Bob',
    createdAt: 2017-03-31T19:21:32.682Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: true },

  { _id: 58deac5e23b5b92ce45bdfaf,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: '58deac3c23b5b92ce45bdfae',
    content: '1 Comment',
    author: 'Kat',
    createdAt: 2017-03-31T19:22:06.974Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: false },

  { _id: 58deac6c23b5b92ce45bdfb0,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: '58deac2223b5b92ce45bdfac',
    content: '2 Comment',
    author: 'Dave',
    createdAt: 2017-03-31T19:22:20.071Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: false },

 { _id: 58deac7a23b5b92ce45bdfb1,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: '58deac2c23b5b92ce45bdfad',
    content: '4 Comment',
    author: 'Bob',
    createdAt: 2017-03-31T19:22:34.865Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: false } ]
</code>```

I am getting stuck because I need to modify this list after it comes out of the database to grab the posts with parentIds and push them into their corresponding parents'comments array.

so the the result actually sent to the client looks like this:

```<code>                [{
                    _id: 58deac2223b5b92ce45bdfa',
                    topicId: '58dd6f541919c541dbf9632d',
                    parentId: null,
                    content: '1 Post',
                    author: 'Bob',
                    isAnon: false,
                    __v: 0,
                    comments: [{
                        _id: 58deac6c23b5b92ce45bdfb0,
                        topicId: '58dd6f541919c541dbf9632d',
                        parentId: '58deac2223b5b92ce45bdfac',
                        content: '2 Comment',
                        author: 'Dave',
                        isAnon: false,
                        __v: 0,
                        comments: [],
                        isArchieved: false,
                        isParent: false
                    }],
                    isArchieved: false,
                    isParent: true
                },

                {
                    _id: 58deac2c23b5b92ce45bdfad,
                    topicId: '58dd6f541919c541dbf9632d',
                    parentId: null,
                    content: '2 Post',
                    author: 'Bob',
                    isAnon: false,
                    __v: 0,
                    comments: [{
                        _id: 58deac7a23b5b92ce45bdfb1,
                        topicId: '58dd6f541919c541dbf9632d',
                        parentId: '58deac2c23b5b92ce45bdfad',
                        content: '4 Comment',
                        author: 'Bob',
                        isAnon: false,
                        __v: 0,
                        comments: [],
                        isArchieved: false,
                        isParent: false
                    }],
                    isArchieved: false,
                    isParent: true
                },

                {
                    _id: 58deac3c23b5b92ce45bdfae,
                    topicId: '58dd6f541919c541dbf9632d',
                    parentId: null,
                    content: '3 Post',
                    author: 'Bob',
                    isAnon: false,
                    __v: 0,
                    comments: [{
                        _id: 58deac5e23b5b92ce45bdfaf,
                        topicId: '58dd6f541919c541dbf9632d',
                        parentId: '58deac3c23b5b92ce45bdfae',
                        content: '1 Comment',
                        author: 'Kat',
                        isAnon: false,
                        __v: 0,
                        comments: [],
                        isArchieved: false,
                        isParent: false
                    }],
                    isArchieved: false,
                    isParent: true
                }
            ]
</code>```

I know I need to recurse through the array but I'm stumped on the logic in between. Any help would be appreciated. Thank you so much.

答:
You could use an object for collecting all nodes and append found children to the comments property. Get the nodes with parentId === null as root noded.

This approach works for unsorted data for any depth and use a single loop to get the nested result.

var data = [{ _id: '58deac2223b5b92ce45bdfac', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '1 Post', author: 'Bob', createdAt: '2017-03-31T19:21:06.698Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac2c23b5b92ce45bdfad', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '2 Post', author: 'Bob', createdAt: '2017-03-31T19:21:16.622Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac3c23b5b92ce45bdfae', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '3 Post', author: 'Bob', createdAt: '2017-03-31T19:21:32.682Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac5e23b5b92ce45bdfaf', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac3c23b5b92ce45bdfae', content: '1 Comment', author: 'Kat', createdAt: '2017-03-31T19:22:06.974Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }, { _id: '58deac6c23b5b92ce45bdfb0', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac2223b5b92ce45bdfac', content: '2 Comment', author: 'Dave', createdAt: '2017-03-31T19:22:20.071Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }, { _id: '58deac7a23b5b92ce45bdfb1', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac2c23b5b92ce45bdfad', content: '4 Comment', author: 'Bob', createdAt: '2017-03-31T19:22:34.865Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }],
    tree = function (data, root) {
        var r = [],
            o = {};

        data.forEach(function (a) {
            a.comments = (o[a._id] && o[a._id].comments || []).concat();
            o[a._id] = a;
            if (a.parentId === root) {
                r.push(a);
            } else {
                o[a.parentId] = o[a.parentId] || {};
                o[a.parentId].comments = o[a.parentId].comments || [];
                o[a.parentId].comments.push(a);
            }
        });
        return r;
    }(data, null);

console.log(tree);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
So this is my method for getting all posts related to their corresponding topics.

const moment = require('moment');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const Post = require('../models/Post');

let posts = {
    getPosts: function(req, res) {
        return Post.find({ topicId: req.params._id })
            .then(function(result) {

                console.log('------------------------------------');
                console.log('Headed to the Client: ', result);
                console.log('------------------------------------');

                res.json(result);

            })
            .catch(function(error) {
                console.log('Nope! Nerd!');
                return Promise.reject(error);
            })
    }
}

the result comes out like so:

[ { _id: 58deac2223b5b92ce45bdfac,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: null,
    content: '1 Post',
    author: 'Bob',
    createdAt: 2017-03-31T19:21:06.698Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: true },

  { _id: 58deac2c23b5b92ce45bdfad,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: null,
    content: '2 Post',
    author: 'Bob',
    createdAt: 2017-03-31T19:21:16.622Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: true },

  { _id: 58deac3c23b5b92ce45bdfae,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: null,
    content: '3 Post',
    author: 'Bob',
    createdAt: 2017-03-31T19:21:32.682Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: true },

  { _id: 58deac5e23b5b92ce45bdfaf,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: '58deac3c23b5b92ce45bdfae',
    content: '1 Comment',
    author: 'Kat',
    createdAt: 2017-03-31T19:22:06.974Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: false },

  { _id: 58deac6c23b5b92ce45bdfb0,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: '58deac2223b5b92ce45bdfac',
    content: '2 Comment',
    author: 'Dave',
    createdAt: 2017-03-31T19:22:20.071Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: false },

 { _id: 58deac7a23b5b92ce45bdfb1,
    topicId: '58dd6f541919c541dbf9632d',
    parentId: '58deac2c23b5b92ce45bdfad',
    content: '4 Comment',
    author: 'Bob',
    createdAt: 2017-03-31T19:22:34.865Z,
    isAnon: false,
    __v: 0,
    comments: [],
    isArchieved: false,
    isParent: false } ]

I am getting stuck because I need to modify this list after it comes out of the database to grab the posts with parentIds and push them into their corresponding parents'comments array.

so the the result actually sent to the client looks like this:

                [{
                    _id: 58deac2223b5b92ce45bdfa',
                    topicId: '58dd6f541919c541dbf9632d',
                    parentId: null,
                    content: '1 Post',
                    author: 'Bob',
                    isAnon: false,
                    __v: 0,
                    comments: [{
                        _id: 58deac6c23b5b92ce45bdfb0,
                        topicId: '58dd6f541919c541dbf9632d',
                        parentId: '58deac2223b5b92ce45bdfac',
                        content: '2 Comment',
                        author: 'Dave',
                        isAnon: false,
                        __v: 0,
                        comments: [],
                        isArchieved: false,
                        isParent: false
                    }],
                    isArchieved: false,
                    isParent: true
                },

                {
                    _id: 58deac2c23b5b92ce45bdfad,
                    topicId: '58dd6f541919c541dbf9632d',
                    parentId: null,
                    content: '2 Post',
                    author: 'Bob',
                    isAnon: false,
                    __v: 0,
                    comments: [{
                        _id: 58deac7a23b5b92ce45bdfb1,
                        topicId: '58dd6f541919c541dbf9632d',
                        parentId: '58deac2c23b5b92ce45bdfad',
                        content: '4 Comment',
                        author: 'Bob',
                        isAnon: false,
                        __v: 0,
                        comments: [],
                        isArchieved: false,
                        isParent: false
                    }],
                    isArchieved: false,
                    isParent: true
                },

                {
                    _id: 58deac3c23b5b92ce45bdfae,
                    topicId: '58dd6f541919c541dbf9632d',
                    parentId: null,
                    content: '3 Post',
                    author: 'Bob',
                    isAnon: false,
                    __v: 0,
                    comments: [{
                        _id: 58deac5e23b5b92ce45bdfaf,
                        topicId: '58dd6f541919c541dbf9632d',
                        parentId: '58deac3c23b5b92ce45bdfae',
                        content: '1 Comment',
                        author: 'Kat',
                        isAnon: false,
                        __v: 0,
                        comments: [],
                        isArchieved: false,
                        isParent: false
                    }],
                    isArchieved: false,
                    isParent: true
                }
            ]

I know I need to recurse through the array but I'm stumped on the logic in between. Any help would be appreciated. Thank you so much.

Body:
You could use an object for collecting all nodes and append found children to the comments property. Get the nodes with parentId === null as root noded.

This approach works for unsorted data for any depth and use a single loop to get the nested result.

var data = [{ _id: '58deac2223b5b92ce45bdfac', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '1 Post', author: 'Bob', createdAt: '2017-03-31T19:21:06.698Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac2c23b5b92ce45bdfad', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '2 Post', author: 'Bob', createdAt: '2017-03-31T19:21:16.622Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac3c23b5b92ce45bdfae', topicId: '58dd6f541919c541dbf9632d', parentId: null, content: '3 Post', author: 'Bob', createdAt: '2017-03-31T19:21:32.682Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: true }, { _id: '58deac5e23b5b92ce45bdfaf', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac3c23b5b92ce45bdfae', content: '1 Comment', author: 'Kat', createdAt: '2017-03-31T19:22:06.974Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }, { _id: '58deac6c23b5b92ce45bdfb0', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac2223b5b92ce45bdfac', content: '2 Comment', author: 'Dave', createdAt: '2017-03-31T19:22:20.071Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }, { _id: '58deac7a23b5b92ce45bdfb1', topicId: '58dd6f541919c541dbf9632d', parentId: '58deac2c23b5b92ce45bdfad', content: '4 Comment', author: 'Bob', createdAt: '2017-03-31T19:22:34.865Z', isAnon: false, __v: 0, comments: [], isArchieved: false, isParent: false }],
    tree = function (data, root) {
        var r = [],
            o = {};

        data.forEach(function (a) {
            a.comments = (o[a._id] && o[a._id].comments || []).concat();
            o[a._id] = a;
            if (a.parentId === root) {
                r.push(a);
            } else {
                o[a.parentId] = o[a.parentId] || {};
                o[a.parentId].comments = o[a.parentId].comments || [];
                o[a.parentId].comments.push(a);
            }
        });
        return r;
    }(data, null);

console.log(tree);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Adding a WHERE condition breaks SQL ORDER BY sorting
I have a table definition similar to the following

```<code>MY_TABLE
==========================
PERSON_ID VARCHAR2(9 BYTE)
ACTN_CD   VARCHAR2(8 BYTE)
LOG_DATE  CHAR(10 BYTE)
...
</code>```

Running the SQL:

```<code>SELECT *
FROM MY_TABLE
WHERE PERSON_ID = '281385010'
ORDER BY TO_DATE(LOG_DATE, 'MM/DD/YYYY') DESC, ACTN_CD;
</code>```

returns the results below.

```<code>PERSON_ID ACTN_CD  LOG_DATE
--------- -------- ----------
281385010 COR-ML   06/28/2016
281385010 COR-ML   06/09/2016
281385010 AUD-01   06/08/2016
281385010 COR-PH   05/26/2016
281385010 AUD-01   05/24/2016
281385010 AUD-01   05/16/2016
281385010 TERM     05/03/2016
</code>```

However, if I specify an ACTN_CD to match on in my statement:

```<code>SELECT *
FROM MY_TABLE
WHERE PERSON_ID = '281385010'
AND ACTN_CD = 'AUD-01'
ORDER BY TO_DATE(LOG_DATE, 'MM/DD/YYYY') DESC, ACTN_CD;
</code>```

My ORDER BY clause seems to get ignored and the results are;

```<code>PERSON_ID ACTN_CD  LOG_DATE
--------- -------- ----------
281385010 AUD-01   05/16/2016
281385010 AUD-01   05/24/2016
281385010 AUD-01   06/08/2016
</code>```

I am stumped as to why the addition of the ACTN_CD criteria would break my sort order.  Has anyone else seen behavior similar to this?

EDIT

To be precise, I am looking for the results to be sorted first by LOG_DATE DESCending then by ACTN_CD ASCending if there are multiple actions on a single date.  This works fine as long as ACTN_CD is not specified in the WHERE clause.  I can literally specify any other field in the table in the WHERE and it will not break this sorting.

ISSUE RESOLVED

I created another table with the same fields as the original and copied some of the data over.  Running the same SQL against this new table yielded the expected results so I started looking for differences.  It turns out that ACTN_CD was part of an index on the table.  Removing the index fixed the sorting issue.  I was unaware that sorting on an indexed field would cause problems, hopefully this will help someone else in the future.  Thanks all.

答: I created another table with the same fields as the original and copied some of the data over. Running the same SQL against this new table yielded the expected results so I started looking for differences. It turns out that ACTN_CD was part of an index on the table. Removing the index fixed the sorting issue. I was unaware that sorting on an indexed field would cause problems, hopefully this will help someone else in the future. Thanks all.</p>

Body:
I have a table definition similar to the following

MY_TABLE
==========================
PERSON_ID VARCHAR2(9 BYTE)
ACTN_CD   VARCHAR2(8 BYTE)
LOG_DATE  CHAR(10 BYTE)
...

Running the SQL:

SELECT *
FROM MY_TABLE
WHERE PERSON_ID = '281385010'
ORDER BY TO_DATE(LOG_DATE, 'MM/DD/YYYY') DESC, ACTN_CD;

returns the results below.

PERSON_ID ACTN_CD  LOG_DATE
--------- -------- ----------
281385010 COR-ML   06/28/2016
281385010 COR-ML   06/09/2016
281385010 AUD-01   06/08/2016
281385010 COR-PH   05/26/2016
281385010 AUD-01   05/24/2016
281385010 AUD-01   05/16/2016
281385010 TERM     05/03/2016

However, if I specify an ACTN_CD to match on in my statement:

SELECT *
FROM MY_TABLE
WHERE PERSON_ID = '281385010'
AND ACTN_CD = 'AUD-01'
ORDER BY TO_DATE(LOG_DATE, 'MM/DD/YYYY') DESC, ACTN_CD;

My ORDER BY clause seems to get ignored and the results are;

PERSON_ID ACTN_CD  LOG_DATE
--------- -------- ----------
281385010 AUD-01   05/16/2016
281385010 AUD-01   05/24/2016
281385010 AUD-01   06/08/2016

I am stumped as to why the addition of the ACTN_CD criteria would break my sort order.  Has anyone else seen behavior similar to this?

EDIT

To be precise, I am looking for the results to be sorted first by LOG_DATE DESCending then by ACTN_CD ASCending if there are multiple actions on a single date.  This works fine as long as ACTN_CD is not specified in the WHERE clause.  I can literally specify any other field in the table in the WHERE and it will not break this sorting.

ISSUE RESOLVED

I created another table with the same fields as the original and copied some of the data over.  Running the same SQL against this new table yielded the expected results so I started looking for differences.  It turns out that ACTN_CD was part of an index on the table.  Removing the index fixed the sorting issue.  I was unaware that sorting on an indexed field would cause problems, hopefully this will help someone else in the future.  Thanks all.


问:
Bootstrap centering a div
I am having trouble centering an animated text div. When I resize the window it is going towards the top instead of staying in the middle. Also I want it on 1/3 of the screen but I tried it with the grid but it doesn't do a lot.

```<code><!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Sam</title>

    <!-- Bootstrap Core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <style>
        #body1 {
            font: normal 40px/50px Arial, sans-serif;
            color: #999;
        }

        p {
            height: 50px;
            float: left;
            margin-right: 0.3em;
        }

        b {
            float: left;
            overflow: hidden;
            position: relative;
            height: 50px;
        }

        span1 {
            display: inline-block;
            color: #e74c3c;
            position: relative;
            white-space: nowrap;
            top: 0;
            left: 0;
            -webkit-animation: move 5s;
            -webkit-animation-iteration-count: infinite;
            -webkit-animation-delay: 1s;
        }

        @keyframes move {
            0% {
                top: 0px;
            }
            20% {
                top: -50px;
            }
            40% {
                top: -100px;
            }
            60% {
                top: -150px;
            }
            80% {
                top: -200px;
            }
        }

        #elem {
            background: url('./drawable/headerBg.jpg') center center no-repeat;
            background-size: 100px 150px;
        }

        a,
        a:focus,
        a:hover {
            color: #fff;
        }

        .btn-default,
        .btn-default:hover,
        .btn-default:focus {
            color: #333;
            text-shadow: none;
            /* Prevent inheritence from `body` */
            background-color: #fff;
            border: 1px solid #fff;
        }

        html,
        body {
            /*css for full size background image*/
            background: url(https://drscdn.500px.org/photo/191618715/q%3D80_m%3D2000/b08d920f4f2d248a837e236e1f5e55af) no-repeat center center fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;

            height: 100%;
            background-color: #060;
            color: #fff;
            text-align: center;
            text-shadow: 0 1px 3px rgba(0, 0, 0, .5);
        }
        /* Extra markup and styles for table-esque vertical and horizontal centering */

        .site-wrapper {
            display: table;
            width: 100%;
            height: 100%;
            /* For at least Firefox */
            min-height: 100%;
            -webkit-box-shadow: inset 0 0 100px rgba(0, 0, 0, .5);
            box-shadow: inset 0 0 100px rgba(0, 0, 0, .5);
        }

        .site-wrapper-inner {
            display: table-cell;
            vertical-align: top;
        }

        .cover-container {
            margin-right: auto;
            margin-left: auto;
        }
        /* Padding for spacing */

        .inner {
            padding: 30px;
        }
        /*
 * Header
 */

        .masthead-brand {
            margin-top: 10px;
            margin-bottom: 10px;
        }

        .masthead-nav>li {
            display: inline-block;
        }

        .masthead-nav>li+li {
            margin-left: 20px;
        }

        .masthead-nav>li>a {
            padding-right: 0;
            padding-left: 0;
            font-size: 16px;
            font-weight: bold;
            color: #fff;
            /* IE8 proofing */
            color: rgba(255, 255, 255, .95);
            border-bottom: 2px solid transparent;
        }

        .masthead-nav>li>a:hover,
        .masthead-nav>li>a:focus {
            background-color: transparent;
            border-bottom-color: #a9a9a9;
            border-bottom-color: rgba(255, 255, 255, .25);
        }

        .masthead-nav>.active>a,
        .masthead-nav>.active>a:hover,
        .masthead-nav>.active>a:focus {
            color: #fff;
            border-bottom-color: #fff;
        }

        @media (min-width: 768px) {
            .masthead-brand {
                float: left;
            }
            .masthead-nav {
                float: right;
            }
        }
        /*
 * Cover
 */

        .cover {
            padding: 0 20px;
        }

        .cover .btn-lg {
            padding: 10px 20px;
            font-weight: bold;
        }
        /*
 * Footer
 */

        .mastfoot {
            color: #999;
            /* IE8 proofing */
            color: rgba(255, 255, 255, .5);
        }
        /*
 * Affix and center
 */

        @media (min-width: 768px) {
            /* Pull out the header and footer */
            .masthead {
                position: fixed;
                top: 0;
            }
            .mastfoot {
                position: fixed;
                bottom: 0;
            }
            /* Start the vertical centering */
            .site-wrapper-inner {
                vertical-align: middle;
            }
            /* Handle the widths */
            .masthead,
            .mastfoot,
            .cover-container {
                width: 100%;
                /* Must be percentage or pixels for horizontal alignment */
            }
        }

        @media (min-width: 992px) {
            .masthead,
            .mastfoot,
            .cover-container {
                width: 700px;
            }
        }
    </style>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

    <!-- Navigation -->
    <div class="site-wrapper">
        <div class="site-wrapper-inner">
            <div class="cover-container">
                <div class="masthead clearfix">
                    <div class="inner">
                        <h3 class="masthead-brand">Cover</h3>

                        <ul class="nav masthead-nav">
                            <li class="active">
                                <a href="#" target="_blank">Home</a>
                            </li>

                            <li>
                                <a href="#">About</a>
                            </li>

                            <li>
                                <a href="#">Contact</a>
                            </li>
                        </ul>
                    </div>
                </div>

                <!-- Page Content -->
                <div class="container">

                    <div class="row">
                        <div class="col-lg-12 text-center">
                            <div id="body1">
                                <p>I'm a</p>
                                <b>
                              <span1>
                              web pls<br />
                              keyboard warrior<br />
                              student<br />
                              sdfsdf developer<br />
                              df
                              </span1>
                              </b>
                            </div>
                        </div>

                    </div>
                </div>
                <!-- /.row -->

            </div>

            <!-- Page Content -->

            <!-- /.row -->

            <!-- /.container -->

            <!-- jQuery Version 1.11.1 -->
            <script src="js/jquery.js"></script>

            <!-- Bootstrap Core JavaScript -->
            <script src="js/bootstrap.min.js"></script>

</body>

</html>
</code>```

答:
33.33334% Columns:

```<code><div class="col-lg-4 col-sm-12">
    col 1
</div>
<div class="col-lg-4 col-sm-12">
    col 2
</div>
<div class="col-lg-4 col-sm-12">
    col 3
</div>
</code>```

For centering the div try:

```<code>text-align:center;
</code>```

or

```<code>display:block;
margin: 0 auto;
</code>```

Title: Bootstrap centering a div

Body:
I am having trouble centering an animated text div. When I resize the window it is going towards the top instead of staying in the middle. Also I want it on 1/3 of the screen but I tried it with the grid but it doesn't do a lot.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Sam</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

Cover

                                Home

                                About

                                Contact

I'm a

                              <span1>
                              web pls

                              keyboard warrior

                              student

                              sdfsdf developer

                              df
                              </span1>

Body:
33.33334% Columns:

<div class="col-lg-4 col-sm-12">
    col 1
</div>
<div class="col-lg-4 col-sm-12">
    col 2
</div>
<div class="col-lg-4 col-sm-12">
    col 3
</div>

For centering the div try:

text-align:center;

or

display:block;
margin: 0 auto;


问:
If else condition in MSSQL
Suppose I have serial number, test name and few other columns, i want to write a condition if TESTNAME is null for a particular serial number then set the TESTNAME to blank else perform inner join

```<code>SELECT
    (A.PTNUMBER + '-' +A.SL_NO) AS ENUMBER,
    D.ENGINEER AS REQ, D.DATETIME as "DATE",
    (select Value
     from DROPDOWN
     where B.TEST_NAME=CONVERT(VARCHAR,DropdownID)) TESTNAME,
    TABLE_NAME AS TABLETD
FROM INSPECTION D
INNER JOIN TABLEA A ON D.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEB B ON B.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEC C ON C.ENGID = CONVERT(VARCHAR,A.EN_ID)
</code>```

答:
```<code>SELECT (A.PTNUMBER + '-' + A.SL_NO) AS ENUMBER,
       D.ENGINEER AS REQ,
       D.DATETIME as "DATE",
       case
        when SerialNo = xxx and TESTNAME is null then ''
        else (select Value from DROPDOWN where B.TEST_NAME = CONVERT(VARCHAR, DropdownID))
       end AS TESTNAME,
       TABLE_NAME AS TABLETD
  FROM INSPECTION D
  INNER JOIN TABLEA A ON D.ENGID = CONVERT(VARCHAR, A.EN_ID)
  INNER JOIN TABLEB B ON B.ENGID = CONVERT(VARCHAR, A.EN_ID)
  INNER JOIN TABLEC C ON C.ENGID = CONVERT(VARCHAR, A.EN_ID);
</code>```

Title: If else condition in MSSQL

Body:
Suppose I have serial number, test name and few other columns, i want to write a condition if TESTNAME is null for a particular serial number then set the TESTNAME to blank else perform inner join

SELECT
    (A.PTNUMBER + '-' +A.SL_NO) AS ENUMBER,
    D.ENGINEER AS REQ, D.DATETIME as "DATE",
    (select Value
     from DROPDOWN
     where B.TEST_NAME=CONVERT(VARCHAR,DropdownID)) TESTNAME,
    TABLE_NAME AS TABLETD
FROM INSPECTION D
INNER JOIN TABLEA A ON D.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEB B ON B.ENGID = CONVERT(VARCHAR,A.EN_ID)
INNER JOIN TABLEC C ON C.ENGID = CONVERT(VARCHAR,A.EN_ID)


问:
Lisp: How to obtain the final loop value?
```<code>(defun index-iteration (n)
  (let ((x 0))
    (loop for j from 0 to n while (< x n) do
      (setf x (max-index-for-iteration j)))))
</code>```

I have the following lisp code, at the end of the loop I want to return the value j. I have investigated:

collect but that returns a list of values with the value I want (the last j at the end)

finally but it didn't work.

return but it ends the loop early

答:
You need to combine finally and return like this:

```<code>(loop ...
  finally (return (1- j)))
</code>```

Please note the unfortunate use
of 1- which is due to the
fact that the finally clause is executed after the termination
clause (while in your case) transfers control there.
IOW, it requires the knowledge about how the termination clause is handled.

You can stay within the loop domain (without the extra let) like
this:

```<code>(loop for j from 0 to n
  for ret = j
  do ...
  finally (return ret))
</code>```

You could also use the maximize clause:

```<code>(loop for j from 0 to n ...
  maximize j)
</code>```

but this relies on the knowledge that the final value of j was the maximum one.

PS. Note also that you do not need the while clause in your loop.

Body:
(defun index-iteration (n)
  (let ((x 0))
    (loop for j from 0 to n while (< x n) do
      (setf x (max-index-for-iteration j)))))

I have the following lisp code, at the end of the loop I want to return the value j. I have investigated:

collect but that returns a list of values with the value I want (the last j at the end)

finally but it didn't work.

return but it ends the loop early

Body:
You need to combine finally and return like this:

(loop ...
  finally (return (1- j)))

Please note the unfortunate use
of 1- which is due to the
fact that the finally clause is executed after the termination
clause (while in your case) transfers control there.
IOW, it requires the knowledge about how the termination clause is handled.

You can stay within the loop domain (without the extra let) like
this:

(loop for j from 0 to n
  for ret = j
  do ...
  finally (return ret))

You could also use the maximize clause:

(loop for j from 0 to n ...
  maximize j)

but this relies on the knowledge that the final value of j was the maximum one.

PS. Note also that you do not need the while clause in your loop.


问:
Line label not displayed when using Region on kml file for GE
I have a kml file base on the on the tutorials presented by Google Earth developer website and by this link. My goal is to draw a line which is contained within a region (fades as I zoom out from it) and that is able to display the label name along the line trajectory.

Instead of the question mark I would like to have the name of such line.

So far I have implemented this lines of code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
   <name>KmlFile</name>
   <Placemark>
      <name>SFO to LAX</name>
      <Style id="line_label">
      <LabelStyle>
         <scale>10</scale>
      </LabelStyle>
      <LineStyle>
          <color>ff00ffff</color>
          <width>5</width>
          <gx:labelVisibility>1</gx:labelVisibility>
      </LineStyle>
      </Style>
      <LineString>
         <tessellate>1</tessellate>
         <coordinates>
         -118.40897,33.943492,0 -122.383103,37.617112,0
         </coordinates>
      </LineString>
      <Region>
      <LatLonAltBox>
         <north>37.617112</north>
         <south>33.943492</south>
         <east>-118.40897</east>
         <west>-122.383103</west>
         <minAltitude>0</minAltitude>
         <maxAltitude>200000</maxAltitude>
         <altitudeMode>clampToGround</altitudeMode>
         </LatLonAltBox>
      <Lod>
         <minLodPixels>1024</minLodPixels>
         <minFadeExtent>1024</minFadeExtent>
      </Lod>
   </Region>
</Placemark>
   <Placemark>
   <name>BOH to MAH</name>
   <Style id="line_label">
      <LabelStyle>
        <scale>1.3</scale>
      </LabelStyle>
      <LineStyle>
         <color>ff00ffff</color>
         <width>5</width>
         <gx:labelVisibility>1</gx:labelVisibility>
      </LineStyle>
   </Style>
   <LineString>
      <tessellate>1</tessellate>
      <coordinates>
      -117.40897,34.943492,0 -121.383103,38.617112,0
   </coordinates>
   </LineString>
  </Placemark>
</Document>
</kml>
</code>```

Can you please suggest me a way to achieve my goal?

答:
Apparently adding the Region to the Placemark doesn't correctly enable the labelVisibility mode in the line style when the feature becomes active. This is a bug in Google Earth. LabelVisibility works only if you don't use a Region.

You can get around this, by adding a Point within a MultiGeometry to the placemark to active with Region. Having a point enables the label to be displayed and the label is displayed at the location of the point.

```<code><Placemark>
      <name>SFO to LAX</name>
      <Style>
        <IconStyle>
            <Icon/>
        </IconStyle>
        <LabelStyle>
             <scale>1.3</scale>
        </LabelStyle>
        <LineStyle>
          <color>ff00ffff</color>
          <width>5</width>
          <gx:labelVisibility>1</gx:labelVisibility>
        </LineStyle>
      </Style>

      <Region>
       ...
      </Region>

   <MultiGeometry>
     <Point>
         <coordinates>-119.884604,35.349412</coordinates>
     </Point>
     <LineString>
         <tessellate>1</tessellate>
         <coordinates>
         -118.40897,33.943492 -122.383103,37.617112
         </coordinates>
        </LineString>
    </MultiGeometry>
</Placemark>
</code>```

Body:
I have a kml file base on the on the tutorials presented by Google Earth developer website and by this link. My goal is to draw a line which is contained within a region (fades as I zoom out from it) and that is able to display the label name along the line trajectory.

Instead of the question mark I would like to have the name of such line.

So far I have implemented this lines of code:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
   <name>KmlFile</name>
   <Placemark>
      <name>SFO to LAX</name>

      <LineString>
         <tessellate>1</tessellate>
         <coordinates>
         -118.40897,33.943492,0 -122.383103,37.617112,0
         </coordinates>
      </LineString>
      <Region>
      <LatLonAltBox>
         <north>37.617112</north>
         <south>33.943492</south>
         <east>-118.40897</east>
         <west>-122.383103</west>
         <minAltitude>0</minAltitude>
         <maxAltitude>200000</maxAltitude>
         <altitudeMode>clampToGround</altitudeMode>
         </LatLonAltBox>
      <Lod>
         <minLodPixels>1024</minLodPixels>
         <minFadeExtent>1024</minFadeExtent>
      </Lod>
   </Region>
</Placemark>
   <Placemark>
   <name>BOH to MAH</name>

   <LineString>
      <tessellate>1</tessellate>
      <coordinates>
      -117.40897,34.943492,0 -121.383103,38.617112,0
   </coordinates>
   </LineString>
  </Placemark>
</Document>
</kml>

Can you please suggest me a way to achieve my goal?

Body:
Apparently adding the Region to the Placemark doesn't correctly enable the labelVisibility mode in the line style when the feature becomes active. This is a bug in Google Earth. LabelVisibility works only if you don't use a Region.

You can get around this, by adding a Point within a MultiGeometry to the placemark to active with Region. Having a point enables the label to be displayed and the label is displayed at the location of the point.

<Placemark>
      <name>SFO to LAX</name>
      <Style>
        <IconStyle>
            <Icon/>
        </IconStyle>
        <LabelStyle>
             <scale>1.3</scale>
        </LabelStyle>
        <LineStyle>
          <color>ff00ffff</color>
          <width>5</width>
          <gx:labelVisibility>1</gx:labelVisibility>
        </LineStyle>
      </Style>

      <Region>
       ...
      </Region>

   <MultiGeometry>
     <Point>
         <coordinates>-119.884604,35.349412</coordinates>
     </Point>
     <LineString>
         <tessellate>1</tessellate>
         <coordinates>
         -118.40897,33.943492 -122.383103,37.617112
         </coordinates>
        </LineString>
    </MultiGeometry>
</Placemark>


问:
4x 25% boxes in one line
I started learning CSS3 and got a problem, i want to create 4 black boxes(divs), and put them on in one line, 3 of them work properly, but 4th is moving to new line, what am i doing wrong?

My guess would be that its because of the 10px margin, but i dont know how to do it properly.

* {
    margin: 0px;
    padding: 0px; }

body {
    font-family: Roboto, sans-serif;
    box-sizing: border-box; }

#wrapper {
    width: 1000px;
    margin-left: auto;
    margin-right: auto; }

#block1 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block2 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block3 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }

#block4 {
    width: 25%;
    height: 100px;
    background-color: black;
    float: left;
    margin-right: 10px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="wrapper">
        <div id="block1"></div>
        <div id="block2"></div>
        <div id="block3"></div>
        <div id="block4"></div>
    </div> </body></code>```

答:
You need to substract your margin-right value from your width, otherwise it adds up to more than 100% width.

Try

```<code>width: calc(25% - 10px);
height: 100px;
background-color: black;
float: left;
margin-right: 10px; }
</code>```

Title: 4x 25% boxes in one line

Body:
You need to substract your margin-right value from your width, otherwise it adds up to more than 100% width.

Try

width: calc(25% - 10px);
height: 100px;
background-color: black;
float: left;
margin-right: 10px; }


问:
Manipulating random number arrays
The question: Given integer values of x and y generate 20 random values within [x, y] interval and put them in an array. Print the array. Determine the index of the largest even negative number in it (ranging from 0 to 19). Account for the possibility that there might be no such number in the array. Calculate the sum of all positive odd numbers. You are only allowed to go through the
array values once. You should define separate functions for generating random numbers and checking even and odd numbers.

What I have written:

```<code>    #include <stdio.h>

int random(int min, int max, int arr[]){
    int i, j = 1;
    for(i = 0; i<20; i++){
        arr[i] = min + rand() % (max+1 - min);}
    for(i = 0; i<20; i++){
        printf("%d. %d\n", j, arr[i]);
        j++;}
    return arr[20];}

int evenodd(int arr[], int size){
    int i, holder, sum, index = 1;
    holder = arr[i];
    for(i = 0; i<20; i++){
        if (holder>0){
            if (holder%2 == 0){
                sum = sum;}
            else{
                sum += i;}}
        else{
            sum = sum;}}
    printf("\nThe sum of all odd positive numbers is %d.", sum);
    for(i = 1; i<20; i++){
        int top = arr[0];
        if (arr[i]<0){
            if(arr[i]<top){
                top = arr[i];
                index = i;}
            else{
                top = top;}}
        else{
            top = top;}}
    printf("\nThe index of the largest negative number is %d", index);}

int main()
{
    int min, max;
    printf("Please input the minimum desired random number: ");
    scanf("%d", &min);
    printf("\nPlease input the maximum desired random number: ");
    scanf("%d", &max);
    int a[20];
    random(min, max, a);
    evenodd(a, 20);
}
</code>```

It prints out fine, but the sum of positive odd number is wrong, as well as the index of the largest negative number.

答: In your loop for(i = 1; i<20; i++) when finding negative numbers, you begin the loop by resetting the value of top to be arr[0], and thus you will always be doing your comparisons against the first value of the array. Perhaps you want to move that initialization out of the loop.

Title: Manipulating random number arrays

Body:
The question: Given integer values of x and y generate 20 random values within [x, y] interval and put them in an array. Print the array. Determine the index of the largest even negative number in it (ranging from 0 to 19). Account for the possibility that there might be no such number in the array. Calculate the sum of all positive odd numbers. You are only allowed to go through the
array values once. You should define separate functions for generating random numbers and checking even and odd numbers.

What I have written:

    #include <stdio.h>

int random(int min, int max, int arr[]){
    int i, j = 1;
    for(i = 0; i<20; i++){
        arr[i] = min + rand() % (max+1 - min);}
    for(i = 0; i<20; i++){
        printf("%d. %d\n", j, arr[i]);
        j++;}
    return arr[20];}

int evenodd(int arr[], int size){
    int i, holder, sum, index = 1;
    holder = arr[i];
    for(i = 0; i<20; i++){
        if (holder>0){
            if (holder%2 == 0){
                sum = sum;}
            else{
                sum += i;}}
        else{
            sum = sum;}}
    printf("\nThe sum of all odd positive numbers is %d.", sum);
    for(i = 1; i<20; i++){
        int top = arr[0];
        if (arr[i]<0){
            if(arr[i]<top){
                top = arr[i];
                index = i;}
            else{
                top = top;}}
        else{
            top = top;}}
    printf("\nThe index of the largest negative number is %d", index);}

int main()
{
    int min, max;
    printf("Please input the minimum desired random number: ");
    scanf("%d", &min);
    printf("\nPlease input the maximum desired random number: ");
    scanf("%d", &max);
    int a[20];
    random(min, max, a);
    evenodd(a, 20);
}

It prints out fine, but the sum of positive odd number is wrong, as well as the index of the largest negative number.


问:
Java Sorting a List whilst ignoring a apostrophe
I have a list that I am sorting which is reading from a CSV file.

Now when i sort the code I get:

But if I sort the CSV file on Excel it's slightly different

So technically Excel is ignoring the case of Apostrophe but mine isn't. The criteria doesn't specify what to do in this case, but I would assume my code is incorrect then. How would i ignore the case of the Apostrophe and go onto the next character?

My code is:

```<code>public static Comparator<Hill> compareName = new Comparator<Hill>() {
    public int compare(Hill one, Hill other) {
        return one.name.compareTo(other.name);
    }
};

public static void exercise5d() {
    List<Hill> hills = readHills();
    for (int i = 0; i < 20; i++) {
        Collections.sort(hills, Hill.compareName);
        System.out.println(hills.get(i));
    }

}
</code>```

答:
I am assuming Hill.name is a String.

In your comparator you could compare Strings after replacing apostrophes like below :

```<code>public int compare(Hill one, Hill other) {

        return one.name.replaceAll("'", "").compareTo(other.name.replaceAll("'","");
    }
</code>```

But do you think you don't want to consider ' ?

Body:
I have a list that I am sorting which is reading from a CSV file.

Now when i sort the code I get:

But if I sort the CSV file on Excel it's slightly different

So technically Excel is ignoring the case of Apostrophe but mine isn't. The criteria doesn't specify what to do in this case, but I would assume my code is incorrect then. How would i ignore the case of the Apostrophe and go onto the next character?

My code is:

public static Comparator<Hill> compareName = new Comparator<Hill>() {
    public int compare(Hill one, Hill other) {
        return one.name.compareTo(other.name);
    }
};

public static void exercise5d() {
    List<Hill> hills = readHills();
    for (int i = 0; i < 20; i++) {
        Collections.sort(hills, Hill.compareName);
        System.out.println(hills.get(i));
    }

}

Body:
I am assuming Hill.name is a String.

In your comparator you could compare Strings after replacing apostrophes like below :

public int compare(Hill one, Hill other) {

        return one.name.replaceAll("'", "").compareTo(other.name.replaceAll("'","");
    }

But do you think you don't want to consider ' ?


问:
Incorrect VM arguments in Tibco6.x Designer
I created a tibco 6.3 BW application using tibco designer on Windows.Application is running fine but whenever I try to add Vm arguments (under Arguments tab) in Run Configurations Menu they gets modified after I close the menu. I was trying to add debug arguments

-agentlib:jdwp=transport=dt_socket,server=y,address=9090,suspend=n

for debugging the application but they always gets modified so that some '=' sign changes into space. So whenever I edit vm args and try to run the application I get invalid arguments error.
I think the problem is similar to this https://superuser.com/questions/392230/incorrect-vm-arguments-in-myeclipse-run-configuration

Any help would be appreciated.

答: Although I don't know why it was happening, but I found a workaround by supplying vm arguments directly to jre, by going to  preferences --> java --> Installed JREs --> Edit JRE --> Default Vm Arguments.</p>


问:
Require files from gem in Ruby script without bundle exec
I have a script that needs to require specific files out of gems defined in the project Gemfile.

```<code>#!/usr/bin/env ruby
require 'some_gem/helpers/some_helper'

... rest of script
</code>```

When I run the script, I get an error about not being able to load some_helper.rb.  If I run with bundle exec command... then everything works.

I understand that bundle exec exposes the Gems to the $LOAD_PATH which lets require work.  Is there a way to move that capability into the script so users don't have to type bundle exec?

Do I just need to add require "bundler/setup" to the script before I require the gem files?

答:
http://bundler.io/v1.12/#getting-started

:)

```<code>#!/usr/bin/env ruby
require 'rubygems' # because reasons.. most probably it is not needed unless you are using really old ruby where it is not loaded by default
                   # also at the moment rubygems and bundler are being merged :)
require 'bundler/setup' # for things installed with bundler
require 'some_gem/helpers/some_helper'
</code>```

You can also check e.g. http://mislav.net/2013/01/understanding-binstubs/

Body:
I have a script that needs to require specific files out of gems defined in the project Gemfile.

#!/usr/bin/env ruby
require 'some_gem/helpers/some_helper'

... rest of script

When I run the script, I get an error about not being able to load some_helper.rb.  If I run with bundle exec command... then everything works.

I understand that bundle exec exposes the Gems to the $LOAD_PATH which lets require work.  Is there a way to move that capability into the script so users don't have to type bundle exec?

Do I just need to add require "bundler/setup" to the script before I require the gem files?

Body:
http://bundler.io/v1.12/#getting-started

:)

#!/usr/bin/env ruby
require 'rubygems' # because reasons.. most probably it is not needed unless you are using really old ruby where it is not loaded by default
                   # also at the moment rubygems and bundler are being merged :)
require 'bundler/setup' # for things installed with bundler
require 'some_gem/helpers/some_helper'

You can also check e.g. http://mislav.net/2013/01/understanding-binstubs/


问:
Sort numbers then strings C#
I want to this list

```<code>A
B
C
111
11
123
1
42
5
</code>```

To be sorted

```<code>1
5
11
42
111
123
A
B
C
</code>```

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

答:
I haven't tested this code for performance, but you can solve this with a Comparer</p>

```<code>public class ArrayItemComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        int xInt = 0, yInt = 0;

        bool parseX = int.TryParse(x, out xInt);
        bool parseY = int.TryParse(y, out yInt);

        if (parseX && parseY)
        {
            return xInt.CompareTo(yInt);
        }
        else if (parseX)
        {
            return -1;
        }
        else if (parseY)
        {
            return 1;
        }
        else
        {
            return x.CompareTo(y);
        }
    }
}
</code>```

Title: Sort numbers then strings C#

Body:
I want to this list

A
B
C
111
11
123
1
42
5

To be sorted

1
5
11
42
111
123
A
B
C

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

Body:
I haven't tested this code for performance, but you can solve this with a Comparer

public class ArrayItemComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        int xInt = 0, yInt = 0;

        bool parseX = int.TryParse(x, out xInt);
        bool parseY = int.TryParse(y, out yInt);

        if (parseX && parseY)
        {
            return xInt.CompareTo(yInt);
        }
        else if (parseX)
        {
            return -1;
        }
        else if (parseY)
        {
            return 1;
        }
        else
        {
            return x.CompareTo(y);
        }
    }
}


问:
Having trouble with padding a CSS menu
I have been asked to "fix" a client's old website which was written in 2011, by a design team that was clearly struggling to understand the then-new HTML5+CSS.  There is a lot wrong with this code, and most of it I've been able to fix, stuff like using

```<code><p> </p>
</code>```

for line breaks.  I'm not even kidding.

Anyway, one of the things I have been asked to do is extend the website's text container and menu, and stretch out the menu's actual text to fit the new width, which has gone fine.  However, I'm having some trouble with padding out the menu text.  I did a search through the forums for some advice, and tried out the style code suggested, but it seems to move the menu text out of the area of menu.jpg where it needs to be.

CSS (this is the client's, so yell at them)

```<code>#header_menu_container
/* This is verbatim from the code I am working with.  I seriously have NO IDEA why this selector even exists. */
{

}

#header_menu
{
    margin: 0;
    display: inline-block;
    list-style: none;
    font-size: 15px;
}

/* header menu colour */
#header_menu li a {
color: #516a82;
}
/* menu hover colour */
#header_menu li a:hover{
color: #b55239;
text-decoration: none;
}

.no_submenu, .has_submenu
{
    display: block;
    float: left;
    position: relative;
}

.no_submenu a, .has_submenu span{
display: block;
font-size: 15px;
font-family: "Times New Roman", Times, serif;
color: #516a82;
text-decoration: none;
}

.no_submenu a:hover, .has_submenu span:hover{
color: #b55239;
}

.has_submenu span{
cursor: pointer;
_cursor: hand;
}

.is_submenu{
position: absolute;
left: -10px;
top: 32px;
background: #dfd7c5;
margin: 0;
padding: 0;
list-style: none;
z-index: 9999;
}

.is_submenu li a{
display: block;
text-align: left;
padding-left: 10px;
width: 122px;
padding-right: 10px;
font-size: 15px;
font-family: "Times New Roman", Times, serif;
color: #516a82;
text-decoration: none;
pading-top: 10px;
padding-bottom: 10px;
line-height: 18px;
}

.is_submenu li a:hover{
color: #b55239;
}
</code>```

HTML (based on client's, with a bit of my modification)

```<code><ul id="header_menu">
                    <li class="no_submenu" style="width: 63px;">
                        <b><a href="./index.html">Home</a></b>
                    </li>
                    <li class="has_submenu" id="who-we-are">
                        <b><span style="width: 103px;">Who We Are</span></b>
                        <ul class="is_submenu" style="display: none;">
                            <li>
                                <b><a href="./whoweare_janyce-lastman.html">Janyce Lastman</a></b>
                            </li>
                            <li>
                                <b><a href="./whoweare_ziny-kirshenbaum.html">Ziny Kirshenbaum</a></b>
                            </li>
                            <li>
                                <b><a href="./whoweare_tutors.html">Tutors</a></b>
                            </li>
                        </ul>
                    </li>

                    <li class="has_submenu" id="services"><span style="width: 73px;"><b>Services</b></span>
                        <ul class="is_submenu" style="display: none;">
                            <li>
                                <b><a href="./services_consultant-to-schools.html">Consultant To Schools</a></b>
                            </li>
                            <li>
                                <b><a href="./services_education-consulting-and-case-management.html">Education Consulting And Case Management</a></b>
                            </li>
                            <li>
                                <b><a href="./services_educational-assessments.html">Educational Assessments</a></b>
                            </li>
                            <li>
                                <b><a href="./services_school-placement-consultation.html">School Placement Consultation</a></b>
                            </li>
                            <li>
                                <b><a href="./services_seminars-and-workshops.html">Seminars And Workshops</a></b>
                            </li>
                            <li>
                                <b><a href="./services_test-tips-support.html">Test Tips Support</a></b>
                            </li>
                            <li>
                                <b><a href="./services_tutoring.html">Tutoring</a></b>
                            </li>
                        </ul>
                    </li>

                    <li class="has_submenu" id="media-and-press">
                        <span style="width: 113px;"><b>Media & Press</b></span>
                            <ul class="is_submenu" style="display: none;">
                                <li>
                                    <b><a href="./media-and-press_in-the-press.html">In the Press</a></b>
                                </li>
                                <li>
                                    <b><a href="./media-and-press_book-reviews.html">Book Reviews</a></b>
                                </li>
                                <li>
                                    <b><a href="./media-and-press_selected-articles.html">Selected Articles</a></b>
                                </li>
                                <li>
                                    <b><a href="./media-and-press_interesting-links.html">Interesting Links</a></b>
                                </li>
                            </ul>
                    </li>
                    <li class="no_submenu" style="width: 53px;">
                        <a href="./faq.html"><b>FAQ</b></a>
                    </li>

                    <li class="has_submenu" id="testimonials"><span style="width: 103px;"><b>Testimonials</b></span>
                        <ul class="is_submenu" style="display: none;">
                            <li>
                                <b><a href="./testimonials_ttg-tutors.html">Testimonials for TTG Tutors</a></b>
                            </li>
                            <li>
                                <b><a href="./testimonials_janyce-lastman.html">Testimonials for Janyce Lastman</a></b>
                            </li>
                        </ul>
                    </li>

                    <li class="has_submenu" id="contact-us">
                    <span style="width: 70px;"><b>Contact</b></span>
                        <ul class="is_submenu" style="display: none;">
                            <li>
                                <b><a href="./contactus_contact-info.html">Contact Info</a></b>
                            </li>
                            <li>
                                <b><a href="./contactus_employment-opportunities.html">Employment Opportunities</a></b>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
</code>```

There's a display call inside a class selector, which is likely part of the issue, but my gut feeling tells me that this needs someone with more expertise to dissect everything wrong with it.

It's one thing to figure out what's wrong with your own code, and another to try and analyze what's wrong with someone else's.  Any advice would be greatly appreciated :)

答:
So looking back over the code again, I think I've figured out the problem.

Instead of putting padding in the CSS, the original authors put a numerical width in a style tag in the HTML for every single menu, e.g.

```<code><span style="width: 73px;"><b>Services</b></span>
</code>```

Idiots.

I'm going to try and write something similar into the stylesheet properly.

Title: Having trouble with padding a CSS menu

Body:
I have been asked to "fix" a client's old website which was written in 2011, by a design team that was clearly struggling to understand the then-new HTML5+CSS.  There is a lot wrong with this code, and most of it I've been able to fix, stuff like using

for line breaks.  I'm not even kidding.

Anyway, one of the things I have been asked to do is extend the website's text container and menu, and stretch out the menu's actual text to fit the new width, which has gone fine.  However, I'm having some trouble with padding out the menu text.  I did a search through the forums for some advice, and tried out the style code suggested, but it seems to move the menu text out of the area of menu.jpg where it needs to be.

CSS (this is the client's, so yell at them)

#header_menu_container
/* This is verbatim from the code I am working with.  I seriously have NO IDEA why this selector even exists. */
{

}

#header_menu
{
    margin: 0;
    display: inline-block;
    list-style: none;
    font-size: 15px;
}

/* header menu colour */
#header_menu li a {
color: #516a82;
}
/* menu hover colour */
#header_menu li a:hover{
color: #b55239;
text-decoration: none;
}

.no_submenu, .has_submenu
{
    display: block;
    float: left;
    position: relative;
}

.no_submenu a, .has_submenu span{
display: block;
font-size: 15px;
font-family: "Times New Roman", Times, serif;
color: #516a82;
text-decoration: none;
}

.no_submenu a:hover, .has_submenu span:hover{
color: #b55239;
}

.has_submenu span{
cursor: pointer;
_cursor: hand;
}

.is_submenu{
position: absolute;
left: -10px;
top: 32px;
background: #dfd7c5;
margin: 0;
padding: 0;
list-style: none;
z-index: 9999;
}

.is_submenu li a{
display: block;
text-align: left;
padding-left: 10px;
width: 122px;
padding-right: 10px;
font-size: 15px;
font-family: "Times New Roman", Times, serif;
color: #516a82;
text-decoration: none;
pading-top: 10px;
padding-bottom: 10px;
line-height: 18px;
}

.is_submenu li a:hover{
color: #b55239;
}

HTML (based on client's, with a bit of my modification)

                        Home

                        Who We Are

                                Janyce Lastman

                                Ziny Kirshenbaum

                                Tutors

Services

                                Consultant To Schools

                                Education Consulting And Case Management

                                Educational Assessments

                                School Placement Consultation

                                Seminars And Workshops

                                Test Tips Support

                                Tutoring

                        Media & Press

                                    In the Press

                                    Book Reviews

                                    Selected Articles

                                    Interesting Links

                        FAQ

Testimonials

                                Testimonials for TTG Tutors

                                Testimonials for Janyce Lastman

                    Contact

                                Contact Info

                                Employment Opportunities

There's a display call inside a class selector, which is likely part of the issue, but my gut feeling tells me that this needs someone with more expertise to dissect everything wrong with it.

It's one thing to figure out what's wrong with your own code, and another to try and analyze what's wrong with someone else's.  Any advice would be greatly appreciated :)

Body:
So looking back over the code again, I think I've figured out the problem.

Instead of putting padding in the CSS, the original authors put a numerical width in a style tag in the HTML for every single menu, e.g.

<span style="width: 73px;"><b>Services</b></span>

Idiots.

I'm going to try and write something similar into the stylesheet properly.


问:
Scale custom UIView size w/o AutoLayout effects

Question

How can a UIView be created with a user-defined size and then scaled up/down to fit as a subview of a UIViewController?

Use-case

I am developing an application with a primary focus on showing a custom UIView on an external monitor attached to the iOS device. The custom view should be created to natively fit the external monitor. Let's say the external display has a resolution of 1920x1080. The UIView would be created to fit that size and then auto layout would do it's thing. - great!

Typically, the application user cannot actually see the external monitor, so another important part of the application is to provide a representation of the external monitor on the iOS device. Of course, these small window is not going to be the same resolution as the external display and simply creating another view and sticking it on the internal display is not going produce the same results because of AutoLayout.

Goal

I'd like to know how to create another custom view instance programmatically at the same dimensions as the external display (so the layout is identical) and then scale that view up/down to fill a subview on the internal display. Again, it is important that the preview window on the internal display is identical to what is being shown on the external display. I understand there may be some scaling artifacts - that is totally OK.

Application Example

The application in question can be viewed at liveevent.software. My question is in reference to the the external display and the preview of the external display as viewed on the iPad screen. Of course, we have this working already, but we are adding more features and need the local preview to be exactly the same as the external to the operator knows if a message is too long etc...

Important Notes

The UIView being scaled does not contain any gesture recognizers or other items requiring user interaction. Just a few UILabels.

The Issue

The current "working" solution is to create create two instances of the custom view and have them adapt according to auto-layout. While this produces a rough estimation of what is being displayed externally, it is not exact. For example, text may break a line on the iOS preview window but not on the actually external display (because it is larger dimensions).

答:
Depending on how "real time" you need this to be, maybe you could take snapshots of the external UIView? This would result in an UIImage, which you can assign to an UIImageView on the internal display. The image dimensions can be set to whatever you want, and the UIImageView would take care of the scaling.

There are many good answers on how to take a snapshot of a view, for example : this one.


问:
CSS Fold items up & down animation
I have a list of items:

Which, I would like to collapse with an animation effect, to just display one item:

As you can see, currently it collapses to one item, but the entire component does not collapse.

I am currently just setting the the items opacity to zero:

css

```<code>.slide-fade-hide {
  transition: all 1.2s ease-out;
  opacity: 0;
  //height: 2em;
}

.slide-fade-show {
  transition: all 1.2s ease-in;
  opacity: 1;
  //height: 2em;
}
</code>```

html

```<code><ion-list>
  <ion-row>
    <ion-col>
      <div id="search">
        <ion-searchbar class="ion-searchtext" id="ion-searchtext" [(ngModel)]="searchQueryText" (ionFocus)="focusSearch($event)" (change)="onChangeText($event)"
          (ionClear)="onCancelText($event)" (ionInput)="onInputText($event)" placeholder="{{jobType === 0 ? favourite ? 'Market Favourites' : 'Market' : favourite ? 'Postings Favourites' : 'Postings'}}"
          debounce="1"></ion-searchbar>
      </div>
      <!--<div id="pinButton"><button ion-button (click)="presentPopover()" color="primary"><ion-icon name="funnel"></ion-icon></button></div>-->
    </ion-col>
  </ion-row>

  <!--<div *ngIf="showExtraSearch === true">-->
  <div id="extra-filter-items" class="slide-fade-hide">
    <ion-row>
      <ion-col>
        <div id="location-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryLocation" (ionClear)="onCancelLocation($event)" (ionInput)="onInputLocation($event)"
            (click)="presentFilterMap()" placeholder="Location" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <div id="categories-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQuerySectors" (ionClear)="onCancelSectors($event)" (ionInput)="onInputSectors($event)"
            (click)="presentFilterCategories()" placeholder="Sectors" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <div id="rating-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryRating" (ionClear)="onCancelRating($event)" (ionInput)="onInputRating($event)"
            (click)="presentFilterRating()" placeholder="Star Rating" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <div id="time-filter">
          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryTime" (ionClear)="onCancelTime($event)" (ionInput)="onInputTime($event)"
            (click)="presentFilterTime()" placeholder="Last Online" debounce="1"></ion-searchbar>
        </div>
      </ion-col>
    </ion-row>
  </div>
</ion-list>
</code>```

javascript

```<code>  showExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-show";
    }
  }

  hideExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-hide";
    }
  }
</code>```

Problem

The items are still present, they just are transparent.

So if I click on them, they still respond.

Also, they are still taking up space, so that the rest of the dom is still beneath it.

Question

How do I allow the items to toggle from 1 item to 5 items with an animation effect as if they are sliding up & down? Also, so they also free up the space beneath them when they are up.

I did look at this example (see "Slide down & Fade"), but as you can see above, this does not achieve what I need.

Thanks

p.s. I am using Ionic2, so don't want to use any other Javascript frameworks like JQuery (just plain javascript and css).

答:
Hey so I see no one answered you yet still. Check out my codepen, relevant code highlights below. Also sorry that I had to use jQuery, I started writing it in javascript and it was so big, jQuery does it without having to manually loop through everything twice (I think i'm just a noob) Anyways hopefully this helps you.

CSS

```<code>.list-item {
    display: block;
    width: 200px;
    height: 50px;
    margin-bottom: 10px;
    line-height: 50px;
    text-align: center;
    background-color: #fff;
    transition: all 0.5s ease;
}

.list-item.hide {
    height: 0;
    margin: 0;
    opacity: 0;
}
</code>```

jQuery

```<code>var listItem = $('.list-item');

listItem.click(function() {
    if( listItem.hasClass('hide')) {
      listItem.removeClass('hide');
    } else {
      listItem.not(this).addClass('hide');
    }
});
</code>```

http://codepen.io/StefanBobrowski/pen/QpzYQj

Title: CSS Fold items up & down animation

Body:
I have a list of items:

Which, I would like to collapse with an animation effect, to just display one item:

As you can see, currently it collapses to one item, but the entire component does not collapse.

I am currently just setting the the items opacity to zero:

css

.slide-fade-hide {
  transition: all 1.2s ease-out;
  opacity: 0;
  //height: 2em;
}

.slide-fade-show {
  transition: all 1.2s ease-in;
  opacity: 1;
  //height: 2em;
}

html

<ion-list>
  <ion-row>
    <ion-col>

        <ion-searchbar class="ion-searchtext" id="ion-searchtext" [(ngModel)]="searchQueryText" (ionFocus)="focusSearch($event)" (change)="onChangeText($event)"
          (ionClear)="onCancelText($event)" (ionInput)="onInputText($event)" placeholder="{{jobType === 0 ? favourite ? 'Market Favourites' : 'Market' : favourite ? 'Postings Favourites' : 'Postings'}}"
          debounce="1"></ion-searchbar>

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

    <ion-row>
      <ion-col>

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryLocation" (ionClear)="onCancelLocation($event)" (ionInput)="onInputLocation($event)"
            (click)="presentFilterMap()" placeholder="Location" debounce="1"></ion-searchbar>

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

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQuerySectors" (ionClear)="onCancelSectors($event)" (ionInput)="onInputSectors($event)"
            (click)="presentFilterCategories()" placeholder="Sectors" debounce="1"></ion-searchbar>

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

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryRating" (ionClear)="onCancelRating($event)" (ionInput)="onInputRating($event)"
            (click)="presentFilterRating()" placeholder="Star Rating" debounce="1"></ion-searchbar>

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

          <ion-searchbar id="ion-locationbar" [(ngModel)]="searchQueryTime" (ionClear)="onCancelTime($event)" (ionInput)="onInputTime($event)"
            (click)="presentFilterTime()" placeholder="Last Online" debounce="1"></ion-searchbar>

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

</ion-list>

javascript

  showExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-show";
    }
  }

  hideExtraFilters(): void {
    let extraItemsElement = document.getElementById('extra-filter-items');
    if (extraItemsElement) {
      extraItemsElement.className = "slide-fade-hide";
    }
  }

Problem

The items are still present, they just are transparent.

So if I click on them, they still respond.

Also, they are still taking up space, so that the rest of the dom is still beneath it.

Question

How do I allow the items to toggle from 1 item to 5 items with an animation effect as if they are sliding up & down? Also, so they also free up the space beneath them when they are up.

I did look at this example (see "Slide down & Fade"), but as you can see above, this does not achieve what I need.

Thanks

p.s. I am using Ionic2, so don't want to use any other Javascript frameworks like JQuery (just plain javascript and css).

Body:
Hey so I see no one answered you yet still. Check out my codepen, relevant code highlights below. Also sorry that I had to use jQuery, I started writing it in javascript and it was so big, jQuery does it without having to manually loop through everything twice (I think i'm just a noob) Anyways hopefully this helps you.

CSS

.list-item {
    display: block;
    width: 200px;
    height: 50px;
    margin-bottom: 10px;
    line-height: 50px;
    text-align: center;
    background-color: #fff;
    transition: all 0.5s ease;
}

.list-item.hide {
    height: 0;
    margin: 0;
    opacity: 0;
}

jQuery

var listItem = $('.list-item');

listItem.click(function() {
    if( listItem.hasClass('hide')) {
      listItem.removeClass('hide');
    } else {
      listItem.not(this).addClass('hide');
    }
});

http://codepen.io/StefanBobrowski/pen/QpzYQj


问:
C# using minTime.ToUniversalTime is an hour out on a clients computer
I don't know a great deal about this subject so forgive my daft question, I have a datagrid that shows the date and time a change was made to the database, it works fine on my PC but on my clients the time is +1 hour. Is this because I have used .ToUniversalTime instead of .ToLocalTime? Thanks for any help.

Update: I've just run the program on my XP machine instead of my Vista machine and the time is +1 hour on XP, the timezone, daylight savings and zone are all the same. Is this a .Net thing?

Thanks

答:
```<code>.ToUniversalTime()
</code>```

gives you the current date time in Coordinated Universal Time (UTC).  In summary this is the current time (GMT) without any seasonal/regional changes.  Typically server applications use UTC for datetime storage as this gives a known baseline for users that may in different time zones.

As for a solution, well this depends on your application and how it is used.  You could store your dates as the current date from the users perspective and ignore UTC but you could run into problems if you have multiple users in different time zones.  Or you could store in UTC and then manage datetimes in the code per the current users locale.

For nothing more than curiosities sake, more info on UTC can be found here:

http://en.wikipedia.org/wiki/Coordinated_Universal_Time

Body:
.ToUniversalTime()

gives you the current date time in Coordinated Universal Time (UTC).  In summary this is the current time (GMT) without any seasonal/regional changes.  Typically server applications use UTC for datetime storage as this gives a known baseline for users that may in different time zones.

As for a solution, well this depends on your application and how it is used.  You could store your dates as the current date from the users perspective and ignore UTC but you could run into problems if you have multiple users in different time zones.  Or you could store in UTC and then manage datetimes in the code per the current users locale.

For nothing more than curiosities sake, more info on UTC can be found here:

http://en.wikipedia.org/wiki/Coordinated_Universal_Time


问:
Programmatically (VBA) close a window opened with RunCommand
Ok, first up is my question:
Of course you can open the Access "Unhide Columns" menu with:

```<code>    DoCmd.RunCommand acCmdUnhideColumns
</code>```

But is there code that could close that pop up menu?  Maybe on a timer, like how you can create a message box to auto close after a set time?

I know this sounds insane, so here's the background to explain why I'm heading down the wrong path.

On a split form I've created a button to load user profiles that show, hide, and rearrange the columns depending on the user's role.

That works fine, but as I learned here on StackExchange: "Design changes made while the form is open in Normal mode can't be saved", so the changes need to be done every time the user opens the form.

I've discovered that just opening and closing the "Unhide Columns" menu triggers access to ask the user if they want to save the layout when the form is closed.  Right now I just set the layout and then open the menu, forcing the user to close it manually, but it would be much smoother if they did not have to do that.  This is just the closest I've come to a workaround that fits our situation.  I know I could set the profile to run whenever the form is open, but some users further customize their layouts beyond the profile and that would interfere with them.  All of the other solutions I can think of are a lot heavier than this would be, assuming I can get it to work.  I'm open to other suggestions though.

Thanks

答:
Are users closing form with the X close? I disable that in design and make them always close forms with a custom button. Code:

DoCmd.Close acForm, Me.Name, acSaveNo

I also disable the app Exit and X Close. They close the db with button on main menu form that never closes. Also customize ribbon, hide navigation pane, and disable function keys and right click. And don't teach them about shift key bypass.

Body:
Ok, first up is my question:
Of course you can open the Access "Unhide Columns" menu with:

    DoCmd.RunCommand acCmdUnhideColumns

But is there code that could close that pop up menu?  Maybe on a timer, like how you can create a message box to auto close after a set time?

I know this sounds insane, so here's the background to explain why I'm heading down the wrong path.

On a split form I've created a button to load user profiles that show, hide, and rearrange the columns depending on the user's role.

That works fine, but as I learned here on StackExchange: "Design changes made while the form is open in Normal mode can't be saved", so the changes need to be done every time the user opens the form.

I've discovered that just opening and closing the "Unhide Columns" menu triggers access to ask the user if they want to save the layout when the form is closed.  Right now I just set the layout and then open the menu, forcing the user to close it manually, but it would be much smoother if they did not have to do that.  This is just the closest I've come to a workaround that fits our situation.  I know I could set the profile to run whenever the form is open, but some users further customize their layouts beyond the profile and that would interfere with them.  All of the other solutions I can think of are a lot heavier than this would be, assuming I can get it to work.  I'm open to other suggestions though.

Thanks