问:
Enzyme render styled component with theme
I am using react with styled-components, and jest enzyme for my tests. I'm having troubles testing a themed component that keeps erroring because of the theme from styled-components.

My component is:

```<code>const Wrapper = styled.header`
  position: fixed;
  top: 0;
  left: 0;

  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;

  width: 100%;
  height: 64px;

  background-color: ${({ theme }) => theme.colors.main.default};
  color: ${({ theme }) => theme.colors.main.text};
`
</code>```

My test is:

```<code>it('should render a <header> tag', () => {
  const renderedComponent = shallow(<Wrapper />)
  expect(renderedComponent.type()).toEqual('header')
})
</code>```

Jest gives me this error:

```<code><Wrapper /> › should render a <header> tag

    TypeError: Cannot read property 'main' of undefined

      at Object.<anonymous>._styledComponents2.default.header.theme (app/containers/AppBar/Wrapper.js:13:182)
</code>```

Basically, it throws an error because themeis undefined so it cannot read the colors property in it. How can I pass the theme to my component ?

答:
I solve this issue by creating a workaround helper function. i got themes object which contains dark and light theme:

```<code>    const CHANNEL = '__styled-components__';
    const broadcast = createBroadcast(themes.dark);

    const nodeWithThemeProp = node => {
      return React.cloneElement(node, { [CHANNEL]: broadcast.subscribe });
    };

    export function mountWithTheme(node, { context, childContextTypes } = {}) {
      return mount(
        nodeWithThemeProp(node),
        {
          context: Object.assign({}, context, {[CHANNEL]: broadcast.subscribe}),
          childContextTypes: Object.assign({}, {[CHANNEL]: createBroadcast(themes.dark).publish}, childContextTypes)
        }
      );
    }
</code>```

now i can get the wrapper component's state and theme is preseted:
        mountWithTheme(<Component {...props} />)

Body:
I am using react with styled-components, and jest enzyme for my tests. I'm having troubles testing a themed component that keeps erroring because of the theme from styled-components.

My component is:

const Wrapper = styled.header`
  position: fixed;
  top: 0;
  left: 0;

  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;

  width: 100%;
  height: 64px;

  background-color: ${({ theme }) => theme.colors.main.default};
  color: ${({ theme }) => theme.colors.main.text};
`

My test is:

it('should render a  tag', () => {
  const renderedComponent = shallow(<Wrapper />)
  expect(renderedComponent.type()).toEqual('header')
})

Jest gives me this error:

<Wrapper /> › should render a  tag

    TypeError: Cannot read property 'main' of undefined

      at Object.<anonymous>._styledComponents2.default.header.theme (app/containers/AppBar/Wrapper.js:13:182)

Basically, it throws an error because themeis undefined so it cannot read the colors property in it. How can I pass the theme to my component ?

Body:
I solve this issue by creating a workaround helper function. i got themes object which contains dark and light theme:

    const CHANNEL = '__styled-components__';
    const broadcast = createBroadcast(themes.dark);

    const nodeWithThemeProp = node => {
      return React.cloneElement(node, { [CHANNEL]: broadcast.subscribe });
    };

    export function mountWithTheme(node, { context, childContextTypes } = {}) {
      return mount(
        nodeWithThemeProp(node),
        {
          context: Object.assign({}, context, {[CHANNEL]: broadcast.subscribe}),
          childContextTypes: Object.assign({}, {[CHANNEL]: createBroadcast(themes.dark).publish}, childContextTypes)
        }
      );
    }

now i can get the wrapper component's state and theme is preseted:
        mountWithTheme(<Component {...props} />)


来源: stackexchange

问:
How to understand array sorting in Swift
Can someone please visualize the process of sorting?

```<code>let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }
</code>```

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

答:
Run it like this in a playground, and you will see how it works in more detail:

```<code>let numbers = [0,2,1]
let sortedNumbers = numbers.sorted {
    print("0: \($0), 1: \($1), returning \($0 > $1)")

    return $0 > $1
}
</code>```

$0 is simply the first argument, and $1 is the second.  The output with your numbers array is:

```<code>0: 2, 1: 0, returning true
0: 1, 1: 0, returning true
0: 1, 1: 2, returning false
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can someone please visualize the process of sorting?

let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

Body:
Run it like this in a playground, and you will see how it works in more detail:

let numbers = [0,2,1]
let sortedNumbers = numbers.sorted {
    print("0: \($0), 1: \($1), returning \($0 > $1)")

    return $0 > $1
}

$0 is simply the first argument, and $1 is the second.  The output with your numbers array is:

0: 2, 1: 0, returning true
0: 1, 1: 0, returning true
0: 1, 1: 2, returning false


问:
SAS Using Data Set to Create Other Data Sets
I am supposed to create a summary data set containing the mean, median, and standard deviation broken down by gender and group (using the CLASS statement). Using this summary data set, create four other data sets (in one DATA step) as follows:

(1) grand mean
(2) stats broken down by gender
(3) stats broken down by group
(4) stats broken down by gender and group

Given the hint to use the CHARTYPE option.

I provided my attempted solution, but I don't think I did it in the way asked.

```<code>DATA CLINICAL;
   *Use LENGTH statement to control the order of
    variables in the data set;
   LENGTH PATIENT VISIT DATE_VISIT 8;
   RETAIN DATE_VISIT WEIGHT;
   DO PATIENT = 1 TO 25;
      IF RANUNI(135) LT .5 THEN GENDER = 'Female';
      ELSE GENDER = 'Male';
      X = RANUNI(135);
      IF X LT .33 THEN GROUP = 'A';
      ELSE IF X LT .66 THEN GROUP = 'B';
      ELSE GROUP = 'C';
      DO VISIT = 1 TO INT(RANUNI(135)*5);
         IF VISIT = 1 THEN DO;
             DATE_VISIT = INT(RANUNI(135)*100) + 15800;
             WEIGHT = INT(RANNOR(135)*10 + 150);
         END;
         ELSE DO;
            DATE_VISIT = DATE_VISIT + VISIT*(10 + INT(RANUNI(135)*50));
            WEIGHT = WEIGHT + INT(RANNOR(135)*10);
         END;
         OUTPUT;
         IF RANUNI(135) LT .2 THEN LEAVE;
      END;
   END;
   DROP X;
   FORMAT DATE_VISIT DATE9.;
RUN;
PROC MEANS DATA=CLINICAL;
CLASS GENDER GROUP;
OUTPUT OUT=SUMMARY
       MEAN=
       MEDIAN=
       STDDEV= / AUTONAME;
