问:
GnuPlot splot function with 2d points
I basically want to draw 2d color surface (or contour plot)
 of rosenbrock function f(x,y) = (a-x)^2 + b * (y-x*x) ^2
and append some points (x,y) on this image.

Sample file with points looks as follows:

```<code>#x #y
15.00000 12.00000
8.00000 9.00000
</code>```

The thing is, both graphs do not share the same coordinate system on output image:

coordinate systems do not overlap on each other

gnuplot code:

```
    #!/usr/bin/env gnuplot
    reset
    set terminal png size 700,700
    enhanced set output 'output.png'
    set tmargin screen 1
    set bmargin screen 0
    set border 0 back
    set size square
    xr=20
    yr=20
    set xrange [-xr:xr]
    set yrange [-yr:yr]
    unset key #disablegraph name
    unset colorbox
    set surface
     set multiplot
    set view map
    set cntrparam levels 10# contour tenderness
    set style data pm3d
    set pm3d
    set contour
    a=1 #rosenbrock parameter
    b=1 #rosenbrock parameter</p>

<code>#set isosamples 50
splot (a-x) * (a-x) + b * (y-x*x) * (y-x*x) # 2d rosenbrock
unset view
unset pm3d
plot 'data.dat' pt 5,           'data.dat'  using 1:2:($0+1) with labels offset 1 notitle
</code>```

答:
mixing 2d and surface plots with multiplot is usually a mess. I guess you probably don't need multiplot in this simple case. Maybe something like this is enough:</p>

```<code>set size square
xr=20
yr=20
set xrange [-xr:xr]
set yrange [-yr:yr]
unset key
unset colorbox
set surface
set pm3d map
set contour
set cntrparam levels 10# contour tenderness

rosenbrock(x,y,a,b)= (a-x) * (a-x) + b * (y-x*x) * (y-x*x)

splot rosenbrock(x,y,1,1) w pm3d, 'data.dat' u 1:2:0 w p pt 5, 'data.dat' using 1:2:(1):($0+1) with labels offset 1,1 notitle
</code>```

Title: GnuPlot splot function with 2d points

Body:
I basically want to draw 2d color surface (or contour plot)
 of rosenbrock function f(x,y) = (a-x)^2 + b * (y-x*x) ^2
and append some points (x,y) on this image.

Sample file with points looks as follows:

#x #y
15.00000 12.00000
8.00000 9.00000

The thing is, both graphs do not share the same coordinate system on output image:

coordinate systems do not overlap on each other

gnuplot code:

    #!/usr/bin/env gnuplot
    reset
    set terminal png size 700,700
    enhanced set output 'output.png'
    set tmargin screen 1
    set bmargin screen 0
    set border 0 back
    set size square
    xr=20
    yr=20
    set xrange [-xr:xr]
    set yrange [-yr:yr]
    unset key #disablegraph name
    unset colorbox
    set surface
     set multiplot
    set view map
    set cntrparam levels 10# contour tenderness
    set style data pm3d
    set pm3d
    set contour
    a=1 #rosenbrock parameter
    b=1 #rosenbrock parameter

#set isosamples 50
splot (a-x) * (a-x) + b * (y-x*x) * (y-x*x) # 2d rosenbrock
unset view
unset pm3d
plot 'data.dat' pt 5,           'data.dat'  using 1:2:($0+1) with labels offset 1 notitle

Body:
mixing 2d and surface plots with multiplot is usually a mess. I guess you probably don't need multiplot in this simple case. Maybe something like this is enough:

set size square
xr=20
yr=20
set xrange [-xr:xr]
set yrange [-yr:yr]
unset key
unset colorbox
set surface
set pm3d map
set contour
set cntrparam levels 10# contour tenderness

rosenbrock(x,y,a,b)= (a-x) * (a-x) + b * (y-x*x) * (y-x*x)

splot rosenbrock(x,y,1,1) w pm3d, 'data.dat' u 1:2:0 w p pt 5, 'data.dat' using 1:2:(1):($0+1) with labels offset 1,1 notitle


来源: stackexchange

问:
Is XHTML really Xtensible?
Is there any way (server- or client-side) that I can actually extend HTML to include new tags?  For example, it would be cool if I could write something like a schema fragment that defined a blogpost, which contains a postname, a postauthor, a posttime, and a postcontent, and thereafter refer to blogpost in my HTML rather than resorting to the basic HTML div and p tags.

答:
You can add custom tags to the DOM tree. You won't get valid XHTML, but browsers will understand those tags as long as you style them correctly.

A very interesting project making use of this browser behavior is WebODF, a tool for bringing ODF documents to the browser. Check out the video on the site and the live demo to get some understanding how this works.

ContentLicense: CC BY-SA 2.5

Title: Is XHTML really Xtensible?


问:
NUnit - assembly that reads and writes file
I am unit testing an assembly that uses  File.WriteAllLines() and File.ReadAllText() to read and write persistent data.  When I run the unit test with the NUnit Gui the test fails with an unauthorizedAccessException.

The path that the file is attempting to read and write is being affected of course by the location of program execution.  Depending on if I run NUnit under Visual Studio or directly from the Nunit /bin folder, this is where the attempted read and write operation is taking place.

I have tried to run NUnit as administrator and have copied all of the assemblies directly to the NUnit /bin folder and the test still fails.

I do not want to directly set a path in the assembly.

Any ideas on how to resolve this issue?

答:
With NUnit 3 you should use TestContext to get either TestDirectory or WorkDirectory.
Also there are File Asserts and Directory Asserts, which may help you write your tests in a more readable way.</p>

ContentLicense: CC BY-SA 4.0


问:
Reload a JComponent
How can I reload a component in a JFrame from inside its own class as if I were to remove it, create a new one and add it back again?

Much like a this.repaint(), but actually reconstructing it, if it's possible.

答:
First of all , you should not add a JComponent directly on a frame , Would be better if you add JPanel on JFrame and then add the components on them ..

For Replacing Component on JPanel , you may use the following functions.

```<code>jPanel.remove(comp);
or
jPanel.removeAll();

jPanel.add(comp);
jPanel.revalidate();
jpanel.repaint();
</code>```

In case you want to do with the JFrame only you need to resize the frame a bit after replacing a component for refreshing the frame using jf.setSize(x,y).

```<code>import javax.swing.*;
import java.util.concurrent.*;
public class FrameReplaceComp {
  public static void main(String[] args) throws Exception {

    JFrame frame = new JFrame("Hello swing");
    final JLabel label = new JLabel("Label 1");
    frame.add(label);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 100);
    frame.setVisible(true);

    Thread.sleep(1000);

    final JLabel label1 = new JLabel("Label 2");
    frame.remove(label);
    frame.add(label1);
    frame.setSize(300,101);

  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reload a JComponent

Body:
First of all , you should not add a JComponent directly on a frame , Would be better if you add JPanel on JFrame and then add the components on them ..

For Replacing Component on JPanel , you may use the following functions.

jPanel.remove(comp);
or
jPanel.removeAll();

jPanel.add(comp);
jPanel.revalidate();
jpanel.repaint();

In case you want to do with the JFrame only you need to resize the frame a bit after replacing a component for refreshing the frame using jf.setSize(x,y).

import javax.swing.*;
import java.util.concurrent.*;
public class FrameReplaceComp {
  public static void main(String[] args) throws Exception {

    JFrame frame = new JFrame("Hello swing");
    final JLabel label = new JLabel("Label 1");
    frame.add(label);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 100);
    frame.setVisible(true);

    Thread.sleep(1000);

    final JLabel label1 = new JLabel("Label 2");
    frame.remove(label);
    frame.add(label1);
    frame.setSize(300,101);

  }
}


问:
Status Code 460 on Application Load Balancer
I'm seeing a concerning amount of 460 status codes in the logs of my Application Load Balancer. I don't see any patterns on these codes in regards to times, servers, or request URLs. According to this forum post, the 460 means:

The client has closed the connection with the ALB before the idle
  timeout has kicked in on either the front-end or the back-end
  connection.

I can see the request making it to the backend server and the backend processes the request without issue and very quickly. Why are these errors happening? This ALB does a significant amount of traffic with 6-8 backend servers.

Example ALB Log:

https 2017-01-30T22:46:27.451363Z app/LOAD-BALANCER/bbab458ad0b80d X.X.X.X:55999 10.5.X.X:80 0.000 -1 -1 460 - 132 0 "GET https://www.website.com:443/app/page HTTP/1.1" "-" ECDHE-RSA-AES128-SHA TLSv1 arn:aws:elasticloadbalancing:us-west-2:743462462234:targetgroup/TARGET-GROUP/e6120e5adr245b79107e "Root=1-588fc23e-77aea5adf4534af3de09659d13a08"

Example NGINX log from the backend:

X.X.X.X   1485807955.048  www.website.com     /app/page   -       GET     200     -       0.056   24      text/html; charset=UTF-8        -

答:
There is probably a clue in this sequence:

0.000 -1 -1 460 -

The fields are request_processing_time, target_processing_time, response_processing_time, elb_status_code, target_status_code

The target_processing_time and response_processing_time fields being -1 suggest that there was a problem dispatching the request to the target host, as per http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html

Check that your target is getting the request, there could be some configuration or networking problem between the ALB and the target. ALB inserts a tracing header X-Amzn-Trace-Id into the request when it sends it to the target, perhaps log these on your NGINX backend and see if you're getting the specific requests that are failing.

I've been dealing with a similar problem and it appears to be related to our hosts dropping TCP packets due to TCP offload on our windows hosts.


问:
Laravel Eloquent: How to select from multiple tables
I'm using Laravel and the Eloquent ORM that it provides but I'm struggling to select the data I need.  I have 3 Models

House

Occupants

Job

A house can have multiple occupants and I can easily get these using the following.

```<code>$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();
</code>```

This works nicely but I also want to select the job of each occupant.  I've got this as a one to one relationship but the jobs are in a seperate table.

Is there a way to also select the related job for each occupant from the jobs table efficiently?  I'm guessing it would be something like this

```<code>$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();
</code>```

答:
This query will load all occupants with active = 1 and their jobs:

```<code>House::with(['occupants' => function($q) {
    $q->where('active', 1);
}, 'occupants.job'])->find($house_id);
</code>```

Body:
I'm using Laravel and the Eloquent ORM that it provides but I'm struggling to select the data I need.  I have 3 Models

House

Occupants

Job

A house can have multiple occupants and I can easily get these using the following.

$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();

This works nicely but I also want to select the job of each occupant.  I've got this as a one to one relationship but the jobs are in a seperate table.

Is there a way to also select the related job for each occupant from the jobs table efficiently?  I'm guessing it would be something like this

$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();

Body:
This query will load all occupants with active = 1 and their jobs:

House::with(['occupants' => function($q) {
    $q->where('active', 1);
}, 'occupants.job'])->find($house_id);


问:
How can I make Intent From Activity to Fragment in android?
Like this. It is working good from fragment to activity.</p>
```<code>Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);
</code>```

答:
You will need a framelayout that will hold the fragments and then add this with fragment_container being the id of the framelayout:</p>

```<code>Fragment fragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
                           .replace(R.id.fragment_container, fragment, ragment.getClass().getSimpleName())
                           .commit();
