问:
How to get the URL with the report parameters and values of the parameters of the executed report
Is it possible to get URL for a executed report (including selected parameter values) that can be emailed to colleagues? That they can follow the link to get the same as I, with the same selected parameters.</p>

答:
It most definitely is possible and I like to create mailto support links on reports that a user can click to send me (the guy that will be looking at their issue) an exact link to the report they use, complete with parameters.

Technet Page: Passing a Report Parameter Within a URL

Here is an example URL that we can break down:

http://server/reportserver?/Sales/Northwest/Employee Sales Report&rs:Command=Render&EmployeeID=1234

"http://" - obviously going to be the same for all links

"server"  - the name of the ssrs server

"reportserver?" - the virtual directory where the report server's reports are accessed from:

You can find this by logging into the server and checking the Reporting Services Configuration Manager settings. The default value is "reportserver" if no one customized yours.

"/Sales/Northwest/Employee Sales Report/": The path to the report including the report name

"&rs:Command=Render": Just a command to the ssrs server to render the report

"&EmployeeID=1234": The parameter part you are interested in. EmployeeID in this case is the exact name of the parameter within your report (not the display name) and obviously 1234 is the value for the link.


来源: stackexchange

问:
sqlite & windows: Not enough storage is available to complete this operation and CoInitialize has not been called
Some days ago I implemented a system for autocomplete suggestions which works with a dictionary depending on the language. Here is how it works:
JQuery UI autocomplete -> call to .php file -> call to VB6 COM dll function -> call to .sqlite file and finding results based on typed letters -> return results to php -> return results to JS.

It works reasonably fast, as in, it takes on average ~7 (milliseconds) to complete each operation. During peak hours, google analytics shows ~1200 online users, and generally each day we get ~half a million calls to this particular function.

From the day this autocomplete suggestion system went online I started noticing hundreds of two very specific error messages:

```<code>Not enough storage is available to complete this operation.

CoInitialize has not been called.
</code>```

Some information which may help:

a) These messages appear mostly during the peak visitors horus

b) They don't always appear only with the specific function, but on others as well (BUT never did before we implemented the aforementioned system)

c) I used sqlite databases before for other stuff (not as much "real-time" though, as in returning results when a user types) but never such a problem appeared

d) The size of the sqlite file is ~350MB with 3 tables, one of them has ~2,2 million entries, the other has 1,6 million and the other ~16thousand entries and all the necessary columns are indexed.

e) Obviously this database is used for read-only operations

f) Once the system gets disabled, all messages stop.

g) I get about a thousand such error messages each day for each message (with about 500.000 calls to the function / day)

The server system is two (x2) boxes: Core I7 4770 at 3,8GHZ, 32GB of RAM, Windows server 2012 and IIS.

The messages appear randomly and only during peak hours. I cannot replicate the problem at the development machine. Searching the internet has been fruitless till now. Any ideas on what's causing it and how to solve would be more than welcome.

Thank you.

答:
The fact this is a transient problem that only happens at peak usage times is a pretty clear indication something is running out of memory - probably your VB DLL (that's likely the only place where CoInitialize is being called).

I've seen similar problems with too many applications running and winDoze running out of "system handles" - I've got a w2K Advanced Server box I've been using as a desktop machine (because m$ doesn't provide an upgrade path from an AS instance to a desktop one) typically running a dozen Explorer windows, WinSCP with 8-10 tabs, several PuTTY sessions, several DOS boxes, remote desktop connections, Firefox with 184 tabs in 4 windows, Thunderbird watching 40 email accounts, WinAmp, and a few others - and PaintShopPro and PhpED just do not want to be running at the same time due to the aforementioned system handle limitation.

Your problems might be fixed simply by throwing more RAM at the issue, but you should probably do some performance checking, and check for system settings to tweak.

ContentLicense: CC BY-SA 3.0

Body:
Some days ago I implemented a system for autocomplete suggestions which works with a dictionary depending on the language. Here is how it works:
JQuery UI autocomplete -> call to .php file -> call to VB6 COM dll function -> call to .sqlite file and finding results based on typed letters -> return results to php -> return results to JS.

It works reasonably fast, as in, it takes on average ~7 (milliseconds) to complete each operation. During peak hours, google analytics shows ~1200 online users, and generally each day we get ~half a million calls to this particular function.

From the day this autocomplete suggestion system went online I started noticing hundreds of two very specific error messages:

Not enough storage is available to complete this operation.

CoInitialize has not been called.

Some information which may help:

a) These messages appear mostly during the peak visitors horus

b) They don't always appear only with the specific function, but on others as well (BUT never did before we implemented the aforementioned system)

c) I used sqlite databases before for other stuff (not as much "real-time" though, as in returning results when a user types) but never such a problem appeared

d) The size of the sqlite file is ~350MB with 3 tables, one of them has ~2,2 million entries, the other has 1,6 million and the other ~16thousand entries and all the necessary columns are indexed.

e) Obviously this database is used for read-only operations

f) Once the system gets disabled, all messages stop.

g) I get about a thousand such error messages each day for each message (with about 500.000 calls to the function / day)

The server system is two (x2) boxes: Core I7 4770 at 3,8GHZ, 32GB of RAM, Windows server 2012 and IIS.

The messages appear randomly and only during peak hours. I cannot replicate the problem at the development machine. Searching the internet has been fruitless till now. Any ideas on what's causing it and how to solve would be more than welcome.

Thank you.


问:
How to interpret Solr Admin Analysis screen
I'm reading the docs on the analyzer screen of the Solr Admin, but I'm still not sure how to determine when a given query matches with something-- is this when it is shaded light blue after a step in its analyzer chain? Also is there a way to see how many it matches on and what words they are specifically?

Finally, what is the difference between typing a query into Field Value (Index) and Field Value (Query)?

Thanks for any help!

答:
In this case could be helpful to post a screenshot of what you're seeing. The panel is split in two sections, the left (field value) simulates the value that would be indexed when you add a document, and the panel on the right simulates the values that will be sent through the query analysis chain. This is designed like this because you ca have different configurations for the index/query in your FieldType.

Yes, the values that match are highlighted with the light blue, also is highlighted multiple times because it starts the first time that the token matched, so if you defined different filters on your FieldType you'll get one row of tokens (token stream) after it goes through that transformation.

If multiple tokens/terms from your query match the field values, then all those terms that matched will be highlighted.

Keep in mind that this is not firing a normal search query to Solr (so you're not searching documents), is just sending what you put on the left and on the right (field value, and query) through the FieldType analysis chain selected (FieldType) and showing what you'll get out (tokens/terms).


问:
Best practices for editing an umbraco controller
I want to make a small change to how the text on panels is displayed in an Umbraco grid.

I've found I can make the change to nestedcontent.controllers.js in just a few lines, and this works.

However, if/when we upgrade Umbraco this change may be lost.

What are the best practices? Alternative ways of changing Umbraco behavior?

答: Looks like it's a package specific file (Nested Content)? You could download the package file, unzip it and make the change before re-zipping it and keep the zip file in a safe place? ;-) Or, if it's a change that everyone could benefit from, make a pull request on Github? </p>


问:
Cross-platform (microcontroller-PC) algorithm development
I was asked to develop a algorithm for network application on C. This project will be developed on Linux for PC and then it will be transferred to a more portable platform, something that will include a microcontroller. There are many microcontroller/companies out there that provide very nice and large libraries for TCP/IP. This software will hold statistics on the network performance.

The whole idea of a cross platform (uC - PC) seems rubbish to me cause eventually the code should be written in a more platform specific way for the microcontroller, but I am not expert to judge anyway.

Is there any clever way of doing this or is there a anyone that did this before? My brainstorming has "Wrapper library" and "Matlab"... Any ideas?

Thx!

答:
I do agree with you to some extent - you do want the target system and the system on which you are developing in the interim should be as close as possible (it is better if they can match). Nevertheless the idea with cross-platform is to get you started with the firmware development while the hardware is being designed. Instead of doing it on Linux - what I would do is to use Embedded OS simulator. Here are the steps

- Step 1: Identify the OS for the Embedded System; make sure that OS has a simulator that runs on PC (Win or Linux)  Typical Embedded OS with Simulator include VxWorks, μC/OS-II, QNX, uClinux ...  Agreeing on the OS means that the hardware design team knows that the OS is the right match for the hardware that is being designed and there is a consensus that the hardware + OS + Application being designed will meet the requirements of the system that is being developed.

- Step 2: Use this simulator to develop the application until the hardware that is being designed is brought up.

- Step 3: Once the first version of the hardware is ready and has been powered up - you can run your application with minimum changes - mostly likely no changes to the code, but changes to the linker/library being used is likely.

The idea of cross-platform if done correct has immense advantages - it helps remove serializing your project development activities.

Given that you mention it is a TCP/IP application - check for Berkeley Sockets support and you use it. Usually this API should not matter if you are using a Simulator, in the extreme case if you have to change the OS for whatever reason your Berkeley Sockets based application is likely to be better portable.

ContentLicense: CC BY-SA 2.5


问:
Selenium and Angularjs wait until to do some actions
I'm using selenium to test AngularJS application. I'm facing issue that I cannot do any actions on the page until it loads fully. I can put Thread.sleep(), but this is not good solution as I know. There many ways to wait until page will be loaded(I google it), but I think I tried them all and still no luck. In my applications when go to webpage, everything looks loaded(from visual perspective), but I can not do any activities until full page loads(around 1 sec).
Can you guys share your implementation how you did it that is actually works

Thank you

My code:

```<code>public By ngWait(final By by) {
    return new FluentBy() {
        @Override
        public void beforeFindElement(WebDriver driver) {
            driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
            ((JavascriptExecutor) driver).executeAsyncScript("var callback = arguments[arguments.length - 1];" +
                    "angular.element(document.body).injector().get('$browser').notifyWhenNoOutstandingRequests(callback);");
            super.beforeFindElement(driver);
        }

        @Override
        public List<WebElement> findElements(SearchContext context) {
            return by.findElements(context);
        }

        @Override
        public WebElement findElement(SearchContext context) {
            return by.findElement(context);
        }

        @Override
        public String toString() {
            return "ngWait(" + by.toString() + ")";
        }
    };
}
</code>```

答:
Sorry I can't post a comment yet so here is my piece of help as an answer.

Following up from the error on the comments on Priyanshu Shekhar's answer, all that means is that jqLite (Angular's basic jquery version) is not enough to do what that code is trying to do.

Including the full jquery version in your page should solve that problem.

