问:
not able to publish custom event in spring before context load
I am trying to publish a custom event in Spring MVC, but is is not firing while context is loading, below are the code snippet,

The onConnectionOpened will be called after connecting to a server which is triggered after bean initialization using @PostConstruct

```<code>@Autowired
private ApplicationEventPublisher publisher;

public void onConnectionOpened(EventObject event) {
    publisher.publishEvent(new StateEvent("ConnectionOpened", event));

}
</code>```

I am using annotation in listener part as below

```<code>@EventListener
public void handleConnectionState(StateEvent event) {
   System.out.println(event);
}
</code>```

I am able to see events fired after the context is loaded or refreshed, is this expected that custom application events can be published after the context loaded or refreshed?.

I am using Spring 4.3.10

Thanks in advance

答:
The @EventListener annotations are processed by the EventListenerMethodProcessor which will run as soon as all beans are instantiated and ready. As you are publishing an event from a @PostConstruct annotated method it might be that not everything is up and running at that moment and @EventListener based methods haven't been detected yet.

Instead what you can do is use the ApplicationListener interface to get the events and process them.

```<code>public class MyEventHandler implements ApplicationListener<StateEvent> {

    public void onApplicationEvent(StateEvent event) {
        System.out.println(event);
    }
}
</code>```

Body:
I am trying to publish a custom event in Spring MVC, but is is not firing while context is loading, below are the code snippet,

The onConnectionOpened will be called after connecting to a server which is triggered after bean initialization using @PostConstruct

@Autowired
private ApplicationEventPublisher publisher;

public void onConnectionOpened(EventObject event) {
    publisher.publishEvent(new StateEvent("ConnectionOpened", event));

}

I am using annotation in listener part as below

@EventListener
public void handleConnectionState(StateEvent event) {
   System.out.println(event);
}

I am able to see events fired after the context is loaded or refreshed, is this expected that custom application events can be published after the context loaded or refreshed?.

I am using Spring 4.3.10

Thanks in advance

Body:
The @EventListener annotations are processed by the EventListenerMethodProcessor which will run as soon as all beans are instantiated and ready. As you are publishing an event from a @PostConstruct annotated method it might be that not everything is up and running at that moment and @EventListener based methods haven't been detected yet.

Instead what you can do is use the ApplicationListener interface to get the events and process them.

public class MyEventHandler implements ApplicationListener<StateEvent> {

    public void onApplicationEvent(StateEvent event) {
        System.out.println(event);
    }
}


来源: stackexchange

问:
SQL MAX(m.time) does not select the highest value
The piece of code:

```<code>SELECT m.message,
          MAX(m.time) AS time,
          m.sender,
          m.receiver,
          m.contact,
          u.ufirstname
FROM( (SELECT message,
                  receiver_uid AS receiver,
                  sender_uid AS sender,
                  time,
                  receiver_uid AS contact
             FROM messages
            WHERE sender_uid = '$me' )
           UNION
           (SELECT message,
                   receiver_uid AS receiver,
                   sender_uid AS sender,
                   time,
                   sender_uid AS contact
              FROM messages
             WHERE receiver_uid = '$me' ) ) AS m,
         users AS u
   WHERE m.contact = u.uid
GROUP BY m.contact
ORDER BY time DESC;
</code>```

My problem is that this piece SHOULD select the most recent message of a conversation.
This is the format of the database:

```<code>Sender_uid | receiver_uid | message | time («What format should this be?)
</code>```

The first part retrieves all the messages in which '$me' (=userID of logged in user) takes part. So all the messages whether '$me' is sending or receiving.
The second part should select the most recent time (highest value) for each 'conversation' (=contact ID, whether contact is receiver or sender)

It does not get the most recent message. It does give you one message from the conversation.

Important hint(?): What I think the script is doing is retrieving the most recent message where '$me' is the sender.

I want it to collect the last message whether $me is receiver or sender.

答:
Please stop abusing MySQL with mixing aggregates and non-aggregates. While MySQL allows it, it is unpredictable which records each column comes from, and they don't even have to be from the same record (in sync)

```<code>SELECT m2.message,
          m2.time AS time,
          m2.sender,
          m2.receiver,
          m.contact,
          u.ufirstname
FROM (
    SELECT
        case when sender_uid = '$me' then receiver_uid else sender_uid end Contact,
        max(time) maxtime
    FROM messages
    WHERE sender_uid = '$me' or receiver_uid = '$me'
    group by case when sender_uid = '$me' then receiver_uid else sender_uid end
) AS m
INNER JOIN messages m2 on m.maxtime = m2.time
    and ((m2.sender_uid = '$me' and m2.receiver_uid = m.Contact)
        or
        (m2.receiver_uid = '$me' and m2.sender_uid = m.Contact))
INNER JOIN users AS u on m.contact = u.uid
ORDER BY time DESC;
</code>```

@updated query - was more complicated that it looked.

The "Contact" is the other party of the conversation.

The inner OR is used to pass through the table only once.

The inner CASE statement is used to get the ID of the other party.
If '$me' is matched to the sender, the receiver becomes the "contact"
otherwise the sender is the "contact"

The join with m2 uses 3 attributes - me, contact (either orientation) and maxtime
This join uses the keys from the inner query (maxTime) to retrieve the
full record from the table

There is a final join with users to get the contact's firstname

ContentLicense: CC BY-SA 2.5

Body:
The piece of code:

SELECT m.message,
          MAX(m.time) AS time,
          m.sender,
          m.receiver,
          m.contact,
          u.ufirstname
FROM( (SELECT message,
                  receiver_uid AS receiver,
                  sender_uid AS sender,
                  time,
                  receiver_uid AS contact
             FROM messages
            WHERE sender_uid = '$me' )
           UNION
           (SELECT message,
                   receiver_uid AS receiver,
                   sender_uid AS sender,
                   time,
                   sender_uid AS contact
              FROM messages
             WHERE receiver_uid = '$me' ) ) AS m,
         users AS u
   WHERE m.contact = u.uid
GROUP BY m.contact
ORDER BY time DESC;

My problem is that this piece SHOULD select the most recent message of a conversation.
This is the format of the database:

Sender_uid | receiver_uid | message | time («What format should this be?)

The first part retrieves all the messages in which '$me' (=userID of logged in user) takes part. So all the messages whether '$me' is sending or receiving.
The second part should select the most recent time (highest value) for each 'conversation' (=contact ID, whether contact is receiver or sender)

It does not get the most recent message. It does give you one message from the conversation.

Important hint(?): What I think the script is doing is retrieving the most recent message where '$me' is the sender.

I want it to collect the last message whether $me is receiver or sender.

Body:
Please stop abusing MySQL with mixing aggregates and non-aggregates. While MySQL allows it, it is unpredictable which records each column comes from, and they don't even have to be from the same record (in sync)

SELECT m2.message,
          m2.time AS time,
          m2.sender,
          m2.receiver,
          m.contact,
          u.ufirstname
FROM (
    SELECT
        case when sender_uid = '$me' then receiver_uid else sender_uid end Contact,
        max(time) maxtime
    FROM messages
    WHERE sender_uid = '$me' or receiver_uid = '$me'
    group by case when sender_uid = '$me' then receiver_uid else sender_uid end
) AS m
INNER JOIN messages m2 on m.maxtime = m2.time
    and ((m2.sender_uid = '$me' and m2.receiver_uid = m.Contact)
        or
        (m2.receiver_uid = '$me' and m2.sender_uid = m.Contact))
INNER JOIN users AS u on m.contact = u.uid
ORDER BY time DESC;

@updated query - was more complicated that it looked.

The "Contact" is the other party of the conversation.

The inner OR is used to pass through the table only once.

The inner CASE statement is used to get the ID of the other party.
If '$me' is matched to the sender, the receiver becomes the "contact"
otherwise the sender is the "contact"

The join with m2 uses 3 attributes - me, contact (either orientation) and maxtime
This join uses the keys from the inner query (maxTime) to retrieve the
full record from the table

There is a final join with users to get the contact's firstname


问:
Node.js TypeError: Wit is not a constructor
How to solve "Wit is not a constructor" error coming from Node.js while executing code given by node-wit and wit.ai documentation.

```<code>// Setting up our bot
const wit = new Wit(WIT_TOKEN, actions);
</code>```

I tried all the ways by upgrading and downgrading npm/node versions, but no luck.

Update: Please find the index.js source I used,

Do I need to change anything in this?