</code>```

Body:
Like this. It is working good from fragment to activity.

Intent intent = new Intent(Location.this,MessageActivity.class);
startActivity(intent);

Body:
You will need a framelayout that will hold the fragments and then add this with fragment_container being the id of the framelayout:

Fragment fragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
                           .replace(R.id.fragment_container, fragment, ragment.getClass().getSimpleName())
                           .commit();


问:
Why BACKSPACE (\b) does not work as intended with a file?
I opened a (text) file, like so: File *fp = fopen("findPattern2.txt", "w+"); in which i have written text. The last character i have in there is a ,. Now i want to delete that character using backspace. I've read the answers here that BACKSPACE only moves the cursor, then i have to overwrite that character by writing on top of it and this is what i do. So I did fprintf(fp, "\b \b") to completely erase the ,, but instead this is what the file shows afterwards:,BS BS. All of these work with a terminal. Why not with a file?

From what I gather the only way to do this to a file would be if i memory mapped it, edit its contents, copy them to a new file and delete the old one.

答:
If you "printf" the BS character to the terminal, the latter interprets this so the cursor will be moved to the left.

But if you "fprintf" the BS character to a file, then the BS character (which is just a byte) will simply be written into the file.


答:
Cursors and line editing are things that consoles and terminals have, not files.

You seem to misunderstand how files work.

There's simply no concept of editing inside a file, it's a sequence of bytes. You can overwrite by using fseek() to move the current location (sometimes called "the cursor" but that's an analogy, it doesn't mean files act like text editors) and then writing the new data.

Title: Why BACKSPACE (\b) does not work as intended with a file?

Body:
I opened a (text) file, like so: File *fp = fopen("findPattern2.txt", "w+"); in which i have written text. The last character i have in there is a ,. Now i want to delete that character using backspace. I've read the answers here that BACKSPACE only moves the cursor, then i have to overwrite that character by writing on top of it and this is what i do. So I did fprintf(fp, "\b \b") to completely erase the ,, but instead this is what the file shows afterwards:,BS BS. All of these work with a terminal. Why not with a file?

From what I gather the only way to do this to a file would be if i memory mapped it, edit its contents, copy them to a new file and delete the old one.


问:
facebook chat in delphi?
I want to connect to facebook chat from my delphi application , change the status message or post something on the wall? Do u know any way i can acomplish this ?</p>

答:
Face book chat uses the XMPP or Jabber Protocol

Other Similar questions on SO

jabber-xmpp-library-for-delphi-7

any-complete-library-for-jabber-in-delphi

Exodus is what we plan on trying in house, http://code.google.com/p/exodus/

As For Posting things on the wall, i think you have to register with Facebook to use the Facebook API

Title: facebook chat in delphi?


问:
How to make debug page in laravel?
I have set mode in .env file as: APP_DEBUG = false;

Now when error is happen it shows empty page with header: "Error".
How to make separated page for that?

答: You can create Blade templates for specific HTTP error codes in resources/views/errors/xxx.blade.php. For instance you can make resources/views/errors/500.blade.php for Internal Server Errors or resources/views/errors/404.blade.php for instances where a page can not be found. More here: https://laravel.com/docs/5.4/errors#custom-http-error-pages

Title: How to make debug page in laravel?


答:
A file is just a collection of bytes that when read in by a program produce  (possibly) meaningful results like a picture or video or whatever. Unless the program knows that a backspace character should delete the proceeding character, it won't do anything.

Your terminal is a program that has been written in just that way to react to special characters like backspace and knows what to do when it receives one though.


问:
Why do I get a mongoose ValidationError?
I am at a beginner level with the MEAN stack, trying to work on the following tutorial: adrianmejia.com/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/. I am using Cloud 9 online IDE.

Part of the tutorial involves testing database POST using curl and Postman. I successfully post a GET request, which at this point in the tutorial gives med an empty array.

I use
curl -XGET myc9urlhere:8080/todos - with success (getting [])

And try curl -XPOST myc9urlhere:8080/todos -d 'name=Somename&completed=false&note=somenote' - failing

The stacktrace is as follows:

```<code>ValidationError: Todo validation failed
    at MongooseError.ValidationError (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/error/validation.js:23:11)
    at model.Document.invalidate (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:1486:32)
    at model.Document.set (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:753:10)
    at model._handleIndex (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:596:14)
    at model.Document.set (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:556:24)
    at model.Document (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:68:10)
    at model.Model (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:47:12)
    at new model (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:3250:13)
    at /home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:1864:51
    at /home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/internal/parallel.js:27:9
    at eachOfArrayLike (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/eachOf.js:57:9)
    at exports.default (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/eachOf.js:9:5)
    at _parallel (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/internal/parallel.js:26:5)
    at parallelLimit (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/parallel.js:85:26)
    at /home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:1882:5
    at Function.create (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:1852:17)
</code>```

A small note is that I have also tried this using the Chrome extension Postman. The tutorial says I must use x-www-form-urlencoded which gives the same error returned. See screenshot. And if I turn to the form-data setting instead, I actually succeed in inserting some data into the database, but just bogus stuff. See the second screenshot.

Postman fail

Postman form-data

I have really tried to research myself - maybe this tutorial is not the greatest place to start either :). Below I will include some details on the code.

Thanks a lot for any help solving this.

Identical to the tutorial, I have created a Model for a todo-list item, as shown (Todo.js):

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

var TodoSchema = new mongoose.Schema({
  name: String,
  completed: Boolean,
  note: String
});

module.exports = mongoose.model('Todo', TodoSchema);
</code>```

Now in my express routing file todos.js I have the following code:

```<code>var express = require('express');
var router = express();
//express.Router() was the original here, that failed on router.get
//as router was then undefined for some reason.

var Todo = require('../models/Todo.js');

/* GET /todos listing. */
router.get('/', function(req, res, next) {
  Todo.find(function (err, todos) {
    if (err) return next(err);
    res.json(todos);
  });
});

/* POST /todos */
router.post('/', function(req, res, next) {
  Todo.create(req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

module.exports = router;
</code>```

Because I do not know exactly what is wrong here I will also post an extract of my app.js showing my database connection

```<code>var routes = require('./routes/index');
var users = require('./routes/users');
var todos = require('./routes/todos');

var app = express();

// load mongoose package
var mongoose = require('mongoose');
// Use native Node promises
mongoose.Promise = global.Promise;
// connect to MongoDB
mongoose.connect('mongodb://'+process.env.IP+'/todo-api')
  .then(() =>  console.log('connection succesful'))
  .catch((err) => console.error(err));

app.use('/', routes);
app.use('/users', users);
app.use('/todos', todos);
</code>```

And the package-json that was generated (I am using Cloud 9 IDE)

```<code>{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "ejs": "*",
    "express": "3.2.6",
    "mongoose": "^4.7.6"
  }
}
</code>```

答: Go to the data folder in your directory. Inside it there is a file mongod.lock. Delete it (you wont require root privileges) just use rm mongod.lock. Come back to main directory and enter ./mongod. hope this will solve the problem</p>

Body:
I am at a beginner level with the MEAN stack, trying to work on the following tutorial: adrianmejia.com/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/. I am using Cloud 9 online IDE.

Part of the tutorial involves testing database POST using curl and Postman. I successfully post a GET request, which at this point in the tutorial gives med an empty array.

I use
curl -XGET myc9urlhere:8080/todos - with success (getting [])

And try curl -XPOST myc9urlhere:8080/todos -d 'name=Somename&completed=false&note=somenote' - failing

The stacktrace is as follows:

ValidationError: Todo validation failed
    at MongooseError.ValidationError (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/error/validation.js:23:11)
    at model.Document.invalidate (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:1486:32)
    at model.Document.set (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:753:10)
    at model._handleIndex (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:596:14)
    at model.Document.set (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:556:24)
    at model.Document (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/document.js:68:10)
    at model.Model (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:47:12)
    at new model (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:3250:13)
    at /home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:1864:51
    at /home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/internal/parallel.js:27:9
    at eachOfArrayLike (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/eachOf.js:57:9)
    at exports.default (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/eachOf.js:9:5)
    at _parallel (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/internal/parallel.js:26:5)
    at parallelLimit (/home/ubuntu/workspace/todo-api/node_modules/mongoose/node_modules/async/parallel.js:85:26)
    at /home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:1882:5
    at Function.create (/home/ubuntu/workspace/todo-api/node_modules/mongoose/lib/model.js:1852:17)

A small note is that I have also tried this using the Chrome extension Postman. The tutorial says I must use x-www-form-urlencoded which gives the same error returned. See screenshot. And if I turn to the form-data setting instead, I actually succeed in inserting some data into the database, but just bogus stuff. See the second screenshot.

Postman fail

Postman form-data

I have really tried to research myself - maybe this tutorial is not the greatest place to start either :). Below I will include some details on the code.

Thanks a lot for any help solving this.

Identical to the tutorial, I have created a Model for a todo-list item, as shown (Todo.js):

var mongoose = require('mongoose');

var TodoSchema = new mongoose.Schema({
  name: String,
  completed: Boolean,
  note: String
});

module.exports = mongoose.model('Todo', TodoSchema);

Now in my express routing file todos.js I have the following code:

var express = require('express');
var router = express();
//express.Router() was the original here, that failed on router.get
//as router was then undefined for some reason.

var Todo = require('../models/Todo.js');

/* GET /todos listing. */
router.get('/', function(req, res, next) {
  Todo.find(function (err, todos) {
    if (err) return next(err);
    res.json(todos);
  });
});