Body:
I'm using selenium to test AngularJS application. I'm facing issue that I cannot do any actions on the page until it loads fully. I can put Thread.sleep(), but this is not good solution as I know. There many ways to wait until page will be loaded(I google it), but I think I tried them all and still no luck. In my applications when go to webpage, everything looks loaded(from visual perspective), but I can not do any activities until full page loads(around 1 sec).
Can you guys share your implementation how you did it that is actually works

Thank you

My code:

public By ngWait(final By by) {
    return new FluentBy() {
        @Override
        public void beforeFindElement(WebDriver driver) {
            driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
            ((JavascriptExecutor) driver).executeAsyncScript("var callback = arguments[arguments.length - 1];" +
                    "angular.element(document.body).injector().get('$browser').notifyWhenNoOutstandingRequests(callback);");
            super.beforeFindElement(driver);
        }

        @Override
        public List<WebElement> findElements(SearchContext context) {
            return by.findElements(context);
        }

        @Override
        public WebElement findElement(SearchContext context) {
            return by.findElement(context);
        }

        @Override
        public String toString() {
            return "ngWait(" + by.toString() + ")";
        }
    };
}


问:
How to know max event period of perf-record
does anyone know how to get the maximum event period value (or the value that kernel actually passes to PMU) of Perf event?

I'm using perf to measure my program as follow:
perf record -d -e cpu/event=0xd0,umask=0x81/ppu,cpu/event=0xd0,umask=0x82/ppu -c 5

cpu/event=0xd0,umask=0x81/ppu means measure all loads in cpu, and cpu/event=0xd0,umask=0x82/ppu is all stores.

I tried to understand how arguments passing in perf by strace, but found nothing.

Is the PMU received a value that over its ability, will still try to reach it? If so, where can find related code and what is its maximum event period of those events?

Thanks everyone.

答:
The perf record command accepts period values much larger than 255. Internally, the processor maintains a counter for recording all the memory loads and memory stores(or for that matter, any other supported event). Once the counter overflows, the processor will record all the information about the memory load/store that you are trying to record(information about architectural state/registers etc.) .

Also once the counter overflows, it must be reset again. Usually the counter is reset to a value less than 0. Since it is set to a value less than zero and it increments, the counter will overflow once it hits 0 again.

This counter reset value that I was talking about is the period value that you asked for. What I mean is that, if the period is specified by -c 1 , it means that the counter reset value will be set to -1, so the next memory load/store will increment the counter to 0(leading to a counter overflow) and you will record the events.

Thus, if you set the period to 1, there will be a counter overflow on each memory load/store event and you will record all of them (this is only conceptual however, the hardware usually cannot do this).

What this means is that, the period value can go as large as the size of a hardware counter for these events. Usually in modern microarchitectures , like Broadwell/Haswell/Skylake, these counters are 48-bits in size. So the period might go as large as 2^48-1. However, usage of such large values are not recommended.

Usually, the period value should be kept to a maximum of 2^32-1 in 32-bit systems and is usually the norm in other systems too.

Sources :

Chapter 18 of this book

Please read the topic Sampling with perf record in this link too

If you want you can read the answer to this question too.


问:
Actionbar custom drawable menuIcon not centered
I'm trying to add a custom Drawable which extends Drawable to my actionBar. This needs to be a custom drawable, since I want to draw on top of a supplied icon (but that's not the issue).

I've added the icon to the menu in my activity like so:

```<code>BadgedIconDrawable drawable = new BadgedIconDrawable(getContext())
    .setIcon(icon);
mMenu.add(0, menuItemId, 0, "")
    .setIcon(drawable)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
</code>```

In the BadgedIconDrawable I take a bitmap for the Icon which I then draw on the canvas:

```<code>@Override
public void draw(@NonNull Canvas canvas) {
    canvas.drawBitmap(mIcon.getBitmap(), null, new Rect(0, 0, mWidth, mHeight), mIconPaint);
}
</code>```

Where the width and height are 24dp, which seems to be the right size for the icon.

The problem is that unlike a regular drawable that's passed to the setIcon for the mMenu, it doesn't seem to align correctly. I can't find how to get it aligned to the center. Image below illustrates the issue. The middle Icon is set through the BadgedIconDrawable.

答:
EDIT

While the below snippet worked, I soon figured this would only work for the toolbar. Not anymore when used in a regular ImageView. So the trick is to use a Rect as to where the bitmap should be drawn. This would have the regular bounds, but when it should be translated, tell the custom Drawable to do so, by modifying the Rect like so:

```<code>// On the fragment/activity create the Drawable, translate it and add to the menu.

public void addBadgedActionBarButton(Drawable icon, int color, String badgeLabel, int menuItemId) {
    if (mMenu == null) {
        throw new IllegalStateException("mMenu = null, Are you sure you are calling addActionBarButton from initMenu()?");
    } else {
        BadgedIconDrawable drawable = new BadgedIconDrawable(getContext());
        drawable.translate(-drawable.getWidth() / 2, -drawable.getHeight() / 2, drawable.getWidth() / 2, drawable.getHeight() / 2)
                .setIcon(icon);

        mMenu.add(Menu.NONE, menuItemId, Menu.NONE, "")
                .setIcon(drawable)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    }
}

// In the BadgedIconDrawable have a function that sets the mDstRect to the translated Rect.

public BadgedIconDrawable translate(int left, int top, int right, int bottom) {
    mDstRect = new Rect(left, top, right, bottom);
    return this;
}

// In the BadgedIconDrawable draw function use the mDstRect to draw on the correct position.

@Override
public void draw(@NonNull Canvas canvas) {
    canvas.drawBitmap(mIcon.getBitmap(), null, mDstRect, mIconPaint);
}
</code>```

With some wild guessing I managed to try to add a negative top and left, which seems to place it in the correct spot. This seems to do the trick.

```<code>@Override
public void draw(@NonNull Canvas canvas) {
    int halfWidth = mWidth / 2;
    int halfHeight = mHeight / 2;
    canvas.drawBitmap(mIcon.getBitmap(), null, new Rect(-halfWidth, -halfHeight, halfWidth, halfHeight), mIconPaint);
}
</code>```

Body:
I'm trying to add a custom Drawable which extends Drawable to my actionBar. This needs to be a custom drawable, since I want to draw on top of a supplied icon (but that's not the issue).

I've added the icon to the menu in my activity like so:

BadgedIconDrawable drawable = new BadgedIconDrawable(getContext())
    .setIcon(icon);
mMenu.add(0, menuItemId, 0, "")
    .setIcon(drawable)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

In the BadgedIconDrawable I take a bitmap for the Icon which I then draw on the canvas:

@Override
public void draw(@NonNull Canvas canvas) {
    canvas.drawBitmap(mIcon.getBitmap(), null, new Rect(0, 0, mWidth, mHeight), mIconPaint);
}

Where the width and height are 24dp, which seems to be the right size for the icon.

The problem is that unlike a regular drawable that's passed to the setIcon for the mMenu, it doesn't seem to align correctly. I can't find how to get it aligned to the center. Image below illustrates the issue. The middle Icon is set through the BadgedIconDrawable.

Body:
EDIT

While the below snippet worked, I soon figured this would only work for the toolbar. Not anymore when used in a regular ImageView. So the trick is to use a Rect as to where the bitmap should be drawn. This would have the regular bounds, but when it should be translated, tell the custom Drawable to do so, by modifying the Rect like so:

// On the fragment/activity create the Drawable, translate it and add to the menu.

public void addBadgedActionBarButton(Drawable icon, int color, String badgeLabel, int menuItemId) {
    if (mMenu == null) {
        throw new IllegalStateException("mMenu = null, Are you sure you are calling addActionBarButton from initMenu()?");
    } else {
        BadgedIconDrawable drawable = new BadgedIconDrawable(getContext());
        drawable.translate(-drawable.getWidth() / 2, -drawable.getHeight() / 2, drawable.getWidth() / 2, drawable.getHeight() / 2)
                .setIcon(icon);

        mMenu.add(Menu.NONE, menuItemId, Menu.NONE, "")
                .setIcon(drawable)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    }
}

// In the BadgedIconDrawable have a function that sets the mDstRect to the translated Rect.

public BadgedIconDrawable translate(int left, int top, int right, int bottom) {
    mDstRect = new Rect(left, top, right, bottom);
    return this;
}

// In the BadgedIconDrawable draw function use the mDstRect to draw on the correct position.

@Override
public void draw(@NonNull Canvas canvas) {
    canvas.drawBitmap(mIcon.getBitmap(), null, mDstRect, mIconPaint);
}

With some wild guessing I managed to try to add a negative top and left, which seems to place it in the correct spot. This seems to do the trick.

@Override
public void draw(@NonNull Canvas canvas) {
    int halfWidth = mWidth / 2;
    int halfHeight = mHeight / 2;
    canvas.drawBitmap(mIcon.getBitmap(), null, new Rect(-halfWidth, -halfHeight, halfWidth, halfHeight), mIconPaint);
}


问:
"errorMessage": Task timed out after 3.00 seconds aws lambda nodejs lambda function trying to connect with RDS
I have written a simple lambda function in nodejs which queries data from amazon rds.(note : my lambda and rds are in default vpc with all ports open and also tried increasing time out in lambda)

My issue is when I test my lambda function I get log output with the queried data but I am also getting

Execution result: failed with "errorMessage": "2017-07-05T15:05:27.425Z 596fdf39-6193-11e7-9176-f58796899f9b Task timed out after 3.00 seconds"
  }

var mysql = require('mysql');