```<code>module.exports = {
  Logger: require('./lib/logger.js').Logger,
  logLevels: require('./lib/logger.js').logLevels,
  Wit: require('./lib/wit.js').Wit,
}

'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
const Logger = require('node-wit').Logger;
const levels = require('node-wit').logLevels;
var app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 3000));

//const Wit = require('node-wit').Wit;
const WIT_TOKEN = process.env.WIT_TOKEN;
const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN;
const Wit = require('node-wit').Wit;

// Server frontpage
app.get('/', function (req, res) {
    debugger;
    res.send('This is TestBot Server');
});

// Messenger API specific code

// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference
const fbReq = request.defaults({
  uri: 'https://graph.facebook.com/me/messages',
  method: 'POST',
  json: true,
  qs: { access_token: FB_PAGE_TOKEN },
  headers: {'Content-Type': 'application/json'},
});

const fbMessage = (recipientId, msg, cb) => {
  const opts = {
    form: {
      recipient: {
        id: recipientId,
      },
      message: {
        text: msg,
      },
    },
  };
  fbReq(opts, (err, resp, data) => {
    if (cb) {
      cb(err || data.error && data.error.message, data);
    }
  });
};

// See the Webhook reference
// https://developers.facebook.com/docs/messenger-platform/webhook-reference
const getFirstMessagingEntry = (body) => {
  const val = body.object == 'page' &&
    body.entry &&
    Array.isArray(body.entry) &&
    body.entry.length > 0 &&
    body.entry[0] &&
    body.entry[0].id === FB_PAGE_ID &&
    body.entry[0].messaging &&
    Array.isArray(body.entry[0].messaging) &&
    body.entry[0].messaging.length > 0 &&
    body.entry[0].messaging[0]
  ;
  return val || null;
};

// Wit.ai bot specific code

// This will contain all user sessions.
// Each session has an entry:
// sessionId -> {fbid: facebookUserId, context: sessionState}
const sessions = {};

const findOrCreateSession = (fbid) => {
  var sessionId;
  // Let's see if we already have a session for the user fbid
  Object.keys(sessions).forEach(k => {
    if (sessions[k].fbid === fbid) {
      // Yep, got it!
      sessionId = k;
    }
  });
  if (!sessionId) {
    // No session found for user fbid, let's create a new one
    sessionId = new Date().toISOString();
    sessions[sessionId] = {fbid: fbid, context: {}};
  }
  return sessionId;
};

// Our bot actions
const actions = {
  say(sessionId, context, message, cb) {
    // Our bot has something to say!
    // Let's retrieve the Facebook user whose session belongs to
    const recipientId = sessions[sessionId].fbid;
    if (recipientId) {
      // Yay, we found our recipient!
      // Let's forward our bot response to her.
      fbMessage(recipientId, message, (err, data) => {
        if (err) {
          console.log(
            'Oops! An error occurred while forwarding the response to',
            recipientId,
            ':',
            err
          );
        }

        // Let's give the wheel back to our bot
        cb();
      });
    } else {
      console.log('Oops! Couldn\'t find user for session:', sessionId);
      // Giving the wheel back to our bot
      cb();
    }
  },
  merge(sessionId, context, entities, message, cb) {
    cb(context);
  },
  error(sessionId, context, error) {
    console.log(error.message);
  },
  // You should implement your custom actions here
  // See https://wit.ai/docs/quickstart
};

const wit = new Wit(WIT_TOKEN, actions);

// Message handler
app.post('/webhook', (req, res) => {
  // Parsing the Messenger API response
  // Setting up our bot
//const wit = new Wit(WIT_TOKEN, actions);
  const messaging = getFirstMessagingEntry(req.body);
  if (messaging && messaging.message && messaging.message.text) {
    // Yay! We got a new message!

    // We retrieve the Facebook user ID of the sender
    const sender = messaging.sender.id;

    // We retrieve the user's current session, or create one if it doesn't exist
    // This is needed for our bot to figure out the conversation history
    const sessionId = findOrCreateSession(sender);

    // We retrieve the message content
    const msg = messaging.message.text;
    const atts = messaging.message.attachments;

    if (atts) {
      // We received an attachment

      // Let's reply with an automatic message
      fbMessage(
        sender,
        'Sorry I can only process text messages for now.'
      );
    } else if (msg) {
      // We received a text message

      // Let's forward the message to the Wit.ai Bot Engine
      // This will run all actions until our bot has nothing left to do
      wit.runActions(
        sessionId, // the user's current session
        msg, // the user's message
        sessions[sessionId].context, // the user's current session state
        (error, context) => {
          if (error) {
            console.log('Oops! Got an error from Wit:', error);
          } else {
            // Our bot did everything it has to do.
            // Now it's waiting for further messages to proceed.
            console.log('Waiting for futher messages.');

            // Based on the session state, you might want to reset the session.
            // This depends heavily on the business logic of your bot.
            // Example:
            // if (context['done']) {
            //   delete sessions[sessionId];
            // }

            // Updating the user's current session state
            sessions[sessionId].context = context;
          }
        }
      );
    }
  }
  res.sendStatus(200);
});
</code>```

答:
Please check your node_modules directory for node-wit package.

If node-wit is present then please require it before trying to create its instance.

```<code>const {Wit} = require('node-wit');

witHandler = new Wit({
      accessToken: accessToken
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to solve "Wit is not a constructor" error coming from Node.js while executing code given by node-wit and wit.ai documentation.

// Setting up our bot
const wit = new Wit(WIT_TOKEN, actions);

I tried all the ways by upgrading and downgrading npm/node versions, but no luck.

Update: Please find the index.js source I used,

Do I need to change anything in this?

module.exports = {
  Logger: require('./lib/logger.js').Logger,
  logLevels: require('./lib/logger.js').logLevels,
  Wit: require('./lib/wit.js').Wit,
}

'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
const Logger = require('node-wit').Logger;
const levels = require('node-wit').logLevels;
var app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 3000));

//const Wit = require('node-wit').Wit;
const WIT_TOKEN = process.env.WIT_TOKEN;
const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN;
const Wit = require('node-wit').Wit;

// Server frontpage
app.get('/', function (req, res) {
    debugger;
    res.send('This is TestBot Server');
});

// Messenger API specific code

// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference
const fbReq = request.defaults({
  uri: 'https://graph.facebook.com/me/messages',
  method: 'POST',
  json: true,
  qs: { access_token: FB_PAGE_TOKEN },
  headers: {'Content-Type': 'application/json'},
});

const fbMessage = (recipientId, msg, cb) => {
  const opts = {
    form: {
      recipient: {
        id: recipientId,
      },
      message: {
        text: msg,
      },
    },
  };
  fbReq(opts, (err, resp, data) => {
    if (cb) {
      cb(err || data.error && data.error.message, data);
    }
  });
};

// See the Webhook reference
// https://developers.facebook.com/docs/messenger-platform/webhook-reference
const getFirstMessagingEntry = (body) => {
  const val = body.object == 'page' &&
    body.entry &&
    Array.isArray(body.entry) &&
    body.entry.length > 0 &&
    body.entry[0] &&
    body.entry[0].id === FB_PAGE_ID &&
    body.entry[0].messaging &&
    Array.isArray(body.entry[0].messaging) &&
    body.entry[0].messaging.length > 0 &&
    body.entry[0].messaging[0]
  ;
  return val || null;
};

// Wit.ai bot specific code

// This will contain all user sessions.
// Each session has an entry:
// sessionId -> {fbid: facebookUserId, context: sessionState}
const sessions = {};

const findOrCreateSession = (fbid) => {
  var sessionId;
  // Let's see if we already have a session for the user fbid
  Object.keys(sessions).forEach(k => {
    if (sessions[k].fbid === fbid) {
      // Yep, got it!
      sessionId = k;
    }
  });
  if (!sessionId) {
    // No session found for user fbid, let's create a new one
    sessionId = new Date().toISOString();
    sessions[sessionId] = {fbid: fbid, context: {}};
  }
  return sessionId;
};

// Our bot actions
const actions = {
  say(sessionId, context, message, cb) {
    // Our bot has something to say!
    // Let's retrieve the Facebook user whose session belongs to
    const recipientId = sessions[sessionId].fbid;
    if (recipientId) {
      // Yay, we found our recipient!
      // Let's forward our bot response to her.
      fbMessage(recipientId, message, (err, data) => {
        if (err) {
          console.log(
            'Oops! An error occurred while forwarding the response to',
            recipientId,
            ':',
            err
          );
        }

        // Let's give the wheel back to our bot
        cb();
      });
    } else {
      console.log('Oops! Couldn\'t find user for session:', sessionId);
      // Giving the wheel back to our bot
      cb();
    }
  },
  merge(sessionId, context, entities, message, cb) {
    cb(context);
  },
  error(sessionId, context, error) {
    console.log(error.message);
  },
  // You should implement your custom actions here
  // See https://wit.ai/docs/quickstart
};

const wit = new Wit(WIT_TOKEN, actions);

// Message handler
app.post('/webhook', (req, res) => {
  // Parsing the Messenger API response
  // Setting up our bot
//const wit = new Wit(WIT_TOKEN, actions);
  const messaging = getFirstMessagingEntry(req.body);
  if (messaging && messaging.message && messaging.message.text) {
    // Yay! We got a new message!

    // We retrieve the Facebook user ID of the sender
    const sender = messaging.sender.id;

    // We retrieve the user's current session, or create one if it doesn't exist
    // This is needed for our bot to figure out the conversation history
    const sessionId = findOrCreateSession(sender);

    // We retrieve the message content
    const msg = messaging.message.text;
    const atts = messaging.message.attachments;

    if (atts) {
      // We received an attachment

      // Let's reply with an automatic message
      fbMessage(
        sender,
        'Sorry I can only process text messages for now.'
      );
    } else if (msg) {
      // We received a text message

      // Let's forward the message to the Wit.ai Bot Engine
      // This will run all actions until our bot has nothing left to do
      wit.runActions(
        sessionId, // the user's current session
        msg, // the user's message
        sessions[sessionId].context, // the user's current session state
        (error, context) => {
          if (error) {
            console.log('Oops! Got an error from Wit:', error);
          } else {
            // Our bot did everything it has to do.
            // Now it's waiting for further messages to proceed.
            console.log('Waiting for futher messages.');

            // Based on the session state, you might want to reset the session.
            // This depends heavily on the business logic of your bot.
            // Example:
            // if (context['done']) {
            //   delete sessions[sessionId];
            // }

            // Updating the user's current session state
            sessions[sessionId].context = context;
          }
        }
      );
    }
  }
  res.sendStatus(200);
});

Body:
Please check your node_modules directory for node-wit package.

If node-wit is present then please require it before trying to create its instance.

const {Wit} = require('node-wit');

witHandler = new Wit({
      accessToken: accessToken
});


问:
Not able to run .vbs file from jenkins which is having excel script
I’m new to Jenkins and now I'm doing basic level of execution. And I need your help resolve my issue. Issue Description: I’m trying to run the .VBS file by using jenkins and getting below error:

C:\Users\Amar\Desktop\Test_Sample.vbs(3, 2) Microsoft Excel: Microsoft Excel cannot access the file ‘C:\Users\Amar\Desktop\New.xlsx’.

There are several possible reasons:

The file name or path does not exist.

The file is being used by another program.

The workbook you are trying to save has the same name as a currently
open workbook.

I have not opened any excel file and path also correct.

please find below batch command : CScript “C:\Users\Amar\Desktop\Test_Sample.vbs”

And in Test_Sample.vbs file having:

```<code>Dim ExcelObj, WbookObj, mysheet
Set ExcelObj= CreateObject("excel.application")
Set WbookObj= ExcelObj.workbooks.open("C:\Users\Amar\Desktop\New.xlsx")
Set mysheet= ExcelObj.ActiveWorkbook.Worksheets("Sheet1")
ExcelObj.Visible = False
ExcelRowCount = mysheet.UsedRange.Rows.Count
For Iterator = 2 To ExcelRowCount
    ModuleName   =   Ucase(Trim(mysheet.Cells(Iterator,1)))
    ExecutionFlag = Ucase(Trim(mysheet.Cells(Iterator,2)))
    if (moduleName="Raj") Then
        Set qtApp = CreateObject("QuickTest.Application")
        If qtApp.launched True then
            qtApp.Launch
        End If
        qtApp.Visible = True
        qtApp.Open "F:\Jenkins_Jobs\OnCall_Sanity_Automation\DriverScript\Sample",  False
        Set QTPTest=qtApp.Test
        QTPTest.Run 'Run the Test QTPTest.Close
        qtApp.quit
        Set qtApp = Nothing
    else
        MsgBox "Name not exists"
    End If