/* POST /todos */
router.post('/', function(req, res, next) {
  Todo.create(req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

module.exports = router;

Because I do not know exactly what is wrong here I will also post an extract of my app.js showing my database connection

var routes = require('./routes/index');
var users = require('./routes/users');
var todos = require('./routes/todos');

var app = express();

// load mongoose package
var mongoose = require('mongoose');
// Use native Node promises
mongoose.Promise = global.Promise;
// connect to MongoDB
mongoose.connect('mongodb://'+process.env.IP+'/todo-api')
  .then(() =>  console.log('connection succesful'))
  .catch((err) => console.error(err));

app.use('/', routes);
app.use('/users', users);
app.use('/todos', todos);

And the package-json that was generated (I am using Cloud 9 IDE)

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "ejs": "*",
    "express": "3.2.6",
    "mongoose": "^4.7.6"
  }
}


问:
Is there another tool out there for building oracle reports other then oracle reports builder?
I cant stand oracle reports builder. Its constantly crashing and sucking in general. Copying and pasting stuff only sometimes works. Elements visualy look selected after you unselect them. AARRRRRRRRGGHHHHHHHHHHHH!!! I need another tool. Are their any alternatives for designing the report jsps? </p>

答:
Microstrategy or Business Objects.
You may develop a custom software as erbsock has told, like a lightweight BO, create views from the selected fields by users, name them as reports and schedule a job to send them as a CSV file or in a jsp file , whatever the view part is.
Also in Oracle Reports Builder, if you are not mentioning the old 6i interfaced tool, try to build one big query and try to build the XML using the publisher. I am outdated about it , but remember something like that.
I will ask about it to an expert friend of mine.

Best Regards,

Kayhan YÜKSEL


答:
You cannot pass the intent to the fragment, what you can do is get the data you have in the intent and pass it to the fragment. The recommended way to do that is to use the newInstance pattern.

Check this answer:
How to pass intent from activity to fragment in Android

Title: How can I make Intent From Activity to Fragment in android?


答: You create a template in the views/error folder with name after the error code you want it to handle see https://laravel.com/docs/5.4/errors#custom-http-error-pages</p>

Title: How to make debug page in laravel?

Body:
I have set mode in .env file as: APP_DEBUG = false;

Now when error is happen it shows empty page with header: "Error".
How to make separated page for that?


问:
Sort in GreenDAO
Raw query:

```<code>SELECT * FROM SAVED_JOB2 S, JOB J WHERE J._id=S._id ORDER BY DATE_SAVED DESC
</code>```

How can I achieve sort for column in JOIN table. I have tried:

```<code>QueryBuilder<Job> queryBuilder = daoSession.queryBuilder(Job.class);
queryBuilder.join(JobDao.Properties.Id, SavedJob2.class, SavedJob2Dao.Properties.Id);
List<Job> list = queryBuilder1.list();
</code>```

This normal JOIN works perfect. But I need to sort for date_saved column in table SavedJob.

I tried to add this line:

```<code>queryBuilder.orderDesc(SavedJob2Dao.Properties.date_saved);
</code>```

But this line returns this error:

Property 'date_saved' is not part of com.xxx.xxx.db.JobDao

```<code>Table JobDao:
id (PK)
title
description
requirements
allowance
type
status

Table SavedJobDao:
id (PK autoincrement)
j_id (FK to JabDao)
date_saved
status
</code>```

答:
You don't need to do any JOIN with greenDao. It works with objects, so in your savedJob you should have an object Job instead job_id.

So you can order by date_saved, but searching in savedJob only, you don't need either JOIN.

There are a lot of examples. And the official doc is awesome!.

Title: Sort in GreenDAO

Body:
Raw query:

SELECT * FROM SAVED_JOB2 S, JOB J WHERE J._id=S._id ORDER BY DATE_SAVED DESC

How can I achieve sort for column in JOIN table. I have tried:

QueryBuilder<Job> queryBuilder = daoSession.queryBuilder(Job.class);
queryBuilder.join(JobDao.Properties.Id, SavedJob2.class, SavedJob2Dao.Properties.Id);
List<Job> list = queryBuilder1.list();

This normal JOIN works perfect. But I need to sort for date_saved column in table SavedJob.

I tried to add this line:

queryBuilder.orderDesc(SavedJob2Dao.Properties.date_saved);

But this line returns this error:

Property 'date_saved' is not part of com.xxx.xxx.db.JobDao

Table JobDao:
id (PK)
title
description
requirements
allowance
type
status

Table SavedJobDao:
id (PK autoincrement)
j_id (FK to JabDao)
date_saved
status


问:
how to add two ultrasonic sensors to PIC microcontroller
i am in troble with when using two ulrasonic sensores, but when working with one sensore, code is working fine. please help me to attach two ultarsnic sensores (HC-SR04) to my code and make this worke fine,

here i am tring to do thing is i want to keep a object with in the range and if the object move LED lights need to be on.

i am using the PIC 16F877A

Working code for one ultrasonic sensor

```<code>    void main()

    {

     int a;

      int b;

      TRISB = 0b00010000;           //RB4 as Input PIN (ECHO)

      TRISC = 0;           //C as Output PINs (LED)

      T1CON = 0x10;                 //Initialize Timer Module

      TRISD  = 1;   // 1 input 0 output ,related to LED (display)

      while(1)

      {

        for(b=1; b<3; b++){

           if (b=2){

                            TMR1H = 0;                  //Sets the Initial Value of Timer

                            TMR1L = 0;                  //Sets the Initial Value of Timer

                            PORTB.F1 = 1;               //TRIGGER HIGH

                            Delay_us(10);               //10uS Delay

                            PORTB.F1 = 0;               //TRIGGER LOW

                            while(!PORTD.F0);           //Waiting for Echo

                            T1CON.F0 = 1;               //Timer Starts

                            while(PORTD.F0);            //Waiting for Echo goes LOW

                            T1CON.F0 = 0;               //Timer Stops

                            a = (TMR1L | (TMR1H<<8));   //Reads Timer Value

                            a = a/58.82;                //Converts Time to Distance

                            a = a + 1;                  //Distance Calibration\
                                     //formular s=ut

                      if(a != 4 ){

                              PORTC = 0b01111111;               // turn on LEDs in the PIC

                              Delay_ms(5);

                              PORTC = 0;               // turn on LEDs in the PIC

                          } else  {

                              //out of range

                              PORTC = 0b00000000;

                          }

                }

              }

      }

    }
</code>```

not working code for two ultarsonic sensers

```<code>    void main()

    {

     int a;

      int b;

      TRISB = 0b00010000;           //RB4 as Input PIN (ECHO)

      TRISC = 0;           //C as Output PINs (LED)

      T1CON = 0x10;                 //Initialize Timer Module

      TRISD  = 1;   // 1 input 0 output ,related to LED (display)

      while(1)

      {

        for(b=1; b<3; b++){

              if(b=1){

                    TMR1H = 0;                  //Sets the Initial Value of Timer

                    TMR1L = 0;                  //Sets the Initial Value of Timer

                    PORTB.F0 = 1;               //TRIGGER HIGH

                    Delay_us(10);               //10uS Delay

                    PORTB.F0 = 0;               //TRIGGER LOW

                    while(!PORTD.F1);           //Waiting for Echo

                    T1CON.F0 = 1;               //Timer Starts

                    while(PORTD.F1);            //Waiting for Echo goes LOW

                    T1CON.F0 = 0;               //Timer Stops

                    a = (TMR1L | (TMR1H<<8));   //Reads Timer Value

                    a = a/58.82;                //Converts Time to Distance

                    a = a + 1;                  //Distance Calibration\
                                   //formular s=ut

                    if(a != 4 ){
            //        PORTB.F3 = 1;
              //      PORTD = 0xFC;              // display number two in LED displa
                //    Delay_ms(5);
                  //  PORTB.F3 = 0;

                            PORTC = 0b00000011;               // turn on LEDs in the PIC

                            Delay_ms(5);

                            PORTC = 0;               // turn on LEDs in the PIC

                        } else  {

                            //out of range

                            PORTC = 0b00000000;

                        }

                }

                else if (b=2){

                      TMR1H = 0;                  //Sets the Initial Value of Timer

                      TMR1L = 0;                  //Sets the Initial Value of Timer

                      PORTB.F1 = 1;               //TRIGGER HIGH

                      Delay_us(10);               //10uS Delay

                      PORTB.F1 = 0;               //TRIGGER LOW

                      while(!PORTD.F0);           //Waiting for Echo

                      T1CON.F0 = 1;               //Timer Starts

                      while(PORTD.F0);            //Waiting for Echo goes LOW

                      T1CON.F0 = 0;               //Timer Stops

                      a = (TMR1L | (TMR1H<<8));   //Reads Timer Value

                      a = a/58.82;                //Converts Time to Distance

                      a = a + 1;                  //Distance Calibration\
                                     //formular s=ut

                      if(a != 4 ){

                              PORTC = 0b01111111;               // turn on LEDs in the PIC

                              Delay_ms(5);

                              PORTC = 0;               // turn on LEDs in the PIC

                          } else  {

                              //out of range

                              PORTC = 0b00000000;

                          }

                }

              }

      }

    }
</code>```

答:
Here is the answer code for two ultrasonic sensors</p>

```<code>    void main()

    {

     int a;

      int b;

      TRISB = 0b00011000;           //RB4 and RB5 as Input PIN (ECHO)
      TRISC = 0;           //C as Output PINs (LED)
      T1CON = 0x10;                 //Initialize Timer Module

      TRISD  = 1;   // 1 input 0 output ,related to LED (display)

      while(1)

      {
        for(b=1; b<3; b++){

              if(b==1){

                    TMR1H = 0;                  //Sets the Initial Value of Timer
                    TMR1L = 0;                  //Sets the Initial Value of Timer

                    PORTB.F0 = 1;               //TRIGGER HIGH
                    Delay_us(10);               //10uS Delay
                    PORTB.F0 = 0;               //TRIGGER LOW

                    while(!PORTB.F4);           //Waiting for Echo
                    T1CON.F0 = 1;               //Timer Starts

                    while(PORTB.F4);            //Waiting for Echo goes LOW
                    T1CON.F0 = 0;               //Timer Stops

                    a = (TMR1L | (TMR1H<<8));   //Reads Timer Value
                    a = a/58.82;                //Converts Time to Distance
                    a = a + 1;                  //Distance Calibration\
                                   //formular s=ut

                    if(a != 4 ){

                            PORTC = 0b00000011;               // turn on LEDs in the PIC

                            Delay_ms(5);
                            PORTC = 0;               // turn on LEDs in the PIC

                        } else  {

                            //out of range

                            PORTC = 0b00000000;

                        }

                }

                else if (b==2){

                      TMR1H = 0;                  //Sets the Initial Value of Timer

                      TMR1L = 0;                  //Sets the Initial Value of Timer

                      PORTB.F1 = 1;               //TRIGGER HIGH

                      Delay_us(10);               //10uS Delay

                      PORTB.F1 = 0;               //TRIGGER LOW

                      while(!PORTB.F5);           //Waiting for Echo

                      T1CON.F0 = 1;               //Timer Starts

                      while(PORTB.F5);            //Waiting for Echo goes LOW

                      T1CON.F0 = 0;               //Timer Stops

                      a = (TMR1L | (TMR1H<<8));   //Reads Timer Value
                      a = a/58.82;                //Converts Time to Distance
                      a = a + 1;                  //Distance Calibration\
                                     //formular s=ut

                      if(a != 4 ){

                              PORTC = 0b01111111;               // turn on LEDs in the PIC
                              Delay_ms(5);
                              PORTC = 0;               // turn on LEDs in the PIC

                          } else  {

                              //out of range
                              PORTC = 0b00000000;

                          }

                }

              }

      }

    }
</code>```

Body:
i am in troble with when using two ulrasonic sensores, but when working with one sensore, code is working fine. please help me to attach two ultarsnic sensores (HC-SR04) to my code and make this worke fine,

here i am tring to do thing is i want to keep a object with in the range and if the object move LED lights need to be on.

i am using the PIC 16F877A

Working code for one ultrasonic sensor

    void main()

    {

     int a;

      int b;

      TRISB = 0b00010000;           //RB4 as Input PIN (ECHO)

      TRISC = 0;           //C as Output PINs (LED)

      T1CON = 0x10;                 //Initialize Timer Module

      TRISD  = 1;   // 1 input 0 output ,related to LED (display)

      while(1)

      {

        for(b=1; b<3; b++){

           if (b=2){

                            TMR1H = 0;                  //Sets the Initial Value of Timer

                            TMR1L = 0;                  //Sets the Initial Value of Timer

                            PORTB.F1 = 1;               //TRIGGER HIGH

                            Delay_us(10);               //10uS Delay

                            PORTB.F1 = 0;               //TRIGGER LOW

                            while(!PORTD.F0);           //Waiting for Echo

                            T1CON.F0 = 1;               //Timer Starts

                            while(PORTD.F0);            //Waiting for Echo goes LOW

                            T1CON.F0 = 0;               //Timer Stops

                            a = (TMR1L | (TMR1H<<8));   //Reads Timer Value

                            a = a/58.82;                //Converts Time to Distance

                            a = a + 1;                  //Distance Calibration\
                                     //formular s=ut

                      if(a != 4 ){

                              PORTC = 0b01111111;               // turn on LEDs in the PIC

                              Delay_ms(5);

                              PORTC = 0;               // turn on LEDs in the PIC

                          } else  {

                              //out of range

                              PORTC = 0b00000000;

                          }

                }

              }

      }

    }

not working code for two ultarsonic sensers

    void main()

    {

     int a;

      int b;

      TRISB = 0b00010000;           //RB4 as Input PIN (ECHO)

      TRISC = 0;           //C as Output PINs (LED)

      T1CON = 0x10;                 //Initialize Timer Module

      TRISD  = 1;   // 1 input 0 output ,related to LED (display)

      while(1)

      {

        for(b=1; b<3; b++){

              if(b=1){

                    TMR1H = 0;                  //Sets the Initial Value of Timer

                    TMR1L = 0;                  //Sets the Initial Value of Timer

                    PORTB.F0 = 1;               //TRIGGER HIGH

                    Delay_us(10);               //10uS Delay

                    PORTB.F0 = 0;               //TRIGGER LOW

                    while(!PORTD.F1);           //Waiting for Echo

                    T1CON.F0 = 1;               //Timer Starts

                    while(PORTD.F1);            //Waiting for Echo goes LOW

                    T1CON.F0 = 0;               //Timer Stops

                    a = (TMR1L | (TMR1H<<8));   //Reads Timer Value

                    a = a/58.82;                //Converts Time to Distance

                    a = a + 1;                  //Distance Calibration\
                                   //formular s=ut

                    if(a != 4 ){
            //        PORTB.F3 = 1;
              //      PORTD = 0xFC;              // display number two in LED displa
                //    Delay_ms(5);
                  //  PORTB.F3 = 0;

                            PORTC = 0b00000011;               // turn on LEDs in the PIC

                            Delay_ms(5);

                            PORTC = 0;               // turn on LEDs in the PIC

                        } else  {

                            //out of range

                            PORTC = 0b00000000;

                        }

                }

                else if (b=2){

                      TMR1H = 0;                  //Sets the Initial Value of Timer

                      TMR1L = 0;                  //Sets the Initial Value of Timer

                      PORTB.F1 = 1;               //TRIGGER HIGH

                      Delay_us(10);               //10uS Delay

                      PORTB.F1 = 0;               //TRIGGER LOW

                      while(!PORTD.F0);           //Waiting for Echo

                      T1CON.F0 = 1;               //Timer Starts

                      while(PORTD.F0);            //Waiting for Echo goes LOW

                      T1CON.F0 = 0;               //Timer Stops

                      a = (TMR1L | (TMR1H<<8));   //Reads Timer Value

                      a = a/58.82;                //Converts Time to Distance

                      a = a + 1;                  //Distance Calibration\
                                     //formular s=ut

                      if(a != 4 ){

                              PORTC = 0b01111111;               // turn on LEDs in the PIC

                              Delay_ms(5);

                              PORTC = 0;               // turn on LEDs in the PIC

                          } else  {

                              //out of range

                              PORTC = 0b00000000;

                          }

                }

              }

      }

    }

Body:
Here is the answer code for two ultrasonic sensors

    void main()

    {

     int a;

      int b;

      TRISB = 0b00011000;           //RB4 and RB5 as Input PIN (ECHO)
      TRISC = 0;           //C as Output PINs (LED)
      T1CON = 0x10;                 //Initialize Timer Module

      TRISD  = 1;   // 1 input 0 output ,related to LED (display)

      while(1)

      {
        for(b=1; b<3; b++){

              if(b==1){

                    TMR1H = 0;                  //Sets the Initial Value of Timer
                    TMR1L = 0;                  //Sets the Initial Value of Timer

                    PORTB.F0 = 1;               //TRIGGER HIGH
                    Delay_us(10);               //10uS Delay
                    PORTB.F0 = 0;               //TRIGGER LOW

                    while(!PORTB.F4);           //Waiting for Echo
                    T1CON.F0 = 1;               //Timer Starts

                    while(PORTB.F4);            //Waiting for Echo goes LOW
                    T1CON.F0 = 0;               //Timer Stops

                    a = (TMR1L | (TMR1H<<8));   //Reads Timer Value
                    a = a/58.82;                //Converts Time to Distance
                    a = a + 1;                  //Distance Calibration\
                                   //formular s=ut

                    if(a != 4 ){

                            PORTC = 0b00000011;               // turn on LEDs in the PIC

                            Delay_ms(5);
                            PORTC = 0;               // turn on LEDs in the PIC

                        } else  {

                            //out of range

                            PORTC = 0b00000000;

                        }

                }

                else if (b==2){

                      TMR1H = 0;                  //Sets the Initial Value of Timer

                      TMR1L = 0;                  //Sets the Initial Value of Timer

                      PORTB.F1 = 1;               //TRIGGER HIGH

                      Delay_us(10);               //10uS Delay

                      PORTB.F1 = 0;               //TRIGGER LOW

                      while(!PORTB.F5);           //Waiting for Echo

                      T1CON.F0 = 1;               //Timer Starts

                      while(PORTB.F5);            //Waiting for Echo goes LOW

                      T1CON.F0 = 0;               //Timer Stops

                      a = (TMR1L | (TMR1H<<8));   //Reads Timer Value
                      a = a/58.82;                //Converts Time to Distance
                      a = a + 1;                  //Distance Calibration\
                                     //formular s=ut

                      if(a != 4 ){

                              PORTC = 0b01111111;               // turn on LEDs in the PIC
                              Delay_ms(5);
                              PORTC = 0;               // turn on LEDs in the PIC

                          } else  {

                              //out of range
                              PORTC = 0b00000000;

                          }

                }

              }

      }

    }


问:
How can i get my Preferences in a other class than the main (Android)?
My main class look like this:

```<code>public class Soundboard extends Activity
{
    SharedPreferences preferences;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

     // Initialize preferences
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

}

private void loadButtonText() {
        startPlayerBtn.setText(preferences.getString("buttontext1", "n/a"));

}
</code>```

This i workning but I have change my code a litte bit with a ButtonAdapter (extra class) but cant find my Preferences there. I you look att the link I have an array that look like this in ButtonAdapter.java:

```<code> public String[] filesnames = {
             "Text button 1",
            "Text button 2",
            "Text button 3"
            };
</code>```

How can I but my settings into the array? Something like this that is not working:

```<code>     public String[] filesnames = {
            preferences.getString("buttontext1", "n/a",
            preferences.getString("buttontext2", "n/a",
            preferences.getString("buttontext3", "n/a"
            };
</code>```

Please help me, I am really stuck.

答:
Change your constructor to look like this:

```<code>public ButtonAdapter(Context c) {
    preferences = PreferenceManager.getDefaultSharedPreferences(c);
    filenames = new String[] {
        preferences.getString("buttontext1", "n/a"),
        preferences.getString("buttontext2", "n/a")
    }
}
</code>```

And then change how you're declaring the filenames array at the end of the class to look like this:

```<code>public String[] filenames;
</code>```

Body:
My main class look like this:

public class Soundboard extends Activity
{
    SharedPreferences preferences;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

     // Initialize preferences
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

}

private void loadButtonText() {
        startPlayerBtn.setText(preferences.getString("buttontext1", "n/a"));

}

This i workning but I have change my code a litte bit with a ButtonAdapter (extra class) but cant find my Preferences there. I you look att the link I have an array that look like this in ButtonAdapter.java:

 public String[] filesnames = {
             "Text button 1",
            "Text button 2",
            "Text button 3"
            };

How can I but my settings into the array? Something like this that is not working:

     public String[] filesnames = {
            preferences.getString("buttontext1", "n/a",
            preferences.getString("buttontext2", "n/a",
            preferences.getString("buttontext3", "n/a"
            };

Please help me, I am really stuck.

Body:
Change your constructor to look like this:

public ButtonAdapter(Context c) {
    preferences = PreferenceManager.getDefaultSharedPreferences(c);
    filenames = new String[] {
        preferences.getString("buttontext1", "n/a"),
        preferences.getString("buttontext2", "n/a")
    }
}

And then change how you're declaring the filenames array at the end of the class to look like this:

public String[] filenames;


问:
Python regex to find phrases contain exact words
I have a list of strings and wish to find exact phases.

So far my code finds the month and year only, but the whole phase including “- Recorded” is needed, like “March 2016 - Recorded”.

How can it add on the “- Recorded” to the regex?

```<code>import re

texts = [

"Shawn Dookhit took annual leave in March 2016 - Recorded The report",
"Soondren Armon took medical leave in February 2017 - Recorded It was in",
"David Padachi took annual leave in May 2016 - Recorded It says",
"Jack Jagoo",
"Devendradutt Ramgolam took medical leave in August 2016 - Recorded Day back",
"Kate Dudhee",
"Vinaye Ramjuttun took annual leave in  - Recorded Answering"

]

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s')

for t in texts:
    try:
        m = regex.search(t)
        print m.group()
    except:
        print "keyword's not found"
</code>```

答:
You got 2 named groups here: month and year which takes month and year from your strings. To get - Recorded into recorded named group you can do this:

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s(?P<recorded>- Recorded)')
```

<p>Or if you can just add <code>- Recorded</code> to your regex without named group:</p>

<pre class="lang-py prettyprint-override"><code>regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s- Recorded')
</code>```

Or you can add named group other with hyphen and one capitalized word:

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s(?P<other>- [A-Z][a-z]+)')
```

I think first or third option is preferable because you already got named groups. Also i recommend you to use this web site http://pythex.org/, it really helps to construct regex :).

Body:
I have a list of strings and wish to find exact phases.

So far my code finds the month and year only, but the whole phase including “- Recorded” is needed, like “March 2016 - Recorded”.

How can it add on the “- Recorded” to the regex?

import re

texts = [

"Shawn Dookhit took annual leave in March 2016 - Recorded The report",
"Soondren Armon took medical leave in February 2017 - Recorded It was in",
"David Padachi took annual leave in May 2016 - Recorded It says",
"Jack Jagoo",
"Devendradutt Ramgolam took medical leave in August 2016 - Recorded Day back",
"Kate Dudhee",
"Vinaye Ramjuttun took annual leave in  - Recorded Answering"

]

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s')

for t in texts:
    try:
        m = regex.search(t)
        print m.group()
    except:
        print "keyword's not found"

Body:
You got 2 named groups here: month and year which takes month and year from your strings. To get - Recorded into recorded named group you can do this:

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s(?P<recorded>- Recorded)')

Or if you can just add - Recorded to your regex without named group:

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s- Recorded')

Or you can add named group other with hyphen and one capitalized word:

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s(?P<other>- [A-Z][a-z]+)')

I think first or third option is preferable because you already got named groups. Also i recommend you to use this web site http://pythex.org/, it really helps to construct regex :).


问:
F# convention for brace placement
Is there a generally accepted convention for brace placement in F#? I found some examples in the documentation here, but they didn't seem to be consistent with each other. In particular, and to take an actual example, is there a consensus as to which is better, this

```<code>seq {
    for polarity, a in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, a) c
    for a0, a1 in orientations (eqn a) do
    for polarity, b in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, b) c
    for b0, b1 in orientations (eqn b) do
    match unify a0 b0 with
    | None ->
        ()
    | Some m ->
        yield
            c
            |> Set.add (true, equal (a0, a1))
            |> Set.add (false, equal (a1, b1))
            |> evalClause m }
</code>```

or this?

```<code>seq {
    for polarity, a in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, a) c
    for a0, a1 in orientations (eqn a) do
    for polarity, b in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, b) c
    for b0, b1 in orientations (eqn b) do
    match unify a0 b0 with
    | None ->
        ()
    | Some m ->
        yield
            c
            |> Set.add (true, equal (a0, a1))
            |> Set.add (false, equal (a1, b1))
            |> evalClause m
}
</code>```

And similarly for square brackets in list and array literals that are too large to be written on one line - is it usual to follow the same convention?

答:
It is inherently difficult to assess what constitutes a "generally accepted" convention... Having said that, there are the F# formatting conventions, part of Fantomas, now also integrated in the Visual F# Power Tools. They discuss placement of braces in records and lists. According to that, the closing brace of a record, or closing ] of a list, should be on the list line - as long as the construct enclosed is not too long. For long constructs, as is the case in your example, the brace should be on a new line.

However, they also say:

Not everyone likes this style, and variation is ok. For large constructs (> 6 lines) the closing token can be on a fresh line

There is no explicit mention of seq { ... }, but I feel that the same logic would apply there. Hence, your second example would be the preferred one.

As for the second part of your question, about arrays and lists: If you go with the Fantomas conventions, short arrays and lists would have their closing thing on the list item, large ones on a new line.

Title: F# convention for brace placement

Body:
Is there a generally accepted convention for brace placement in F#? I found some examples in the documentation here, but they didn't seem to be consistent with each other. In particular, and to take an actual example, is there a consensus as to which is better, this

seq {
    for polarity, a in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, a) c
    for a0, a1 in orientations (eqn a) do
    for polarity, b in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, b) c
    for b0, b1 in orientations (eqn b) do
    match unify a0 b0 with
    | None ->
        ()
    | Some m ->
        yield
            c
            |> Set.add (true, equal (a0, a1))
            |> Set.add (false, equal (a1, b1))
            |> evalClause m }

or this?

seq {
    for polarity, a in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, a) c
    for a0, a1 in orientations (eqn a) do
    for polarity, b in Set.filter (fun (polarity, _) -> polarity) c do
    let c = Set.remove (polarity, b) c
    for b0, b1 in orientations (eqn b) do
    match unify a0 b0 with
    | None ->
        ()
    | Some m ->
        yield
            c
            |> Set.add (true, equal (a0, a1))
            |> Set.add (false, equal (a1, b1))
            |> evalClause m
}

And similarly for square brackets in list and array literals that are too large to be written on one line - is it usual to follow the same convention?


问:
Facing Issue on Getting Current Tabs and Selected Tab URL on Chrome API
I am trying to get the URL of all opened Tabs and Selected Tab using thiese two snippet

```<code>// For Getting URL of All Opened Tabs
chrome.tabs.getCurrent(function(tabs) {
for (var i = 0; i < tabs.length; i++) {
    console.log(tab.url);
     }
});