exports.handler = (event, context) => {
var con = mysql.createConnection({
  host: "testdb.cxyzu.ap-south-1.rds.amazonaws.com",
  user: "root",
  password: "mypassword",
  database: "test",
  port: "3306",
 // debug: true
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
 // var sql = "INSERT INTO users (id, name) VALUES (4, 'dfdd')";
var sql = "select * from test.users";
  con.query(sql, function (err, result) {
    if (err) throw err;
//    console.log("1 record inserted");
      console.log(result);
  });
});
//callback("sucess");
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>START RequestId: 596fdf39-6193-11e7-9176-f58796899f9b Version: $LATEST
2017-07-05T15:05:24.680Z 596fdf39-6193-11e7-9176-f58796899f9b Connected!
2017-07-05T15:05:24.684Z 596fdf39-6193-11e7-9176-f58796899f9b [ RowDataPacket { id: 1, name: 'sai' },
  RowDataPacket { id: 2, name: 'chandra' },
  RowDataPacket { id: 3, name: 'AA' },
  RowDataPacket { id: 4, name: 'dfdd' } ]
END RequestId: 596fdf39-6193-11e7-9176-f58796899f9b
REPORT RequestId: 596fdf39-6193-11e7-9176-f58796899f9b Duration: 3003.80 ms Billed Duration: 3000 ms  Memory Size: 1536 MB Max Memory Used: 21 MB
2017-07-05T15:05:27.425Z 596fdf39-6193-11e7-9176-f58796899f9b Task timed out after 3.00 seconds</code>```

答:
You need to exit the lambda through a success or error callback. Otherwise, the engine stays on until a timeout occurs.

The easiest way to exit your lambda would be to call 'context.succeed("done");' after you code is done.

```<code>var mysql = require('mysql');

exports.handler = (event, context) => {
var con = mysql.createConnection({
  host: "testdb.cxyzu.ap-south-1.rds.amazonaws.com",
  user: "root",
  password: "mypassword",
  database: "test",
  port: "3306",
 // debug: true
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
 // var sql = "INSERT INTO users (id, name) VALUES (4, 'dfdd')";
var sql = "select * from test.users";
  con.query(sql, function (err, result) {
    if (err) throw err;
//    console.log("1 record inserted");
      console.log(result);
      context.succeed("done");
  });
});
//callback("sucess");
}
</code>```

Here some basic introduction to the topic:

Lambda Function Handler (Node.js)

Body:
I have written a simple lambda function in nodejs which queries data from amazon rds.(note : my lambda and rds are in default vpc with all ports open and also tried increasing time out in lambda)

My issue is when I test my lambda function I get log output with the queried data but I am also getting

Execution result: failed with "errorMessage": "2017-07-05T15:05:27.425Z 596fdf39-6193-11e7-9176-f58796899f9b Task timed out after 3.00 seconds"
  }

var mysql = require('mysql');

exports.handler = (event, context) => {
var con = mysql.createConnection({
  host: "testdb.cxyzu.ap-south-1.rds.amazonaws.com",
  user: "root",
  password: "mypassword",
  database: "test",
  port: "3306",
 // debug: true
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
 // var sql = "INSERT INTO users (id, name) VALUES (4, 'dfdd')";
var sql = "select * from test.users";
  con.query(sql, function (err, result) {
    if (err) throw err;
//    console.log("1 record inserted");
      console.log(result);
  });
});
//callback("sucess");
}

START RequestId: 596fdf39-6193-11e7-9176-f58796899f9b Version: $LATEST
2017-07-05T15:05:24.680Z 596fdf39-6193-11e7-9176-f58796899f9b Connected!
2017-07-05T15:05:24.684Z 596fdf39-6193-11e7-9176-f58796899f9b [ RowDataPacket { id: 1, name: 'sai' },
  RowDataPacket { id: 2, name: 'chandra' },
  RowDataPacket { id: 3, name: 'AA' },
  RowDataPacket { id: 4, name: 'dfdd' } ]
END RequestId: 596fdf39-6193-11e7-9176-f58796899f9b
REPORT RequestId: 596fdf39-6193-11e7-9176-f58796899f9b Duration: 3003.80 ms Billed Duration: 3000 ms  Memory Size: 1536 MB Max Memory Used: 21 MB
2017-07-05T15:05:27.425Z 596fdf39-6193-11e7-9176-f58796899f9b Task timed out after 3.00 seconds

Body:
You need to exit the lambda through a success or error callback. Otherwise, the engine stays on until a timeout occurs.

The easiest way to exit your lambda would be to call 'context.succeed("done");' after you code is done.

var mysql = require('mysql');

exports.handler = (event, context) => {
var con = mysql.createConnection({
  host: "testdb.cxyzu.ap-south-1.rds.amazonaws.com",
  user: "root",
  password: "mypassword",
  database: "test",
  port: "3306",
 // debug: true
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
 // var sql = "INSERT INTO users (id, name) VALUES (4, 'dfdd')";
var sql = "select * from test.users";
  con.query(sql, function (err, result) {
    if (err) throw err;
//    console.log("1 record inserted");
      console.log(result);
      context.succeed("done");
  });
});
//callback("sucess");
}

Here some basic introduction to the topic:

Lambda Function Handler (Node.js)


问:
Sqoop import --target-dir not working instead places the files in default directory
Sqoop import script:

```<code>sqoop import --connect jdbc:mysql://localhost/retail_db --username root --password cloudera --target-dir /user/cloudera/retail_db/products_test --table products --hive-import  --create-hive-table  --hive-table retail_db.products_test
</code>```

After successful sqoop import and Hive table creation
the location is /hive/warehouse/retail_db.db/products_test instead of /user/cloudera/retail_db/products_test

HIVE:

```<code>SHOW CREATE TABLE products_test;

CREATE TABLE `products_test`(
  `product_id` int,
  `product_category_id` int,
  `product_name` string,
  `product_description` string,
  `product_price` double,
  `product_image` string)
COMMENT 'Imported by sqoop on 2017/07/05 05:52:43'
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'field.delim'='\u0001',
  'line.delim'='\n',
  'serialization.format'='\u0001')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'hdfs://quickstart.cloudera:8020/user/hive/warehouse/retail_db.db/products_test'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='true',
  'numFiles'='4',
  'totalSize'='173993',
  'transient_lastDdlTime'='1499259177')
Time taken: 0.892 seconds, Fetched: 25 row(s)
</code>```

答:
the directory  /user/cloudera is where data is imported and this will b picked up by hive and create table. So to create a Hive table in this directory u need to re-frame query like

```<code>sqoop import --connect jdbc:mysql://localhost/retail_db --username root --password cloudera --target-dir /user/cloudera/retail_db/products_test --table products --hive-import  --create-hive-table  --hive-table --warehouse-dir /user/cloudera retail_db.products_test
</code>```

i have added the warehouse directory(--warehouse-dir ) option. Hope it helps.

Body:
Sqoop import script:

sqoop import --connect jdbc:mysql://localhost/retail_db --username root --password cloudera --target-dir /user/cloudera/retail_db/products_test --table products --hive-import  --create-hive-table  --hive-table retail_db.products_test

After successful sqoop import and Hive table creation
the location is /hive/warehouse/retail_db.db/products_test instead of /user/cloudera/retail_db/products_test

HIVE:

SHOW CREATE TABLE products_test;

CREATE TABLE `products_test`(
  `product_id` int,
  `product_category_id` int,
  `product_name` string,
  `product_description` string,
  `product_price` double,
  `product_image` string)
COMMENT 'Imported by sqoop on 2017/07/05 05:52:43'
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'field.delim'='\u0001',
  'line.delim'='\n',
  'serialization.format'='\u0001')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'hdfs://quickstart.cloudera:8020/user/hive/warehouse/retail_db.db/products_test'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='true',
  'numFiles'='4',
  'totalSize'='173993',
  'transient_lastDdlTime'='1499259177')
Time taken: 0.892 seconds, Fetched: 25 row(s)

Body:
the directory  /user/cloudera is where data is imported and this will b picked up by hive and create table. So to create a Hive table in this directory u need to re-frame query like

sqoop import --connect jdbc:mysql://localhost/retail_db --username root --password cloudera --target-dir /user/cloudera/retail_db/products_test --table products --hive-import  --create-hive-table  --hive-table --warehouse-dir /user/cloudera retail_db.products_test

i have added the warehouse directory(--warehouse-dir ) option. Hope it helps.


问:
How to debug mysql foreign key constraint, ON DELETE CASCADE not deleting rows from Child table on production environment
I have defined 2 tables and a foriegn key constraint between them as follows:

```<code>| users | CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_master_id` int(11) NOT NULL,
  `user_type_id` int(11) NOT NULL,
  `user_group_id` int(11) NOT NULL,
  `user_type_code` char(1) NOT NULL,
  `membership_number` varchar(40) NOT NULL,
  `password` varchar(60) NOT NULL,
  `email` varchar(200) NOT NULL,
  `isd` varchar(10) NOT NULL,
  `mobile` varchar(20) NOT NULL,
  `passenger_id` int(11) NOT NULL,
  `added_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `added_by` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
  KEY `account_master_id` (`account_master_id`),
  CONSTRAINT `acMaster_to_user` FOREIGN KEY (`account_master_id`) REFERENCES `account_master` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=189 DEFAULT CHARSET=utf8 |