Next
</code>```

Please help me to resolve the issue.

Thanks, Amar

Update

Console Output:

Building in workspace C:\Program Files
  (x86)\Jenkins\workspace\Excel_Test [Excel]

  $ cmd /c call C:\WINDOWS\TEMP\jenkin02.bat (C:\Program Files
  (x86)\Jenkins\workspace\Excel_Test>CScript )
  C:\Users\Admin\Desktop\Test_Sample.vbs"
  C:\Users\Admin\Desktop\Test_Sample.vbs(3, 2) Microsoft Excel:
  Microsoft Excel cannot access the file
  C:\Users\Admin\Desktop\New.xlsx.   There are several possible reasons:
  ** The file name or path does not exist.**   The file is being used by another program.   The workbook you are trying to save has the same
  name as a currently open workbook.

答:
If you are working on 64-bit Windows Operating System.

Then go to

```<code>C:\Windows\SysWOW64\config\systemProfile
</code>```

Above Folder and create an empty Folder, and name it "Desktop" inside "systemProfile".

For doing this, you need system admin access

After creating the folder as mentioned, then run your build in Jenkins.

Body:
I’m new to Jenkins and now I'm doing basic level of execution. And I need your help resolve my issue. Issue Description: I’m trying to run the .VBS file by using jenkins and getting below error:

C:\Users\Amar\Desktop\Test_Sample.vbs(3, 2) Microsoft Excel: Microsoft Excel cannot access the file ‘C:\Users\Amar\Desktop\New.xlsx’.

There are several possible reasons:

The file name or path does not exist.

The file is being used by another program.

The workbook you are trying to save has the same name as a currently
open workbook.

I have not opened any excel file and path also correct.

please find below batch command : CScript “C:\Users\Amar\Desktop\Test_Sample.vbs”

And in Test_Sample.vbs file having:

Dim ExcelObj, WbookObj, mysheet
Set ExcelObj= CreateObject("excel.application")
Set WbookObj= ExcelObj.workbooks.open("C:\Users\Amar\Desktop\New.xlsx")
Set mysheet= ExcelObj.ActiveWorkbook.Worksheets("Sheet1")
ExcelObj.Visible = False
ExcelRowCount = mysheet.UsedRange.Rows.Count
For Iterator = 2 To ExcelRowCount
    ModuleName   =   Ucase(Trim(mysheet.Cells(Iterator,1)))
    ExecutionFlag = Ucase(Trim(mysheet.Cells(Iterator,2)))
    if (moduleName="Raj") Then
        Set qtApp = CreateObject("QuickTest.Application")
        If qtApp.launched True then
            qtApp.Launch
        End If
        qtApp.Visible = True
        qtApp.Open "F:\Jenkins_Jobs\OnCall_Sanity_Automation\DriverScript\Sample",  False
        Set QTPTest=qtApp.Test
        QTPTest.Run 'Run the Test QTPTest.Close
        qtApp.quit
        Set qtApp = Nothing
    else
        MsgBox "Name not exists"
    End If
Next

Please help me to resolve the issue.

Thanks, Amar

Update

Console Output:

Building in workspace C:\Program Files
  (x86)\Jenkins\workspace\Excel_Test [Excel]

  $ cmd /c call C:\WINDOWS\TEMP\jenkin02.bat (C:\Program Files
  (x86)\Jenkins\workspace\Excel_Test>CScript )
  C:\Users\Admin\Desktop\Test_Sample.vbs"
  C:\Users\Admin\Desktop\Test_Sample.vbs(3, 2) Microsoft Excel:
  Microsoft Excel cannot access the file
  C:\Users\Admin\Desktop\New.xlsx.   There are several possible reasons:
  ** The file name or path does not exist.**   The file is being used by another program.   The workbook you are trying to save has the same
  name as a currently open workbook.

Body:
If you are working on 64-bit Windows Operating System.

Then go to

C:\Windows\SysWOW64\config\systemProfile

Above Folder and create an empty Folder, and name it "Desktop" inside "systemProfile".

For doing this, you need system admin access

After creating the folder as mentioned, then run your build in Jenkins.


问:
Spring maven - run specific tests (via annotations or maven profile)
Using a Spring maven context, I would like to run specific tests based on a maven profile. I would like to have an easy way of tagging the test groups. If possible I would like to use the annotations.
Which options are there, like maven command line parameters, maven profiles specification, etc.

Say I have the following tests:

Example:

```<code>// annotation("integration")
public class GeopointFormatterTest {
    @Test
    public void testIntegration1() {  ...  }
    @Test
    public void testIntegration2() {  ...  }
</code>```

Annotations like @Profile (which is for creating beans) and @ActiveProfile (which is for selecting specific profiles for creating beans) cannot be used for selecting tests, of course. All tests just run for statements like:

mvn clean install -Pdevelopment

mvn clean install -Pdevelopment -Dspring.profiles.active=acceptance

mvn clean install -Pdevelopment -Dspring.profiles.active=integration

As suggested, I used also @IfProfileValue. This is a good way for selecting tests based on system property values. System property values can be overruled by a CustomProfileValueSource class, like in: @ProfileValueSourceConfiguration(CustomProfileValueSource.class)

EDIT and ALTERNATIVE

The GREAT answers below focus on JUnit's @Category mechanism. Thanks to all!

A different approach is via these steps: [1] set a property within a maven profile and [2] use the property to skip tests via the  of the standard surefire test plugin.

[1] Setting the properties via a profile:

```<code><profiles>
    <profile>
        <id>integrationtests</id>
        <properties>
            <integration.skip>false</integration.skip>
            <acceptance.skip>true</acceptance.skip>
        </properties>
    </profile>
    ... other profiles
</code>```

[2] Using the properties in the surefire test plugin to skip tests.

```<code><build>
   <plugins>
      <plugin>
         <!-- Run the integration test-->
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>${surefire.plugin.version}</version>
         <configuration>
            <skipTests>${acceptance.skip}</skipTests>
</code>```

Start in maven: mvn clean install –Pintegrationtests

答:
Take a look at junit categories.

You'd tag your tests with specific category annotations

```<code>public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }

@Category(SlowTests.class)
public class A {
    @Test public void a() {}
}
</code>```

then form a suite like

```<code>@RunWith(Categories.class)
@IncludeCategory({FastTests.class})
@SuiteClasses({A.class, B.class})
public static class FastTestSuite {
     //
}
</code>```

And then run it with

```<code>mvn -Dtest=FastTestSuite test
</code>```

Note also that if you don't want to manually specify your unit test case classes in the suite class, you can also use the help of ClasspathSuite and then just limit based on categories.

Body:
Using a Spring maven context, I would like to run specific tests based on a maven profile. I would like to have an easy way of tagging the test groups. If possible I would like to use the annotations.
Which options are there, like maven command line parameters, maven profiles specification, etc.

Say I have the following tests:

Example:

// annotation("integration")
public class GeopointFormatterTest {
    @Test
    public void testIntegration1() {  ...  }
    @Test
    public void testIntegration2() {  ...  }

Annotations like @Profile (which is for creating beans) and @ActiveProfile (which is for selecting specific profiles for creating beans) cannot be used for selecting tests, of course. All tests just run for statements like:

mvn clean install -Pdevelopment

mvn clean install -Pdevelopment -Dspring.profiles.active=acceptance

mvn clean install -Pdevelopment -Dspring.profiles.active=integration

As suggested, I used also @IfProfileValue. This is a good way for selecting tests based on system property values. System property values can be overruled by a CustomProfileValueSource class, like in: @ProfileValueSourceConfiguration(CustomProfileValueSource.class)

EDIT and ALTERNATIVE

The GREAT answers below focus on JUnit's @Category mechanism. Thanks to all!

A different approach is via these steps: [1] set a property within a maven profile and [2] use the property to skip tests via the  of the standard surefire test plugin.

[1] Setting the properties via a profile:

<profiles>
    <profile>
        <id>integrationtests</id>
        <properties>
            <integration.skip>false</integration.skip>
            <acceptance.skip>true</acceptance.skip>
        </properties>
    </profile>
    ... other profiles

[2] Using the properties in the surefire test plugin to skip tests.

<build>
   <plugins>
      <plugin>

         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>${surefire.plugin.version}</version>
         <configuration>
            <skipTests>${acceptance.skip}</skipTests>

Start in maven: mvn clean install –Pintegrationtests

Body:
Take a look at junit categories.

You'd tag your tests with specific category annotations

public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }

@Category(SlowTests.class)
public class A {
    @Test public void a() {}
}

then form a suite like

@RunWith(Categories.class)
@IncludeCategory({FastTests.class})
@SuiteClasses({A.class, B.class})
public static class FastTestSuite {
     //
}

And then run it with

mvn -Dtest=FastTestSuite test

Note also that if you don't want to manually specify your unit test case classes in the suite class, you can also use the help of ClasspathSuite and then just limit based on categories.


问:
Android faster download of files with Multi thread
I'm working on an app that requires downloading of big video files (300-500MB).

I would like to know if there's a way to speed up the download of a single file using multi-threading.

I've saw this type of implementation on applications like TubeMate, but I clueless about the code used to achieve it.

I don't need you to code for me :) I just need a starting point, like an article or tutorial about this, tks.

答:
Video can be represented as byte array. If you want to load array faster you can divide it in parts and load every part in separate thread.
   The best way to do that is using ThreadPoolExecutor to run the task and FutureTask to retrieve results.
   In case you need to dawnload video from the internet, your server should support api calls that can give you  "part" of video.
Here is the good sample of how to use Executors and Futures: https://www.journaldev.com/1650/java-futuretask-example-program</p>


问:
Can a value from a JTextField be forced into the ValueModel (JGoodies)
I have this code:

```<code>this.trigger = new Trigger();
this.presentationModel = new PresentationModel(this.personBean, this.trigger);
final ValueModel firstNameAdapter = presentationModel.getBufferedModel("firstName");
final JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
</code>```

and

```<code>firstNameTextField.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            trigger.triggerCommit();
        }
    });