// For Getting URL of Selected Tab
chrome.tabs.getSelected(function(tab) {
     console.log(tab.url);
});
</code>```

but neither of them working. For getting All Tabs I am getting this error:

Error in response to tabs.getCurrent: TypeError: Cannot read property 'length' of undefined

and for getting the selected Tab

undefined

can you please let me know why this is happening and how can I fix it?

答:
chrome.tabs.getSelected has been deprecated. so we should use tabs.query({active: true}... instead.

chrome.tabs.getCurrent passes a single tab to the callback function. It doesn't "Getting URL of All Opened Tabs", it:

Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).

So:

```<code>// Write the URL of the current tab to the console
chrome.tabs.getCurrent(tab => console.log(tab.url));
</code>```

This requires the "activeTab" or "tabs" permission in the manifest. If there is an error it won't throw an exception, instead it will populate chrome.runtime.lastError.

I find it easier to deal with all the callbacks using an asynchronous or promise wrapper library like chrome-extension-async. This let's us use async/await syntax and a regular try-catch:

```<code>try {
    const currentTab = await chrome.tabs.getCurrent();
    console.log(currentTab.url);
}
catch(err) {
    // Handle errors
}
</code>```

In your popup.html you can't access chrome.tabs.getCurrent - you have to use chrome.tabs.query instead:

```<code>async function writeAllTabUrlToConsole() {
    try {
        // Get all the tabs
        const tabs = await chrome.tabs.query({});

        // Write all their URLs to the popup's console
        for(let t of tabs)
            console.log(t.url, t.active);
    }
    catch(err) {
        // Handle errors
    }
}
</code>```

Body:
I am trying to get the URL of all opened Tabs and Selected Tab using thiese two snippet

// For Getting URL of All Opened Tabs
chrome.tabs.getCurrent(function(tabs) {
for (var i = 0; i < tabs.length; i++) {
    console.log(tab.url);
     }
});

// For Getting URL of Selected Tab
chrome.tabs.getSelected(function(tab) {
     console.log(tab.url);
});

but neither of them working. For getting All Tabs I am getting this error:

Error in response to tabs.getCurrent: TypeError: Cannot read property 'length' of undefined

and for getting the selected Tab

undefined

can you please let me know why this is happening and how can I fix it?

Body:
chrome.tabs.getSelected has been deprecated. so we should use tabs.query({active: true}... instead.

chrome.tabs.getCurrent passes a single tab to the callback function. It doesn't "Getting URL of All Opened Tabs", it:

Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).

So:

// Write the URL of the current tab to the console
chrome.tabs.getCurrent(tab => console.log(tab.url));

This requires the "activeTab" or "tabs" permission in the manifest. If there is an error it won't throw an exception, instead it will populate chrome.runtime.lastError.

I find it easier to deal with all the callbacks using an asynchronous or promise wrapper library like chrome-extension-async. This let's us use async/await syntax and a regular try-catch:

try {
    const currentTab = await chrome.tabs.getCurrent();
    console.log(currentTab.url);
}
catch(err) {
    // Handle errors
}

In your popup.html you can't access chrome.tabs.getCurrent - you have to use chrome.tabs.query instead:

async function writeAllTabUrlToConsole() {
    try {
        // Get all the tabs
        const tabs = await chrome.tabs.query({});

        // Write all their URLs to the popup's console
        for(let t of tabs)
            console.log(t.url, t.active);
    }
    catch(err) {
        // Handle errors
    }
}


问:
subprocess python filenotfounderror: [winerror 2]
I've been using Jupyter Notebook to learn Principal Component Analysis from kaggle), but when I run this code

```<code>     from subprocess import check_output
     print(check_output(["ls", "../input"]).decode("utf8"))