user_oauth | CREATE TABLE `user_oauth` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `service` varchar(30) NOT NULL,
  `auth_id` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `auto_share` tinyint(4) NOT NULL,
  `photo` varchar(255) NOT NULL,
  `auth_token_short` varchar(255) DEFAULT NULL,
  `auth_details` text NOT NULL,
  `device_type` varchar(60) NOT NULL,
  `login_date` datetime NOT NULL,
  `login_ip` varchar(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user` (`user_id`),
  CONSTRAINT `user_to_oauth` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=109 DEFAULT CHARSET=latin1 |
</code>```

on deleting a row from users table, deletes corresponding entries from user_oauth table in LOCAL and Staging environment. but however same thing is not working in PRODUCTION environment. I want to know how can i debug this.

update:

both tables are innodb

running mysql in strict mode

答:
The reasons why foreign keys might not work are:

they are not supported (e.g. on MyISAM-tables)

they are disabled

MySQL allows you to disable foreign key contraints by setting the system variable foreign_key_checks to 0. This will allow you to violate all foreign key constraints (e.g. delete a parent or add parentless childs). But it will in turn also disable related features like cascades, which are there to automatically prevent specific constraint violations (by e.g. deleting the children) - which of course won't occur anymore if the option is disabled.

The idea is to help you with some administration tasks, e.g. importing data when the referenced data is not yet there, but should usually not be used during normal operation. If the setting reappears, you might want to check your apps if one is setting this option by accident, as it is enabled after every server start by default and has to be disabled explicitely.

You can check the current setting by e.g. using

```<code>select @@foreign_key_checks;
</code>```

You can use

```<code>SET foreign_key_checks = 1;
</code>```

to enable it again, but be aware that it will not check your current data:

Setting foreign_key_checks to 1 does not trigger a scan of the existing table data. Therefore, rows added to the table while foreign_key_checks=0 will not be verified for consistency.

So you will have to check and fix it yourself. You can do it either before or after you enabled the setting again, although it might be easier to do it before. To trigger a recheck, you can and should drop and recreate the foreign key, just to make sure everything is consistent now.

Body:
I have defined 2 tables and a foriegn key constraint between them as follows:

| users | CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_master_id` int(11) NOT NULL,
  `user_type_id` int(11) NOT NULL,
  `user_group_id` int(11) NOT NULL,
  `user_type_code` char(1) NOT NULL,
  `membership_number` varchar(40) NOT NULL,
  `password` varchar(60) NOT NULL,
  `email` varchar(200) NOT NULL,
  `isd` varchar(10) NOT NULL,
  `mobile` varchar(20) NOT NULL,
  `passenger_id` int(11) NOT NULL,
  `added_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `added_by` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
  KEY `account_master_id` (`account_master_id`),
  CONSTRAINT `acMaster_to_user` FOREIGN KEY (`account_master_id`) REFERENCES `account_master` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=189 DEFAULT CHARSET=utf8 |

user_oauth | CREATE TABLE `user_oauth` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `service` varchar(30) NOT NULL,
  `auth_id` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `auto_share` tinyint(4) NOT NULL,
  `photo` varchar(255) NOT NULL,
  `auth_token_short` varchar(255) DEFAULT NULL,
  `auth_details` text NOT NULL,
  `device_type` varchar(60) NOT NULL,
  `login_date` datetime NOT NULL,
  `login_ip` varchar(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user` (`user_id`),
  CONSTRAINT `user_to_oauth` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=109 DEFAULT CHARSET=latin1 |

on deleting a row from users table, deletes corresponding entries from user_oauth table in LOCAL and Staging environment. but however same thing is not working in PRODUCTION environment. I want to know how can i debug this.

update:

both tables are innodb

running mysql in strict mode

Body:
The reasons why foreign keys might not work are:

they are not supported (e.g. on MyISAM-tables)

they are disabled

MySQL allows you to disable foreign key contraints by setting the system variable foreign_key_checks to 0. This will allow you to violate all foreign key constraints (e.g. delete a parent or add parentless childs). But it will in turn also disable related features like cascades, which are there to automatically prevent specific constraint violations (by e.g. deleting the children) - which of course won't occur anymore if the option is disabled.

The idea is to help you with some administration tasks, e.g. importing data when the referenced data is not yet there, but should usually not be used during normal operation. If the setting reappears, you might want to check your apps if one is setting this option by accident, as it is enabled after every server start by default and has to be disabled explicitely.

You can check the current setting by e.g. using

select @@foreign_key_checks;

You can use

SET foreign_key_checks = 1;

to enable it again, but be aware that it will not check your current data:

Setting foreign_key_checks to 1 does not trigger a scan of the existing table data. Therefore, rows added to the table while foreign_key_checks=0 will not be verified for consistency.

So you will have to check and fix it yourself. You can do it either before or after you enabled the setting again, although it might be easier to do it before. To trigger a recheck, you can and should drop and recreate the foreign key, just to make sure everything is consistent now.


问:
Is there a built-in function to sort and filter a python list in one step?
Given a directory of files all with numeric names, I currently sort and filter the directory list in two steps.

```<code>#files = os.listdir(path)
files = ["0", "1", "10", "5", "2", "11", "4", "15", "18", "14", "7", "8", "9"]

firstFile =  5
lastFile  = 15

#filter out any files that are not in the desired range
files = filter(lambda f: int(f) >= firstFile and int(f) < lastFile, files)

#sort the remaining files by timestamp
files.sort(lambda a,b: cmp(int(a), int(b)))
</code>```

Is there a python function that combines the filter and sort operations so the list only needs to be iterated over once?

答:
The most straightforward way to do this is (in 2.6 at least) is to create a filtering generator using itertools.ifilter and then sort it:

```<code>>>> from itertools import ifilter
>>> seq = [ 1, 43, 2, 10, 11, 91, 201]
>>> gen = ifilter(lambda x: x % 2 == 1, seq)
>>> sorted(gen)
[1, 11, 43, 91, 201]
</code>```

The underlying sequence doesn't get traversed and filtered until sorted starts iterating over it.

Body:
Given a directory of files all with numeric names, I currently sort and filter the directory list in two steps.

#files = os.listdir(path)
files = ["0", "1", "10", "5", "2", "11", "4", "15", "18", "14", "7", "8", "9"]

firstFile =  5
lastFile  = 15

#filter out any files that are not in the desired range
files = filter(lambda f: int(f) >= firstFile and int(f) < lastFile, files)

#sort the remaining files by timestamp
files.sort(lambda a,b: cmp(int(a), int(b)))

Is there a python function that combines the filter and sort operations so the list only needs to be iterated over once?

Body:
The most straightforward way to do this is (in 2.6 at least) is to create a filtering generator using itertools.ifilter and then sort it:

>>> from itertools import ifilter
>>> seq = [ 1, 43, 2, 10, 11, 91, 201]
>>> gen = ifilter(lambda x: x % 2 == 1, seq)
>>> sorted(gen)
[1, 11, 43, 91, 201]

The underlying sequence doesn't get traversed and filtered until sorted starts iterating over it.


问:
How to make a 1s second pause inside a forEach loop reading a firebase file?
I have the follow javascript function that reads data from firebase inside an each loop.

I am using it to plot the data in a google map trough its API.

I would like to know how to make a 1second pause between each round of the loop.

var markers = [];
var mapObject;
var z = 0;
var myLatLngA = [];

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    snapshot.forEach(function(item) {
      var objc = {
        lat: item.val().lat,
        lng: item.val().lng
      };
      myLatLngA.push(objc);
      //setMapOnAll(null);
      var marker = new google.maps.Marker({
        position: myLatLngA[z],
        map: mapObject
      });
      markers.push(marker);
      marker.setMap(mapObject);
      z++;
    });
  });
});
```

答:
<s>Wrap your loop code in a setTimeout:

```<code>$(function () {
    firebase.database().ref('clicks').on('value', function (snapshot) {
        snapshot.forEach(function (item) {
            setTimeout(function () {
                var objc = {
                    lat: item.val().lat,
                    lng: item.val().lng
                };
                myLatLngA.push(objc);
                //setMapOnAll(null);
                var marker = new google.maps.Marker({
                    position: myLatLngA[z],
                    map: mapObject
                });
                markers.push(marker);
                marker.setMap(mapObject);
                z++;
            }, 1000); // 1 second
        });
    });
});
</code>```

</s>
Use RxJs observables, so something like:

```<code>let markers = [];
let mapObject;
let z = 0;
let myLatLngA = [];

$(function () {
    const clickValueObserver = Rx.Observable.fromEvent(firebase.database().ref('clicks'), 'value')
        .map(snapshot => Rx.Observable.from(snapshot)
            .concatMap(item => Rx.Observable.timer(1000) // every 1 second
                .mapTo(item)))
        .concatAll();

    clickValueObserver.subscribe(item => {
        let objc = {
            lat: item.val().lat,
            lng: item.val().lng
        };
        myLatLngA.push(objc);
        //setMapOnAll(null);
        let marker = new google.maps.Marker({
            position: myLatLngA[z],
            map: mapObject
        });
        markers.push(marker);
        marker.setMap(mapObject);
        z++;
    });
});
</code>```

The difficult part was figuring out how to prevent it from stopping midway through processing an event data when a new event arrives yet, keep track of all the events and process them even with the delay in the processing. The concatX methods were really the key.

Sample: (click X times and observe that the contents of the array is displayed every 1 second, and this is done X times):

const myStuff = Array.from(Array(5).keys());
let clicks = Rx.Observable.fromEvent(document, 'click')
  .mapTo(Rx.Observable.from(myStuff)
    .concatMap(myVal => Rx.Observable.timer(1000)
      .mapTo(myVal)));
clicks.concatAll().subscribe(val => console.log(val));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.min.js"></script></code>```

Ref: https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35

Body:
<s>Wrap your loop code in a setTimeout:

$(function () {
    firebase.database().ref('clicks').on('value', function (snapshot) {
        snapshot.forEach(function (item) {
            setTimeout(function () {
                var objc = {
                    lat: item.val().lat,
                    lng: item.val().lng
                };
                myLatLngA.push(objc);
                //setMapOnAll(null);
                var marker = new google.maps.Marker({
                    position: myLatLngA[z],
                    map: mapObject
                });
                markers.push(marker);
                marker.setMap(mapObject);
                z++;
            }, 1000); // 1 second
        });
    });
});

</s>
Use RxJs observables, so something like:

let markers = [];
let mapObject;
let z = 0;
let myLatLngA = [];

$(function () {
    const clickValueObserver = Rx.Observable.fromEvent(firebase.database().ref('clicks'), 'value')
        .map(snapshot => Rx.Observable.from(snapshot)
            .concatMap(item => Rx.Observable.timer(1000) // every 1 second
                .mapTo(item)))
        .concatAll();

    clickValueObserver.subscribe(item => {
        let objc = {
            lat: item.val().lat,
            lng: item.val().lng
        };
        myLatLngA.push(objc);
        //setMapOnAll(null);
        let marker = new google.maps.Marker({
            position: myLatLngA[z],
            map: mapObject
        });
        markers.push(marker);
        marker.setMap(mapObject);
        z++;
    });
});

The difficult part was figuring out how to prevent it from stopping midway through processing an event data when a new event arrives yet, keep track of all the events and process them even with the delay in the processing. The concatX methods were really the key.

Sample: (click X times and observe that the contents of the array is displayed every 1 second, and this is done X times):

const myStuff = Array.from(Array(5).keys());
let clicks = Rx.Observable.fromEvent(document, 'click')
  .mapTo(Rx.Observable.from(myStuff)
    .concatMap(myVal => Rx.Observable.timer(1000)
      .mapTo(myVal)));
clicks.concatAll().subscribe(val => console.log(val));

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.min.js"></script>

Ref: https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35


问:
Insert data to MySql with loop instead of one by one
My Html code is below:

```<code><form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">
    <tr>
        <td><input type="text" name="finanIns1" id="finanIns1" value=""></td>

        <td id="balance"><input type="number" name="balance1" id="balance1" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm1" id="monthlyComm1" value="" min="0"></td>
    </tr>
    <tr>
        <td><input type="text" name="finanIns2" id="finanIns2" value=""></td>

        <td id="balance"><input type="number" name="balance2" id="balance2" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm2" id="monthlyComm2" value="" min="0"></td>
    </tr>
    <tr>
        <td><input type="text" name="finanIns3" id="finanIns3" value=""></td>

        <td id="balance"><input type="number" name="balance3" id="balance3" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm3" id="monthlyComm3" value="" min="0"></td>
    </tr>
    <tr>

</form>
</code>```

My post.php code is below:

```<code>    require_once 'db/dbfunction.php';
    require_once 'db/dbCreditAssessment.php';

    session_start();
    $con = open_connection();
$finanIns1 = $_POST['finanIns1'];
$balance1 = $_POST['balance1'];
$monthlyComm1 = $_POST['monthlyComm1'];

$finanIns2 = $_POST['finanIns2'];
$balance2 = $_POST['balance2'];
$monthlyComm2 = $_POST['monthlyComm2'];

$finanIns3 = $_POST['finanIns3'];
$balance3 = $_POST['balance3'];
$monthlyComm3 = $_POST['monthlyComm3'];

addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1);
addemployementdetails($con,$finanIns2,$balance2,$monthlyComm2);
addemployementdetails($con,$finanIns3,$balance3,$monthlyComm3);

close_connection($con);
</code>```

my dbCreditAssessment.php code is below:

```<code>function addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1){

    $query = "insert into employementdetails(finance,balance,monthlycomm)
            values('$finanIns1','$balance1','$monthlyComm1')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }
}
</code>```

this function will repeat 3 times.
Actually, there are a lot more of the same fields to key in. e.g. finanIns1, finanIns2, finanIns3, finanIns4, finanIns5, ect.

Is there any way to use a loop to replace this way of inserting data?
Also, if the fields are empty, the data will not be inserted to Mysql

答:
this might help.

```<code>for($i = 1 ; $i < 4 ; $i++){
  $finanIns = $_POST['finanIns'.$i];
  $balance = $_POST['balance3'.$i];
  $monthlyComm = $_POST['monthlyComm3'.$i];
  if($finanIns != "" && $balance != "" && $monthlyComm != ""){
    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
  }
}
</code>```

another code snippet

IF number of inputs are user desired.then you need to add a hidden input that holds the number of table row that contains the finanIns,balance,monthlyComm inputs.

you can put name="finanIns[]" if you have 3 or more inputs there. if YES then just use it and access the value as $_POST['finanIns'][$i]

```<code>for($i = 1 ; $i < $_POST['number_of_inputs']  ; $i++){
  $finanIns = $_POST['finanIns'][$i];
  $balance = $_POST['balance'][$i];
  $monthlyComm = $_POST['monthlyComm'][$i];
  if($finanIns != "" && $balance != "" && $monthlyComm != ""){
    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
  }
}
</code>```

Body:
My Html code is below:

<form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">

        <input type="text" name="finanIns1" id="finanIns1" value="">

        <input type="number" name="balance1" id="balance1" value="" min="0">
        <input type="number" name="monthlyComm1" id="monthlyComm1" value="" min="0">

        <input type="text" name="finanIns2" id="finanIns2" value="">

        <input type="number" name="balance2" id="balance2" value="" min="0">
        <input type="number" name="monthlyComm2" id="monthlyComm2" value="" min="0">

        <input type="text" name="finanIns3" id="finanIns3" value="">

        <input type="number" name="balance3" id="balance3" value="" min="0">
        <input type="number" name="monthlyComm3" id="monthlyComm3" value="" min="0">

</form>

My post.php code is below:

    require_once 'db/dbfunction.php';
    require_once 'db/dbCreditAssessment.php';

    session_start();
    $con = open_connection();
$finanIns1 = $_POST['finanIns1'];
$balance1 = $_POST['balance1'];
$monthlyComm1 = $_POST['monthlyComm1'];

$finanIns2 = $_POST['finanIns2'];
$balance2 = $_POST['balance2'];
$monthlyComm2 = $_POST['monthlyComm2'];

$finanIns3 = $_POST['finanIns3'];
$balance3 = $_POST['balance3'];
$monthlyComm3 = $_POST['monthlyComm3'];

addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1);
addemployementdetails($con,$finanIns2,$balance2,$monthlyComm2);
addemployementdetails($con,$finanIns3,$balance3,$monthlyComm3);

close_connection($con);

my dbCreditAssessment.php code is below:

function addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1){

    $query = "insert into employementdetails(finance,balance,monthlycomm)
            values('$finanIns1','$balance1','$monthlyComm1')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !
";
                     echo "Back to Home";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }
}