</code>```

So when I push the enter button on the JTextField, I expect the value in my ValueModel class to be the same as the value in my JTextField. This doesn't happen unless I click outside the JTextField, then back inside the JTextField, and then push enter. If I just type in the text and hit enter, the ValueModel does not get the updated value. I am stuck on this problem, can anybody help?

BTW, I used this link for figuring out JGoodies in the first place: JGoodies Tutorial

答:
I looked through the JGoodies API (should have done this sooner) and found an unexpected static call, Bindings.commitImmediately()

If I call this method before my call to trigger.triggerCommit(), everything works as expected :)

Body:
I have this code:

this.trigger = new Trigger();
this.presentationModel = new PresentationModel(this.personBean, this.trigger);
final ValueModel firstNameAdapter = presentationModel.getBufferedModel("firstName");
final JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);

and

firstNameTextField.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            trigger.triggerCommit();
        }
    });

So when I push the enter button on the JTextField, I expect the value in my ValueModel class to be the same as the value in my JTextField. This doesn't happen unless I click outside the JTextField, then back inside the JTextField, and then push enter. If I just type in the text and hit enter, the ValueModel does not get the updated value. I am stuck on this problem, can anybody help?

BTW, I used this link for figuring out JGoodies in the first place: JGoodies Tutorial


问:
how to use CircularProgressBar in C# winform
I need a function to show a progress ring in dialog when query data in a database, the traditional progress bar is not good for me because I don't know exactly how long the waiting time will last.
So I installed CircularProgressBar from Nuget to show the progress ring.
but there is no example code, I don't know how to use it.
Did anyone use this control before?
my questions are:
1. how can I drag this control to a toolbox, now I cannot see this CircularProgressBar control in the toolbox of visual studio 2015 even though I already see this reference in a project;
2. how to invoke it or write some show/close code to show it and close it when I need it in a dialog.
thanks,</p>

答:
you can look at this article. the sample code in that article is :

```<code>#region Includes
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Text;
using System.Windows.Forms;
#endregion

#region CircularProgressBar

public class CircularProgressBar : Control
{

    #region Enums

    public enum _ProgressShape
    {
        Round,
        Flat
    }

    #endregion
    #region Variables

    private long _Value;
    private long _Maximum = 100;
    private Color _ProgressColor1 = Color.FromArgb(92, 92, 92);
    private Color _ProgressColor2 = Color.FromArgb(92, 92, 92);
    private _ProgressShape ProgressShapeVal;

    #endregion
    #region Custom Properties

    public long Value
    {
        get { return _Value; }
        set
        {
            if (value > _Maximum)
                value = _Maximum;
            _Value = value;
            Invalidate();
        }
    }

    public long Maximum
    {
        get { return _Maximum; }
        set
        {
            if (value < 1)
                value = 1;
            _Maximum = value;
            Invalidate();
        }
    }

    public Color ProgressColor1
    {
        get { return _ProgressColor1; }
        set
        {
            _ProgressColor1 = value;
            Invalidate();
        }
    }

    public Color ProgressColor2
    {
        get { return _ProgressColor2; }
        set
        {
            _ProgressColor2 = value;
            Invalidate();
        }
    }

    public _ProgressShape ProgressShape
    {
        get { return ProgressShapeVal; }
        set
        {
            ProgressShapeVal = value;
            Invalidate();
        }
    }

    #endregion
    #region EventArgs

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        SetStandardSize();
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        SetStandardSize();
    }

    protected override void OnPaintBackground(PaintEventArgs p)
    {
        base.OnPaintBackground(p);
    }

    #endregion

    public CircularProgressBar()
    {
        Size = new Size(130, 130);
        Font = new Font("Segoe UI", 15);
        MinimumSize = new Size(100, 100);
        DoubleBuffered = true;
    }

    private void SetStandardSize()
    {
        int _Size = Math.Max(Width, Height);
        Size = new Size(_Size, _Size);
    }

    public void Increment(int Val)
    {
        this._Value += Val;
        Invalidate();
    }

    public void Decrement(int Val)
    {
        this._Value -= Val;
        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (Bitmap bitmap = new Bitmap(this.Width, this.Height))
        {
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.Clear(this.BackColor);
                using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle, this._ProgressColor1, this._ProgressColor2, LinearGradientMode.ForwardDiagonal))
                {
                    using (Pen pen = new Pen(brush, 14f))
                    {
                        switch (this.ProgressShapeVal)
                        {
                            case _ProgressShape.Round:
                                pen.StartCap = LineCap.Round;
                                pen.EndCap = LineCap.Round;
                                break;

                            case _ProgressShape.Flat:
                                pen.StartCap = LineCap.Flat;
                                pen.EndCap = LineCap.Flat;
                                break;
                        }
                        graphics.DrawArc(pen, 0x12, 0x12, (this.Width - 0x23) - 2, (this.Height - 0x23) - 2, -90, (int)Math.Round((double)((360.0 / ((double)this._Maximum)) * this._Value)));
                    }
                }
                using (LinearGradientBrush brush2 = new LinearGradientBrush(this.ClientRectangle, Color.FromArgb(0x34, 0x34, 0x34), Color.FromArgb(0x34, 0x34, 0x34), LinearGradientMode.Vertical))
                {
                    graphics.FillEllipse(brush2, 0x18, 0x18, (this.Width - 0x30) - 1, (this.Height - 0x30) - 1);
                }
                SizeF MS = graphics.MeasureString(Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value)), Font);
                graphics.DrawString(Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value)), Font, Brushes.White, Convert.ToInt32(Width / 2 - MS.Width / 2), Convert.ToInt32(Height / 2 - MS.Height / 2));
                e.Graphics.DrawImage(bitmap, 0, 0);
                graphics.Dispose();
                bitmap.Dispose();
            }
        }
    }
}

#endregion
</code>```

then you can Use this control any where you want to show progressbar.
UPDATE

How to Use:

Open your application where you want to use Circular Progress Bar.

Select & Drop CircularProgressBar.cs file on your project in solution explorer.

Just Compile your application & you will see a circularprogressbar option in your toolbox.

4. Use & give values to it like you give to the default progress bar. It will works.

Body:
you can look at this article. the sample code in that article is :

#region Includes
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Text;
using System.Windows.Forms;
#endregion

#region CircularProgressBar

public class CircularProgressBar : Control
{

    #region Enums

    public enum _ProgressShape
    {
        Round,
        Flat
    }

    #endregion
    #region Variables

    private long _Value;
    private long _Maximum = 100;
    private Color _ProgressColor1 = Color.FromArgb(92, 92, 92);
    private Color _ProgressColor2 = Color.FromArgb(92, 92, 92);
    private _ProgressShape ProgressShapeVal;

    #endregion
    #region Custom Properties

    public long Value
    {
        get { return _Value; }
        set
        {
            if (value > _Maximum)
                value = _Maximum;
            _Value = value;
            Invalidate();
        }
    }

    public long Maximum
    {
        get { return _Maximum; }
        set
        {
            if (value < 1)
                value = 1;
            _Maximum = value;
            Invalidate();
        }
    }

    public Color ProgressColor1
    {
        get { return _ProgressColor1; }
        set
        {
            _ProgressColor1 = value;
            Invalidate();
        }
    }

    public Color ProgressColor2
    {
        get { return _ProgressColor2; }
        set
        {
            _ProgressColor2 = value;
            Invalidate();
        }
    }

    public _ProgressShape ProgressShape
    {
        get { return ProgressShapeVal; }
        set
        {
            ProgressShapeVal = value;
            Invalidate();
        }
    }

    #endregion
    #region EventArgs

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        SetStandardSize();
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        SetStandardSize();
    }

    protected override void OnPaintBackground(PaintEventArgs p)
    {
        base.OnPaintBackground(p);
    }

    #endregion

    public CircularProgressBar()
    {
        Size = new Size(130, 130);
        Font = new Font("Segoe UI", 15);
        MinimumSize = new Size(100, 100);
        DoubleBuffered = true;
    }

    private void SetStandardSize()
    {
        int _Size = Math.Max(Width, Height);
        Size = new Size(_Size, _Size);
    }

    public void Increment(int Val)
    {
        this._Value += Val;
        Invalidate();
    }

    public void Decrement(int Val)
    {
        this._Value -= Val;
        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (Bitmap bitmap = new Bitmap(this.Width, this.Height))
        {
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.Clear(this.BackColor);
                using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle, this._ProgressColor1, this._ProgressColor2, LinearGradientMode.ForwardDiagonal))
                {
                    using (Pen pen = new Pen(brush, 14f))
                    {
                        switch (this.ProgressShapeVal)
                        {
                            case _ProgressShape.Round:
                                pen.StartCap = LineCap.Round;
                                pen.EndCap = LineCap.Round;
                                break;

                            case _ProgressShape.Flat:
                                pen.StartCap = LineCap.Flat;
                                pen.EndCap = LineCap.Flat;
                                break;
                        }
                        graphics.DrawArc(pen, 0x12, 0x12, (this.Width - 0x23) - 2, (this.Height - 0x23) - 2, -90, (int)Math.Round((double)((360.0 / ((double)this._Maximum)) * this._Value)));
                    }
                }
                using (LinearGradientBrush brush2 = new LinearGradientBrush(this.ClientRectangle, Color.FromArgb(0x34, 0x34, 0x34), Color.FromArgb(0x34, 0x34, 0x34), LinearGradientMode.Vertical))
                {
                    graphics.FillEllipse(brush2, 0x18, 0x18, (this.Width - 0x30) - 1, (this.Height - 0x30) - 1);
                }
                SizeF MS = graphics.MeasureString(Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value)), Font);
                graphics.DrawString(Convert.ToString(Convert.ToInt32((100 / _Maximum) * _Value)), Font, Brushes.White, Convert.ToInt32(Width / 2 - MS.Width / 2), Convert.ToInt32(Height / 2 - MS.Height / 2));
                e.Graphics.DrawImage(bitmap, 0, 0);
                graphics.Dispose();
                bitmap.Dispose();
            }
        }
    }
}

#endregion

then you can Use this control any where you want to show progressbar.
UPDATE

How to Use:

Open your application where you want to use Circular Progress Bar.

Select & Drop CircularProgressBar.cs file on your project in solution explorer.

Just Compile your application & you will see a circularprogressbar option in your toolbox.

4. Use & give values to it like you give to the default progress bar. It will works.


问:
odoo interface display incorrectly
I have starting to learn odoo recently and using odoo:10.0. but I have a problem with odoo interface where it display almost nothing at all. Here are my screenshots :

My odoo before sign in:

My odoo after sign in:

答:
I managed myself to fix the problem.
My problem is that there is an error in js where this line:

```<code>odoo.define('web.csrt', function(required) {
 var token = " some_long_number";
 required('web.core').csrt_token = token;
 required('qweb').default_dict.csrt_token = token;
}
</code>```

Uncaught ReferencesError: odoo is not defined

First I install odoo to another device, then I access my localhost:8069 with that device by using local IP (192.168.x.x:8069)

After the the website in that device loads correctly, my original device starts to display correctly.

Title: odoo interface display incorrectly

Body:
I managed myself to fix the problem.
My problem is that there is an error in js where this line:

odoo.define('web.csrt', function(required) {
 var token = " some_long_number";
 required('web.core').csrt_token = token;
 required('qweb').default_dict.csrt_token = token;
}

Uncaught ReferencesError: odoo is not defined

First I install odoo to another device, then I access my localhost:8069 with that device by using local IP (192.168.x.x:8069)

After the the website in that device loads correctly, my original device starts to display correctly.


问:
Angular UI router doesn't process the resolve function when i use async/await feature?
I've been trying to render certain template related to a state and component according to this article

In my project running under dev-server it all works fine and when I execute $state.go("home") the component template is loaded how I expect but when I do this in a testing environment, this doesn't work.

Before, in testing, when I use the "old way" using "template" instead "component" with ui-router, execute $rootScope.$digest() was enough for add the template inside the

 but using this new way this doesn't work anymore.

What am I doing wrong?

Edit: I've been trying to deeply understand the problem and I see that the problem is related to the HTTP request that was done. Maybe it's related to the way that my promise resolves on the resolve callback using async/await. Please check the Service:

Service

export class TodoService {
    constructor($http, BASE_URL) {
        this.http = $http;
        this.url = `${BASE_URL}/todos`
    }
    async getTodos() {
        const apiResponse = await this.http.get(this.url)
        return apiResponse.data.todos
    }
}```
</div>
</div>
</p>

<p><strong>Router</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import '@uirouter/angularjs'

export function routes($stateProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false,
        rewriteLinks: true,
    })

    $stateProvider
        .state("home", {
            url: "/",
            component: "todoList",
            resolve: {
                todosList: TodoService => TodoService.getTodos()
            }
        })
}</code>```

Test

import { routes } from "routes"
import { TodoListComponent } from "components/todoList.component"
import { TodoService } from "services/todo.service"

describe("TodoListComponent rendering and interaction on '/' base path", () => {
    let componentDOMelement
    let stateService

    beforeAll(() => {
        angular
            .module("Test", [
                "ui.router"
            ])
            .config(routes)
            .constant("BASE_URL", "http://localhost:5000/api")
            .component("todoList", TodoListComponent)
            .service("TodoService", TodoService)
            //I enable this for better logs about the problem
            .run(['$rootScope','$trace', function($rootScope, $trace) {
               $trace.enable("TRANSITION")
             }])
    })
    beforeEach(angular.mock.module("Test"))

    beforeEach(inject(($rootScope, $compile, $state, $httpBackend) => {
        //build the scene
        //1st render the root element of scene: We needs a router view for load the base path
        let scope = $rootScope.$new()
        componentDOMelement = angular.element("

")

        $compile(componentDOMelement)(scope)
        scope.$digest()

         document.body.appendChild(componentDOMelement[0]) //This is a hack for jsdom before the $rootScope.$digest() call
        //2nd let's create a fake server for intercept the http requests and fake the responses
        const todosResponse = require(`${__dirname}/../../stubs/todos_get.json`)
        $httpBackend
            .whenGET(/.+\/todos/)
            .respond((method, url, data, headers, params) => {
                return [200, todosResponse]
            })

        //3rd Let's generate the basic scenario: Go at home state ("/" path)
        $state.go("home")
        $rootScope.$digest()
        $httpBackend.flush()
    }))

    it("Should be render a list", () => {
        console.log("HTML rendered")
        console.log(document.querySelectorAll("html")[0].outerHTML)
    })
})```
</div>
</div>
</p>