RUN;
</code>```

答:
No, what they're asking you to do is:

Use the OUTPUT statement in PROC MEANS to create a summary dataset.  Choose the appropriate TYPES and CLASS values in PROC MEANS such that all four sets of data are represented on the output.

Using a single data step that has four dataset names on the data statement, selectively output those rows to the correct dataset.  You would use the _TYPE_ variable to determine which dataset a row  would be output to.

CHARTYPES just means your _TYPE_ variable will look like 1001 instead of 9 (the binary representation, basically).  1001 indicates which class variable is used (the first and the fourth) to create that breakout.  (With only two class variables, you would have values 00, 01, 10, 11 possible).  This is sometimes easier for non-programmers who aren't used to thinking in binary (these values would be 0, 1, 2, and 3 in decimal without CHARTYPES and thus might be more difficult for you to tell which corresponds to which variable).

Body:
I am supposed to create a summary data set containing the mean, median, and standard deviation broken down by gender and group (using the CLASS statement). Using this summary data set, create four other data sets (in one DATA step) as follows:

(1) grand mean
(2) stats broken down by gender
(3) stats broken down by group
(4) stats broken down by gender and group

Given the hint to use the CHARTYPE option.

I provided my attempted solution, but I don't think I did it in the way asked.

DATA CLINICAL;
   *Use LENGTH statement to control the order of
    variables in the data set;
   LENGTH PATIENT VISIT DATE_VISIT 8;
   RETAIN DATE_VISIT WEIGHT;
   DO PATIENT = 1 TO 25;
      IF RANUNI(135) LT .5 THEN GENDER = 'Female';
      ELSE GENDER = 'Male';
      X = RANUNI(135);
      IF X LT .33 THEN GROUP = 'A';
      ELSE IF X LT .66 THEN GROUP = 'B';
      ELSE GROUP = 'C';
      DO VISIT = 1 TO INT(RANUNI(135)*5);
         IF VISIT = 1 THEN DO;
             DATE_VISIT = INT(RANUNI(135)*100) + 15800;
             WEIGHT = INT(RANNOR(135)*10 + 150);
         END;
         ELSE DO;
            DATE_VISIT = DATE_VISIT + VISIT*(10 + INT(RANUNI(135)*50));
            WEIGHT = WEIGHT + INT(RANNOR(135)*10);
         END;
         OUTPUT;
         IF RANUNI(135) LT .2 THEN LEAVE;
      END;
   END;
   DROP X;
   FORMAT DATE_VISIT DATE9.;
RUN;
PROC MEANS DATA=CLINICAL;
CLASS GENDER GROUP;
OUTPUT OUT=SUMMARY
       MEAN=
       MEDIAN=
       STDDEV= / AUTONAME;
RUN;


问:
select part of a string after certain number of special character
I have a data.table with a column

```<code>V1
a_b_c_las_poi
a_b_c_kiosk_pran
a_b_c_qwer_ok
</code>```

I would like to add a new column to this data.table which does not include the last part of string after the "_".

UPDATE

So i would like the output to be

a_b_c_las
a_b_c_kiosk
a_b_c_qwer

答:
You can do this with sub and a regular expression.

```<code>sub("(.*)_.*", "\\1", V1)
[1] "a_b_c_las"   "a_b_c_kiosk" "a_b_c_qwer"
</code>```

Body:
I have a data.table with a column

V1
a_b_c_las_poi
a_b_c_kiosk_pran
a_b_c_qwer_ok

I would like to add a new column to this data.table which does not include the last part of string after the "_".

UPDATE

So i would like the output to be

a_b_c_las
a_b_c_kiosk
a_b_c_qwer

Body:
You can do this with sub and a regular expression.

sub("(.*)_.*", "\\1", V1)
[1] "a_b_c_las"   "a_b_c_kiosk" "a_b_c_qwer"


问:
Crawling a certain depth per site in Nutch
I'm trying to crawl a large number of sites using Nutch V1.12, while I have no problem crawling sites I can't controll the crawl as much as I would like. The problem mainly lies with that there doesn't seem to be possible to do a crawl where the depth is counted from each new host it reaches. As I understand it a round in the crawl-script is considered as depth of the crawl. But this means that sites that are found early in the crawl is crawled more than those sites found later.

Is there a way to achieve this functionallity of a crawl depth per site?

答:
The problem mainly lies with that there doesn't seem to be possible to do a crawl where the depth is counted from each new host it reaches.

Correct, the depth is counted from the seeds, regardless of where the URLs are in a particular site.

As I understand it a round in the crawl-script is considered as depth of the crawl.

No. The depth is generated by the scoring-depth plugin, regardless of the number of rounds. They are often the same, especially at the beginning of a crawl, but not necessarily.

But this means that sites that are found early in the crawl is crawled more than those sites found later.

Yes. The depth limitation is useful for cases where we want to the crawl to stay within the boundaries of the seeds. For crawls that go beyond the original domains, you'll get the limitations you highlighted.

It should be possible to modify the code so that the depth is reset when changing host or domain but this will cause all sorts of issues e.g. what if the target URL does not correspond to the root? e.g. you'd get domain.com/path with depth 0 but if the latter has a link to domain.com/, it would get a depth of 1, which is not intuitive.

I suppose the term depth is slightly ambiguous or misleading in Nutch. 'step' would be a more accurate one as it does not assume any place within a site's hierarchy.


问:
Why does supertest (testing express) return a status of 301 and not 200?
I have an express based restful app, which I decided to test using supertest.  This is my first testing with supertest and I am confused.  One of the routes is:

```<code>/api/version
</code>```

Which returns the version:

```<code>export function index(req: express.Request, res: express.Response) {
   log('index of version.controller');
   let ver = { version: version.getVersion() +  ' & textAngular: v' + textAngularVersion.getTextAngularVersion() };
   res.setHeader('Content-Type', 'application/json');
   return res.status(200).json(ver);
}
</code>```

Which works fine and when I look in Chrome at 'http://localhost:9000/api/version/' I see:

```<code>{"version":"v0.00.000-38-gf395113 & textAngular: v1.5.16"}
</code>```

which is what I expect. And the status is either 200 (or 304 if it has been cached by Chrome) as expected.

HOWEVER, When I test with mocha and supertest:

```<code>describe('GET /api/version', () => {
     it('should respond with version', (done: any) => {
       request(app.server)
        .get('/api/version')
        .expect('Content-Type', 'text/html; charset=UTF-8')
        .expect(200)
        .end((err: any, res: any) => {
           if (err) {
             return done(err);
          }
          done();
        });
     });
});
</code>```

I see:

```<code>Error: expected 200 "OK", got 301 "Moved Permanently"
</code>```

Unless I comment out the expect(200) line.  Also I was surprised that I didn't see a 'Content-Type' of 'application/json'. Which is what I set above.

I would love to understand why this is happening?

The application is a bit large, and I can report more details, but I suspect that someone understands why a status of 304 shows up.

If I comment out the expect(200) line and capture the response I see:

```<code>2017-02-26T14:51:08-0700 <log> app.js:124 (Server.<anonymous>) Express server listening on 9000, in test mode
  GET /api/version
  ::ffff:127.0.0.1 - GET /api/version HTTP/1.1 301 57 - 6.867 ms
  Response {
    domain: null,
      _events: {},
    _eventsCount: 0,
      _maxListeners: undefined,
      res:
    IncomingMessage {
      _readableState:
        ReadableState {
        objectMode: false,
          highWaterMark: 16384,
          buffer: [Object],
          length: 0,
          pipes: null,
          pipesCount: 0,
          flowing: true,
          ended: true,
          endEmitted: true,
          reading: false,
          sync: true,
          needReadable: false,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          defaultEncoding: 'utf8',
          ranOut: false,
          awaitDrain: 0,
          readingMore: false,
          decoder: [Object],
          encoding: 'utf8' },
      readable: false,
        domain: null,
        _events:
      { end: [Object],
        data: [Object],
        error: [Object],
        close: [Function: bound emit] },
      _eventsCount: 4,
        _maxListeners: undefined,
        socket:
      Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Object],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      connection:
        Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Object],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers:
      { 'x-powered-by': 'Express',
        'content-type': 'text/html; charset=UTF-8',
        'content-length': '57',
        'x-content-type-options': 'nosniff',
        location: '/api/version/',
        date: 'Sun, 26 Feb 2017 21:51:08 GMT',
        connection: 'close' },
      rawHeaders:
        [ 'X-Powered-By',
          'Express',
          'Content-Type',
          'text/html; charset=UTF-8',
          'Content-Length',
          '57',
          'X-Content-Type-Options',
          'nosniff',
          'Location',
          '/api/version/',
          'Date',
          'Sun, 26 Feb 2017 21:51:08 GMT',
          'Connection',
          'close' ],
          trailers: {},
      rawTrailers: [],
        upgrade: false,
        url: '',
        method: null,
        statusCode: 301,
        statusMessage: 'Moved Permanently',
        client:
      Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Object],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      _consuming: true,
        _dumped: false,
        req:
      ClientRequest {
        domain: null,
          _events: [Object],
          _eventsCount: 3,
          _maxListeners: undefined,
          output: [],
          outputEncodings: [],
          outputCallbacks: [],
          outputSize: 0,
          writable: true,
          _last: true,
          upgrading: false,
          chunkedEncoding: false,
          shouldKeepAlive: false,
          useChunkedEncodingByDefault: false,
          sendDate: false,
          _removedHeader: {},
        _contentLength: 0,
          _hasBody: true,
          _trailer: '',
          finished: true,
          _headerSent: true,
          socket: [Object],
          connection: [Object],
          _header: 'GET /api/version HTTP/1.1\r\nHost: 127.0.0.1:9000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/3.5.0\r\nConnection: close\r\n\r\n',
          _headers: [Object],
          _headerNames: [Object],
          _onPendingData: null,
          agent: [Object],
          socketPath: undefined,
          timeout: undefined,
          method: 'GET',
          path: '/api/version',
          _ended: true,
          res: [Circular],
          aborted: undefined,
          timeoutCb: null,
          upgradeOrConnect: false,
          parser: null,
          maxHeadersCount: null },
      text: 'Redirecting to <a href="/api/version/">/api/version/</a>\n',
        read: [Function] },
    request:
      Test {
      domain: null,
        _events: {},
      _eventsCount: 0,
        _maxListeners: undefined,
        _agent: false,
        _formData: null,
        method: 'GET',
        url: 'http://127.0.0.1:9000/api/version',
        _header: { 'user-agent': 'node-superagent/3.5.0' },
      header: { 'User-Agent': 'node-superagent/3.5.0' },
      writable: true,
        _redirects: 1,
        _maxRedirects: 0,
        cookies: '',
        qs: {},
      qsRaw: [],
        _redirectList: [],
        _streamRequest: false,
        _buffer: true,
        app:
      Server {
        domain: null,
          _events: [Object],
          _eventsCount: 4,
          _maxListeners: undefined,
          _connections: 0,
          _handle: [Object],
          _usingSlaves: false,
          _slaves: [],
          _unref: false,
          allowHalfOpen: true,
          pauseOnConnect: false,
          httpAllowHalfOpen: false,
          timeout: 120000,
          _pendingResponseData: 0,
          maxHeadersCount: null,
          _connectionKey: '6::::9000' },
      _asserts: [ [Function: bound ] ],
      req:
        ClientRequest {
        domain: null,
          _events: [Object],
          _eventsCount: 3,
          _maxListeners: undefined,
          output: [],
          outputEncodings: [],
          outputCallbacks: [],
          outputSize: 0,
          writable: true,
          _last: true,
          upgrading: false,
          chunkedEncoding: false,
          shouldKeepAlive: false,
          useChunkedEncodingByDefault: false,
          sendDate: false,
          _removedHeader: {},
        _contentLength: 0,
          _hasBody: true,
          _trailer: '',
          finished: true,
          _headerSent: true,
          socket: [Object],
          connection: [Object],
          _header: 'GET /api/version HTTP/1.1\r\nHost: 127.0.0.1:9000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/3.5.0\r\nConnection: close\r\n\r\n',
          _headers: [Object],
          _headerNames: [Object],
          _onPendingData: null,
          agent: [Object],
          socketPath: undefined,
          timeout: undefined,
          method: 'GET',
          path: '/api/version',
          _ended: true,
          res: [Object],
          aborted: undefined,
          timeoutCb: null,
          upgradeOrConnect: false,
          parser: null,
          maxHeadersCount: null },
      protocol: 'http:',
        host: '127.0.0.1:9000',
        _endCalled: true,
        _callback: [Function],
        res:
      IncomingMessage {
        _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 4,
          _maxListeners: undefined,
          socket: [Object],
          connection: [Object],
          httpVersionMajor: 1,
          httpVersionMinor: 1,
          httpVersion: '1.1',
          complete: true,
          headers: [Object],
          rawHeaders: [Object],
          trailers: {},
        rawTrailers: [],
          upgrade: false,
          url: '',
          method: null,
          statusCode: 301,
          statusMessage: 'Moved Permanently',
          client: [Object],
          _consuming: true,
          _dumped: false,
          req: [Object],
          text: 'Redirecting to <a href="/api/version/">/api/version/</a>\n',
          read: [Function] },
      response: [Circular],
        called: true },
    req:
      ClientRequest {
      domain: null,
        _events:
      { drain: [Object],
        error: [Object],
        prefinish: [Function: requestOnPrefinish] },
      _eventsCount: 3,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
      _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket:
      Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Circular],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      connection:
        Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Circular],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      _header: 'GET /api/version HTTP/1.1\r\nHost: 127.0.0.1:9000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/3.5.0\r\nConnection: close\r\n\r\n',
        _headers:
      { host: '127.0.0.1:9000',
        'accept-encoding': 'gzip, deflate',
        'user-agent': 'node-superagent/3.5.0' },
      _headerNames:
      { host: 'Host',
        'accept-encoding': 'Accept-Encoding',
        'user-agent': 'User-Agent' },
      _onPendingData: null,
        agent:
      Agent {
        domain: null,
          _events: [Object],
          _eventsCount: 1,
          _maxListeners: undefined,
          defaultPort: 80,
          protocol: 'http:',
          options: [Object],
          requests: {},
        sockets: [Object],
          freeSockets: {},
        keepAliveMsecs: 1000,
          keepAlive: false,
          maxSockets: Infinity,
          maxFreeSockets: 256 },
      socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/api/version',
        _ended: true,
        res:
      IncomingMessage {
        _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 4,
          _maxListeners: undefined,
          socket: [Object],
          connection: [Object],
          httpVersionMajor: 1,
          httpVersionMinor: 1,
          httpVersion: '1.1',
          complete: true,
          headers: [Object],
          rawHeaders: [Object],
          trailers: {},
        rawTrailers: [],
          upgrade: false,
          url: '',
          method: null,
          statusCode: 301,
          statusMessage: 'Moved Permanently',
          client: [Object],
          _consuming: true,
          _dumped: false,
          req: [Circular],
          text: 'Redirecting to <a href="/api/version/">/api/version/</a>\n',
          read: [Function] },
      aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null },
    text: 'Redirecting to <a href="/api/version/">/api/version/</a>\n',
      body: {},
    files: undefined,
      buffered: true,
      headers:
    { 'x-powered-by': 'Express',
      'content-type': 'text/html; charset=UTF-8',
      'content-length': '57',
      'x-content-type-options': 'nosniff',
      location: '/api/version/',
      date: 'Sun, 26 Feb 2017 21:51:08 GMT',
      connection: 'close' },
    header:
    { 'x-powered-by': 'Express',
      'content-type': 'text/html; charset=UTF-8',
      'content-length': '57',
      'x-content-type-options': 'nosniff',
      location: '/api/version/',
      date: 'Sun, 26 Feb 2017 21:51:08 GMT',
      connection: 'close' },
    statusCode: 301,
      status: 301,
      statusType: 3,
      info: false,
      ok: false,
      redirect: true,
      clientError: false,
      serverError: false,
      error: false,
      accepted: false,
      noContent: false,
      badRequest: false,
      unauthorized: false,
      notAcceptable: false,
      forbidden: false,
      notFound: false,
      type: 'text/html',
      charset: 'UTF-8',
      links: {},
    setEncoding: [Function: bound ],
    redirects: [] }
  ✓ should respond with version (107ms)