</code>```

I got an error below

```<code>FileNotFoundError Traceback (most recent call last)
<ipython-input-3-de0e39ca3ab8> in <module>()
      1 from subprocess import check_output
----> 2 print(check_output(["ls", "C:/Users/wanglei/Documents/input"]).decode("utf8"))

D:\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    624
    625     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 626                **kwargs).stdout
    627
    628

D:\Anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    691         kwargs['stdin'] = PIPE
    692
--> 693     with Popen(*popenargs, **kwargs) as process:
    694         try:
    695             stdout, stderr = process.communicate(input, timeout=timeout)

D:\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
    945                                 c2pread, c2pwrite,
    946                                 errread, errwrite,
--> 947                                 restore_signals, start_new_session)
    948         except:
    949             # Cleanup if the child failed starting.

D:\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
   1222                                          env,
   1223                                          cwd,
-> 1224                                          startupinfo)
   1225             finally:
   1226                 # Child is launched. Close the parent's copy of those pipe
</code>```

The path is correct, and it seems that all the call from subprocess  will fail similarly.

Does anyone have any idea why this is happening?

答:
try specifying the working directory by adding a cwd arguement, this should work</p>

```<code>import os, subprocess
cwd = os.getcwd()
proc = subprocess.Popen(["ls" ,"../input"], cwd=cwd, stdout=subprocess.PIPE)
output = proc.stdout.read().decode("utf8")
</code>```

Body:
I've been using Jupyter Notebook to learn Principal Component Analysis from kaggle), but when I run this code

     from subprocess import check_output
     print(check_output(["ls", "../input"]).decode("utf8"))

I got an error below

FileNotFoundError Traceback (most recent call last)
<ipython-input-3-de0e39ca3ab8> in <module>()
      1 from subprocess import check_output
----> 2 print(check_output(["ls", "C:/Users/wanglei/Documents/input"]).decode("utf8"))

D:\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
    624
    625     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 626                **kwargs).stdout
    627
    628

D:\Anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    691         kwargs['stdin'] = PIPE
    692
--> 693     with Popen(*popenargs, **kwargs) as process:
    694         try:
    695             stdout, stderr = process.communicate(input, timeout=timeout)

D:\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
    945                                 c2pread, c2pwrite,
    946                                 errread, errwrite,
--> 947                                 restore_signals, start_new_session)
    948         except:
    949             # Cleanup if the child failed starting.

D:\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
   1222                                          env,
   1223                                          cwd,
-> 1224                                          startupinfo)
   1225             finally:
   1226                 # Child is launched. Close the parent's copy of those pipe

The path is correct, and it seems that all the call from subprocess  will fail similarly.

Does anyone have any idea why this is happening?

Body:
try specifying the working directory by adding a cwd arguement, this should work

import os, subprocess
cwd = os.getcwd()
proc = subprocess.Popen(["ls" ,"../input"], cwd=cwd, stdout=subprocess.PIPE)
output = proc.stdout.read().decode("utf8")


问:
How to serve an image along with other information using express api
I want my express api to serve an image file along with other image information.How to make this work at the same time.. thanks.</p>

答:
You can use res.append() Appends the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value. The value parameter can be a string or an array.

res.attachment('path/to/logo.png');
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png


问:
phantomjs call from node.js uing spawn does not seem to execute script
I am trying to generate a pdf file from a dynamic handlebar webpage that would display data from the database.  Once I get this to work on my local machine, I would like to move the code up to elastic beanstalk.  The code seems to run that initially makes the call to spawn, however, call to phantomjs does not seem to kick off the script passed to it.  Just to confirm, I added a console.log statement at the very beginning of the file and never the print out.  Not to mention the other print statement in the script file.  The code is below:

```<code>code that performs the spawn:
var childArgs = [
                  //'--debug=true',
                  path.join(__dirname, '../phantom/capture.js'),
                  id,
                  filename
                ];

            let child = spawn(phantomjs.path, childArgs, {detached: false});

            console.log('set up stderr.....');
            child.stderr.on('data', (data) => {
              console.log('ps stderr: ${data}');
            });

            console.log('set up stdout.....');
            child.stdout.on('data', (data) => {
              console.log('ps stdout: ${data}');
            });

            console.log('set up close.....');
            child.on('close', (code) => {
                console.log('this is a test 2.....');
                console.log(code);
                if (code !== 0){
                    let error = new Error('An error occurred while creating the current report.');
                    error.status = 500;
                    reject(error);
                }

                resolve(fname);
                return;
            });

capture.js:
console.log('we are inside....');
let os = require('os');
var system = require('system');
console.log('we are inside.... 1');
var page = require('webpage').create();
let phantom = require('phantomjs-prebuilt');
console.log('we are inside....2');
var args = system.args;
console.log('we are inside....3');