<p>The HTML result that not rendering</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code><html>
<head>
<style type="text/css">
@charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate) {
  display:none !important;
}
ng\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{
  position:absolute;
}
</style>
</head>
<body><!-- uiView: -->
</body>
</html></code>```

Also, I traced the stateChange before the HTML:

```<code>console.log node_modules/@uirouter/core/_bundles/ui-router-core.js:1276
    Transition #0-0: Started  -> "Transition#0( ''{} -> 'home'{} )"

console.log node_modules/@uirouter/core/_bundles/ui-router-core.js:1282
    Transition #1-0: Ignored  <> "Transition#1( ''{} -> 'home'{} )"

console.log node_modules/@uirouter/core/_bundles/ui-router-core.js:1313
    Transition #1-0: <- Rejected "Transition#1( ''{} -> 'home'{} )", reason: Transition Rejection($id: 0 type: 5, message: The transition was ignored, detail: "undefined")
</code>```

I see a problem in a transition but no reason was given.

========================================================================

Edit 2
Finally we found the problem but I can't figure out the real problem. I created a branch in my project for showing the problem. This it's related to async/await javascript feature:

```<code>export class TodoService {
    constructor($http, BASE_URL) {
        this.http = $http;
        this.url = `${BASE_URL}/todos`
    }
    //Interchange the comment on the getTodos method and run `npm run tdd` for see the problem:
    //When async/await doesn't used, the html associated to the resolve in the
    // "/" route that used this service, the promise was resolved that expected.
    //The idea for this branch it's research about the problem and propose a way
    //for we can use async/await on the production code and on the testing environment
    async getTodos() {
        const apiResponse = await this.http.get(this.url)
        return apiResponse.data.todos
    }
    // getTodos() {
    //     return this.http.get(this.url).then(res => res.data.todos)
    // }
}
</code>```

The repository

So my new Questions are:

Why the way that I use the async/await functionality it's not compatible with the ui-router resolve on testing environment but in production code it works?

Maybe it's related to $httpBackend.flush() call?

Edit 3
The issue 3522 reported in angular UI router repository

答:
The issue is that angular expects an angular Promise that's why your then will work but your await won't, you can solve this by using a library like: https://www.npmjs.com/package/angular-async-await or make a construction like they're demonstrating here https://medium.com/@alSkachkov/using-async-await-function-in-angular-1-5-babel-6-387f7c43948c

Good luck with your problem!

Body:
I've been trying to render certain template related to a state and component according to this article

In my project running under dev-server it all works fine and when I execute $state.go("home") the component template is loaded how I expect but when I do this in a testing environment, this doesn't work.

Before, in testing, when I use the "old way" using "template" instead "component" with ui-router, execute $rootScope.$digest() was enough for add the template inside the

 but using this new way this doesn't work anymore.

What am I doing wrong?

Edit: I've been trying to deeply understand the problem and I see that the problem is related to the HTTP request that was done. Maybe it's related to the way that my promise resolves on the resolve callback using async/await. Please check the Service:

Service

export class TodoService {
    constructor($http, BASE_URL) {
        this.http = $http;
        this.url = `${BASE_URL}/todos`
    }
    async getTodos() {
        const apiResponse = await this.http.get(this.url)
        return apiResponse.data.todos
    }
}

Router

import '@uirouter/angularjs'

export function routes($stateProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false,
        rewriteLinks: true,
    })

    $stateProvider
        .state("home", {
            url: "/",
            component: "todoList",
            resolve: {
                todosList: TodoService => TodoService.getTodos()
            }
        })
}

Test

import { routes } from "routes"
import { TodoListComponent } from "components/todoList.component"
import { TodoService } from "services/todo.service"

describe("TodoListComponent rendering and interaction on '/' base path", () => {
    let componentDOMelement
    let stateService

    beforeAll(() => {
        angular
            .module("Test", [
                "ui.router"
            ])
            .config(routes)
            .constant("BASE_URL", "http://localhost:5000/api")
            .component("todoList", TodoListComponent)
            .service("TodoService", TodoService)
            //I enable this for better logs about the problem
            .run(['$rootScope','$trace', function($rootScope, $trace) {
               $trace.enable("TRANSITION")
             }])
    })
    beforeEach(angular.mock.module("Test"))

    beforeEach(inject(($rootScope, $compile, $state, $httpBackend) => {
        //build the scene
        //1st render the root element of scene: We needs a router view for load the base path
        let scope = $rootScope.$new()
        componentDOMelement = angular.element("

")

        $compile(componentDOMelement)(scope)
        scope.$digest()

         document.body.appendChild(componentDOMelement[0]) //This is a hack for jsdom before the $rootScope.$digest() call
        //2nd let's create a fake server for intercept the http requests and fake the responses
        const todosResponse = require(`${__dirname}/../../stubs/todos_get.json`)
        $httpBackend
            .whenGET(/.+\/todos/)
            .respond((method, url, data, headers, params) => {
                return [200, todosResponse]
            })

        //3rd Let's generate the basic scenario: Go at home state ("/" path)
        $state.go("home")
        $rootScope.$digest()
        $httpBackend.flush()
    }))

    it("Should be render a list", () => {
        console.log("HTML rendered")
        console.log(document.querySelectorAll("html")[0].outerHTML)
    })
})

The HTML result that not rendering

Also, I traced the stateChange before the HTML:

console.log node_modules/@uirouter/core/_bundles/ui-router-core.js:1276
    Transition #0-0: Started  -> "Transition#0( ''{} -> 'home'{} )"

console.log node_modules/@uirouter/core/_bundles/ui-router-core.js:1282
    Transition #1-0: Ignored  <> "Transition#1( ''{} -> 'home'{} )"

console.log node_modules/@uirouter/core/_bundles/ui-router-core.js:1313
    Transition #1-0: <- Rejected "Transition#1( ''{} -> 'home'{} )", reason: Transition Rejection($id: 0 type: 5, message: The transition was ignored, detail: "undefined")

I see a problem in a transition but no reason was given.

========================================================================

Edit 2
Finally we found the problem but I can't figure out the real problem. I created a branch in my project for showing the problem. This it's related to async/await javascript feature:

export class TodoService {
    constructor($http, BASE_URL) {
        this.http = $http;
        this.url = `${BASE_URL}/todos`
    }
    //Interchange the comment on the getTodos method and run `npm run tdd` for see the problem:
    //When async/await doesn't used, the html associated to the resolve in the
    // "/" route that used this service, the promise was resolved that expected.
    //The idea for this branch it's research about the problem and propose a way
    //for we can use async/await on the production code and on the testing environment
    async getTodos() {
        const apiResponse = await this.http.get(this.url)
        return apiResponse.data.todos
    }
    // getTodos() {
    //     return this.http.get(this.url).then(res => res.data.todos)
    // }
}

The repository

So my new Questions are:

Why the way that I use the async/await functionality it's not compatible with the ui-router resolve on testing environment but in production code it works?

Maybe it's related to $httpBackend.flush() call?

Edit 3
The issue 3522 reported in angular UI router repository


问:
SSRS Conditional Summing
I have an SSRS report that displays several pages of rows.  In each row is a "TYPE" field.  In that TYPE field there is either an "M" for the value or a "P" for the value.  At the end of the report I want to summ up all the price values for the "P" TYPES.  I tried this but it prioduced an #Error:

```<code>=Sum(iif(Fields!TYPE.Value = "P",Fields!EXT_QTY.Value * Fields!PRICE.Value ,0))
</code>```

this summed all rows

```<code>=iif(Fields!PART_TYPE.Value = "P" ,  Sum(Fields!EXT_QTY.Value * Fields!PRICE.Value ),  0 )
</code>```

I'm sure this is do-able.  Any ideas?  Thanks

答:
Found the answer....</p>

```<code>=SUM(IIF(Fields!PART_TYPE.Value ="P",CDbl(Fields!EXT_QTY.Value * Fields!PRICE.Value), CDbl(0.0)))
</code>```

Title: SSRS Conditional Summing

Body:
I have an SSRS report that displays several pages of rows.  In each row is a "TYPE" field.  In that TYPE field there is either an "M" for the value or a "P" for the value.  At the end of the report I want to summ up all the price values for the "P" TYPES.  I tried this but it prioduced an #Error:

=Sum(iif(Fields!TYPE.Value = "P",Fields!EXT_QTY.Value * Fields!PRICE.Value ,0))

this summed all rows

=iif(Fields!PART_TYPE.Value = "P" ,  Sum(Fields!EXT_QTY.Value * Fields!PRICE.Value ),  0 )

I'm sure this is do-able.  Any ideas?  Thanks

Body:
Found the answer....

=SUM(IIF(Fields!PART_TYPE.Value ="P",CDbl(Fields!EXT_QTY.Value * Fields!PRICE.Value), CDbl(0.0)))


问:
looping tableview cell label text from an array
I have an array :

```<code>let BRIArray = ["ATM BRI", "Internet Banking BRI"]
</code>```

and then I count it at cellForRowAt:

```<code>let BRIArrayCount = BRIArray.count
</code>```

and then I loop it :

```<code>for i in 0 ..< BRIArrayCount {
                print (i) //i will increment up one with each iteration of the for loop
                cell.lblBankPayment.text = "\(BRIArray[i])"
                print("BRIArray: \(BRIArray[i])")
            }