</code>```

Where I notice: text: 'Redirecting to /api/version/\n' which gives a clue.
You help is greatly appreciated.

答:
I had the same issue. If it is the same issue for you, you just need to change

```<code>.get('/api/version')
</code>```

to

```<code>.get('/api/version/')
</code>```

That trailing forward slash makes a world of difference for the test.

Body:
I have an express based restful app, which I decided to test using supertest.  This is my first testing with supertest and I am confused.  One of the routes is:

/api/version

Which returns the version:

export function index(req: express.Request, res: express.Response) {
   log('index of version.controller');
   let ver = { version: version.getVersion() +  ' & textAngular: v' + textAngularVersion.getTextAngularVersion() };
   res.setHeader('Content-Type', 'application/json');
   return res.status(200).json(ver);
}

Which works fine and when I look in Chrome at 'http://localhost:9000/api/version/' I see:

{"version":"v0.00.000-38-gf395113 & textAngular: v1.5.16"}

which is what I expect. And the status is either 200 (or 304 if it has been cached by Chrome) as expected.

HOWEVER, When I test with mocha and supertest:

describe('GET /api/version', () => {
     it('should respond with version', (done: any) => {
       request(app.server)
        .get('/api/version')
        .expect('Content-Type', 'text/html; charset=UTF-8')
        .expect(200)
        .end((err: any, res: any) => {
           if (err) {
             return done(err);
          }
          done();
        });
     });
});

I see:

Error: expected 200 "OK", got 301 "Moved Permanently"

Unless I comment out the expect(200) line.  Also I was surprised that I didn't see a 'Content-Type' of 'application/json'. Which is what I set above.

I would love to understand why this is happening?

The application is a bit large, and I can report more details, but I suspect that someone understands why a status of 304 shows up.

If I comment out the expect(200) line and capture the response I see:

2017-02-26T14:51:08-0700 <log> app.js:124 (Server.<anonymous>) Express server listening on 9000, in test mode
  GET /api/version
  ::ffff:127.0.0.1 - GET /api/version HTTP/1.1 301 57 - 6.867 ms
  Response {
    domain: null,
      _events: {},
    _eventsCount: 0,
      _maxListeners: undefined,
      res:
    IncomingMessage {
      _readableState:
        ReadableState {
        objectMode: false,
          highWaterMark: 16384,
          buffer: [Object],
          length: 0,
          pipes: null,
          pipesCount: 0,
          flowing: true,
          ended: true,
          endEmitted: true,
          reading: false,
          sync: true,
          needReadable: false,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          defaultEncoding: 'utf8',
          ranOut: false,
          awaitDrain: 0,
          readingMore: false,
          decoder: [Object],
          encoding: 'utf8' },
      readable: false,
        domain: null,
        _events:
      { end: [Object],
        data: [Object],
        error: [Object],
        close: [Function: bound emit] },
      _eventsCount: 4,
        _maxListeners: undefined,
        socket:
      Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Object],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      connection:
        Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Object],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers:
      { 'x-powered-by': 'Express',
        'content-type': 'text/html; charset=UTF-8',
        'content-length': '57',
        'x-content-type-options': 'nosniff',
        location: '/api/version/',
        date: 'Sun, 26 Feb 2017 21:51:08 GMT',
        connection: 'close' },
      rawHeaders:
        [ 'X-Powered-By',
          'Express',
          'Content-Type',
          'text/html; charset=UTF-8',
          'Content-Length',
          '57',
          'X-Content-Type-Options',
          'nosniff',
          'Location',
          '/api/version/',
          'Date',
          'Sun, 26 Feb 2017 21:51:08 GMT',
          'Connection',
          'close' ],
          trailers: {},
      rawTrailers: [],
        upgrade: false,
        url: '',
        method: null,
        statusCode: 301,
        statusMessage: 'Moved Permanently',
        client:
      Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Object],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      _consuming: true,
        _dumped: false,
        req:
      ClientRequest {
        domain: null,
          _events: [Object],
          _eventsCount: 3,
          _maxListeners: undefined,
          output: [],
          outputEncodings: [],
          outputCallbacks: [],
          outputSize: 0,
          writable: true,
          _last: true,
          upgrading: false,
          chunkedEncoding: false,
          shouldKeepAlive: false,
          useChunkedEncodingByDefault: false,
          sendDate: false,
          _removedHeader: {},
        _contentLength: 0,
          _hasBody: true,
          _trailer: '',
          finished: true,
          _headerSent: true,
          socket: [Object],
          connection: [Object],
          _header: 'GET /api/version HTTP/1.1\r\nHost: 127.0.0.1:9000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/3.5.0\r\nConnection: close\r\n\r\n',
          _headers: [Object],
          _headerNames: [Object],
          _onPendingData: null,
          agent: [Object],
          socketPath: undefined,
          timeout: undefined,
          method: 'GET',
          path: '/api/version',
          _ended: true,
          res: [Circular],
          aborted: undefined,
          timeoutCb: null,
          upgradeOrConnect: false,
          parser: null,
          maxHeadersCount: null },
      text: 'Redirecting to /api/version/\n',
        read: [Function] },
    request:
      Test {
      domain: null,
        _events: {},
      _eventsCount: 0,
        _maxListeners: undefined,
        _agent: false,
        _formData: null,
        method: 'GET',
        url: 'http://127.0.0.1:9000/api/version',
        _header: { 'user-agent': 'node-superagent/3.5.0' },
      header: { 'User-Agent': 'node-superagent/3.5.0' },
      writable: true,
        _redirects: 1,
        _maxRedirects: 0,
        cookies: '',
        qs: {},
      qsRaw: [],
        _redirectList: [],
        _streamRequest: false,
        _buffer: true,
        app:
      Server {
        domain: null,
          _events: [Object],
          _eventsCount: 4,
          _maxListeners: undefined,
          _connections: 0,
          _handle: [Object],
          _usingSlaves: false,
          _slaves: [],
          _unref: false,
          allowHalfOpen: true,
          pauseOnConnect: false,
          httpAllowHalfOpen: false,
          timeout: 120000,
          _pendingResponseData: 0,
          maxHeadersCount: null,
          _connectionKey: '6::::9000' },
      _asserts: [ [Function: bound ] ],
      req:
        ClientRequest {
        domain: null,
          _events: [Object],
          _eventsCount: 3,
          _maxListeners: undefined,
          output: [],
          outputEncodings: [],
          outputCallbacks: [],
          outputSize: 0,
          writable: true,
          _last: true,
          upgrading: false,
          chunkedEncoding: false,
          shouldKeepAlive: false,
          useChunkedEncodingByDefault: false,
          sendDate: false,
          _removedHeader: {},
        _contentLength: 0,
          _hasBody: true,
          _trailer: '',
          finished: true,
          _headerSent: true,
          socket: [Object],
          connection: [Object],
          _header: 'GET /api/version HTTP/1.1\r\nHost: 127.0.0.1:9000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/3.5.0\r\nConnection: close\r\n\r\n',
          _headers: [Object],
          _headerNames: [Object],
          _onPendingData: null,
          agent: [Object],
          socketPath: undefined,
          timeout: undefined,
          method: 'GET',
          path: '/api/version',
          _ended: true,
          res: [Object],
          aborted: undefined,
          timeoutCb: null,
          upgradeOrConnect: false,
          parser: null,
          maxHeadersCount: null },
      protocol: 'http:',
        host: '127.0.0.1:9000',
        _endCalled: true,
        _callback: [Function],
        res:
      IncomingMessage {
        _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 4,
          _maxListeners: undefined,
          socket: [Object],
          connection: [Object],
          httpVersionMajor: 1,
          httpVersionMinor: 1,
          httpVersion: '1.1',
          complete: true,
          headers: [Object],
          rawHeaders: [Object],
          trailers: {},
        rawTrailers: [],
          upgrade: false,
          url: '',
          method: null,
          statusCode: 301,
          statusMessage: 'Moved Permanently',
          client: [Object],
          _consuming: true,
          _dumped: false,
          req: [Object],
          text: 'Redirecting to /api/version/\n',
          read: [Function] },
      response: [Circular],
        called: true },
    req:
      ClientRequest {
      domain: null,
        _events:
      { drain: [Object],
        error: [Object],
        prefinish: [Function: requestOnPrefinish] },
      _eventsCount: 3,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
      _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket:
      Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Circular],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      connection:
        Socket {
        connecting: false,
          _hadError: false,
          _handle: null,
          _parent: null,
          _host: null,
          _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 8,
          _maxListeners: undefined,
          _writableState: [Object],
          writable: false,
          allowHalfOpen: false,
          destroyed: true,
          _bytesDispatched: 137,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          parser: null,
          _httpMessage: [Circular],
          read: [Function],
          _consuming: true,
          _idleNext: null,
          _idlePrev: null,
          _idleTimeout: -1 },
      _header: 'GET /api/version HTTP/1.1\r\nHost: 127.0.0.1:9000\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: node-superagent/3.5.0\r\nConnection: close\r\n\r\n',
        _headers:
      { host: '127.0.0.1:9000',
        'accept-encoding': 'gzip, deflate',
        'user-agent': 'node-superagent/3.5.0' },
      _headerNames:
      { host: 'Host',
        'accept-encoding': 'Accept-Encoding',
        'user-agent': 'User-Agent' },
      _onPendingData: null,
        agent:
      Agent {
        domain: null,
          _events: [Object],
          _eventsCount: 1,
          _maxListeners: undefined,
          defaultPort: 80,
          protocol: 'http:',
          options: [Object],
          requests: {},
        sockets: [Object],
          freeSockets: {},
        keepAliveMsecs: 1000,
          keepAlive: false,
          maxSockets: Infinity,
          maxFreeSockets: 256 },
      socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/api/version',
        _ended: true,
        res:
      IncomingMessage {
        _readableState: [Object],
          readable: false,
          domain: null,
          _events: [Object],
          _eventsCount: 4,
          _maxListeners: undefined,
          socket: [Object],
          connection: [Object],
          httpVersionMajor: 1,
          httpVersionMinor: 1,
          httpVersion: '1.1',
          complete: true,
          headers: [Object],
          rawHeaders: [Object],
          trailers: {},
        rawTrailers: [],
          upgrade: false,
          url: '',
          method: null,
          statusCode: 301,
          statusMessage: 'Moved Permanently',
          client: [Object],
          _consuming: true,
          _dumped: false,
          req: [Circular],
          text: 'Redirecting to /api/version/\n',
          read: [Function] },
      aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null },
    text: 'Redirecting to /api/version/\n',
      body: {},
    files: undefined,
      buffered: true,
      headers:
    { 'x-powered-by': 'Express',
      'content-type': 'text/html; charset=UTF-8',
      'content-length': '57',
      'x-content-type-options': 'nosniff',
      location: '/api/version/',
      date: 'Sun, 26 Feb 2017 21:51:08 GMT',
      connection: 'close' },
    header:
    { 'x-powered-by': 'Express',
      'content-type': 'text/html; charset=UTF-8',
      'content-length': '57',
      'x-content-type-options': 'nosniff',
      location: '/api/version/',
      date: 'Sun, 26 Feb 2017 21:51:08 GMT',
      connection: 'close' },
    statusCode: 301,
      status: 301,
      statusType: 3,
      info: false,
      ok: false,
      redirect: true,
      clientError: false,
      serverError: false,
      error: false,
      accepted: false,
      noContent: false,
      badRequest: false,
      unauthorized: false,
      notAcceptable: false,
      forbidden: false,
      notFound: false,
      type: 'text/html',
      charset: 'UTF-8',
      links: {},
    setEncoding: [Function: bound ],
    redirects: [] }
  ✓ should respond with version (107ms)

Where I notice: text: 'Redirecting to /api/version/\n' which gives a clue.
You help is greatly appreciated.

Body:
I had the same issue. If it is the same issue for you, you just need to change

.get('/api/version')

to

.get('/api/version/')

That trailing forward slash makes a world of difference for the test.


问:
What's a PHP regex to target certain URLs?
I have some basic HTML which I am calling str_replace() on, I need to append all URLs found within an HTML string with a 'generate_book.php?link=', but I need to exclude any external links, eg;

Link  --  this should become  --

Link  --  this should be left alone

Your brain powa is appreciated!

答:
You'll want to use a look-ahead at the beginning to make sure it does not match HTTP or HTTPS.  You could also add mailto if you are worried about it.

```<code>$str = preg_replace("/(?<=href=\")(?!http:\/\/|https:\/\/)([^\"]+)/i", "generate_book.php?link=$1", $str);
</code>```

This regex also uses a look-behind ( the (?<=href=\")) so that it doesn't actually match the href=".

Warnings:

Need to be aware of which URL schemes will be in the HTML besides HTTP and HTTPS, if any.

Some tags like the link tag also have an href attribute.  Make sure you aren't replacing these.  If you need to match only A tags by using Regex, your regex complexity will grow considerably and still won't really be safe.

Regex Eval is much less efficient and unsafe, but if you need URL encoding, you can attempt to URL encode it at replace time like the second return of the other answer does.

Overall, Regex is not necessarily the best solution for this.  You might be better off with an HTML parser...

ContentLicense: CC BY-SA 2.5

Body:
You'll want to use a look-ahead at the beginning to make sure it does not match HTTP or HTTPS.  You could also add mailto if you are worried about it.

$str = preg_replace("/(?<=href=\")(?!http:\/\/|https:\/\/)([^\"]+)/i", "generate_book.php?link=$1", $str);

This regex also uses a look-behind ( the (?<=href=\")) so that it doesn't actually match the href=".

Warnings:

Need to be aware of which URL schemes will be in the HTML besides HTTP and HTTPS, if any.

Some tags like the link tag also have an href attribute.  Make sure you aren't replacing these.  If you need to match only A tags by using Regex, your regex complexity will grow considerably and still won't really be safe.

Regex Eval is much less efficient and unsafe, but if you need URL encoding, you can attempt to URL encode it at replace time like the second return of the other answer does.

Overall, Regex is not necessarily the best solution for this.  You might be better off with an HTML parser...


问:
Introducing new hypothesis in the premises
My current goals are following:

```<code>  n' : nat
  IHn' : forall m : nat, n' + n' = m + m -> n' = m
  m' : nat
  H1 : n' + n' = m' + m'
  ============================
   S n' = S m'