if (args.length === 1) {
  phantom.exit(0);
} else {
    page.viewportSize = { width: 2000, height: 800 };
//page.paperSize = { format: 'Letter', orientation: 'landscape', margin: '1cm' };
page.paperSize = { width: '1280px', height: '800px', margin: '0px' };
page.settings.localToRemoteUrlAccessEnabled = true;
page.settings.loadImages = true;
page.settings.javascriptEnabled = true;

let done = false;
//"http://example.com/order/" + args[1] + '?token=' + args[2]
page.open("http://example.com/order/" + args[1], function start(status) {
  if (status === "success"){
      page.render(os.tmpdir() + '/' + args[2], { format: 'pdf' });
  }

  done = true;
});

var intervalId = setInterval(function(){
    if (done){
        phantom.exit();
    }
}, 100);
}
</code>```

I am at a loss on where the problem can be.  The first line of capture.js does not seem to get called.  1) What is the problem that I am missing?  2) How can I fix it?

答: The problem could be that PhantomJS couldn't run the capture.js with the path with dots due to security reasons. Try to run the capture.js from the current directory, for example.</p>

Body:
I am trying to generate a pdf file from a dynamic handlebar webpage that would display data from the database.  Once I get this to work on my local machine, I would like to move the code up to elastic beanstalk.  The code seems to run that initially makes the call to spawn, however, call to phantomjs does not seem to kick off the script passed to it.  Just to confirm, I added a console.log statement at the very beginning of the file and never the print out.  Not to mention the other print statement in the script file.  The code is below:

code that performs the spawn:
var childArgs = [
                  //'--debug=true',
                  path.join(__dirname, '../phantom/capture.js'),
                  id,
                  filename
                ];

            let child = spawn(phantomjs.path, childArgs, {detached: false});

            console.log('set up stderr.....');
            child.stderr.on('data', (data) => {
              console.log('ps stderr: ${data}');
            });

            console.log('set up stdout.....');
            child.stdout.on('data', (data) => {
              console.log('ps stdout: ${data}');
            });

            console.log('set up close.....');
            child.on('close', (code) => {
                console.log('this is a test 2.....');
                console.log(code);
                if (code !== 0){
                    let error = new Error('An error occurred while creating the current report.');
                    error.status = 500;
                    reject(error);
                }

                resolve(fname);
                return;
            });

capture.js:
console.log('we are inside....');
let os = require('os');
var system = require('system');
console.log('we are inside.... 1');
var page = require('webpage').create();
let phantom = require('phantomjs-prebuilt');
console.log('we are inside....2');
var args = system.args;
console.log('we are inside....3');

if (args.length === 1) {
  phantom.exit(0);
} else {
    page.viewportSize = { width: 2000, height: 800 };
//page.paperSize = { format: 'Letter', orientation: 'landscape', margin: '1cm' };
page.paperSize = { width: '1280px', height: '800px', margin: '0px' };
page.settings.localToRemoteUrlAccessEnabled = true;
page.settings.loadImages = true;
page.settings.javascriptEnabled = true;

let done = false;
//"http://example.com/order/" + args[1] + '?token=' + args[2]
page.open("http://example.com/order/" + args[1], function start(status) {
  if (status === "success"){
      page.render(os.tmpdir() + '/' + args[2], { format: 'pdf' });
  }

  done = true;
});

var intervalId = setInterval(function(){
    if (done){
        phantom.exit();
    }
}, 100);
}

I am at a loss on where the problem can be.  The first line of capture.js does not seem to get called.  1) What is the problem that I am missing?  2) How can I fix it?


问:
Fabric: check if user is connected to Twitter
I'm using Fabric and I want to check, from my android application if the user is connected on the Twitter application or in the browser. So I have to check the active session. For that I use this code:

```<code>    TwitterSession twitterSession = TwitterCore.getInstance().getSessionManager().getActiveSession();
</code>```

And this is how Fabric added the code in the onCreate of the MainActivity:

```<code>    TwitterAuthConfig authConfig = new TwitterAuthConfig(twitterKey, twitterSecretKey);
    Fabric.with(this, new Twitter(authConfig));