</code>```

But the result just get last string and loop it like image below:

How to correct the loop inside cellForRowAt to show all array string in cell label text?

答:
No need to use loop
instead of loop
just use

cell.lblBankPayment.text = "(BRIArray[indexPath.row])"

if you want all the text in single label concat string in loop then set it

let str = "(str)(" ")(BRIArray[index])"

Body:
I have an array :

let BRIArray = ["ATM BRI", "Internet Banking BRI"]

and then I count it at cellForRowAt:

let BRIArrayCount = BRIArray.count

and then I loop it :

for i in 0 ..< BRIArrayCount {
                print (i) //i will increment up one with each iteration of the for loop
                cell.lblBankPayment.text = "\(BRIArray[i])"
                print("BRIArray: \(BRIArray[i])")
            }

But the result just get last string and loop it like image below:

How to correct the loop inside cellForRowAt to show all array string in cell label text?


问:
Is there an API for the Google Answer Boxes?
The Google Answer Boxes (sometimes called Featured Snippets, Knowledge Cards, or Live Results) are extremely helpful. I'd like to extract the information and use it in my own program. Looking at the HTML code, it's not quite so straight forward as pulling it from there. I've done quite a bit of research, but I can't seem to find any support for them. Does anyone know if there is an API (or part of the Web Search API) where you can retrieve the information returned from the Answer Box?

I saw the answer here:
google api for glorious info box?
, but the solution presented was deprecated last month.

Just for an example, this is the HTML code for "What is the time in japan":

```<code><!--m--><div data-hveid="30">
<div class="vk_c vk_gy vk_sh card-section _MZc">
<div class="vk_bk vk_ans">6:37 AM</div>
<div class="vk_gy vk_sh"> Tuesday, <span class="_Hq">August 4, 2015</span>
<span class="_Hq"> (GMT+9) </span>
</div> <span class="vk_gy vk_sh">  Time in Japan  </span>
</code>```

Which is VERY different from "where is tokyo located":

```<code><!--m-->
<div class="_uX kno-fb-ctx" aria-level="3" role="heading" data-hveid="41" data-ved="0CCkQtwcoATACahUKEwiLjemg8I3HAhUTKYgKHU7jCho">
<div class="_eF" data-tts="answers" data-tts-text="Japan">Japan</div>
<div class="_Tfc">
</div></div>
<!--n-->
</li><li class="mod" data-md="61" style="clear:none">
<!--m-->
<div class="_oDd" data-hveid="42">
<span class="_Tgc _y9e">Tokyo consists of the southwestern part of the Kanto region, the <b>Izu Islands</b>, and the <b>Ogasawara Islands</b>. Tokyo is the capital of <b>Japan</b>, and the place where over 13 million people live, making it one of the most populous cities in the world.</span></div>
</code>```

I essentially need to extract "6:37 AM" from the first and "Japan" from the second, but performing a dynamic string search would be difficult as they are in very different formats.

答:
A bit late, but here is a working solution in 2017 that uses Python and Selenium (with the headless chromedriver) to extract the "primary" text from the answer box, based on the fact that the formatting of the search page and answer box is reasonably consistent across different types of queries (though I haven't tested this exhaustively). Of course, the element coordinates may change depending on resolution/window size, but adjusting for that is easy enough.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--window-size=1024x768")
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)

def ask_google(query):

    # Search for query
    query = query.replace(' ', '+')

    driver.get('http://www.google.com/search?q=' + query)

    # Get text from Google answer box

    answer = driver.execute_script(
            "return document.elementFromPoint(arguments[0], arguments[1]);",
            350, 230).text

    return answer
</code>```

And testing this approach with your queries (or close to them) produces:

```<code>ask_google("what is the time in Japan")

"4:36 PM"

ask_google("where is tokyo located in japan")

"Situated on the Kanto Plain, Tokyo is one of three large cities, the other two being Yokohama and Kawasaki, located along the northwestern shore of Tokyo Bay, an inlet of the Pacific Ocean on east-central Honshu, the largest of the islands of Japan."
</code>```

Body:
The Google Answer Boxes (sometimes called Featured Snippets, Knowledge Cards, or Live Results) are extremely helpful. I'd like to extract the information and use it in my own program. Looking at the HTML code, it's not quite so straight forward as pulling it from there. I've done quite a bit of research, but I can't seem to find any support for them. Does anyone know if there is an API (or part of the Web Search API) where you can retrieve the information returned from the Answer Box?

I saw the answer here:
google api for glorious info box?
, but the solution presented was deprecated last month.

Just for an example, this is the HTML code for "What is the time in japan":

6:37 AM

 Tuesday, August 4, 2015
 (GMT+9)

   Time in Japan

Which is VERY different from "where is tokyo located":

Japan

Tokyo consists of the southwestern part of the Kanto region, the Izu Islands, and the Ogasawara Islands. Tokyo is the capital of Japan, and the place where over 13 million people live, making it one of the most populous cities in the world.

I essentially need to extract "6:37 AM" from the first and "Japan" from the second, but performing a dynamic string search would be difficult as they are in very different formats.

Body:
A bit late, but here is a working solution in 2017 that uses Python and Selenium (with the headless chromedriver) to extract the "primary" text from the answer box, based on the fact that the formatting of the search page and answer box is reasonably consistent across different types of queries (though I haven't tested this exhaustively). Of course, the element coordinates may change depending on resolution/window size, but adjusting for that is easy enough.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--window-size=1024x768")
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)

def ask_google(query):

    # Search for query
    query = query.replace(' ', '+')

    driver.get('http://www.google.com/search?q=' + query)

    # Get text from Google answer box

    answer = driver.execute_script(
            "return document.elementFromPoint(arguments[0], arguments[1]);",
            350, 230).text

    return answer

And testing this approach with your queries (or close to them) produces:

ask_google("what is the time in Japan")

"4:36 PM"

ask_google("where is tokyo located in japan")

"Situated on the Kanto Plain, Tokyo is one of three large cities, the other two being Yokohama and Kawasaki, located along the northwestern shore of Tokyo Bay, an inlet of the Pacific Ocean on east-central Honshu, the largest of the islands of Japan."

ContentLicense: CC BY-SA 4.0


问:
trouble with two locations in nginx config
I have 2 links: myserver.org and myserver.org/support
I need first link follow to /var/www/myserver.org and second to /var/www/support
My config now:
first file & link

```<code>server {
    listen 80 default_server;

    server_name groupmanager.org;
    charset utf-8;

    root /var/www/groupmanager.org;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    access_log /var/log/nginx/groupmanager.org_access.log;
    error_log /var/log/nginx/groupmanager.org_error.log;

    include /etc/nginx/templates/php-fpm.conf;
}

server {
  listen 80;

  server_name www.groupmanager.org;
  rewrite ^(.*) http://groupmanager.org$1 permanent;
}
</code>```

Second file & link:

```<code>server {
  listen 80;

  server_name 163.172.88.31/support;
  charset utf-8;

  root /var/www/support;
  index index.php;

  access_log /var/log/nginx/support_access.log;
  error_log /var/log/nginx/support_error.log;

  include /etc/nginx/templates/php-fpm.conf;
}

server {

  listen 80;

  server_name www.163.172.88.31/support;
  rewrite ^(.*) http://163.172.88.31/support$1 permanent;
}
</code>```

php-fpm.conf

```<code>location ~ \.php$ {
   try_files $uri =404;
   fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location ~ /\.ht {
   deny all;
}

location ~* \.(gif|jpeg|jpg|txt|png|tif|tiff|ico|jng|bmp|doc|pdf|rtf|xls|ppt|rar|rpm|swf|zip|bin|exe|dll|deb|cur)$ {
  expires 168h;
}

location ~* \.(css|js)$ {
  expires 180m;
}
</code>```

First link works fine, second - no. I see '403 Forbidden'
What is not rigth?
Permissions for folders are the same, I think, they are right.