</code>```

Now, I want to apply H1 in IHn' such that the following hypothesis is introduced:

```<code>n' = m'
</code>```

I have tried this:

```<code>apply H1 with (m := m') in IHn'.
</code>```

But that gives me this error:

```<code>Error: No such bound variable m.
</code>```

This is the complete reproducible program with those goals:

```<code>Theorem my_theorem : forall n m,
     n + n = m + m -> n = m.
Proof.
  intros n. induction n as [| n'].
  - simpl.
    intros m H.
    symmetry in H.
    destruct m as [| m'].
    + reflexivity.
    + rewrite -> plus_Sn_m in H.
      inversion H.
  - simpl.
    rewrite <- plus_n_Sm.
    intros m.
    intros H.
    destruct m as [| m'].
    + simpl in H.
      inversion H.
    + rewrite -> plus_Sn_m in H.
      rewrite <- plus_n_Sm in H.
      inversion H.
Abort.
</code>```

答: The problem is that you had your apply backwards.  You need to write apply IHn' with (m := m') in H1.  Note that in this case it is safe to omit the with (m := m') clause, since Coq is smart enough to figure out that information on its own.

Body:
My current goals are following:

  n' : nat
  IHn' : forall m : nat, n' + n' = m + m -> n' = m
  m' : nat
  H1 : n' + n' = m' + m'
  ============================
   S n' = S m'

Now, I want to apply H1 in IHn' such that the following hypothesis is introduced:

n' = m'

I have tried this:

apply H1 with (m := m') in IHn'.

But that gives me this error:

Error: No such bound variable m.

This is the complete reproducible program with those goals:

Theorem my_theorem : forall n m,
     n + n = m + m -> n = m.
Proof.
  intros n. induction n as [| n'].
  - simpl.
    intros m H.
    symmetry in H.
    destruct m as [| m'].
    + reflexivity.
    + rewrite -> plus_Sn_m in H.
      inversion H.
  - simpl.
    rewrite <- plus_n_Sm.
    intros m.
    intros H.
    destruct m as [| m'].
    + simpl in H.
      inversion H.
    + rewrite -> plus_Sn_m in H.
      rewrite <- plus_n_Sm in H.
      inversion H.
Abort.


问:
Applying multiple CSS classes to an angular select?
I had a normal select in a component's template like this:

```<code><select id='target-region' multiple="" class="ui dropdown">
    <option selected value="01">Europe</option>
    <option value="02">North America</option>
    <option value="03">South America</option>
    <option value="04">Asia</option>
    <option value="05">Africa</option>
</select>
</code>```

This dropdown looks something like this:

I tried to turn it into an angular select like so:

```<code><select id="target-region" class="ui dropdown" ng-model="$ctrl.targetRegion" ng-options="item.name for item in $ctrl.TARGET_REGIONS track by item.value" multiple=""></select>
</code>```

And I placed the following in the JS for the component:

```<code>this.TARGET_REGIONS = [
    { value: '01', name: 'Europe' },
    { value: '02', name: 'North America' },
    { value: '03', name: 'South America' },
    { value: '04', name: 'Asia' },
    { value: '05', name: 'Africa' },
];
this.targetRegion = [this.TARGET_REGIONS[0]];
</code>```

There are no errors, but the dropdown select is now displaying in an odd way:

My styling seems to not take effect and clicking on the different options does not select them, so it's not even functional.

I inspected the select and saw this:

This indicates that the ui dropdown classes are being applied to an outer wrapper div created by angular rather than being applied to the select.

At the very least, I'm wondering: how do I make the ui dropdown classes apply directly to the select?

答:
if you're directly trying to convert into angular, you need to change some of the javascript/css in order for ng-options to work. if you dont want to change anything, i sugggest you try this </p>

```<code><select id='target-region' multiple="" class="ui dropdown">
<option ng-repeat="item in $ctrl.TARGET_REGIONS" value="item.value" >{{item.name}}</option>
</select>
</code>```

Body:
I had a normal select in a component's template like this:

<select id='target-region' multiple="" class="ui dropdown">
    <option selected value="01">Europe</option>
    <option value="02">North America</option>
    <option value="03">South America</option>
    <option value="04">Asia</option>
    <option value="05">Africa</option>
</select>

This dropdown looks something like this:

I tried to turn it into an angular select like so:

<select id="target-region" class="ui dropdown" ng-model="$ctrl.targetRegion" ng-options="item.name for item in $ctrl.TARGET_REGIONS track by item.value" multiple=""></select>

And I placed the following in the JS for the component:

this.TARGET_REGIONS = [
    { value: '01', name: 'Europe' },
    { value: '02', name: 'North America' },
    { value: '03', name: 'South America' },
    { value: '04', name: 'Asia' },
    { value: '05', name: 'Africa' },
];
this.targetRegion = [this.TARGET_REGIONS[0]];

There are no errors, but the dropdown select is now displaying in an odd way:

My styling seems to not take effect and clicking on the different options does not select them, so it's not even functional.

I inspected the select and saw this:

This indicates that the ui dropdown classes are being applied to an outer wrapper div created by angular rather than being applied to the select.

At the very least, I'm wondering: how do I make the ui dropdown classes apply directly to the select?

Body:
if you're directly trying to convert into angular, you need to change some of the javascript/css in order for ng-options to work. if you dont want to change anything, i sugggest you try this

<select id='target-region' multiple="" class="ui dropdown">
<option ng-repeat="item in $ctrl.TARGET_REGIONS" value="item.value" >{{item.name}}</option>
</select>


问:
Customization of URL's of theme post types
We are trying to setup a new url structure for themes custom post type called Tour Item. We want to rename that in url to say example "Property"
http://gotravel.mikado-themes.com/tour-item/gaudis-city/
here is the url structure so you get the idea..
so we would like for it to be http://gotravel.mikado-themes.com/property/gaudis-city/ - for example.

Also we would like to add categories into url structure, example
www.travel.com/greece/santorini/property/name-of-property.

One tiny problem is that this theme adds custom post types with plugin, and we would like to avoid editing plugins because of future updates. Is there some function that I can add to edit a custom post type added by plugin.
I tried several ones but none of them works unfortunately.

Any help is appreciated.

Thanks in advance!

答:
I have changed once the plugin custom post type as you have described above. I also faced the same issue but i solved with this code.

```<code>add_action('registered_post_type', 'rename_custom_post_type_name', 10, 2);
function rename_custom_post_type_name($post_type, $args) {
global $wp_rewrite;
if ($post_type == 'tour-item') { //your old slug here
    $args->rewrite['slug'] = 'property'; //write your new slug here
    if ( $args->has_archive ) {
            $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
            if ( $args->rewrite['with_front'] )
                    $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
            else
                    $archive_slug = $wp_rewrite->root . $archive_slug;
            add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
            if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
                    $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
                    add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
                    add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
            }
            if ( $args->rewrite['pages'] )
                    add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
    }
    $permastruct_args = $args->rewrite;
    $permastruct_args['feed'] = $permastruct_args['feeds'];
    add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
}
}
</code>```

Since, you are trying to update the post url, it has to be changed in lot of places.

Another problem of yours which is you want your category to work which i will not able to help you right now.

Hope this works for you to change url to new one.

Thanks

Body:
I have changed once the plugin custom post type as you have described above. I also faced the same issue but i solved with this code.

add_action('registered_post_type', 'rename_custom_post_type_name', 10, 2);
function rename_custom_post_type_name($post_type, $args) {
global $wp_rewrite;
if ($post_type == 'tour-item') { //your old slug here
    $args->rewrite['slug'] = 'property'; //write your new slug here
    if ( $args->has_archive ) {
            $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
            if ( $args->rewrite['with_front'] )
                    $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
            else
                    $archive_slug = $wp_rewrite->root . $archive_slug;
            add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
            if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
                    $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
                    add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
                    add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
            }
            if ( $args->rewrite['pages'] )
                    add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
    }
    $permastruct_args = $args->rewrite;
    $permastruct_args['feed'] = $permastruct_args['feeds'];
    add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
}
}

Since, you are trying to update the post url, it has to be changed in lot of places.

Another problem of yours which is you want your category to work which i will not able to help you right now.

Hope this works for you to change url to new one.

Thanks


问:
I can't run a android project on my Zenphone 5
I have a problem with the marked area in the image below.

Can anyone please tell me how to fix this?

答:
Uncheck the instant run in File >>Settings >>Build,Execution,Deployment >> Instant Run

and change the USB cable, having Enabled ADB Integration via Tools > Android > Enable ADB Integration.


问:
Android add contact email
I'm trying to insert a new contact into the Androids contact list. Adding a name and phone numbers works fine, but adding an email address doesn't work. My code:

```<code>//name is a string
//phone and email are string arrays
ContentValues values = new ContentValues();
values.put(People.NAME, name);
Uri newPerson = People.createPersonInMyContactsGroup(cr, values);
if (newPerson != null) {
    for (i=0; i<phone.length; i++) {
        Log.i("Phone",""+phone[i]);
        values.clear();
        Uri mobilesUri = Uri.withAppendedPath(newPerson,People.Phones.CONTENT_DIRECTORY);
        values.put(People.Phones.NUMBER,phone[i]);
        values.put(People.Phones.TYPE,People.Phones.TYPE_MOBILE);
        Uri phonesUpdate = cr.insert(mobilesUri, values);
    }
    for (i=0; i<email.length; i++) {
        Log.i("Email",""+email[i]);
        values.clear();
        Uri emailUri = Uri.withAppendedPath(newPerson,People.ContactMethods.CONTENT_DIRECTORY);
        values.put(People.ContactMethods.KIND,People.ContactMethods.KIND_EMAIL);
        values.put(People.ContactMethods.TYPE,People.ContactMethods.TYPE_HOME);
        values.put(People.ContactMethods.DATA,email[i]);
        Uri emailUpdate = cr.insert(emailUri, values);
    }
}
</code>```

I get an error in this line:

```<code>values.put(People.ContactMethods.KIND,People.ContactMethods.KIND_EMAIL);
</code>```

of

error: cannot find symbol

Edit: I forgot to mention I use Xcode/Ant and revision 8 (2.2 (Froyo)).

答:
This works for me:

```<code>    values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL);
</code>```

which I got from the well-hidden (at least for Contact programming info):
developer.android.com: Content Providers: Modifying data in a provider

Title: Android add contact email

Body:
I'm trying to insert a new contact into the Androids contact list. Adding a name and phone numbers works fine, but adding an email address doesn't work. My code:

//name is a string
//phone and email are string arrays
ContentValues values = new ContentValues();
values.put(People.NAME, name);
Uri newPerson = People.createPersonInMyContactsGroup(cr, values);
if (newPerson != null) {
    for (i=0; i<phone.length; i++) {
        Log.i("Phone",""+phone[i]);
        values.clear();
        Uri mobilesUri = Uri.withAppendedPath(newPerson,People.Phones.CONTENT_DIRECTORY);
        values.put(People.Phones.NUMBER,phone[i]);
        values.put(People.Phones.TYPE,People.Phones.TYPE_MOBILE);
        Uri phonesUpdate = cr.insert(mobilesUri, values);
    }
    for (i=0; i<email.length; i++) {
        Log.i("Email",""+email[i]);
        values.clear();
        Uri emailUri = Uri.withAppendedPath(newPerson,People.ContactMethods.CONTENT_DIRECTORY);
        values.put(People.ContactMethods.KIND,People.ContactMethods.KIND_EMAIL);
        values.put(People.ContactMethods.TYPE,People.ContactMethods.TYPE_HOME);
        values.put(People.ContactMethods.DATA,email[i]);
        Uri emailUpdate = cr.insert(emailUri, values);
    }
}

I get an error in this line:

values.put(People.ContactMethods.KIND,People.ContactMethods.KIND_EMAIL);

of

error: cannot find symbol

Edit: I forgot to mention I use Xcode/Ant and revision 8 (2.2 (Froyo)).

Body:
This works for me:

    values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL);

which I got from the well-hidden (at least for Contact programming info):
developer.android.com: Content Providers: Modifying data in a provider


问:
Is a statement void(); legal and what is it actually?
I have a little piece of code which has a statement void();

```<code>int main()
{
   void( ); // 1: parses fine in GCC 5.4.0 -Wpedantic
   // void;    // 2: error declaration does not declare anything
}
</code>```

What is 1 void() exactly?

An anonymous function declaration?

A type declaration?

An empty expression?

What makes 1 void() different from 2 void;?

I have read already:

Is sizeof(void()) a legal expression? but there void() is considered a type in sizeof

What does the void() in decltype(void()) mean exactly? where it is considered in declspec.

And I read Is void{} legal or not?

But I am curious if the loose statement void(); is different from one of those (and why of course)

答:
A void expression.

The compiler won't create any code for it, e.g.,

in VS

```<code>_asm
{
    nop;
}
void();
_asm
{
    nop;
}
</code>```

produces this assembly:

```<code>_asm
{
    nop;
003017CE  nop
}
void();
_asm
{
    nop;
003017CF  nop
}
</code>```

Body:
I have a little piece of code which has a statement void();

int main()
{
   void( ); // 1: parses fine in GCC 5.4.0 -Wpedantic
   // void;    // 2: error declaration does not declare anything
}

What is 1 void() exactly?

An anonymous function declaration?

A type declaration?

An empty expression?

What makes 1 void() different from 2 void;?

I have read already:

Is sizeof(void()) a legal expression? but there void() is considered a type in sizeof

What does the void() in decltype(void()) mean exactly? where it is considered in declspec.

And I read Is void{} legal or not?

But I am curious if the loose statement void(); is different from one of those (and why of course)

Body:
A void expression.

The compiler won't create any code for it, e.g.,

in VS

_asm
{
    nop;
}
void();
_asm
{
    nop;
}

produces this assembly:

_asm
{
    nop;
003017CE  nop
}
void();
_asm
{
    nop;
003017CF  nop
}


问:
insertMapObject Function Android Returning 23 code Cartotype
Firstly, Cartotype provides API for providing the Map in Android,iOS and other platforms  as per my knowledge .

from the docs i found a function that meets my need

```<code>native int com.cartotype.Framework.insertMapObject  (   int     aMapHandle,
int     aMapObjectType,
String  aLayerName,
Geometry    aGeometry,
String  aStringAttributes,
int     aIntAttribute,
long    aId,
boolean     aReplace
)
</code>```

But the parameters they refer to i couldn't be successful in getting those and finally got as

```<code>// Second or continuing measurement, add to arrays
// and draw line
iDistanceMeasurementX = extendArray(
iDistanceMeasurementX, thisPoint[0]);
iDistanceMeasurementY = extendArray(
iDistanceMeasurementY, thisPoint[1]);

// _thread.iFramework.deleteMapObjects(0,
// ID_MEASUREMENT_TOOL, ID_MEASUREMENT_TOOL, null);
// _thread.iFramework.addLineOrPolygonObject(
// "measurementtool", iDistanceMeasurementX,
// iDistanceMeasurementY,
// Framework.DEGREE_COORDS, null, 0,
// ID_MEASUREMENT_TOOL, false);

//Drawing line geometry
Geometry geometry = new Geometry(Framework.DEGREE_COORDS);
geometry.appendPoint(thisPoint[0],thisPoint[1]);
geometry.beginContour();

 try {
                                int abc = _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        ID_MEASUREMENT_TOOL, false);
                                Toast.makeText(getContext(),abc,Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

//Drawing line with coordinates
// _thread.iFramework.insertPointMapObject(0,"measurementtool", iDistanceMeasurementX[0],iDistanceMeasurementY[0] ,MapObject.LINE_TYPE, "", 0,
// ID_MEASUREMENT_TOOL, false);
//Toast.makeText(getContext(),"Draw Line ",Toast.LENGTH_SHORT).show();
getMapAndDraw(); // Inefficient, we are drawing
</code>```

Those 'abc' int returns a value 23 and needs to be 0,if success according to the docs.

MY NEED IS DRAW A LINE b\w 2 Coordinates

Any help will be appreciated

答:
At first glance it seems that only one point is being added to the Geometry object. You need two points to draw a line. Also, the call to beginContour is not needed.

But you mentioned that you're getting the 'duplicate object' error (23). That's because more than one object has been inserted with the id ID_MEASUREMENT_TOOL. By the way, you can get a reference to the CartoType error code constants for Android here:

http://www.cartotype.com/assets/android_api_doc/classcom_1_1cartotype_1_1_error.html

Body:
Firstly, Cartotype provides API for providing the Map in Android,iOS and other platforms  as per my knowledge .

from the docs i found a function that meets my need

native int com.cartotype.Framework.insertMapObject  (   int     aMapHandle,
int     aMapObjectType,
String  aLayerName,
Geometry    aGeometry,
String  aStringAttributes,
int     aIntAttribute,
long    aId,
boolean     aReplace
)

But the parameters they refer to i couldn't be successful in getting those and finally got as

// Second or continuing measurement, add to arrays
// and draw line
iDistanceMeasurementX = extendArray(
iDistanceMeasurementX, thisPoint[0]);
iDistanceMeasurementY = extendArray(
iDistanceMeasurementY, thisPoint[1]);

// _thread.iFramework.deleteMapObjects(0,
// ID_MEASUREMENT_TOOL, ID_MEASUREMENT_TOOL, null);
// _thread.iFramework.addLineOrPolygonObject(
// "measurementtool", iDistanceMeasurementX,
// iDistanceMeasurementY,
// Framework.DEGREE_COORDS, null, 0,
// ID_MEASUREMENT_TOOL, false);

//Drawing line geometry
Geometry geometry = new Geometry(Framework.DEGREE_COORDS);
geometry.appendPoint(thisPoint[0],thisPoint[1]);
geometry.beginContour();

 try {
                                int abc = _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        ID_MEASUREMENT_TOOL, false);
                                Toast.makeText(getContext(),abc,Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

//Drawing line with coordinates
// _thread.iFramework.insertPointMapObject(0,"measurementtool", iDistanceMeasurementX[0],iDistanceMeasurementY[0] ,MapObject.LINE_TYPE, "", 0,
// ID_MEASUREMENT_TOOL, false);
//Toast.makeText(getContext(),"Draw Line ",Toast.LENGTH_SHORT).show();
getMapAndDraw(); // Inefficient, we are drawing

Those 'abc' int returns a value 23 and needs to be 0,if success according to the docs.

MY NEED IS DRAW A LINE b\w 2 Coordinates

Any help will be appreciated


问:
Can I use moq Mock<MyClass> to mock a class, not an interface?
Going through https://github.com/Moq/moq4/wiki/Quickstart, I see it Mock an interface.

I have a class in my legacy code which does not have an interface. When I Mock<MyClass>, I get the following exception:

Additional information: Can not instantiate proxy of class: MyCompnay.Mylegacy.MyClass.

How can I use Moq to mock class from legacy code?

答:
It is possible to Mock concrete classes

```<code>[TestClass]
public class PlaceholderParserFixture
{

  public class Foo
  {
     public virtual int GetValue()
     {
        return 11;
     }
  }

  public class Bar
  {
     private readonly Foo _foo;

     public Bar(Foo foo)
     {
        _foo = foo;
     }

     public int GetValue()
     {
        return _foo.GetValue();
     }
  }

  [TestMethod]
  public void MyTestMethod()
  {
     var foo = new Mock<Foo>();
     foo.Setup(mk => mk.GetValue()).Returns(16);
     var bar = new Bar(foo.Object);

     Assert.AreEqual(16, bar.GetValue());
  }

}
</code>```

but,

It must be a public class

The method to be mocked must be virtual

The messages I got for:

Making the class internal

Castle.DynamicProxy.Generators.GeneratorException: Type MoqFixture+Foo is not public. Can not create proxy for types that are not accessible.

or, having a non-virtual method

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: mk => mk.GetValue()

do not match your cannot instantiate message, so something else seems to be wrong.

If you do not have a default constructor on the mocked object you can get that error message

e.g.

```<code>public class Foo
{

    private int _value;
    public Foo(int value)
    {
       _value = value;
    }

    public virtual int GetValue()
    {
        return _value;
    }
}
</code>```

one can get around this by passing values into the Mock<> ctor

e.g.

```<code>var foo = new Mock<Foo>(MockBehavior.Strict, new object[] { 11 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It is possible to Mock concrete classes

[TestClass]
public class PlaceholderParserFixture
{

  public class Foo
  {
     public virtual int GetValue()
     {
        return 11;
     }
  }

  public class Bar
  {
     private readonly Foo _foo;

     public Bar(Foo foo)
     {
        _foo = foo;
     }

     public int GetValue()
     {
        return _foo.GetValue();
     }
  }

  [TestMethod]
  public void MyTestMethod()
  {
     var foo = new Mock<Foo>();
     foo.Setup(mk => mk.GetValue()).Returns(16);
     var bar = new Bar(foo.Object);

     Assert.AreEqual(16, bar.GetValue());
  }

}

but,

It must be a public class

The method to be mocked must be virtual

The messages I got for:

Making the class internal

Castle.DynamicProxy.Generators.GeneratorException: Type MoqFixture+Foo is not public. Can not create proxy for types that are not accessible.

or, having a non-virtual method

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: mk => mk.GetValue()

do not match your cannot instantiate message, so something else seems to be wrong.

If you do not have a default constructor on the mocked object you can get that error message

e.g.

public class Foo
{

    private int _value;
    public Foo(int value)
    {
       _value = value;
    }

    public virtual int GetValue()
    {
        return _value;
    }
}

one can get around this by passing values into the Mock<> ctor

e.g.

var foo = new Mock<Foo>(MockBehavior.Strict, new object[] { 11 });


问:
Android Studio cannot resolve org.junit
I am using JUnit tests in Android Studio 1.2.2. The tests run without a problem. The only thing that puzzles me is that Android Studio cannot resolve the actual org.junit package. Obviously it does resolve it otherwise the tests wouldn't run. But the import and annotations are marked red in Android Studio as shown here. Is this a bug in Android Studio? I tried rebuilding the app and restarting Android Studio but this doesn't correct the problem.</p>

```<code>import org.junit.Test;

import static org.junit.Assert.*; // cannot resolve symbol 'junit'

public class CanadaTest
{
    @Test
    public void testCountryName() throws Exception
    {
        int x = 0;
        x++;
    }
}
</code>```

答: If you've reinstalled android studio remember by default it is not using your systems JDK (Project structure -> SDK location -> jdk location).</p>

Title: Android Studio cannot resolve org.junit

Body:
I am using JUnit tests in Android Studio 1.2.2. The tests run without a problem. The only thing that puzzles me is that Android Studio cannot resolve the actual org.junit package. Obviously it does resolve it otherwise the tests wouldn't run. But the import and annotations are marked red in Android Studio as shown here. Is this a bug in Android Studio? I tried rebuilding the app and restarting Android Studio but this doesn't correct the problem.

import org.junit.Test;

import static org.junit.Assert.*; // cannot resolve symbol 'junit'

public class CanadaTest
{
    @Test
    public void testCountryName() throws Exception
    {
        int x = 0;
        x++;
    }
}


问:
Case insensitive search for multiple matches in a hash, merge the keys and add up the values
I have a hash containing a very big list of words (keys) and their frequency (values).

My problem is that the same word can appear several times with different cases, like this :

```<code>de => 14477841
la => 6577441
et => 5327316
PAR => 1670264
PaR => 1669878
PAr => 1669877
</code>```

When that happens, I would like to find all the different versions of a same word in the hash, regardless of the case, and merge them while adding up the values so here I'd get :

```<code>de => 14477841
la => 6577441
et => 5327316
par => 5010019
</code>```

("par" is here in lower case but I don't really care, as long as there's only one version of it.)

I've tried to get the different keys in a array and check if a different version of each item of this list existed in the hash. There are a lot of different case patterns that I can't think of and have trouble to predict.

Here is a sample of my code, for what it's worth (it partially works but I still get duplicates)

```<code>my %hashoutput;
my %hash = map { my ( $key, $value ) = split "\t"; ( $key, $value ) } @lignes;

foreach $ligne (@lignes) #list of keys and values separated by a tab
{

($cleorigine, $valeur) = split /\t/, $ligne;    #get the key and value
$cle = $cleorigine =~ s/^([A-Z])/lc($1)/gr;     # different versions of it
$clemaj = $cleorigine =~ s/^([a-z])/uc($1)/ge;

    if ($cleorigine !~ /[0-9]{2}/g)
    {
        if ($ligne =~ /^([A-Z]|[ÉÈÊÂÀÙÛÇÔÎÏ])/g)
        {
            if (exists $hash{lc($cleorigine)})
            {
                $valeur1 = $valeur + $hash{lc($cleorigine)};
                $hashoutput{ $cleorigine } = $valeur1;
            }
            if (not exists $hash{lc($cleorigine)})
            {
                if (exists $hash{$cle})
                {
                    $valeur2 = $valeur + $hash{$cle};
                    $hashoutput{ $cleorigine } = $valeur2;
                }
            }
        }
        elsif ($ligne =~ /^([a-z]|[éèêâàùûçôîï])/g)
        {

            if (exists $hash{$clemaj})
            {
            }
            elsif (not exists $hash{uc($clemaj)})
            {
                {
                    $hashoutput{ $cleorigine } = $valeur;
                }
            }

        }
    }
}
</code>```

Is there a better / simpler way to do it ?

答:
Create a new hash from the old one by aggregating the values for equivalent keys

Like this. Note that the data is deleted from the original hash so as to save space. The fc operator does Unicode case folding so that it will work on non-ASCII characters

```<code>use strict;
use warnings 'all';
use feature 'fc';

my %data = (
    de  => 14477841,
    la  =>  6577441,
    et  =>  5327316,
    PAR =>  1670264,
    PaR =>  1669878,
    PAr =>  1669877,
);

my %new_data;

$new_data{ fc $_ } += delete $data{$_} for keys %data;

use Data::Dump 'dd';
dd \%new_data;
</code>```

output

```<code>{ de => 14477841, et => 5327316, la => 6577441, par => 5010019 }
</code>```

Body:
I have a hash containing a very big list of words (keys) and their frequency (values).

My problem is that the same word can appear several times with different cases, like this :

de => 14477841
la => 6577441
et => 5327316
PAR => 1670264
PaR => 1669878
PAr => 1669877

When that happens, I would like to find all the different versions of a same word in the hash, regardless of the case, and merge them while adding up the values so here I'd get :

de => 14477841
la => 6577441
et => 5327316
par => 5010019

("par" is here in lower case but I don't really care, as long as there's only one version of it.)

I've tried to get the different keys in a array and check if a different version of each item of this list existed in the hash. There are a lot of different case patterns that I can't think of and have trouble to predict.

Here is a sample of my code, for what it's worth (it partially works but I still get duplicates)

my %hashoutput;
my %hash = map { my ( $key, $value ) = split "\t"; ( $key, $value ) } @lignes;

foreach $ligne (@lignes) #list of keys and values separated by a tab
{

($cleorigine, $valeur) = split /\t/, $ligne;    #get the key and value
$cle = $cleorigine =~ s/^([A-Z])/lc($1)/gr;     # different versions of it
$clemaj = $cleorigine =~ s/^([a-z])/uc($1)/ge;

    if ($cleorigine !~ /[0-9]{2}/g)
    {
        if ($ligne =~ /^([A-Z]|[ÉÈÊÂÀÙÛÇÔÎÏ])/g)
        {
            if (exists $hash{lc($cleorigine)})
            {
                $valeur1 = $valeur + $hash{lc($cleorigine)};
                $hashoutput{ $cleorigine } = $valeur1;
            }
            if (not exists $hash{lc($cleorigine)})
            {
                if (exists $hash{$cle})
                {
                    $valeur2 = $valeur + $hash{$cle};
                    $hashoutput{ $cleorigine } = $valeur2;
                }
            }
        }
        elsif ($ligne =~ /^([a-z]|[éèêâàùûçôîï])/g)
        {

            if (exists $hash{$clemaj})
            {
            }
            elsif (not exists $hash{uc($clemaj)})
            {
                {
                    $hashoutput{ $cleorigine } = $valeur;
                }
            }

        }
    }
}

Is there a better / simpler way to do it ?

Body:
Create a new hash from the old one by aggregating the values for equivalent keys

Like this. Note that the data is deleted from the original hash so as to save space. The fc operator does Unicode case folding so that it will work on non-ASCII characters

use strict;
use warnings 'all';
use feature 'fc';

my %data = (
    de  => 14477841,
    la  =>  6577441,
    et  =>  5327316,
    PAR =>  1670264,
    PaR =>  1669878,
    PAr =>  1669877,
);

my %new_data;

$new_data{ fc $_ } += delete $data{$_} for keys %data;

use Data::Dump 'dd';
dd \%new_data;

output

{ de => 14477841, et => 5327316, la => 6577441, par => 5010019 }


问:
How to show a login modal in Rails if a user tries to access an authorized section
How would you implement a modal window saying "In order you to access this area you have to be logged in.." in combination with a login form below it every time a user tries to access authorized content.
I'm using Rails 3, Devise and CanCan.

My first thoughts were do put it somewhere in the application_controller.rb:

```<code># application_controller.rb
rescue_from CanCan::AccessDenied do |exception|
  flash[:error] = "Access denied."
  redirect_to root_url
end
</code>```

答:
I'm not using a modal window, but this works

```<code>rescue_from CanCan::AccessDenied do |exception|
    unless anybody_signed_in?
      authenticate_user!
    else
      flash[:alert] = "Access denied."
      redirect_to root_url
    end
 end
</code>```

It will redirect the use to the login form. When the user provides his credentials, he'll be shown the page he wanted to access.

Body:
How would you implement a modal window saying "In order you to access this area you have to be logged in.." in combination with a login form below it every time a user tries to access authorized content.
I'm using Rails 3, Devise and CanCan.

My first thoughts were do put it somewhere in the application_controller.rb:

# application_controller.rb
rescue_from CanCan::AccessDenied do |exception|
  flash[:error] = "Access denied."
  redirect_to root_url
end

Body:
I'm not using a modal window, but this works

rescue_from CanCan::AccessDenied do |exception|
    unless anybody_signed_in?
      authenticate_user!
    else
      flash[:alert] = "Access denied."
      redirect_to root_url
    end
 end

It will redirect the use to the login form. When the user provides his credentials, he'll be shown the page he wanted to access.


问:
Getting Max Value in Rows for a Column
I have a bit of SQL code that works well and I need to tweak it to get the max value for the RevisionNo column. Its not working for me and I not sure if I need a Having clause or how to best implement it.  Here is the working code:

```<code>SELECT ValueText FROM VariableValue
   WHERE (VariableID = 60) AND (DocumentID IN
               (SELECT DocumentID FROM Documents
                   WHERE (deleted = 0 and DocumentID IN
                             (SELECT DocumentID FROM Documents WHERE (Filename LIKE 'TCT-013963%.SLDASM'))))
</code>```

This is not:

```<code>SELECT ValueText FROM VariableValue
   WHERE (VariableID = 60) AND MAX(RevisionNo) AND (DocumentID IN
               (SELECT DocumentID FROM Documents
                   WHERE (deleted = 0 and DocumentID IN
                             (SELECT DocumentID FROM Documents WHERE (Filename LIKE 'TCT-013963%.SLDASM')))))
</code>```

The result I am getting with the query that runs returns two rows of from the valuetext column (this is a description field and I want the latest, hence the max value on the RevisionNo column).

|ValueText|RevisionNo|

|PRESSURE VESSEL FRONT END ASSY BNCT|1|

|PRESSURE VESSEL FRONT END ASSY NUBEAM|7|

答:
```<code>SELECT TOP 1 ValueText FROM VariableValue
   WHERE (VariableID = 60) AND (DocumentID IN
       (SELECT DocumentID FROM Documents
           WHERE (deleted = 0 and DocumentID IN
               (SELECT DocumentID FROM Documents WHERE (Filename LIKE 'TCT-013963%.SLDASM')))))
                   ORDER BY RevisionNo DESC
</code>```

Title: Getting Max Value in Rows for a Column

Body:
I have a bit of SQL code that works well and I need to tweak it to get the max value for the RevisionNo column. Its not working for me and I not sure if I need a Having clause or how to best implement it.  Here is the working code:

SELECT ValueText FROM VariableValue
   WHERE (VariableID = 60) AND (DocumentID IN
               (SELECT DocumentID FROM Documents
                   WHERE (deleted = 0 and DocumentID IN
                             (SELECT DocumentID FROM Documents WHERE (Filename LIKE 'TCT-013963%.SLDASM'))))

This is not:

SELECT ValueText FROM VariableValue
   WHERE (VariableID = 60) AND MAX(RevisionNo) AND (DocumentID IN
               (SELECT DocumentID FROM Documents
                   WHERE (deleted = 0 and DocumentID IN
                             (SELECT DocumentID FROM Documents WHERE (Filename LIKE 'TCT-013963%.SLDASM')))))

The result I am getting with the query that runs returns two rows of from the valuetext column (this is a description field and I want the latest, hence the max value on the RevisionNo column).

|ValueText|RevisionNo|

|PRESSURE VESSEL FRONT END ASSY BNCT|1|

|PRESSURE VESSEL FRONT END ASSY NUBEAM|7|


问:
Tensorflow contrib.layers compatibility on Windows
I'm currently trying to learn more about the layers API of tensorflow, for this I'm trying the cloud-ml samples (census: https://github.com/GoogleCloudPlatform/cloudml-samples/tree/master/census).

When I launch the script on my Windows computer (Windows-10, run in local, not distributed, CPU mode), I get the following error:

```<code>   File "\*\Anaconda3\lib\site-packages\tensorflow\contrib\layers\python\layers\feature_column.py", line 1652, in insert_transformed_feature name="bucketize")
   File "\*\Anaconda3\lib\site-packages\tensorflow\contrib\layers\python\ops\bucketization_op.py", line 48, in bucketize
      return _bucketization_op.bucketize(input_tensor, boundaries, name=name)
AttributeError: 'NoneType' object has no attribute 'bucketize'
</code>```

In the code of tensorflow (I used version 1.0.0, and upgraded it to 1.0.1 with the same error), I saw in the file tensorflow\contrib\layers\python\ops\bucketization_op.py that the op was loaded from native code:

```<code>_bucketization_op = loader.load_op_library(
    resource_loader.get_path_to_datafile("_bucketization_op.so"))
</code>```

At this point I actually have two questions:

Am I wrong to think that this is only valid on Linux, or the .dll might have been renamed .so to keep a coherent Python code? If there's such a renaming, can someone tell me where I could find this file as a quick search into the folder gave no result for *.dll or *.so (I assume every native code is wrapped by SWIG inside the _pywrap_tensorflow.pyd)?

Does anyone have a clue of why this kind of error could happen?

答:
TL;DR: These ops should now work in the current nightly build of TensorFlow. I've sent out a pull request to add support in the upcoming 1.1 release.

The explanation is a bit tortuous, but I'll attempt to lay out the key points.

In general, the tf.contrib libraries have limited support on Windows, often because they depend on platform-specific code that does not work (or has not historically worked) on Windows. Until very recently the tf.load_op_library() API did not work on Windows, but a recent pull request added support for it. Nightly builds for TensorFlow on Windows now include .dll files for some extension libraries, and the loader library includes code that converts the .so extension to .dll on Windows.

As a historical workaround for this problem, we statically linked every tf.contrib kernel into _pywrap_tensorflow.pyd, and made loader.load_op_library() fail silently if the extension was not present on Windows. However, there are two ways to get the generated Python wrapper functions for each op:

The more common way, which (e.g.) tf.contrib.tensor_forest uses is to generate the Python source at build time and include the generated code in the PIP package. This works fine on Windows.

The less common way, which bucketization_op.py uses is to generate the Python source at run time, and return a generated Python module from loader.load_op_library(). Since we made this fail silently and return None on Windows, calling _bucketization_op.bucketize() doesn't work.

Finally, due to operational concerns, we determined  that it would be useful to switch between the static and dynamic linking of the tf.contrib kernels on all platforms, and the easiest way to do that would be to generate the wrapper code statically. A recent change (which alas just missed the branch for the 1.1 release) made the generation of wrapper code consistent across all of the tf.contrib libraries.

I hope this makes sense. As a result of all of these changes, if you upgrade to a nightly build of TensorFlow the problem should be fixed, and
hopefully we can merge the change into the 1.1 release as well!

Body:
I'm currently trying to learn more about the layers API of tensorflow, for this I'm trying the cloud-ml samples (census: https://github.com/GoogleCloudPlatform/cloudml-samples/tree/master/census).

When I launch the script on my Windows computer (Windows-10, run in local, not distributed, CPU mode), I get the following error:

   File "\*\Anaconda3\lib\site-packages\tensorflow\contrib\layers\python\layers\feature_column.py", line 1652, in insert_transformed_feature name="bucketize")
   File "\*\Anaconda3\lib\site-packages\tensorflow\contrib\layers\python\ops\bucketization_op.py", line 48, in bucketize
      return _bucketization_op.bucketize(input_tensor, boundaries, name=name)
AttributeError: 'NoneType' object has no attribute 'bucketize'

In the code of tensorflow (I used version 1.0.0, and upgraded it to 1.0.1 with the same error), I saw in the file tensorflow\contrib\layers\python\ops\bucketization_op.py that the op was loaded from native code:

_bucketization_op = loader.load_op_library(
    resource_loader.get_path_to_datafile("_bucketization_op.so"))

At this point I actually have two questions:

Am I wrong to think that this is only valid on Linux, or the .dll might have been renamed .so to keep a coherent Python code? If there's such a renaming, can someone tell me where I could find this file as a quick search into the folder gave no result for *.dll or *.so (I assume every native code is wrapped by SWIG inside the _pywrap_tensorflow.pyd)?

Does anyone have a clue of why this kind of error could happen?


问:
Blink the time like a real digital clock
I am displaying the current time like this way :

```<code>$('#mydiv').html(
   new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }));
</code>```

and it is displayed for example like this :

16:13

How is it possible to make the two dots blink every one second like a real digital clock?

答:
I was intrigued so I could not help answering.

var toggle = true;
setInterval(function() {
  var d = new Date().toLocaleTimeString('en-US', { hour12: false, hour: 'numeric', minute: 'numeric' });
  var parts = d.split(":");
  $('#hours').text(parts[0]);
  $('#minutes').text(parts[1]);
  $("#colon").css({ visibility: toggle?"visible":"hidden"});
  toggle=!toggle;
},1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#colon { visibility:hidden }</code>```

:

```

Body:
I am displaying the current time like this way :

$('#mydiv').html(
   new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }));

and it is displayed for example like this :

16:13

How is it possible to make the two dots blink every one second like a real digital clock?

Body:
I was intrigued so I could not help answering.

var toggle = true;
setInterval(function() {
  var d = new Date().toLocaleTimeString('en-US', { hour12: false, hour: 'numeric', minute: 'numeric' });
  var parts = d.split(":");
  $('#hours').text(parts[0]);
  $('#minutes').text(parts[1]);
  $("#colon").css({ visibility: toggle?"visible":"hidden"});
  toggle=!toggle;
},1000);

#colon { visibility:hidden }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span id="hours"></span><span id="colon">:</span><span id="minutes"></span>
</div>


问:
Install RPM package with Python Yum API with --downloadonly
I am trying to install/download an RPM package through the Yum API with Python. But I am not able to supply the --downloadonly option, it seems to be ignored by the install method.

Here is my code so far:

```<code>import yum

yb = yum.YumBase()
args = {"name":"git", "downloadonly": True}
yb.install(**args)
yb.processDeps()
yb.buildTransaction()
yb.processTransaction()
</code>```

This will install the package on the system, but not honor the downloadonly option.

What is the proper way of telling Yum to only download a package through the Python Yum API?

答:
This is what you need:

```<code>import yum

yb = yum.YumBase()
yb.conf.downloadonly = True
args = {'name':'git'}
yb.install(**args)
yb.buildTransaction()
yb.processTransaction()
</code>```

After executing this python script, you can find the downloaded package in

```<code>/var/cache/yum/x86_64/7/base/packages/
</code>```

The path above may be different for you depending on the distro.

Body:
I am trying to install/download an RPM package through the Yum API with Python. But I am not able to supply the --downloadonly option, it seems to be ignored by the install method.

Here is my code so far:

import yum

yb = yum.YumBase()
args = {"name":"git", "downloadonly": True}
yb.install(**args)
yb.processDeps()
yb.buildTransaction()
yb.processTransaction()

This will install the package on the system, but not honor the downloadonly option.

What is the proper way of telling Yum to only download a package through the Python Yum API?

Body:
This is what you need:

import yum

yb = yum.YumBase()
yb.conf.downloadonly = True
args = {'name':'git'}
yb.install(**args)
yb.buildTransaction()
yb.processTransaction()

After executing this python script, you can find the downloaded package in

/var/cache/yum/x86_64/7/base/packages/

The path above may be different for you depending on the distro.


问:
Two floats throw TypeError: unsupported operand type(s) for +: 'float' and 'str'
I am running into an issue with the following line of code:

underground['distributed_load_C'] = float(ugLineList[21])*1000 + ('+' if float(ugLineList[24]) >= 0.0 else '-') + abs(float(ugLineList[24]))*1000j

The original values pulled from ugLineList are strings and I try to type cast them into floats before addition. Even though I try to type cast them I am getting the following error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

I've tried type casting them before this statement, and checking that the code snippets are truly floats:
print type(float(ugLineList[21])*1000), type(float(ugLineList[24]))
---> <type 'float'> <type 'float'>

I am really confused as to what is going on here so any help is greatly appreciated.

Thanks!!

答:
I am not sure what you are trying to do by checking the sign of the value and then performing an abs, but I would bet that you can simply drop it:

```<code>underground['distributed_load_C'] = float(ugLineList[21])*1000 + float(ugLineList[24])*1000j
</code>```

Body:
I am not sure what you are trying to do by checking the sign of the value and then performing an abs, but I would bet that you can simply drop it:

underground['distributed_load_C'] = float(ugLineList[21])*1000 + float(ugLineList[24])*1000j


问:
Averaging floating value in assembly
I have to get average. In C++ since I don't pass it the length of the array
I don't   know how to divide it by that.

Here's how I'm passing my values in C++

```<code>extern "C" double Average (long [6]);

        _Average proc

        finit
        mov  ecx, 6  ; number of elements
        mov  ebx, [esp + 4] ; address of the array
        fldz

   L1:
        fld REAL4 PTR [ebx]  ; get elements of array
        fadd
        add ebx, 4

        loop L1
        fdiv DWORD PTR [esp + 4]

        fwait

        ret

       _Average endp
</code>```

答:
You already know that it's six elements long, since you're using that as your loop count (in ecx) and it is specified in the prototype. The only alternative is to pass another parameter with the length (as you would have to do in pure C++ anyway).

You also need to use fild instead of fld to load a long, since it is not a floating point variable, as well as changing REAL4 PTR to DWORD PTR. Alternatively, change long to float. (Another alternative is changing long to double, though this changes the size of the data type which will require more modifications.)

Title: Averaging floating value in assembly

Body:
I have to get average. In C++ since I don't pass it the length of the array
I don't   know how to divide it by that.

Here's how I'm passing my values in C++

extern "C" double Average (long [6]);

        _Average proc

        finit
        mov  ecx, 6  ; number of elements
        mov  ebx, [esp + 4] ; address of the array
        fldz

   L1:
        fld REAL4 PTR [ebx]  ; get elements of array
        fadd
        add ebx, 4

        loop L1
        fdiv DWORD PTR [esp + 4]

        fwait

        ret

       _Average endp