</code>```

Is Fabric initialized correctly?

Why I'm always getting null in the twitterSession? Even if I test it in the  onCreate of the MainActivity?

答:
rTry this

```<code>iv_tweet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                twitterAuthClient.authorize(LoginActivity.this, new Callback<TwitterSession>() {
                    @Override
                    public void success(Result<TwitterSession> twitterSessionResult) {
                        Log.e("success1", "success1");
                        final TwitterSession session = Twitter.getSessionManager().getActiveSession();

                    }

                    @Override

                    public void failure(TwitterException e) {
                        Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
</code>```

and  in onActivity result

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE) {
            twitterAuthClient.onActivityResult(requestCode, resultCode, data);
        }

    }
</code>```

If that doesn't meet your need please comment below

Body:
I'm using Fabric and I want to check, from my android application if the user is connected on the Twitter application or in the browser. So I have to check the active session. For that I use this code:

    TwitterSession twitterSession = TwitterCore.getInstance().getSessionManager().getActiveSession();

And this is how Fabric added the code in the onCreate of the MainActivity:

    TwitterAuthConfig authConfig = new TwitterAuthConfig(twitterKey, twitterSecretKey);
    Fabric.with(this, new Twitter(authConfig));

Is Fabric initialized correctly?

Why I'm always getting null in the twitterSession? Even if I test it in the  onCreate of the MainActivity?

Body:
rTry this

iv_tweet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                twitterAuthClient.authorize(LoginActivity.this, new Callback<TwitterSession>() {
                    @Override
                    public void success(Result<TwitterSession> twitterSessionResult) {
                        Log.e("success1", "success1");
                        final TwitterSession session = Twitter.getSessionManager().getActiveSession();

                    }

                    @Override

                    public void failure(TwitterException e) {
                        Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

and  in onActivity result

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE) {
            twitterAuthClient.onActivityResult(requestCode, resultCode, data);
        }

    }

If that doesn't meet your need please comment below


答:
This code runs the ls command, which is available on all POSIX-conforming systems.

You are using Microsoft Windows. Microsoft Windows does not conform to POSIX by default. For instance, there is no ls binary. Therefore, subprocess cannot find the file ls, and thus emits a FileNotFoundError.

You can install Microsoft's Bash on Windows, which will give you ls.

However, the pythonic and more portable way to list a directory is not to use subprocess in the first place, but the built-in os.listdir:

```<code>import os
print(os.listdir('../input'))
</code>```

Title: subprocess python filenotfounderror: [winerror 2]

Body:
This code runs the ls command, which is available on all POSIX-conforming systems.

You are using Microsoft Windows. Microsoft Windows does not conform to POSIX by default. For instance, there is no ls binary. Therefore, subprocess cannot find the file ls, and thus emits a FileNotFoundError.

You can install Microsoft's Bash on Windows, which will give you ls.

However, the pythonic and more portable way to list a directory is not to use subprocess in the first place, but the built-in os.listdir:

import os
print(os.listdir('../input'))


问:
Firebase Cloud Messaging PHP Integration send push notification
I have integrated the FCM push notification functionality in the PHP. Now, notification is working fine but the badge number is not working.

I have added the badge = 1but every time is't showing 1 instead of increment badges number. I want to send the auto incremented badge number.

Please see my php file code:

```<code> <?php

    $ch = curl_init("https://fcm.googleapis.com/fcm/send");

    //The device token.
    $token = "DEVICE_TOKEN_HERE"; //token here

    //Title of the Notification.
    $title = "Title Notification";

    //Body of the Notification.
    $body = "This is the body show Notification";

    //Creating the notification array.
    $notification = array('title' =>$title, 'text' => $body, 'sound' => 'default', 'badge' => '1');

    //This array contains, the token and the notification. The 'to' attribute stores the token.
    $arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');

    //Generating JSON encoded string form the above array.
    $json = json_encode($arrayToSend);
    //Setup headers:
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key=API_KEY_HERE'; // key here

    //Setup curl, add headers and post parameters.
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);

    //Send the request
    $response = curl_exec($ch);

    //Close request
    curl_close($ch);
    return $response;

?>
</code>```

Please help me!!! Thanks.

答:
This is the expected behavior. iOS doesn't auto-increment the badge you send. You'll have to determine the supposed to be value of the badge on your server-side before you send it.

Also see this post.

Body:
I have integrated the FCM push notification functionality in the PHP. Now, notification is working fine but the badge number is not working.

I have added the badge = 1but every time is't showing 1 instead of increment badges number. I want to send the auto incremented badge number.

Please see my php file code:

 <?php

    $ch = curl_init("https://fcm.googleapis.com/fcm/send");

    //The device token.
    $token = "DEVICE_TOKEN_HERE"; //token here

    //Title of the Notification.
    $title = "Title Notification";

    //Body of the Notification.
    $body = "This is the body show Notification";

    //Creating the notification array.
    $notification = array('title' =>$title, 'text' => $body, 'sound' => 'default', 'badge' => '1');

    //This array contains, the token and the notification. The 'to' attribute stores the token.
    $arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');

    //Generating JSON encoded string form the above array.
    $json = json_encode($arrayToSend);
    //Setup headers:
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key=API_KEY_HERE'; // key here

    //Setup curl, add headers and post parameters.
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);

    //Send the request
    $response = curl_exec($ch);

    //Close request
    curl_close($ch);
    return $response;

?>

Please help me!!! Thanks.


问:
Drupal 7 Solr 4 $query group by
I'm beginner in Drupal 7 et Solr 4. I have $query and I want to do a group by category.
How can I add 'group by' as a parameter to $query (DrupalSolrQueryInterface) ??</p>

答: I solve my problem. In the view of Apache Solr, I enter the parameter and and add the field of group by. That's all.</p>

Title: Drupal 7 Solr 4 $query group by


问:
How to convert a number where I replaced the dot with a comma from a string back to a decimal number
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using  ParseFloat the 2 decimals after the comma disappear.

Example:

User enter in the input field : 79,99 which is then set into the variable totalAmount:

```<code>$('#amount-1').keyup(function() {

getRefundAmount(1); // This function calls the calcTotalAmount function

})

function calcTotalAmount() {
console.log('calcTotalAmount');

var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;

for(var i = 1; i < 4; i++ ) {
    rowAmount = parseFloat($('#amount-' + i).val());
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
}

var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);

$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
    $('#footer-total').text("0.00");
}
}
</code>```

The Result displayed in the footer is : 79.00 instead of 79.99

答:
I tried your code in jsfiddle and got an error on the ".toFixed(2)"
After changing it a bit i could prevent the error.:

```<code>$(function() {
   var totalAmount = '79,99';
   totalAmount = parseFloat( totalAmount.toString().replace(/\,/g, '.'));
   totalAmount = totalAmount.toFixed(2);
   $('#footer-refund').text(totalAmount)
});
</code>```

https://jsfiddle.net/jkrielaars/2gb59xss/1/

Body:
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using  ParseFloat the 2 decimals after the comma disappear.

Example:

User enter in the input field : 79,99 which is then set into the variable totalAmount:

$('#amount-1').keyup(function() {

getRefundAmount(1); // This function calls the calcTotalAmount function

})

function calcTotalAmount() {
console.log('calcTotalAmount');

var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;

for(var i = 1; i < 4; i++ ) {
    rowAmount = parseFloat($('#amount-' + i).val());
    rowRefund = parseFloat($('#result-' + i).text());
    if(!isNaN(rowAmount)) {
        totalAmount += rowAmount;
        totalRefund += rowRefund;
    }
}

var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);

$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
    $('#footer-total').text("0.00");
}
}

The Result displayed in the footer is : 79.00 instead of 79.99

Body:
I tried your code in jsfiddle and got an error on the ".toFixed(2)"
After changing it a bit i could prevent the error.:

$(function() {
   var totalAmount = '79,99';
   totalAmount = parseFloat( totalAmount.toString().replace(/\,/g, '.'));
   totalAmount = totalAmount.toFixed(2);
   $('#footer-refund').text(totalAmount)
});

https://jsfiddle.net/jkrielaars/2gb59xss/1/


问:
Amazon MWS - request signature calculated does not match the signature provided
Getting the following error message from https://mws.amazonservices.com/:

```<code><Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
−
<Message>
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
</Message>
</code>```

Here is the VB.net code I am using to calculate the request.  I have removed the SecretKey and AWSAccessKeyId for security reasons.

```<code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sURL As String = "https://mws.amazonservices.com/"

        Dim sRequest As String = ""
        sRequest &= "Acknowledged=" & Server.UrlEncode("false")
        sRequest &= "&Action=" & Server.UrlEncode("GetReportList")
        sRequest &= "&AWSAccessKeyId=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Marketplace=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Merchant=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&SignatureMethod=" & Server.UrlEncode("HmacSHA256")
        sRequest &= "&SignatureVersion=" & Server.UrlEncode("2")
        sRequest &= "&Timestamp=" & Server.UrlEncode(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssCST"))
        sRequest &= "&Version=" & Server.UrlEncode("2009-01-01")

        Dim StringToSign As String = "GET\n" & "mws.amazonservices.com\n" & "/\n" & sRequest
        sRequest &= "&Signature=" & Server.UrlEncode(HashString(StringToSign))

        Response.Write("<a href=""" & sURL & "?" & sRequest & """>Click here</a>")

    End Sub

    Public Shared Function HashString(ByVal StringToHash As String) As String
        Dim myEncoder As New System.Text.UTF8Encoding
        Dim Key() As Byte = myEncoder.GetBytes("REMOVED-FOR-SECURITY")
        Dim XML() As Byte = myEncoder.GetBytes(StringToHash)
        Dim myHMACSHA256 As New System.Security.Cryptography.HMACSHA256(Key)
        Dim HashCode As Byte() = myHMACSHA256.ComputeHash(XML)
        Return Convert.ToBase64String(HashCode)
    End Function
</code>```

答:
I ran into the same error message when using WebClient to download a file on an Amazon 3S url.
I blogged about it here:
http://blog.cdeutsch.com/2010/11/net-webclient-403-forbidden-error.html

The final solution I used was found here:
GETting a URL with an url-encoded slash

Body:
Getting the following error message from https://mws.amazonservices.com/:

<Type>Sender</Type>
SignatureDoesNotMatch
−
<Message>
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
</Message>

Here is the VB.net code I am using to calculate the request.  I have removed the SecretKey and AWSAccessKeyId for security reasons.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sURL As String = "https://mws.amazonservices.com/"

        Dim sRequest As String = ""
        sRequest &= "Acknowledged=" & Server.UrlEncode("false")
        sRequest &= "&Action=" & Server.UrlEncode("GetReportList")
        sRequest &= "&AWSAccessKeyId=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Marketplace=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Merchant=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&SignatureMethod=" & Server.UrlEncode("HmacSHA256")
        sRequest &= "&SignatureVersion=" & Server.UrlEncode("2")
        sRequest &= "&Timestamp=" & Server.UrlEncode(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssCST"))
        sRequest &= "&Version=" & Server.UrlEncode("2009-01-01")

        Dim StringToSign As String = "GET\n" & "mws.amazonservices.com\n" & "/\n" & sRequest
        sRequest &= "&Signature=" & Server.UrlEncode(HashString(StringToSign))

        Response.Write("Click here")

    End Sub

    Public Shared Function HashString(ByVal StringToHash As String) As String
        Dim myEncoder As New System.Text.UTF8Encoding
        Dim Key() As Byte = myEncoder.GetBytes("REMOVED-FOR-SECURITY")
        Dim XML() As Byte = myEncoder.GetBytes(StringToHash)
        Dim myHMACSHA256 As New System.Security.Cryptography.HMACSHA256(Key)
        Dim HashCode As Byte() = myHMACSHA256.ComputeHash(XML)
        Return Convert.ToBase64String(HashCode)
    End Function


问:
AJAX: Submitting a form without refreshing the page
I have a form similar to the following:

```<code><form method="post" action="mail.php" id="myForm">
   <input type="text" name="fname">
   <input type="text" name="lname">
   <input type="text" name="email">
    <input type="submit">
</form>
</code>```

I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.

I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):

```<code>$.post('mail.php', $('#myForm').serialize());
</code>```

If possible, I would like to get help implementing this using AJAX,

Many thanks in advance

答:
The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:</p>

```<code>var form = document.getElementById('myForm');
var params = {
  method: 'post',
  body: new FormData(form),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
};

form.addEventListener('submit', function (e) {
  window.fetch('mail.php', params).then(function (response) {
    console.log(response.text());
  });
  e.preventDefault();
});
</code>```

Body:
I have a form similar to the following:

<form method="post" action="mail.php" id="myForm">
   <input type="text" name="fname">
   <input type="text" name="lname">
   <input type="text" name="email">
    <input type="submit">
</form>

I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.

I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):

$.post('mail.php', $('#myForm').serialize());

If possible, I would like to get help implementing this using AJAX,

Many thanks in advance

Body:
The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:

var form = document.getElementById('myForm');
var params = {
  method: 'post',
  body: new FormData(form),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
};

form.addEventListener('submit', function (e) {
  window.fetch('mail.php', params).then(function (response) {
    console.log(response.text());
  });
  e.preventDefault();
});


问:
include gwt-graphics into a Eclipse WebApp-Project
I try to include the gwt-graphics library into a WebApp-Project made with Eclipse.

This is the description: https://code.google.com/archive/p/gwt-graphics/wikis/Manual.wiki

"Download gwt-graphics.jar and add it to the class path of your GWT project. In addition, you have to add the following line to the GWT module file:  After these two steps, you are ready to use GWT Graphics in your GWT project!"

I have done this and after I start the app in super-dev-mode, I got an error from the compiler:

"[ERROR] Unable to find 'org/vaadin/gwtgraphics/GWTGraphics.gwt.xml' on your classpath; could be a typo, or maybe you forgot to include a classpath entry for source?"

I am not sure how I can solve this.

答: Did you add it to the class path? If not, you can right click to the jar file and do Add to Classpath</p>


问:
JSF 1.2 outputText tag generates a span
I am new to JSF 1.2,
I am trying to output some text into my javascript call like so

```<code>something(<t:outputText value="#{bean.val}"/>)
</code>```

but instead of getting plain text output, this is all being wrapped in a span. How do i get rid of the span?

答:
I am not sure about t:outputText, but an h:outputText without any other attribute than value should not render any HTML element.

```<code>something(<h:outputText value="#{bean.val}"/>);
</code>```

If you're using id, styleClass or something like that, then it will indeed render a  since those attributes has to get somewhere anyway.

If you're using Facelets as view technology instead of legacy JSP, then you could also just use EL in template text like follows:

```something(#{bean.val})```

Title: JSF 1.2 outputText tag generates a span

Body:
I am new to JSF 1.2,
I am trying to output some text into my javascript call like so

something(<t:outputText value="#{bean.val}"/>)

but instead of getting plain text output, this is all being wrapped in a span. How do i get rid of the span?

Body:
I am not sure about t:outputText, but an h:outputText without any other attribute than value should not render any HTML element.

something(<h:outputText value="#{bean.val}"/>);

If you're using id, styleClass or something like that, then it will indeed render a <span> since those attributes has to get somewhere anyway.

If you're using Facelets as view technology instead of legacy JSP, then you could also just use EL in template text like follows:

something(#{bean.val})