答:
This works:

groupmanager.org.conf

```<code>server {
    listen 80 default_server;

    server_name groupmanager.org;
    charset utf-8;

    root /var/www/groupmanager.org;
    index index.php;

    location /support/ {
        alias /var/www/support/;
        index index.php;

        access_log /var/log/nginx/support_access.log;
        error_log /var/log/nginx/support_error.log;

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME  /var/www/$fastcgi_script_name;
        }
    }

    access_log /var/log/nginx/groupmanager.org_access.log;
    error_log /var/log/nginx/groupmanager.org_error.log;

    include /etc/nginx/templates/php-fpm.conf;
}

server {
  listen 80;

  server_name www.groupmanager.org;
  rewrite ^(.*) http://groupmanager.org$1 permanent;
}
</code>```

php-fpm.conf

```<code>location ~ \.php$ {
   try_files $uri =404;
   fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location ~ /\.ht {
   deny all;
}

location ~* \.(gif|jpeg|jpg|txt|png|tif|tiff|ico|jng|bmp|doc|pdf|rtf|xls|ppt|rar|rpm|swf|zip|bin|exe|dll|deb|cur)$ {
  expires 168h;
}

location ~* \.(css|js)$ {
  expires 180m;
}
</code>```

Body:
I have 2 links: myserver.org and myserver.org/support
I need first link follow to /var/www/myserver.org and second to /var/www/support
My config now:
first file & link

server {
    listen 80 default_server;

    server_name groupmanager.org;
    charset utf-8;

    root /var/www/groupmanager.org;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    access_log /var/log/nginx/groupmanager.org_access.log;
    error_log /var/log/nginx/groupmanager.org_error.log;

    include /etc/nginx/templates/php-fpm.conf;
}

server {
  listen 80;

  server_name www.groupmanager.org;
  rewrite ^(.*) http://groupmanager.org$1 permanent;
}

Second file & link:

server {
  listen 80;

  server_name 163.172.88.31/support;
  charset utf-8;

  root /var/www/support;
  index index.php;

  access_log /var/log/nginx/support_access.log;
  error_log /var/log/nginx/support_error.log;

  include /etc/nginx/templates/php-fpm.conf;
}

server {

  listen 80;

  server_name www.163.172.88.31/support;
  rewrite ^(.*) http://163.172.88.31/support$1 permanent;
}

php-fpm.conf

location ~ \.php$ {
   try_files $uri =404;
   fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location ~ /\.ht {
   deny all;
}

location ~* \.(gif|jpeg|jpg|txt|png|tif|tiff|ico|jng|bmp|doc|pdf|rtf|xls|ppt|rar|rpm|swf|zip|bin|exe|dll|deb|cur)$ {
  expires 168h;
}

location ~* \.(css|js)$ {
  expires 180m;
}

First link works fine, second - no. I see '403 Forbidden'
What is not rigth?
Permissions for folders are the same, I think, they are right.

Body:
This works:

groupmanager.org.conf

server {
    listen 80 default_server;

    server_name groupmanager.org;
    charset utf-8;

    root /var/www/groupmanager.org;
    index index.php;

    location /support/ {
        alias /var/www/support/;
        index index.php;

        access_log /var/log/nginx/support_access.log;
        error_log /var/log/nginx/support_error.log;

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME  /var/www/$fastcgi_script_name;
        }
    }

    access_log /var/log/nginx/groupmanager.org_access.log;
    error_log /var/log/nginx/groupmanager.org_error.log;

    include /etc/nginx/templates/php-fpm.conf;
}

server {
  listen 80;

  server_name www.groupmanager.org;
  rewrite ^(.*) http://groupmanager.org$1 permanent;
}

php-fpm.conf

location ~ \.php$ {
   try_files $uri =404;
   fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location ~ /\.ht {
   deny all;
}

location ~* \.(gif|jpeg|jpg|txt|png|tif|tiff|ico|jng|bmp|doc|pdf|rtf|xls|ppt|rar|rpm|swf|zip|bin|exe|dll|deb|cur)$ {
  expires 168h;
}

location ~* \.(css|js)$ {
  expires 180m;
}


问:
Can I calculate loss dynamically during every session with tensorflow?
In tensorflow, can I do:

```<code>optimizer = tf.train.AdamOptimizer()
with tf.Session() as sess:
    for i in batch_loop:
        batch_input, batch_label = getBatchData()
        batch_output = sess.run(output, feed_dict={input: batch_input})

        # calculate the loss based on the batch_output and batch_label
        loss = getLoss(batch_output, batch_label)
        grads_and_vars = optimizer.compute_gradients(loss)
        opt_operation = optimizer.apply_gradients(grads_and_vars)
        sess.run(opt_operation)
</code>```

Can we do something like these ? I can not pre-define the loss function until I get the real output.

答:
You can use a tf.placeholder to pre-define your loss function, and feed them when you get the real output batch_output and batch_label.

For more information, see tf.placeholder

Body:
In tensorflow, can I do:

optimizer = tf.train.AdamOptimizer()
with tf.Session() as sess:
    for i in batch_loop:
        batch_input, batch_label = getBatchData()
        batch_output = sess.run(output, feed_dict={input: batch_input})

        # calculate the loss based on the batch_output and batch_label
        loss = getLoss(batch_output, batch_label)
        grads_and_vars = optimizer.compute_gradients(loss)
        opt_operation = optimizer.apply_gradients(grads_and_vars)
        sess.run(opt_operation)

Can we do something like these ? I can not pre-define the loss function until I get the real output.


问:
Ankh plugin for VS2008 problem
My ankhv plugin for vs2008 ceased to work.  I can't select in Tools->Options->Source Control, although there is an entry AnkhSVN in that combobox "Current source control plugin".   It continues to work with visual studio 2010.  I tried to run devenv /resetsettings with no help.  I also tried to repair (not reinstall) visual studio.  Any leads would be appreciated.</p>

答: Try devenv /setup instead, if that doesn't work try reinstalling

Title: Ankh plugin for VS2008 problem


问:
Send data WITHIN JSON via AJAX
I want to append another home_address within the array address.

```<code>  "fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    }
  ]
}
</code>```

The problem is the code gets added to end.

```<code>"fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    },
    {
      "aid": 4,
      "home_address": "5804",
      "id": 2
    }
  ]
}
</code>```

Here is my sample ajax code

```<code>var addnumber = {
                  "aid": 4,
                  "home_address": "5804"
            }

     $.ajax({
                    type:'POST',
                    url: 'http://localhost:3000/fieldlist',
                    data: JSON.stringify(addnumber),
                    contentType: 'application/json',
                    dataType: 'json'

        });
</code>```

Is there anyway I can append within the address array and not after the code block? Or should I change the structure of my JSON?

答:
Access the fieldlist[0].address and push into it instead of the fieldlist.

var fieldlist = [
  {
    "id": 1,
    "street_name": "N. 10th",
    "address": [
      {
        "aid": 1,
        "home_address": "5801",
        "city": "Philadelphia"
      },
      {
        "aid": 2,
        "home_address": "5802",
        "city": "Philadelphia"
      }
    ]
  }
];

const newAddr = {"aid": 4, "home_address": "5804", "id": 2 };
fieldlist[0].address.push(newAddr);

console.log(fieldlist);```

Title: Send data WITHIN JSON via AJAX

Body:
I want to append another home_address within the array address.

  "fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    }
  ]
}

The problem is the code gets added to end.

"fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    },
    {
      "aid": 4,
      "home_address": "5804",
      "id": 2
    }
  ]
}

Here is my sample ajax code

var addnumber = {
                  "aid": 4,
                  "home_address": "5804"
            }

     $.ajax({
                    type:'POST',
                    url: 'http://localhost:3000/fieldlist',
                    data: JSON.stringify(addnumber),
                    contentType: 'application/json',
                    dataType: 'json'

        });

Is there anyway I can append within the address array and not after the code block? Or should I change the structure of my JSON?


问:
Which escape sequences are allowed in a string enclosed in a pair of single quotes in PHP?
I'm using PHP 7.1.11

As mentioned in the PHP manual

To specify a literal single quote in a string which is already
  enclosed in a pair of single quotes, escape it with a backslash ().
  To specify a literal backslash, double it (\). All other instances of
  backslash will be treated as a literal backslash: this means that the
  other escape sequences you might be used to, such as \r or \n, will be
  output literally as specified rather than having any special meaning.

I'm not understanding the above paragraph due to which following doubts have been created in my mind :

Can only single quotes be specified in a string(using the escape sequence character \') already enclosed in single quotes?

Consider the below sentence

To specify a literal backslash, double it (\).

Actually, I can simply specify a single backslash literal by adding single \ in a string which is already enclosed in a pair of single quotes then why the manual is saying that I have to use double slash(\\) to specify it?

Now consider the below sentence

All other instances of
  backslash will be treated as a literal backslash: this means that the
  other escape sequences you might be used to, such as \r or \n, will be
  output literally as specified rather than having any special meaning.

Does this mean that no other escape sequence character except the single quote(\') can be added in a string quoted in single quotes? Will the characters like \r, \t and \n will get printed as it is like a simple text in a browser?

Someone please clarify all of my above doubts.

Thanks.

答:
Regarding "first paragraph", it's about escaping backslash right before your escaped single quote

```<code>echo '\\\'' // Output: \'
</code>```

All other backslashes output as it is, so there is no possibility to write "new line" symbol with single quotes.

```<code>echo '\n\ \'' // Output: \n\ '
</code>```

Body:
Regarding "first paragraph", it's about escaping backslash right before your escaped single quote

echo '\\\'' // Output: \'

All other backslashes output as it is, so there is no possibility to write "new line" symbol with single quotes.

echo '\n\ \'' // Output: \n\ '


问:
convert matlab code to c code
is there s a way to convert simulink blocks or a matlab ".m" code to C code automatically ?</p>

答:
I'm not aware of any direct translation tool, but there are a few alternatives:

Matlab Compiler will let you create a shared library (callable from C code) from your .m code.

GNU Octave is an open source interpreter that has many of the same functions as Matlab. It is open source, and written in C. You might feasibly build a C library based on on this, although it would be a lot more heavy-weight than option (1).

Title: convert matlab code to c code


问:
ionic 3 read stored value native storage in function ionViewDidLoad ()
I'm having a problem, I'd like to read a value saved in the Native Storage Cordova plugin in the function -> ionViewDidLoad ().

Description of the function:

ionViewDidLoad () = "Runs when the page has loaded. This event only
  happens once per page being created. If a page leaves but is cached,
  then this event will not fire again on a subsequent viewing. The
  ionViewDidLoad event is good place to put your setup code for the
  page."

The action I try to do and display a message when opening the application. But if the user does not want it to open each time the application starts, I want to make a condition in the function ionViewDidLoad () so that it opens according to the user's wishes.

Home.ts page

```<code>    import { Component } from '@angular/core';
    import { NavController, AlertController } from 'ionic-angular';

    import { ParamProviders } from '../../providers/paramProviders';
    import { NativeStorage } from '@ionic-native/native-storage';

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html',
      providers: [ParamProviders]
    })
    export class HomePage {

      boolBienvenue: boolean;

      constructor(public navCtrl: NavController, private alertCtrl: AlertController, private nativeStorage: NativeStorage, private paramService: ParamProviders) {
      }

      ionViewDidLoad() {
         this.boolBienvenue1()
         console.log(this.boolBienvenue);
         if ( this.boolBienvenue == true ) {
            this.demarrage();
        }
      }

     public boolBienvenue1() {
        this.nativeStorage.getItem('storage_pref')
          .then(
            data => this.boolBienvenue = data.bienvenue,
            error => console.error(error)
        )

  }

     public demarrage() {
        let alert = this.alertCtrl.create({
          title: 'Bienvenue dans HackChat !!',
          message: 'Avant de discuter avec vos amies ou vos proches, veuillez configurer l\'application en y indiquant l\'adresse de votre serveur ainsi que votre login et mot de pass dans l\'onglet Paramétres. Une fois que vous serrez connecté, vous pourrez discuter.<br />Allez y c\'est à vous !!<br /><br />Voulez vous que cette bulle d\'information s\'affiche lors de l\'ouverture de HackChat ?',
          buttons: [
            {
              text: 'Non',
              handler: () => {
                console.log('Disagree clicked');
              }
            },
            {
              text: 'Oui',
              handler: () => {
                console.log('Agree clicked');
              }
            }
          ]
        });
        alert.present();
      }
}
</code>```

Parameter.ts Page

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { NativeStorage } from '@ionic-native/native-storage';

/*
  Generated class for the PeopleSearch provider.
  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ParamProviders {

    linkServer: string ;
    user: string;
    password: string;
    bienvenue: boolean = true;
    notification: boolean = false;
    vibration: boolean = false;

  constructor(public http: Http, private nativeStorage: NativeStorage) {
  }

public savePref(): void {
    this.nativeStorage.setItem('storage_pref', {
        linkServer: this.linkServer,
        user: this.user,
        password: this.password,
        bienvenue: this.bienvenue,
        notification: this.notification,
        vibration: this.vibration
    })
    .then(
      () => console.log(this.linkServer),
      error => console.error('Error storing item', error)
    );
}

public loadPref():void {
  this.nativeStorage.getItem('storage_pref')
    .then(
      data => {
        this.linkServer = data.linkServer;
        this.user = data.user;
        this.password = data.password;
        this.bienvenue = data.bienvenue;
        this.notification = data.notification;
        this.vibration = data.vibration;
      },
      error => console.error(error)
  );
 }
}
</code>```