this function will repeat 3 times.
Actually, there are a lot more of the same fields to key in. e.g. finanIns1, finanIns2, finanIns3, finanIns4, finanIns5, ect.

Is there any way to use a loop to replace this way of inserting data?
Also, if the fields are empty, the data will not be inserted to Mysql

Body:
this might help.

for($i = 1 ; $i < 4 ; $i++){
  $finanIns = $_POST['finanIns'.$i];
  $balance = $_POST['balance3'.$i];
  $monthlyComm = $_POST['monthlyComm3'.$i];
  if($finanIns != "" && $balance != "" && $monthlyComm != ""){
    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
  }
}

another code snippet

IF number of inputs are user desired.then you need to add a hidden input that holds the number of table row that contains the finanIns,balance,monthlyComm inputs.

you can put name="finanIns[]" if you have 3 or more inputs there. if YES then just use it and access the value as $_POST['finanIns'][$i]

for($i = 1 ; $i < $_POST['number_of_inputs']  ; $i++){
  $finanIns = $_POST['finanIns'][$i];
  $balance = $_POST['balance'][$i];
  $monthlyComm = $_POST['monthlyComm'][$i];
  if($finanIns != "" && $balance != "" && $monthlyComm != ""){
    addemployementdetails($con,$finanIns,$balance,$monthlyComm);
  }
}


问:
Change position of labels to be inside data set circles
I am using the iOS-Charts framework and have the following chart:

I would like to change the position of the numbers (labels) to appear within the circle. Is it possible to achieve this?

答:
Inside LineChartRenderer.swift, increased the value of y when text is being drawn, I increase it by 30 in this example:

```<code> if dataSet.isDrawValuesEnabled {
                    ChartUtils.drawText(
                        context: context,
                        text: formatter.stringForValue(
                            e.y,
                            entry: e,
                            dataSetIndex: i,
                            viewPortHandler: viewPortHandler),
                        point: CGPoint(
                            x: pt.x,
                            y: pt.y - CGFloat(valOffset) - valueFont.lineHeight  + 30),
                        align: .center,
                        attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)])
 }
</code>```

Result:

Body:
Inside LineChartRenderer.swift, increased the value of y when text is being drawn, I increase it by 30 in this example:

 if dataSet.isDrawValuesEnabled {
                    ChartUtils.drawText(
                        context: context,
                        text: formatter.stringForValue(
                            e.y,
                            entry: e,
                            dataSetIndex: i,
                            viewPortHandler: viewPortHandler),
                        point: CGPoint(
                            x: pt.x,
                            y: pt.y - CGFloat(valOffset) - valueFont.lineHeight  + 30),
                        align: .center,
                        attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)])
 }

Result:


问:
Android Chronometer always resets to 00:00
In an app I'm working on I need to have a timer that tracks the time from the first login until a certain goal is met. For the timer I have been using a Chronometer.

My problem is that the timer will reset if the user force-closes the app from their background apps. I need the timer to persist and update even if the app is force-closed by the user.

Currently, my code looks as follows:

```<code>            try{
            FileInputStream fileIn = openFileInput(timerFilename);
            InputStreamReader InputRead = new InputStreamReader(fileIn);

            char[] timeInputBuffer = new char[HomeScreen.READ_BLOCK_SIZE];
            t="";
            int timeCharRead;

            while((timeCharRead = InputRead.read(timeInputBuffer))> 0){
                String readString = String.copyValueOf(timeInputBuffer, 0, timeCharRead);
                t += readString;
            }
            InputRead.close();
        } catch(Exception e){
            e.printStackTrace();
        }

 if(t == null) {
        try {
            mChronometer.setBase(SystemClock.elapsedRealtime());
            mChronometer.start();
            FileOutputStream fileout = openFileOutput(timerFilename, MODE_PRIVATE);
            OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
            outputWriter.write(Long.toString(SystemClock.elapsedRealtime()));
            outputWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else{
        long currentTime = SystemClock.elapsedRealtime() - Long.parseLong(t);

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

        mChronometer.setBase(currentTime);
        mChronometer.setText(sdf.format(new Date(currentTime)));
        mChronometer.start();
    }
</code>```

I have omitted some unrelated code for brevity.

The main issue is that after supplying the currentTime long to mChronometer.setBase() and then calling mChronometer.start() the timer seems to be completely random and not start where I want it to.

I understand from researching online that calling setBase() and start() will still cause the timer to start counting from 00:00 but I was under the impression that calling mChronometer.setText() should solve that problem, which it is not.

So my question, how can I keep the timer on-time even if the app is forcibly closed?

答:
From developer.android.com

A service is a component that runs in the background to perform
  long-running operations or to perform work for remote processes. A
  service does not provide a user interface. For example, a service
  might play music in the background while the user is in a different
  application, or it might fetch data over the network without blocking
  user interaction with an activity. Another component, such as an
  activity, can start the service and let it run or bind to it in order
  to interact with it. A service is implemented as a subclass of Service
  and you can learn more about it in the Services developer guide.

So, as long as you create a service, and the user exits your app it will still run. Just like the example above.

This should give you all the information you need:
https://developer.android.com/guide/components/services.html

You can also refer to this for a example on how to implement a countdown timer that runs in a service.

EDIT:

Chronometeris a UI widget (actually a TextView) in Android. So, you can't use it for non-UI purposes. Try to use Timer or CountDownTimer instead.

See this for an example usage of Timer inside Service:

https://stackoverflow.com/a/3819721/5250273

Body:
In an app I'm working on I need to have a timer that tracks the time from the first login until a certain goal is met. For the timer I have been using a Chronometer.

My problem is that the timer will reset if the user force-closes the app from their background apps. I need the timer to persist and update even if the app is force-closed by the user.