Can you help me
Thank you

答:
Accessing the storage is an asynchronous job, therefore your following code most probably doesn't work because the result of the async job is resolved after you try to ask if your boolean value is set

```<code>ionViewDidLoad() {
     this.boolBienvenue1() // Here you don't wait for async job
     console.log(this.boolBienvenue); // So this value might or might not be set
     if ( this.boolBienvenue == true ) {
        this.demarrage();
    }
  }

 public boolBienvenue1() {
    this.nativeStorage.getItem('storage_pref')
      .then(
        data => this.boolBienvenue = data.bienvenue,
        error => console.error(error)
    )
 }
</code>```

You could, for example, modify your code like following:

```<code> ionViewDidLoad() {
     this.nativeStorage.getItem('storage_pref')
      .then(
        (data) => {
             if ( data !== null && data.bienvenue ) {
                this.demarrage();
             }
        }
        error => console.error(error)
    )
 }
</code>```

P.S.: Not related to your question, but if I may, to test if a boolean is true in a condition you do not need to add == true, the boolean value itself is enough. I mean:

```<code> if (something == true)
</code>```

should be written

```<code> if (something)
</code>```

Body:
I'm having a problem, I'd like to read a value saved in the Native Storage Cordova plugin in the function -> ionViewDidLoad ().

Description of the function:

ionViewDidLoad () = "Runs when the page has loaded. This event only
  happens once per page being created. If a page leaves but is cached,
  then this event will not fire again on a subsequent viewing. The
  ionViewDidLoad event is good place to put your setup code for the
  page."

The action I try to do and display a message when opening the application. But if the user does not want it to open each time the application starts, I want to make a condition in the function ionViewDidLoad () so that it opens according to the user's wishes.

Home.ts page

    import { Component } from '@angular/core';
    import { NavController, AlertController } from 'ionic-angular';

    import { ParamProviders } from '../../providers/paramProviders';
    import { NativeStorage } from '@ionic-native/native-storage';

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html',
      providers: [ParamProviders]
    })
    export class HomePage {

      boolBienvenue: boolean;

      constructor(public navCtrl: NavController, private alertCtrl: AlertController, private nativeStorage: NativeStorage, private paramService: ParamProviders) {
      }

      ionViewDidLoad() {
         this.boolBienvenue1()
         console.log(this.boolBienvenue);
         if ( this.boolBienvenue == true ) {
            this.demarrage();
        }
      }

     public boolBienvenue1() {
        this.nativeStorage.getItem('storage_pref')
          .then(
            data => this.boolBienvenue = data.bienvenue,
            error => console.error(error)
        )

  }

     public demarrage() {
        let alert = this.alertCtrl.create({
          title: 'Bienvenue dans HackChat !!',
          message: 'Avant de discuter avec vos amies ou vos proches, veuillez configurer l\'application en y indiquant l\'adresse de votre serveur ainsi que votre login et mot de pass dans l\'onglet Paramétres. Une fois que vous serrez connecté, vous pourrez discuter.
Allez y c\'est à vous !!

Voulez vous que cette bulle d\'information s\'affiche lors de l\'ouverture de HackChat ?',
          buttons: [
            {
              text: 'Non',
              handler: () => {
                console.log('Disagree clicked');
              }
            },
            {
              text: 'Oui',
              handler: () => {
                console.log('Agree clicked');
              }
            }
          ]
        });
        alert.present();
      }
}

Parameter.ts Page

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { NativeStorage } from '@ionic-native/native-storage';

/*
  Generated class for the PeopleSearch provider.
  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ParamProviders {

    linkServer: string ;
    user: string;
    password: string;
    bienvenue: boolean = true;
    notification: boolean = false;
    vibration: boolean = false;

  constructor(public http: Http, private nativeStorage: NativeStorage) {
  }

public savePref(): void {
    this.nativeStorage.setItem('storage_pref', {
        linkServer: this.linkServer,
        user: this.user,
        password: this.password,
        bienvenue: this.bienvenue,
        notification: this.notification,
        vibration: this.vibration
    })
    .then(
      () => console.log(this.linkServer),
      error => console.error('Error storing item', error)
    );
}

public loadPref():void {
  this.nativeStorage.getItem('storage_pref')
    .then(
      data => {
        this.linkServer = data.linkServer;
        this.user = data.user;
        this.password = data.password;
        this.bienvenue = data.bienvenue;
        this.notification = data.notification;
        this.vibration = data.vibration;
      },
      error => console.error(error)
  );
 }
}

Can you help me
Thank you

Body:
Accessing the storage is an asynchronous job, therefore your following code most probably doesn't work because the result of the async job is resolved after you try to ask if your boolean value is set

ionViewDidLoad() {
     this.boolBienvenue1() // Here you don't wait for async job
     console.log(this.boolBienvenue); // So this value might or might not be set
     if ( this.boolBienvenue == true ) {
        this.demarrage();
    }
  }

 public boolBienvenue1() {
    this.nativeStorage.getItem('storage_pref')
      .then(
        data => this.boolBienvenue = data.bienvenue,
        error => console.error(error)
    )
 }

You could, for example, modify your code like following:

 ionViewDidLoad() {
     this.nativeStorage.getItem('storage_pref')
      .then(
        (data) => {
             if ( data !== null && data.bienvenue ) {
                this.demarrage();
             }
        }
        error => console.error(error)
    )
 }

P.S.: Not related to your question, but if I may, to test if a boolean is true in a condition you do not need to add == true, the boolean value itself is enough. I mean:

 if (something == true)

should be written

 if (something)


问:
convert list of lists with time strings to seconds and find count times between
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

```<code>Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
</code>```

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

答:
```<code>from datetime import datetime, timedelta

arr = [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

def convert(t):
    return datetime.strptime(t, "%H:%M:%S")

def append_start_end(element):
    if len(element) > 0:
        hour = element[0].split(":")[0]
        first = ["{}:00:00".format(hour)]
        last = ["{}:59:59".format(hour)]
        return first + element + last
    return []

result = []
for d in arr:
    d = append_start_end(d)
    result.append(
        [(convert(f[1]) - convert(f[0])  - timedelta(minutes=5) ).total_seconds()
         for f in zip(d[:-1], d[1:])
         if convert(f[1]) - convert(f[0])  > timedelta(minutes=5)]
    )

print(result)
</code>```

Updated: removed steps in slices:

```<code>for f in zip(d[:-1:2], d[1::2])
</code>```

Output now:

```<code>[[], [], [32.0, 2199.0], []]
</code>```

Body:
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

Body:
from datetime import datetime, timedelta

arr = [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

def convert(t):
    return datetime.strptime(t, "%H:%M:%S")

def append_start_end(element):
    if len(element) > 0:
        hour = element[0].split(":")[0]
        first = ["{}:00:00".format(hour)]
        last = ["{}:59:59".format(hour)]
        return first + element + last
    return []

result = []
for d in arr:
    d = append_start_end(d)
    result.append(
        [(convert(f[1]) - convert(f[0])  - timedelta(minutes=5) ).total_seconds()
         for f in zip(d[:-1], d[1:])
         if convert(f[1]) - convert(f[0])  > timedelta(minutes=5)]
    )

print(result)

Updated: removed steps in slices:

for f in zip(d[:-1:2], d[1::2])

Output now:

[[], [], [32.0, 2199.0], []]