Currently, my code looks as follows:

            try{
            FileInputStream fileIn = openFileInput(timerFilename);
            InputStreamReader InputRead = new InputStreamReader(fileIn);

            char[] timeInputBuffer = new char[HomeScreen.READ_BLOCK_SIZE];
            t="";
            int timeCharRead;

            while((timeCharRead = InputRead.read(timeInputBuffer))> 0){
                String readString = String.copyValueOf(timeInputBuffer, 0, timeCharRead);
                t += readString;
            }
            InputRead.close();
        } catch(Exception e){
            e.printStackTrace();
        }

 if(t == null) {
        try {
            mChronometer.setBase(SystemClock.elapsedRealtime());
            mChronometer.start();
            FileOutputStream fileout = openFileOutput(timerFilename, MODE_PRIVATE);
            OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
            outputWriter.write(Long.toString(SystemClock.elapsedRealtime()));
            outputWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else{
        long currentTime = SystemClock.elapsedRealtime() - Long.parseLong(t);

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

        mChronometer.setBase(currentTime);
        mChronometer.setText(sdf.format(new Date(currentTime)));
        mChronometer.start();
    }

I have omitted some unrelated code for brevity.

The main issue is that after supplying the currentTime long to mChronometer.setBase() and then calling mChronometer.start() the timer seems to be completely random and not start where I want it to.

I understand from researching online that calling setBase() and start() will still cause the timer to start counting from 00:00 but I was under the impression that calling mChronometer.setText() should solve that problem, which it is not.

So my question, how can I keep the timer on-time even if the app is forcibly closed?


问:
Is there a C compiler that targets the 8086?
I have an 8086 CPU emulator. It emulates only 8086 instructions. I am searching now for a C compiler to target this emulator with. Is there any C compiler out there that can do this?

Also, having a usable libc and such is not important to me. The emulator uses custom(ie, non-PC) hardware and therefor any libc or even ctr0 would probably have to be rewritten anyway

答:
Open Watcom

Digital Mars

bcc

Body:
Open Watcom

Digital Mars

bcc


答:
You could just delay the appearance of the markers.</p>

```<code>$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    var func = function(item) {
      var objc = {
        lat: item.val().lat,
        lng: item.val().lng
      };
      myLatLngA.push(objc);
      //setMapOnAll(null);
      var marker = new google.maps.Marker({
        position: myLatLngA[z],
        map: mapObject
      });
      markers.push(marker);
      marker.setMap(mapObject);
      z++;
    }
    var i = 0;
    snapshot.forEach(function(item) {
        setTimeout(function() {
            func(item)
        }), i++ * 1000);
    });
  });
});
</code>```

Title: How to make a 1s second pause inside a forEach loop reading a firebase file?

Body:
I have the follow javascript function that reads data from firebase inside an each loop.

I am using it to plot the data in a google map trough its API.

I would like to know how to make a 1second pause between each round of the loop.

var markers = [];
var mapObject;
var z = 0;
var myLatLngA = [];

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    snapshot.forEach(function(item) {
      var objc = {
        lat: item.val().lat,
        lng: item.val().lng
      };
      myLatLngA.push(objc);
      //setMapOnAll(null);
      var marker = new google.maps.Marker({
        position: myLatLngA[z],
        map: mapObject
      });
      markers.push(marker);
      marker.setMap(mapObject);
      z++;
    });
  });
});

Body:
You could just delay the appearance of the markers.

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    var func = function(item) {
      var objc = {
        lat: item.val().lat,
        lng: item.val().lng
      };
      myLatLngA.push(objc);
      //setMapOnAll(null);
      var marker = new google.maps.Marker({
        position: myLatLngA[z],
        map: mapObject
      });
      markers.push(marker);
      marker.setMap(mapObject);
      z++;
    }
    var i = 0;
    snapshot.forEach(function(item) {
        setTimeout(function() {
            func(item)
        }), i++ * 1000);
    });
  });
});


问:
How to show animation in verifone vx520?
I want to show animation in verifone vx520. Here is my code but it doesn't show anything on the screen. How should I my initialize my bitmapped file to this function?
How can I use and animate animationbmp?

```<code>#define RGB2PIXEL565(r,g,b)            \
         ((((r) & 0xf8) << 8) | (((g) & 0xfc) << 3) | (((b) & 0xf8) >> 3))
void animate(void) {
char animationbmp[]="move.bmp"
    int con;
short * frameBuffer;
         frameBuffer=(short*)malloc(8);
         con = open (DEV_CONSOLE, 0);
         frameBuffer[0]= RGB2PIXEL565 (0xFF,  0,  0 ); // red
         frameBuffer[1]= RGB2PIXEL565 (0,   0xFF, 0 ); // green
         frameBuffer[2]= RGB2PIXEL565 (0,   0,  0xFF); // blue
         frameBuffer[3]= RGB2PIXEL565 (0xFF, 0, 0xFF); // purple

         set_display_coordinate_mode (PIXEL_MODE);
         display_frame_buffer(0,0,4,1,frameBuffer);
         display_frame_buffer(1,2,2,2,frameBuffer);
         display_frame_buffer(5,1,1,4,frameBuffer);
}
</code>```

答:
I don't know exactly if Verifone Vx520 can show animation files, but the easiest way to display animation is to periodically change pictures. Here are an example of code:

```<code>void animation(char *file1, char *file2, int x, int y){
    set_display_coordinate_mode(PIXEL_MODE);
    put_BMP_at(x,y, (char *)file1);    //Draw image on a display starting from pos (x;y)
    SVC_WAIT(some_pause_in_msec);    //system function like "sleep"
    put_BMP_at(x,y, (char *)file2);    //Draw image on a display
    SVC_WAIT(some_pause_in_msec);
    set_display_coordinate_mode(CHARACTER_MODE);    //Back to text display mode (optional)
}
</code>```

About how to work with image files (".BMP") you can read here.
Your files must be black-white ".bmp" files for Vx520.

Body:
I want to show animation in verifone vx520. Here is my code but it doesn't show anything on the screen. How should I my initialize my bitmapped file to this function?
How can I use and animate animationbmp?

#define RGB2PIXEL565(r,g,b)            \
         ((((r) & 0xf8) << 8) | (((g) & 0xfc) << 3) | (((b) & 0xf8) >> 3))
void animate(void) {
char animationbmp[]="move.bmp"
    int con;
short * frameBuffer;
         frameBuffer=(short*)malloc(8);
         con = open (DEV_CONSOLE, 0);
         frameBuffer[0]= RGB2PIXEL565 (0xFF,  0,  0 ); // red
         frameBuffer[1]= RGB2PIXEL565 (0,   0xFF, 0 ); // green
         frameBuffer[2]= RGB2PIXEL565 (0,   0,  0xFF); // blue
         frameBuffer[3]= RGB2PIXEL565 (0xFF, 0, 0xFF); // purple

         set_display_coordinate_mode (PIXEL_MODE);
         display_frame_buffer(0,0,4,1,frameBuffer);
         display_frame_buffer(1,2,2,2,frameBuffer);
         display_frame_buffer(5,1,1,4,frameBuffer);
}

Body:
I don't know exactly if Verifone Vx520 can show animation files, but the easiest way to display animation is to periodically change pictures. Here are an example of code:

void animation(char *file1, char *file2, int x, int y){
    set_display_coordinate_mode(PIXEL_MODE);
    put_BMP_at(x,y, (char *)file1);    //Draw image on a display starting from pos (x;y)
    SVC_WAIT(some_pause_in_msec);    //system function like "sleep"
    put_BMP_at(x,y, (char *)file2);    //Draw image on a display
    SVC_WAIT(some_pause_in_msec);
    set_display_coordinate_mode(CHARACTER_MODE);    //Back to text display mode (optional)
}

About how to work with image files (".BMP") you can read here.
Your files must be black-white ".bmp" files for Vx520.


问:
Group DataFrame, apply function with inputs then add result back to original
Can't find this question anywhere, so just try here instead:

What I'm trying to do is basically alter an existing DataFrame object using groupby-functionality, and a self-written function:

```<code>benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c
</code>```

What I want to do, is to groupby field_1, apply a function using specific columns as input, in this case columns x and y, then add back the result to the original DataFrame benchmark as a new column called new_field. The function itself is dependent on the value in field_1, i.e. field_1=a will yield a different result compared to field_1=b etc. (hence the grouping to start with).

Pseudo-code would be something like:

```<code>1. grouped_data = benchmark.groupby(['field_1'])
2. apply own_function to grouped_data; with inputs ('x', 'y', grouped_data)
3. add back result from function to benchmark as column 'new_field'
</code>```

Thanks,

ALTERATION:

```<code>benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c
</code>```

Elaboration:

I also have a DataFrame separate_data containing separate values for x,

```<code>separate_data =

x    a    b    c

1    1    3    7
2    2    5    6
3    2    4    4
4    2    5    9
5    6    1    10
</code>```

that will need to be interpolated onto the existing benchmark DataFrame. Which column in separate_data that should be used for interpolation is dependent on column field_1 in benchmark (i.e. values in set (a,b,c) above). The interpolated value in the new column, is based on x-value in benchmark.

Result:

benchmark =

```<code>x    y    z    field_1  field_new

1    1    3    a        interpolate using separate_data with x=1 and col=a
1    2    5    b        interpolate using separate_data with x=1 and col=b
9    2    4    a        ... etc
1    2    5    c        ...
4    6    1    c        ...
</code>```

Makes sense?

答:
Here is a working example:

```<code># Sample function that sums x and y, then append the field as string.
def func(x, y, z):
    return (x + y).astype(str) + z

benchmark['new_field'] = benchmark.groupby('field_1')\
                                  .apply(lambda x: func(x['x'], x['y'], x['field_1']))\
                                  .reset_index(level = 0, drop = True)
</code>```

Result:

```<code>benchmark
Out[139]:
   x  y  z field_1 new_field
0  1  1  3       a        2a
1  1  2  5       b        3b
2  9  2  4       a       11a
3  1  2  5       c        3c
4  4  6  1       c       10c
</code>```

Body:
Can't find this question anywhere, so just try here instead:

What I'm trying to do is basically alter an existing DataFrame object using groupby-functionality, and a self-written function:

benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c

What I want to do, is to groupby field_1, apply a function using specific columns as input, in this case columns x and y, then add back the result to the original DataFrame benchmark as a new column called new_field. The function itself is dependent on the value in field_1, i.e. field_1=a will yield a different result compared to field_1=b etc. (hence the grouping to start with).

Pseudo-code would be something like:

1. grouped_data = benchmark.groupby(['field_1'])
2. apply own_function to grouped_data; with inputs ('x', 'y', grouped_data)
3. add back result from function to benchmark as column 'new_field'

Thanks,

ALTERATION:

benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c

Elaboration:

I also have a DataFrame separate_data containing separate values for x,

separate_data =

x    a    b    c

1    1    3    7
2    2    5    6
3    2    4    4
4    2    5    9
5    6    1    10

that will need to be interpolated onto the existing benchmark DataFrame. Which column in separate_data that should be used for interpolation is dependent on column field_1 in benchmark (i.e. values in set (a,b,c) above). The interpolated value in the new column, is based on x-value in benchmark.

Result:

benchmark =

x    y    z    field_1  field_new

1    1    3    a        interpolate using separate_data with x=1 and col=a
1    2    5    b        interpolate using separate_data with x=1 and col=b
9    2    4    a        ... etc
1    2    5    c        ...
4    6    1    c        ...

Makes sense?

Body:
Here is a working example:

# Sample function that sums x and y, then append the field as string.
def func(x, y, z):
    return (x + y).astype(str) + z

benchmark['new_field'] = benchmark.groupby('field_1')\
                                  .apply(lambda x: func(x['x'], x['y'], x['field_1']))\
                                  .reset_index(level = 0, drop = True)

Result:

benchmark
Out[139]:
   x  y  z field_1 new_field
0  1  1  3       a        2a
1  1  2  5       b        3b
2  9  2  4       a       11a
3  1  2  5       c        3c
4  4  6  1       c       10c


问:
Getting Cm to ft values and displaying in other element gives reference error
I have the conversion math correct(looked it up here), but getting the value from the element that displays the height in cm, then parse it to ft/inch and display it on(on click) the right hand span does not work, i get a reference error(converter not defined).

I cannot figure out why it is undefined, is it because of hoisting or can the parseInt function not have the parameters as they are?

Here is the function

```<code>var displayInches = document.getElementById("heightInches");

displayInches.addEventListener("click", function() {
toFeet(converter);
});

function toFeet(converter) {
var heightOutputCM = document.getElementById("yourHeight");
 var converter = parseInt(heightOutputCM.value);
 var realFeet = converter * 0.3937 / 12;
 var feet = Math.floor(realFeet);
 var inches = Math.round((realFeet - feet) * 12);
 return feet + "and" + inches;
 }
</code>```

Here is the link:

https://codepen.io/damianocel/pen/ZyRogX

答:
HTML

```<code><h1>Alcohol blood level calculator</h1>

<fieldset>
      <legend>Your Indicators</legend><br>
      <label for="height" class="margin">Height:</label>
      <span class="leftlabel" id=""><span id="yourHeight"></span>Cm</span>
      <input type="range" id="UserInputHeight" name="height" min="0" max="200" step="1" style="width: 200px">
      <span id="heightInchesSpan"  class="rightlabel"><span id="heightInches"></span>Ft</span>
      <br>
      <label for="" class="margin">Gender:</label>
      <span class="leftlabel">Male</span>
      <input type="range" id="salary" name="salary" min="0" max="1" style="width: 200px">
      <span class="rightlabel">Female</span>
 </fieldset>
</code>```

JS

```<code>// get and display height

var displayHeightInput = document.getElementById("UserInputHeight");

displayHeightInput.addEventListener("input", function() {
  sliderChange(this.value);
});

function sliderChange(val) {
  var heightOutput = document.getElementById("yourHeight");
  heightOutput.innerHTML = val;
  toFeet();
  return val;
}

function toFeet() {
  var heightOutputCM = document.getElementById("yourHeight");
  var converter = parseInt(heightOutputCM.innerHTML);
  var realFeet = converter * 0.3937 / 12;
  var feet = Math.floor(realFeet);
  var inches = Math.round((realFeet - feet) * 12);
  document.getElementById("heightInches").innerHTML=feet + "and" + inches;
  return feet + " and " + inches;
}
</code>```

Body:
I have the conversion math correct(looked it up here), but getting the value from the element that displays the height in cm, then parse it to ft/inch and display it on(on click) the right hand span does not work, i get a reference error(converter not defined).

I cannot figure out why it is undefined, is it because of hoisting or can the parseInt function not have the parameters as they are?

Here is the function

var displayInches = document.getElementById("heightInches");

displayInches.addEventListener("click", function() {
toFeet(converter);
});

function toFeet(converter) {
var heightOutputCM = document.getElementById("yourHeight");
 var converter = parseInt(heightOutputCM.value);
 var realFeet = converter * 0.3937 / 12;
 var feet = Math.floor(realFeet);
 var inches = Math.round((realFeet - feet) * 12);
 return feet + "and" + inches;
 }

Here is the link:

https://codepen.io/damianocel/pen/ZyRogX

Body:
HTML

<h1>Alcohol blood level calculator</h1>

<fieldset>
      <legend>Your Indicators</legend><br>
      <label for="height" class="margin">Height:</label>
      <span class="leftlabel" id=""><span id="yourHeight"></span>Cm</span>
      <input type="range" id="UserInputHeight" name="height" min="0" max="200" step="1" style="width: 200px">
      <span id="heightInchesSpan"  class="rightlabel"><span id="heightInches"></span>Ft</span>
      <br>
      <label for="" class="margin">Gender:</label>
      <span class="leftlabel">Male</span>
      <input type="range" id="salary" name="salary" min="0" max="1" style="width: 200px">
      <span class="rightlabel">Female</span>
 </fieldset>

JS

// get and display height

var displayHeightInput = document.getElementById("UserInputHeight");

displayHeightInput.addEventListener("input", function() {
  sliderChange(this.value);
});

function sliderChange(val) {
  var heightOutput = document.getElementById("yourHeight");
  heightOutput.innerHTML = val;
  toFeet();
  return val;
}

function toFeet() {
  var heightOutputCM = document.getElementById("yourHeight");
  var converter = parseInt(heightOutputCM.innerHTML);
  var realFeet = converter * 0.3937 / 12;
  var feet = Math.floor(realFeet);
  var inches = Math.round((realFeet - feet) * 12);
  document.getElementById("heightInches").innerHTML=feet + "and" + inches;
  return feet + " and " + inches;
}


问:
Displaying JPA resultList in console
I've just started to learn JPA 2 and am trying to make a simple display of my table content in console.

This is how my method looks like:

```<code>public static List<Bronie> getListaBroni() {

    EntityManager em = DatabaseHandler.getEntityManager();
    String qString = "SELECT b FROM Bronie b";

    TypedQuery<Bronie> q = em.createQuery(qString, Bronie.class);

    result = q.getResultList();

    return result;

}
</code>```

I'm trying to display it in console, but the result I get is:

```<code>Hibernate: select bronie0_.id as id1_1_, bronie0_.ilosc as ilosc2_1_, bronie0_.kaliber as kaliber3_1_, bronie0_.model_broni as model_br4_1_ from bronie bronie0_
[arma.itemdb.Bronie@7662c85f]
</code>```

So far there's only one object in the database, but I see no point of putting more of them for this question.

I know I have to, somehow, divide the objects I receive in parts that represent different columns, but I have no clue how. And how to avoid this kind of display

```<code>Bronie@7662c85f
</code>```

later?

Don't know if it helps, but I'll be trying to put the result list into a TableView at the end, so I'll probably need to separate each column from the object anyway.

答:
Whenever you try to print a object it calls the toString() method on it. The default implementation returns the object class and hashcode. So if you want to print the Bronie object data you have to @Override the toString() method in you class.

```<code>@Override
public String toString() {
    return "Prop1: '" + this.prop1+ "', Prop2: '" + this.prop2+ "'....;
}
</code>```

Title: Displaying JPA resultList in console

Body:
I've just started to learn JPA 2 and am trying to make a simple display of my table content in console.

This is how my method looks like:

public static List<Bronie> getListaBroni() {

    EntityManager em = DatabaseHandler.getEntityManager();
    String qString = "SELECT b FROM Bronie b";

    TypedQuery<Bronie> q = em.createQuery(qString, Bronie.class);

    result = q.getResultList();

    return result;

}

I'm trying to display it in console, but the result I get is:

Hibernate: select bronie0_.id as id1_1_, bronie0_.ilosc as ilosc2_1_, bronie0_.kaliber as kaliber3_1_, bronie0_.model_broni as model_br4_1_ from bronie bronie0_
[arma.itemdb.Bronie@7662c85f]

So far there's only one object in the database, but I see no point of putting more of them for this question.

I know I have to, somehow, divide the objects I receive in parts that represent different columns, but I have no clue how. And how to avoid this kind of display

Bronie@7662c85f

later?

Don't know if it helps, but I'll be trying to put the result list into a TableView at the end, so I'll probably need to separate each column from the object anyway.

Body:
Whenever you try to print a object it calls the toString() method on it. The default implementation returns the object class and hashcode. So if you want to print the Bronie object data you have to @Override the toString() method in you class.

@Override
public String toString() {
    return "Prop1: '" + this.prop1+ "', Prop2: '" + this.prop2+ "'....;
}


问:
How to link Facebook account to Firebase user in iOS
I'm developing an iOS game in swift and I'm using Firebase database to store some informations about the users (nickname, score, friendly challenges, ...). My idea is to make something similar to Supercell's games where a player can login with its own email and then if he wants some social features he can login using Facebook SDK.

I have both of them working but I can't find a way to join the two. With Facebook Graph API I get all the user's friends already using my game and I want to link them to their own profile on my database.

I tried using the Facebook UID I get during login and the Facebook UID I get from the list of friends but I discovered they are not the same. If the user successfully login I use FBSDKLoginButtonDelegate function

```<code>func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
    print(result.token.userID)
}
</code>```

but as far as I know this token is different in each app. Then I get all the Facebook friends already using my game with this graph request

```<code>let request = FBSDKGraphRequest(graphPath: "me/friends?fields=name,picture", parameters: nil)
</code>```

and for each one I take the "id" field in the JSON response.

I thought about generating a UID then storing it in firebase and maybe in some Facebook field I can get from Facebook Graph API but I don't know which field.

Maybe the solution is easier than I think.

答:
Ok,I think I was misunderstanding something because now it works. The code I posted in my question works correctly to join a private database with Facebook informations.
Thanks to @CBroe comment I tried several times and made it work.</p>

Body:
I'm developing an iOS game in swift and I'm using Firebase database to store some informations about the users (nickname, score, friendly challenges, ...). My idea is to make something similar to Supercell's games where a player can login with its own email and then if he wants some social features he can login using Facebook SDK.

I have both of them working but I can't find a way to join the two. With Facebook Graph API I get all the user's friends already using my game and I want to link them to their own profile on my database.

I tried using the Facebook UID I get during login and the Facebook UID I get from the list of friends but I discovered they are not the same. If the user successfully login I use FBSDKLoginButtonDelegate function

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
    print(result.token.userID)
}

but as far as I know this token is different in each app. Then I get all the Facebook friends already using my game with this graph request

let request = FBSDKGraphRequest(graphPath: "me/friends?fields=name,picture", parameters: nil)

and for each one I take the "id" field in the JSON response.

I thought about generating a UID then storing it in firebase and maybe in some Facebook field I can get from Facebook Graph API but I don't know which field.

Maybe the solution is easier than I think.


问:
Run Infinispan cluster with Server management console using Docker swarm
Hi have successfully managed to get an Infinispan cluster running using docker swarm.  I used this site to figure out how to do it  http://blog.infinispan.org/2016/07/improved-infinispan-docker-image.html

I created my own Overlay network called infinispan.
I then spun up a jgroups-gossip service using the following command:

```<code>docker service create --name jgroupsGossip --replicas 2 --network infinispan jboss/jgroups-gossip
</code>```

Then I spun up a cluster using:

```<code>docker service create --name infinispanTest --replicas 4 --network infinispan jboss/infinispan-server:latest -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]
</code>```

The following command shows the clusters are able to see each other across the two nodes in the swarm

```<code>docker exec -it {CONTAINER_ID} /opt/jboss/infinispan-server/bin/ispn-cli.sh -c "/subsystem=datagrid-infinispan/cache-container=clustered:read-attribute(name=members)"
</code>```

My problem is trying to get the management console running using the following two commands instead of the infinispanTest service.

```<code>docker service create --name infinispanUI --replicas 2 --network infinispan --publish 9990:9990 jboss/infinispan-server domain-controller -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]

docker service create --name infinispanCluster --replicas 4 --network infinispan jboss/infinispan-server host-controller -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]
</code>```

The infinispanCluster service refuses to spin up and when accessing the management console on ip-address:9990 it asks for credentials and then just shows a blank screen.  Anyone tired this setup before and made any progress

Managed to get some logs from one of the infinispanCluster containers.

```<code>Entry point arguments: host-controller -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]
Added user 'user' to file '/opt/jboss/infinispan-server/standalone/configuration/application-users.properties'
Added user 'user' to file '/opt/jboss/infinispan-server/domain/configuration/application-users.properties'
=========================================================================

JBoss Bootstrap Environment

JBOSS_HOME: /opt/jboss/infinispan-server

JAVA: /usr/lib/jvm/java/bin/java

JAVA_OPTS: -server -Xms64m -Xmx512m -XX:MaxMetaspaceSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true

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

15:23:59,225 INFO  [org.jboss.modules] (main) JBoss Modules version 1.5.2.Final
15:23:59,371 INFO  [org.jboss.as.process.Host Controller.status] (main) WFLYPC0018: Starting process 'Host Controller'
[Host Controller] 15:23:59,911 INFO  [org.jboss.modules] (main) JBoss Modules version 1.5.2.Final
[Host Controller] 15:24:00,087 INFO  [org.jboss.msc] (main) JBoss MSC version 1.2.6.Final
[Host Controller] 15:24:00,132 INFO  [org.jboss.as] (MSC service thread 1-7) WFLYSRV0049: Infinispan Server 9.1.0.CR1 (WildFly Core 2.2.0.Final) starting
[Host Controller] 15:24:00,781 INFO  [org.jboss.as.controller.management-deprecated] (Controller Boot Thread) WFLYCTL0028: Attribute 'permgen-size' in the resource at address '/host=c04c29fac2cd/jvm=default' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
[Host Controller] 15:24:00,782 INFO  [org.jboss.as.controller.management-deprecated] (Controller Boot Thread) WFLYCTL0028: Attribute 'max-permgen-size' in the resource at address '/host=c04c29fac2cd/jvm=default' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
[Host Controller] 15:24:00,816 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
[Host Controller]     ("host" => "c04c29fac2cd"),
[Host Controller]     ("core-service" => "discovery-options"),
[Host Controller]     ("static-discovery" => "primary")
[Host Controller] ]) - failure description: "WFLYCTL0113: '' is an invalid value for parameter host. Values must have a minimum length of 1 characters"
[Host Controller] 15:24:00,822 INFO  [org.xnio] (MSC service thread 1-4) XNIO version 3.4.0.Final
[Host Controller] 15:24:00,828 INFO  [org.xnio.nio] (MSC service thread 1-4) XNIO NIO Implementation Version 3.4.0.Final
[Host Controller] 15:24:00,859 FATAL [org.jboss.as.host.controller] (Controller Boot Thread) WFLYHC0034: Host Controller boot has failed in an unrecoverable manner; exiting. See previous messages for details.
[Host Controller] 15:24:00,860 FATAL [org.jboss.as.host.controller] (Controller Boot Thread) WFLYHC0178: Aborting with exit code 99
[Host Controller] 15:24:00,871 INFO  [org.jboss.as] (MSC service thread 1-2) WFLYSRV0050: Infinispan Server 9.1.0.CR1 (WildFly Core 2.2.0.Final) stopped in 6ms
[Host Controller]
15:24:01,198 INFO  [org.jboss.as.process.Host Controller.status] (reaper for Host Controller) WFLYPC0011: Process 'Host Controller' finished with an exit status of 99
15:24:01,200 INFO  [org.jboss.as.process] (Thread-8) WFLYPC0017: Shutting down process controller
15:24:01,201 INFO  [org.jboss.as.process] (Thread-8) WFLYPC0016: All processes finished; exiting
</code>```

答:
The domain mode currently works by linking containers by name. The domain controller is called "dc" and the slaves are linked to it so that the variables DC_PORT, DC_HOST, etc are visible.

Can you follow this naming on docker swarm?

Body:
Hi have successfully managed to get an Infinispan cluster running using docker swarm.  I used this site to figure out how to do it  http://blog.infinispan.org/2016/07/improved-infinispan-docker-image.html

I created my own Overlay network called infinispan.
I then spun up a jgroups-gossip service using the following command:

docker service create --name jgroupsGossip --replicas 2 --network infinispan jboss/jgroups-gossip

Then I spun up a cluster using:

docker service create --name infinispanTest --replicas 4 --network infinispan jboss/infinispan-server:latest -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]

The following command shows the clusters are able to see each other across the two nodes in the swarm

docker exec -it {CONTAINER_ID} /opt/jboss/infinispan-server/bin/ispn-cli.sh -c "/subsystem=datagrid-infinispan/cache-container=clustered:read-attribute(name=members)"

My problem is trying to get the management console running using the following two commands instead of the infinispanTest service.

docker service create --name infinispanUI --replicas 2 --network infinispan --publish 9990:9990 jboss/infinispan-server domain-controller -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]

docker service create --name infinispanCluster --replicas 4 --network infinispan jboss/infinispan-server host-controller -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]

The infinispanCluster service refuses to spin up and when accessing the management console on ip-address:9990 it asks for credentials and then just shows a blank screen.  Anyone tired this setup before and made any progress

Managed to get some logs from one of the infinispanCluster containers.

Entry point arguments: host-controller -Djboss.default.jgroups.stack=tcp-gossip -Djgroups.gossip.initial_hosts=jgroupsGossip[12001]
Added user 'user' to file '/opt/jboss/infinispan-server/standalone/configuration/application-users.properties'
Added user 'user' to file '/opt/jboss/infinispan-server/domain/configuration/application-users.properties'
=========================================================================

JBoss Bootstrap Environment

JBOSS_HOME: /opt/jboss/infinispan-server

JAVA: /usr/lib/jvm/java/bin/java

JAVA_OPTS: -server -Xms64m -Xmx512m -XX:MaxMetaspaceSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true

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

15:23:59,225 INFO  [org.jboss.modules] (main) JBoss Modules version 1.5.2.Final
15:23:59,371 INFO  [org.jboss.as.process.Host Controller.status] (main) WFLYPC0018: Starting process 'Host Controller'
[Host Controller] 15:23:59,911 INFO  [org.jboss.modules] (main) JBoss Modules version 1.5.2.Final
[Host Controller] 15:24:00,087 INFO  [org.jboss.msc] (main) JBoss MSC version 1.2.6.Final
[Host Controller] 15:24:00,132 INFO  [org.jboss.as] (MSC service thread 1-7) WFLYSRV0049: Infinispan Server 9.1.0.CR1 (WildFly Core 2.2.0.Final) starting
[Host Controller] 15:24:00,781 INFO  [org.jboss.as.controller.management-deprecated] (Controller Boot Thread) WFLYCTL0028: Attribute 'permgen-size' in the resource at address '/host=c04c29fac2cd/jvm=default' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
[Host Controller] 15:24:00,782 INFO  [org.jboss.as.controller.management-deprecated] (Controller Boot Thread) WFLYCTL0028: Attribute 'max-permgen-size' in the resource at address '/host=c04c29fac2cd/jvm=default' is deprecated, and may be removed in future version. See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.
[Host Controller] 15:24:00,816 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
[Host Controller]     ("host" => "c04c29fac2cd"),
[Host Controller]     ("core-service" => "discovery-options"),
[Host Controller]     ("static-discovery" => "primary")
[Host Controller] ]) - failure description: "WFLYCTL0113: '' is an invalid value for parameter host. Values must have a minimum length of 1 characters"
[Host Controller] 15:24:00,822 INFO  [org.xnio] (MSC service thread 1-4) XNIO version 3.4.0.Final
[Host Controller] 15:24:00,828 INFO  [org.xnio.nio] (MSC service thread 1-4) XNIO NIO Implementation Version 3.4.0.Final
[Host Controller] 15:24:00,859 FATAL [org.jboss.as.host.controller] (Controller Boot Thread) WFLYHC0034: Host Controller boot has failed in an unrecoverable manner; exiting. See previous messages for details.
[Host Controller] 15:24:00,860 FATAL [org.jboss.as.host.controller] (Controller Boot Thread) WFLYHC0178: Aborting with exit code 99
[Host Controller] 15:24:00,871 INFO  [org.jboss.as] (MSC service thread 1-2) WFLYSRV0050: Infinispan Server 9.1.0.CR1 (WildFly Core 2.2.0.Final) stopped in 6ms
[Host Controller]
15:24:01,198 INFO  [org.jboss.as.process.Host Controller.status] (reaper for Host Controller) WFLYPC0011: Process 'Host Controller' finished with an exit status of 99
15:24:01,200 INFO  [org.jboss.as.process] (Thread-8) WFLYPC0017: Shutting down process controller
15:24:01,201 INFO  [org.jboss.as.process] (Thread-8) WFLYPC0016: All processes finished; exiting


答:
Try something like this:

```<code>groups = benchmark.groupby(benchmark["field_1"])
benchmark = benchmark.join(groups.apply(your_function), on="field_1")
</code>```

In your_function you would create the new column using the other columns that you need, e.g. average them, sum them, etc.

Documentation for apply.
Documentation for join.

Title: Group DataFrame, apply function with inputs then add result back to original

Body:
Try something like this:

groups = benchmark.groupby(benchmark["field_1"])
benchmark = benchmark.join(groups.apply(your_function), on="field_1")

In your_function you would create the new column using the other columns that you need, e.g. average them, sum them, etc.

Documentation for apply.
Documentation for join.


问:
How to build ionic 2 ios app on windows 10?
I am new to ionic 2 and i want to build my app to ios version. What requirements need to install on my windows 10 PC?  Thanks. I hope you can help me. :)</p>

答:
The only way I can think of is by using Ionic Cloud Services:

Ionic Packages makes it easy to build a native binary of your app in
  the cloud. Perfect for developers using Windows that want to build iOS
  apps.

This lets you:

Send your packaged app to others

Build your app for platforms not supported by your computer (e.g. iOS builds on Windows)

Build .ipa and .apk files that you can submit to app stores

You can check the prerequisites here and the steps required to build, here.

EDIT:

You can also take a look at this amazing post from Josh Morony.