问:
Convert std::vector<std::string> to const char* const*
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

```<code>std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();
</code>```

But when I compile, I got this :

```<code>error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();
</code>```

Here's a live example

答:
With c_str you will get const char*. A const char* const* is an array of const char*.

```<code>  vector<string> vectorOfStrings = {
    "Aa",
    "Bb",
    "Cc"
  };

  vector<const char*> vectorOfCStyleStrings(3);

  // convert from string to C style strings
  for (string item : vectorOfStrings)
    vectorOfCStyleStrings.push_back(item.c_str());

  // get vector like a const C style array
  const char* const* arrayOfCStyleStrings = vectorOfCStyleStrings.data();
</code>```

Body:
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();

But when I compile, I got this :

error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();

Here's a live example

Body:
With c_str you will get const char*. A const char* const* is an array of const char*.

  vector<string> vectorOfStrings = {
    "Aa",
    "Bb",
    "Cc"
  };

  vector<const char*> vectorOfCStyleStrings(3);

  // convert from string to C style strings
  for (string item : vectorOfStrings)
    vectorOfCStyleStrings.push_back(item.c_str());

  // get vector like a const C style array
  const char* const* arrayOfCStyleStrings = vectorOfCStyleStrings.data();


来源: stackexchange

问:
Adding value to individual array values
I am trying to make a leader which starts at a point as per users input and then the second point will be 50 units away in the x & y. I think the concept should work but what i am having problems with adding the 50 to the array values. This is what i have and i'm getting a type mismatch :</p>

```<code>Set annotationObject = Nothing
Dim StartPoint As Variant
leaderType = acLineWithArrow
Dim Count As Integer
Dim points(0 To 5) As Double

StartPoint = ACAD.ActiveDocument.Utility.GetPoint(, "Specify insertion point")
MsgBox StartPoint(0) & "," & StartPoint(1) & "," & StartPoint(2)

StartPoint(3) = StartPoint(0) + 50
StartPoint(4) = StartPoint(1) + 50
StartPoint(5) = StartPoint(2)

Set leader1 = ACAD.ActiveDocument.ModelSpace.AddLeader(StartPoint, annotationObject, leaderType)
</code>```

答:
The line below assigns an array with 3 elements to the variable StartPoint, which is a variant.

```<code>StartPoint = ACAD.ActiveDocument.Utility.GetPoint(, "Specify insertion point")
</code>```

then, the line below tried to add another element to the variant StartPoint.

```<code>StartPoint(3) = StartPoint(0) + 50
</code>```

But since StartPoint already received an array with a single dimension with 3 elements, its internal representation is already set. "Variant variables maintain an internal representation of the values that they store ( - from microsoft)."

Try this:

```<code>Dim StartPoint As Variant
Dim LeaderPt(8) As Double    'a separate array for leader points

'Specify insertion point
StartPoint = ACAD.ActiveDocument.Utility.GetPoint(, "Specify insertion point")

'-----Set points for the leader-----
LeaderPt(0) = StartPoint(0)
LeaderPt(1) = StartPoint(1)
LeaderPt(2) = StartPoint(2)

LeaderPt(3) = StartPoint(0) + 50   '2nd point x coordinate.
LeaderPt(4) = StartPoint(1) + 50   '2nd point y coordinate.
LeaderPt(5) = StartPoint(2)

'add a third point so the last point of the leader won't be set to (0,0,0)
LeaderPt(6) = LeaderPt(3) + 25     '3rd point x coordinate. Offset from second point
LeaderPt(7) = LeaderPt(4)          '3rd point y coordinate. Same as the second point
LeaderPt(8) = LeaderPt(5)
'---

Set leader1 = ACAD.ActiveDocument.ModelSpace.AddLeader(LeaderPt, annotationObject, leaderType)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adding value to individual array values

Body:
I am trying to make a leader which starts at a point as per users input and then the second point will be 50 units away in the x & y. I think the concept should work but what i am having problems with adding the 50 to the array values. This is what i have and i'm getting a type mismatch :

Set annotationObject = Nothing
Dim StartPoint As Variant
leaderType = acLineWithArrow
Dim Count As Integer
Dim points(0 To 5) As Double

StartPoint = ACAD.ActiveDocument.Utility.GetPoint(, "Specify insertion point")
MsgBox StartPoint(0) & "," & StartPoint(1) & "," & StartPoint(2)

StartPoint(3) = StartPoint(0) + 50
StartPoint(4) = StartPoint(1) + 50
StartPoint(5) = StartPoint(2)

Set leader1 = ACAD.ActiveDocument.ModelSpace.AddLeader(StartPoint, annotationObject, leaderType)

Body:
The line below assigns an array with 3 elements to the variable StartPoint, which is a variant.

StartPoint = ACAD.ActiveDocument.Utility.GetPoint(, "Specify insertion point")

then, the line below tried to add another element to the variant StartPoint.

StartPoint(3) = StartPoint(0) + 50

But since StartPoint already received an array with a single dimension with 3 elements, its internal representation is already set. "Variant variables maintain an internal representation of the values that they store ( - from microsoft)."

Try this:

Dim StartPoint As Variant
Dim LeaderPt(8) As Double    'a separate array for leader points

'Specify insertion point
StartPoint = ACAD.ActiveDocument.Utility.GetPoint(, "Specify insertion point")

'-----Set points for the leader-----
LeaderPt(0) = StartPoint(0)
LeaderPt(1) = StartPoint(1)
LeaderPt(2) = StartPoint(2)

LeaderPt(3) = StartPoint(0) + 50   '2nd point x coordinate.
LeaderPt(4) = StartPoint(1) + 50   '2nd point y coordinate.
LeaderPt(5) = StartPoint(2)

'add a third point so the last point of the leader won't be set to (0,0,0)
LeaderPt(6) = LeaderPt(3) + 25     '3rd point x coordinate. Offset from second point
LeaderPt(7) = LeaderPt(4)          '3rd point y coordinate. Same as the second point
LeaderPt(8) = LeaderPt(5)
'---

Set leader1 = ACAD.ActiveDocument.ModelSpace.AddLeader(LeaderPt, annotationObject, leaderType)


问:
Retrieving an entry from a column and comparing with other entries from the same column
I have a database of employees with salary and names as columns. I want to list all employees who are paid more than a particular person named 'x' from the database itself.

How do I solve this query?

答:
Get the salary of the employee 'x' as inner query and check all the records by comparing their salary with x's salary and display them.</p>

```<code>SELECT *
FROM employees
WHERE salary > (SELECT salary
        FROM employees
        WHERE name = 'x' );
</code>```

Body:
Get the salary of the employee 'x' as inner query and check all the records by comparing their salary with x's salary and display them.

SELECT *
FROM employees
WHERE salary > (SELECT salary
        FROM employees
        WHERE name = 'x' );


问:
CellID location with CDMA
Is there a way to determine location via CellID on a CDMA network? I can get a network ID, base station ID, and system ID programatically, but is there an api somewhere to convert these to lat, long coordinates? The CdmaCellLocation.getBaseStationLatitude() and CdmaCellLocation.getBaseStationLongitude() methods return some junk number. Can I convert the cdma dating I'm getting to CID and LAC somehow?

I'm getting a system ID of 40, a network ID of 3, and a base station ID of 4672, and that appears to be exactly worthless.

答: You can download Cell Towers database from opencellid.org . It is a table that it's columns is Cell id , MCC , MNC , Latitude , Logitude and etc . You can Lookup your position of BTS using it's cell id .

ContentLicense: CC BY-SA 2.5

Title: CellID location with CDMA


问:
Avoid repetition when selecting two columns of same table
Each time I would like to work on two variables from the same table, I repeat the table's name for selecting them like in the following example:

```<code>boxplot(hospital.Weight, hospital.Sex)
</code>```

This is a problem if the table's name changes because it requires two further changes to get it right.

Is there a more elegant way to avoid the repetition in the function call?

I tried:

```<code>boxplot(hospital( : , {'Weight', 'Sex'}))
</code>```

But this returns the columns as tables and boxplot as far as I understand only takes vectors.

答:
The answer by @qbzenker is probably the best approach, but if you look for somthing else, you can use cell arrays for this:

```<code>C = table2cell(hospital(:,{'Weight','Sex'})); % this is the only place to change the table name
boxplot([C{:,1}],[C{:,2}])
</code>```

If you want this in a nicer syntax, you can write a small function like:

```<code>function my_BoxPlot(T,F)
C = table2cell(T(:,F));
boxplot([C{:,1}],[C{:,2}])
end
</code>```

and then call it with your preferred syntax:

```<code>subplot 121
my_BoxPlot(hospital,{'Weight','Sex'})
subplot 122
my_BoxPlot(hospital,{'Age','Sex'})
</code>```

Body:
Each time I would like to work on two variables from the same table, I repeat the table's name for selecting them like in the following example:

boxplot(hospital.Weight, hospital.Sex)

This is a problem if the table's name changes because it requires two further changes to get it right.

Is there a more elegant way to avoid the repetition in the function call?

I tried:

boxplot(hospital( : , {'Weight', 'Sex'}))

But this returns the columns as tables and boxplot as far as I understand only takes vectors.

Body:
The answer by @qbzenker is probably the best approach, but if you look for somthing else, you can use cell arrays for this:

C = table2cell(hospital(:,{'Weight','Sex'})); % this is the only place to change the table name
boxplot([C{:,1}],[C{:,2}])

If you want this in a nicer syntax, you can write a small function like:

function my_BoxPlot(T,F)
C = table2cell(T(:,F));
boxplot([C{:,1}],[C{:,2}])
end

and then call it with your preferred syntax:

subplot 121
my_BoxPlot(hospital,{'Weight','Sex'})
subplot 122
my_BoxPlot(hospital,{'Age','Sex'})


问:
how to create simple nodejs script to wrap an binary/executable?
I want to create a nodejs file, that simple runs/wraps an executable binary file with all inputs and outputs.

For now at least on windows.

Why:
wanted to install an executable tool over npm install -g, to have it in console, without PATH changes. (npm global packages are included in PATH)

答:
You can use the bin-wrapper npm package.

EDIT:

There's a better alternative called bin-manager.

Installation:

```<code>$ npm install --save bin-manager
</code>```

Usage

```<code>const bmanager = require('bin-manager');

const base = 'https://github.com/imagemin/gifsicle-bin/raw/master/vendor';
const bin = bmanager('bin', 'gifsicle')
  .src(base + '/macos/gifsicle', 'darwin')
  .src(base + '/linux/x64/gifsicle', 'linux', 'x64')
  .src(base + '/win/x64/gifsicle.exe', 'win32', 'x64')
  .use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');

bin.run(['--version'], (err, out) => {
  if (err) {
    console.log(error);
    return;
  }
  console.log(out.stdout);
});
</code>```

Body:
You can use the bin-wrapper npm package.

EDIT:

There's a better alternative called bin-manager.

Installation:

$ npm install --save bin-manager

Usage

const bmanager = require('bin-manager');

const base = 'https://github.com/imagemin/gifsicle-bin/raw/master/vendor';
const bin = bmanager('bin', 'gifsicle')
  .src(base + '/macos/gifsicle', 'darwin')
  .src(base + '/linux/x64/gifsicle', 'linux', 'x64')
  .src(base + '/win/x64/gifsicle.exe', 'win32', 'x64')
  .use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');

bin.run(['--version'], (err, out) => {
  if (err) {
    console.log(error);
    return;
  }
  console.log(out.stdout);
});


问:
Laravel Datatables search on nested Relationship
I'm currently using datatabels 7.0 and Laravel 5.4
data in my grid is showing correctly but when I want to search on nested relationship column I got below error:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'course_semester.semester.name' in 'where clause' (SQL: select count(*) as aggregate from (select '1' as `row_count` from `videos` where LOWER(`videos`.`id`) LIKE %%te%% and LOWER(`videos`.`name`) LIKE %%te%% and LOWER(`course_semester`.`semester`.`name`) LIKE %%te%%) count_row_table)
</code>```

Here is my code

Controller

```<code>$videos = Video::with(['course_semester' => function ($query) {
            return $query->with('course', 'semester');
        }])->select('videos.*');
        return Datatables::of($videos)
                ->addColumn('check', '<input type="checkbox" name="selected-videos" value="{{$id}}">')
                ->escapeColumns([])
                ->make(true);
</code>```

Javascript

```<code>columns: [
                 { data: 'check' , name: 'check',orderable: false, searchable: false },
                 { data: 'id', name: 'videos.id' },
                 { data: 'name', name: 'videos.name' },
                 { data: 'course_semester.semester.name', name: 'course_semester.semester.name'},
                 { data: 'course_semester.course.name', name: 'course_semester.course.name'},
                 { data: 'status', name: 'videos.status' },
                 { data: 'comment', name: 'videos.comment' },
                 { data: 'video_date', name: 'videos.video_date' },
            ]
</code>```

Can anyone help me and notice my problem?

Thanks in advance.

答:
Because of using select() here, you do not load the relationship. Also, use dot syntax for nested eager loading:

```<code>$videos = Video::with(['course_semester', 'course_semester.course'])
</code>```

Body:
I'm currently using datatabels 7.0 and Laravel 5.4
data in my grid is showing correctly but when I want to search on nested relationship column I got below error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'course_semester.semester.name' in 'where clause' (SQL: select count(*) as aggregate from (select '1' as `row_count` from `videos` where LOWER(`videos`.`id`) LIKE %%te%% and LOWER(`videos`.`name`) LIKE %%te%% and LOWER(`course_semester`.`semester`.`name`) LIKE %%te%%) count_row_table)

Here is my code

Controller

$videos = Video::with(['course_semester' => function ($query) {
            return $query->with('course', 'semester');
        }])->select('videos.*');
        return Datatables::of($videos)
                ->addColumn('check', '<input type="checkbox" name="selected-videos" value="{{$id}}">')
                ->escapeColumns([])
                ->make(true);

Javascript

columns: [
                 { data: 'check' , name: 'check',orderable: false, searchable: false },
                 { data: 'id', name: 'videos.id' },
                 { data: 'name', name: 'videos.name' },
                 { data: 'course_semester.semester.name', name: 'course_semester.semester.name'},
                 { data: 'course_semester.course.name', name: 'course_semester.course.name'},
                 { data: 'status', name: 'videos.status' },
                 { data: 'comment', name: 'videos.comment' },
                 { data: 'video_date', name: 'videos.video_date' },
            ]

Can anyone help me and notice my problem?

Thanks in advance.

Body:
Because of using select() here, you do not load the relationship. Also, use dot syntax for nested eager loading:

$videos = Video::with(['course_semester', 'course_semester.course'])


问:
value dependent color plot in gnuplot
My dataset is something like this:

```<code><timestamp> <value>
</code>```

Value ranges from 0 to 500000. I'm using GNUplot to plot my data (X marks). I would like to split my value range (0-500000) to e.g. 5 main ranges and assign them a color (example: 0-100000 is green, 100001-200000 is blue, etc.).

This is the (plot) command I use now:

```<code>plot "data/${Y}${m}${d}_strikes" using 1:2 with points title "lightning strike"
</code>```

I've read about creating a palette. Can anyone help please?

答:
I've found a solution:</p>

```<code>set yrange [0:500000]
set cbrange [0:500000]
set palette defined ( 0 "green", 50000 "blue", 100000 "orange", 400000 "red" )
plot "data/${Y}${m}${d}_strikes" using 1:2:2 with points title "lightning strike" linecolor palette
</code>```

Title: value dependent color plot in gnuplot

Body:
My dataset is something like this:

<timestamp> <value>

Value ranges from 0 to 500000. I'm using GNUplot to plot my data (X marks). I would like to split my value range (0-500000) to e.g. 5 main ranges and assign them a color (example: 0-100000 is green, 100001-200000 is blue, etc.).

This is the (plot) command I use now:

plot "data/${Y}${m}${d}_strikes" using 1:2 with points title "lightning strike"

I've read about creating a palette. Can anyone help please?

Body:
I've found a solution:

set yrange [0:500000]
set cbrange [0:500000]
set palette defined ( 0 "green", 50000 "blue", 100000 "orange", 400000 "red" )
plot "data/${Y}${m}${d}_strikes" using 1:2:2 with points title "lightning strike" linecolor palette


问:
passing variable to jquery click function
Hi I need to pass the  id variable from the following hyperlink to a jquery click function

Here is the link

```<code><a id='howdy' href='#' course_id = 5>Howdy</a>
</code>```

And here is the click function that I attempted to utilize:

```<code>$('a#howdy').click(function(e){
  $.get('insert_courses.php' + data.course_id, function(data){
    modal.open({content: data});
  });
});
</code>```

I need the correct syntax to put in place of

```<code>+ data.course_id
</code>```

as this doesn't seem to work thanks

答:
Well, you should ideally use data(), to get the relevant attribute. That's the correct way of using JQuery and also the way in which additional attributes can be set/get in your DOM. Check the API for more details: https://api.jquery.com/data/

And below is your updated code, using data():

$('a#howdy').click(function(e) {
  console.log($(this).data("course-id"));
  $.get('insert_courses.php?id=' + $(this).data("course-id"), function(data) {
    modal.open({
      content: data
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Howdy</code>```

Body:
Hi I need to pass the  id variable from the following hyperlink to a jquery click function

Here is the link

Howdy

And here is the click function that I attempted to utilize:

$('a#howdy').click(function(e){
  $.get('insert_courses.php' + data.course_id, function(data){
    modal.open({content: data});
  });
});

I need the correct syntax to put in place of

+ data.course_id

as this doesn't seem to work thanks

Body:
Well, you should ideally use data(), to get the relevant attribute. That's the correct way of using JQuery and also the way in which additional attributes can be set/get in your DOM. Check the API for more details: https://api.jquery.com/data/

And below is your updated code, using data():

$('a#howdy').click(function(e) {
  console.log($(this).data("course-id"));
  $.get('insert_courses.php?id=' + $(this).data("course-id"), function(data) {
    modal.open({
      content: data
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id='howdy' href='#' data-course-id=5>Howdy</a>


问:
Xcode not Importing Firebase
I have installed the SDK and when I did the

Import Firbase

then continued my project to add FIRAuth.auth it did not come up and neither are other commands.

答:
While you haven't given us much to work with, I'll give this a shot.

Firstly, I would follow this tutorial which describes how to install it. I will also detail it here.

You will need to install CocoaPods

sudo gem install cocoapods

Create a Firebase project in the Firebase Console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.

Click Add Firebase to your iOS app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.

When prompted, enter your app's bundle ID. It's important to enter the bundle ID your app is using; this can only be set when you add an app to your Firebase project.

At the end, you'll download a GoogleService-Info.plist file. You can download this file again at any time.

If you haven't done so already, copy this into your Xcode project root.

ADDING THE SDK

Open the terminal and CD to your project directory.

Type pod init, then nano Podfile

Add pod 'Firebase/Core' before end

Then CTRL + X, y, Enter

Now type pod install

Then, open your-project.xcworkspace (Important to open the xcworkspace and not the other)

And finally, Download a GoogleService-Info.plist file from [Firebase console and include it in your app.

Yay!

Now in your app

import Firebase

Title: Xcode not Importing Firebase


问:
Javascript - only allow numbers in input field & a character counter
I have an input field. I want it so that only numbers can be used in the input field.

Below the input field I also want a counter that shows the number of characters currently inside the input field.

HTML:

```<code><input type="text" id="test" onkeypress="return isNumber(event)" />
<p id='demo'></p>
</code>```

Javascript:

```<code>function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
    let inputLength = inputValue.length;
    document.getElementById("demo").innerHTML = inputLength;
    return true;
    }
</code>```

jsfiddle:
http://jsfiddle.net/s831nwej/

It almost works. The problem is that the character counter below the input box is always 1 character less than the total number of characters in the input field. I think there is some quark about the keypress event that I am missing.

答:
I would like to answer why your keypress creates this unexpected behavior. First of all, it is not related to javascript, it's the feature of your Operating System which interprets your keystrokes and displays them on screen. So, there is nothing you can do with javascript. So, How it works?
When you press a key

WM_KEYDOWN and WM_SYSKEYDOWN

messages are sent(condition: the key is not hold) and

key-state flag is set to zero.

But if condition is you press and hold the key, the flag:

key-state flag set to 1.

So from there until

WM_KEYUP or WM_SYSKEYUP

message is not set or key-state flag is set to 1 the data is not stored in input box value. However, it display them inside input box. That's why your keypress do not count the current input value. if you would use

```<code>keyup event
</code>```

then it would be able to count the current input value also because your OS has done its

WM_KEYUP

work. for more details how your keyboard works you may refer to this link:
About Keyboard

and for your next question "number input" you may use regular expression check using and do something like this:

```<code>var regEx = /^\d+$/;
//then do some check.
if(!regEx.test(document.getElementById("test"))) return false;
</code>```

or you may inside your html input tag

```<code><input type="number" .. >
<!-- else you may -->
<input type="text" ... pattern = "\d">;
</code>```

Notic: you also need to check for null values.

Body:
I have an input field. I want it so that only numbers can be used in the input field.

Below the input field I also want a counter that shows the number of characters currently inside the input field.

HTML:

<input type="text" id="test" onkeypress="return isNumber(event)" />

Javascript:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
    let inputLength = inputValue.length;
    document.getElementById("demo").innerHTML = inputLength;
    return true;
    }

jsfiddle:
http://jsfiddle.net/s831nwej/

It almost works. The problem is that the character counter below the input box is always 1 character less than the total number of characters in the input field. I think there is some quark about the keypress event that I am missing.

Body:
I would like to answer why your keypress creates this unexpected behavior. First of all, it is not related to javascript, it's the feature of your Operating System which interprets your keystrokes and displays them on screen. So, there is nothing you can do with javascript. So, How it works?
When you press a key

WM_KEYDOWN and WM_SYSKEYDOWN

messages are sent(condition: the key is not hold) and

key-state flag is set to zero.

But if condition is you press and hold the key, the flag:

key-state flag set to 1.

So from there until

WM_KEYUP or WM_SYSKEYUP

message is not set or key-state flag is set to 1 the data is not stored in input box value. However, it display them inside input box. That's why your keypress do not count the current input value. if you would use

keyup event

then it would be able to count the current input value also because your OS has done its

WM_KEYUP

work. for more details how your keyboard works you may refer to this link:
About Keyboard

and for your next question "number input" you may use regular expression check using and do something like this:

var regEx = /^\d+$/;
//then do some check.
if(!regEx.test(document.getElementById("test"))) return false;

or you may inside your html input tag

<input type="number" .. >
<!-- else you may -->
<input type="text" ... pattern = "\d">;

Notic: you also need to check for null values.


问:
Incorrect result while adding with parseFloat in Javascript
I want to perform addition of floating point numbers. I will always have always have only 2 decimal places.

However if I do:

```<code>         var num = 0;
         num += parseFloat("2434545.64").toFixed(2);
         num += parseFloat("454560.91").toFixed(2);
</code>```

I get the value as 02434545.64454560.91
It is appending instead of adding. Also will the addition be accurate always?

答:
toFixed() return a  String.
So you concatenate two String.

You should use toFixed() only in the last statement and you should not mix this invocation with a += operator in a even statement because here :

```<code>num += parseFloat("2434545.64").toFixed(2);
</code>```

parseFloat("2434545.64").toFixed(2) is evaluated first.

It produces a String.

Then its num += String result is evaluated.

So, it would concatenate a Float with a String. Which produces again a String concatenation and not an arithmetic operation.

Just invoke toFixed() in a distinct statement :

```<code>var num = 0;
num += parseFloat("2434545.64");
num += parseFloat("454560.91");
num = num.toFixed(2);
</code>```

Body:
I want to perform addition of floating point numbers. I will always have always have only 2 decimal places.

However if I do:

         var num = 0;
         num += parseFloat("2434545.64").toFixed(2);
         num += parseFloat("454560.91").toFixed(2);

I get the value as 02434545.64454560.91
It is appending instead of adding. Also will the addition be accurate always?

Body:
toFixed() return a  String.
So you concatenate two String.

You should use toFixed() only in the last statement and you should not mix this invocation with a += operator in a even statement because here :

num += parseFloat("2434545.64").toFixed(2);

parseFloat("2434545.64").toFixed(2) is evaluated first.

It produces a String.

Then its num += String result is evaluated.

So, it would concatenate a Float with a String. Which produces again a String concatenation and not an arithmetic operation.

Just invoke toFixed() in a distinct statement :

var num = 0;
num += parseFloat("2434545.64");
num += parseFloat("454560.91");
num = num.toFixed(2);


问:
Control hardware back button in ionic framework
i'd like to control the event of "press hardware back button" in ionic framework. This is my code. Why does not it work? thank you

```<code>.run(function ($ionicPlatform) {
        $ionicPlatform.ready(function () {
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }

            $ionicPlatform.registerBackButtonAction(function (event) {
                event.preventDefault();
                event.stopPropagation();
                alert("Stop");
            }, 100);
        });
    })
</code>```

i also try the other solution:

```<code>    .run(function ($ionicPlatform) {
        $ionicPlatform.ready(function () {
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }
        });

        $ionicPlatform.registerBackButtonAction(function (event) {
                event.preventDefault();
                event.stopPropagation();
                alert("Stop");
            }, 100);
    })
</code>```

but it still doesn't work

thank you

答:
In a cordova based application (Ionic) the following three methods can be used to override hardware back button.

onHardwareBackButton

offHardwareBackButton

registerBackButtonAction

Look at http://www.codeexpertz.com/blog/mobile/override-hardware-back-button-cordova-based-application-ionic for details

Body:
i'd like to control the event of "press hardware back button" in ionic framework. This is my code. Why does not it work? thank you

.run(function ($ionicPlatform) {
        $ionicPlatform.ready(function () {
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }

            $ionicPlatform.registerBackButtonAction(function (event) {
                event.preventDefault();
                event.stopPropagation();
                alert("Stop");
            }, 100);
        });
    })

i also try the other solution:

    .run(function ($ionicPlatform) {
        $ionicPlatform.ready(function () {
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }
        });

        $ionicPlatform.registerBackButtonAction(function (event) {
                event.preventDefault();
                event.stopPropagation();
                alert("Stop");
            }, 100);
    })

but it still doesn't work

thank you


问:
Trouble downloading xls file while using RSelenium via docker
I've been trying to download an excel file (.xls) from a particular website. I am pasting my whole R code below (after setting up a docker container).

```<code> ePrefs = makeFirefoxProfile(
 list(
 browser.download.dir = "/home/seluser/Downloads",
 "browser.download.folderList" = 2L,
 "browser.download.manager.showWhenStarting" = FALSE,
 "browser.helperApps.neverAsk.saveToDisk" = "application/vnd.ms-excel,
  application/xls, application/x-xls, application/vnd-xls,
  application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ))

  remDr = remoteDriver(extraCapabilities = ePrefs, port = 4445)
  remDr$open()
  remDr$navigate("https://www.aeaweb.org/joe/listings?")

  webelem1 = remDr$findElement(using = 'id', "published-date")
  webelem1$clickElement()

  webelem2 = remDr$findElement("css", "[value = 'week']")
  webelem2$clickElement()

  webelem3 = remDr$findElement("css", "[value = 'Apply Filter']")
  webelem3$clickElement()
  Sys.sleep(10)

  webelem4 = remDr$findElement("css", "[feature = 'download']")
  webelem4$clickElement()

 webelem5 = remDr$findElement("xpath",
 "/html/body/main/div/section/div/div[2]/div[2]/div/ul/li[3]/a")
 webelem5$clickElement()
</code>```

Everything works fine, but at the last step (click) the selenium browser still opens up the usual dialogue window asking me if I want to save the file or open it, even though I have the overriding commands in the eprefs bit of the code.

I have manually downloaded the file that the last click should be directly downloading and verified that the content type is
application/vnd.ms-excel. Is there something I am doing wrong? Any help is appreciated.

答:
The mime type the server is returning is application/force-download. Add this to your list and observe HOST and container download locations are mapped and the following works for me:

```<code># initiate docker container mapping download locations
# here HOST is linux
# docker run -d -p 4445:4444 -p 5901:5900 -v /home/john/test:/home/seluser/Downloads selenium/standalone-firefox-debug:2.53.1

library(RSelenium)
ePrefs <- makeFirefoxProfile(
  list(
    browser.download.dir = "/home/seluser/Downloads",
    "browser.download.folderList" = 2L,
    "browser.download.manager.showWhenStarting" = FALSE,
    "browser.helperApps.neverAsk.saveToDisk" = "application/vnd.ms-excel,
    application/xls, application/x-xls, application/vnd-xls,
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
    application/force-download"
  ))

remDr <- remoteDriver(extraCapabilities = ePrefs, port = 4445)
remDr$open()
remDr$navigate("https://www.aeaweb.org/joe/listings?")

webelem1 <- remDr$findElement(using = 'id', "published-date")
webelem1$clickElement()

webelem2 <- remDr$findElement("css", "[value = 'week']")
webelem2$clickElement()

webelem3 <- remDr$findElement("css", "[value = 'Apply Filter']")
webelem3$clickElement()
Sys.sleep(10)

webelem4 <- remDr$findElement("css", "[feature = 'download']")
webelem4$clickElement()

webelem5 = remDr$findElement("xpath",
                             "/html/body/main/div/section/div/div[2]/div[2]/div/ul/li[3]/a")
webelem5$clickElement()

list.files("/home/john/test/")

> list.files("/home/john/test/")
[1] "joe_resultset.xls"
</code>```

Body:
I've been trying to download an excel file (.xls) from a particular website. I am pasting my whole R code below (after setting up a docker container).

 ePrefs = makeFirefoxProfile(
 list(
 browser.download.dir = "/home/seluser/Downloads",
 "browser.download.folderList" = 2L,
 "browser.download.manager.showWhenStarting" = FALSE,
 "browser.helperApps.neverAsk.saveToDisk" = "application/vnd.ms-excel,
  application/xls, application/x-xls, application/vnd-xls,
  application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ))

  remDr = remoteDriver(extraCapabilities = ePrefs, port = 4445)
  remDr$open()
  remDr$navigate("https://www.aeaweb.org/joe/listings?")

  webelem1 = remDr$findElement(using = 'id', "published-date")
  webelem1$clickElement()

  webelem2 = remDr$findElement("css", "[value = 'week']")
  webelem2$clickElement()

  webelem3 = remDr$findElement("css", "[value = 'Apply Filter']")
  webelem3$clickElement()
  Sys.sleep(10)

  webelem4 = remDr$findElement("css", "[feature = 'download']")
  webelem4$clickElement()

 webelem5 = remDr$findElement("xpath",
 "/html/body/main/div/section/div/div[2]/div[2]/div/ul/li[3]/a")
 webelem5$clickElement()

Everything works fine, but at the last step (click) the selenium browser still opens up the usual dialogue window asking me if I want to save the file or open it, even though I have the overriding commands in the eprefs bit of the code.

I have manually downloaded the file that the last click should be directly downloading and verified that the content type is
application/vnd.ms-excel. Is there something I am doing wrong? Any help is appreciated.

Body:
The mime type the server is returning is application/force-download. Add this to your list and observe HOST and container download locations are mapped and the following works for me:

# initiate docker container mapping download locations
# here HOST is linux
# docker run -d -p 4445:4444 -p 5901:5900 -v /home/john/test:/home/seluser/Downloads selenium/standalone-firefox-debug:2.53.1

library(RSelenium)
ePrefs <- makeFirefoxProfile(
  list(
    browser.download.dir = "/home/seluser/Downloads",
    "browser.download.folderList" = 2L,
    "browser.download.manager.showWhenStarting" = FALSE,
    "browser.helperApps.neverAsk.saveToDisk" = "application/vnd.ms-excel,
    application/xls, application/x-xls, application/vnd-xls,
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
    application/force-download"
  ))

remDr <- remoteDriver(extraCapabilities = ePrefs, port = 4445)
remDr$open()
remDr$navigate("https://www.aeaweb.org/joe/listings?")

webelem1 <- remDr$findElement(using = 'id', "published-date")
webelem1$clickElement()

webelem2 <- remDr$findElement("css", "[value = 'week']")
webelem2$clickElement()

webelem3 <- remDr$findElement("css", "[value = 'Apply Filter']")
webelem3$clickElement()
Sys.sleep(10)

webelem4 <- remDr$findElement("css", "[feature = 'download']")
webelem4$clickElement()

webelem5 = remDr$findElement("xpath",
                             "/html/body/main/div/section/div/div[2]/div[2]/div/ul/li[3]/a")
webelem5$clickElement()

list.files("/home/john/test/")

> list.files("/home/john/test/")
[1] "joe_resultset.xls"


问:
Set the center of custom MKAnnotationView
I am using the custom MKAnnotationView. I use the autolayouts which are working fine, but the position(frame) of annotation view is not appropriate.

```<code>func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
{
    if view.annotation is MKUserLocation
    {
        return
    }

    let starbucksAnnotation = view.annotation as! LiquorLocation
    let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
    let calloutView = views?[0] as! CustomCalloutView
    calloutView.labelLiquorShopName.text = starbucksAnnotation.title
    calloutView.labelLiquorShopAddress.text = starbucksAnnotation.address
    calloutView.labelLiquorShopAwayDistance.text = starbucksAnnotation.locationKmAway
    calloutView.imageViewLiquorShop.image = starbucksAnnotation.liquorShopIcon

    calloutView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(calloutView)
    mapView.setCenter((view.annotation?.coordinate)!, animated: true)
}
</code>```

What I am doing wrong?  I want to center the annotation view at the top of the pin.

答:
Autolayouts again save my day. I add the layout constraint between my calloutview and view(MKAnnotationView). I write below lines underneath view.addSubview(calloutView) in didSelect method.

```<code>let horizontalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let verticalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
        let widthConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: calloutView.frame.size.width)
        view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint])
</code>```

Body:
I am using the custom MKAnnotationView. I use the autolayouts which are working fine, but the position(frame) of annotation view is not appropriate.

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
{
    if view.annotation is MKUserLocation
    {
        return
    }

    let starbucksAnnotation = view.annotation as! LiquorLocation
    let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
    let calloutView = views?[0] as! CustomCalloutView
    calloutView.labelLiquorShopName.text = starbucksAnnotation.title
    calloutView.labelLiquorShopAddress.text = starbucksAnnotation.address
    calloutView.labelLiquorShopAwayDistance.text = starbucksAnnotation.locationKmAway
    calloutView.imageViewLiquorShop.image = starbucksAnnotation.liquorShopIcon

    calloutView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(calloutView)
    mapView.setCenter((view.annotation?.coordinate)!, animated: true)
}

What I am doing wrong?  I want to center the annotation view at the top of the pin.

Body:
Autolayouts again save my day. I add the layout constraint between my calloutview and view(MKAnnotationView). I write below lines underneath view.addSubview(calloutView) in didSelect method.

let horizontalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let verticalConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
        let widthConstraint = NSLayoutConstraint(item: calloutView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: calloutView.frame.size.width)
        view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint])


答:
Here you go with the solution

```<code>var num = 0;
     num += 2434545.64;
     num += 454560.91;
console.log(parseFloat(num).toFixed(2));
</code>```

Here is the documentation for parseFloat https://www.w3schools.com/jsref/jsref_parsefloat.asp

Title: Incorrect result while adding with parseFloat in Javascript

Body:
Here you go with the solution

var num = 0;
     num += 2434545.64;
     num += 454560.91;
console.log(parseFloat(num).toFixed(2));

Here is the documentation for parseFloat https://www.w3schools.com/jsref/jsref_parsefloat.asp


问:
Error in enabling a selector using jQuery
I'm trying to enable a multi selector only when a checkbox is checked. My code is generating an alert, but won't enable the selector

Selector & checkbox html+Script:

Enabling function:

```<code>$("#checkbox").bind("click", function () {

     if ($('#checkbox').is(":checked"))
          {  alert("checked");
            $("#sel").attr('disabled',false);

          }
    else
          {
            //Do nothing
          }
});
</code>```

答:
using multiselect, try this:</p>

```<code>$('#example-getting-started').removeAttr('disabled');

// And maybe, refresh the plugin
$('#example-getting-started').multiSelect('refresh');
</code>```

Body:
I'm trying to enable a multi selector only when a checkbox is checked. My code is generating an alert, but won't enable the selector

Selector & checkbox html+Script:

Enabling function:

$("#checkbox").bind("click", function () {

     if ($('#checkbox').is(":checked"))
          {  alert("checked");
            $("#sel").attr('disabled',false);

          }
    else
          {
            //Do nothing
          }
});

Body:
using multiselect, try this:

$('#example-getting-started').removeAttr('disabled');

// And maybe, refresh the plugin
$('#example-getting-started').multiSelect('refresh');


问:
HQl equivalent of sql query
```<code>String SQL_QUERY = "SELECT count(*) FROM (SELECT * FROM Url as U where U.pageType=" + 1 + " group  by U.pageId having count(U.pageId) = 1)";
query = session.createQuery(SQL_QUERY);
</code>```

I am getting an error

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 23 [ SELECT count() FROM (SELECT * FROM Url as U where U.pageType = 2 group by U.pageId having count(U.pageId) = 1)]

答:
In HQL you cannot use subqueries in FROM clause.

In this particular case (with having count(U.pageId) = 1) the same result should be produced by the following query (though I'm not sure about performance):

```<code>SELECT count(u) FROM Url u WHERE u.pageType = 2 AND
    1 = (SELECT count(uu) FROM Url uu WHERE u.pageId = uu.pageId)
</code>```

If it's not suitable, you can use session.createSQLQuery().

Title: HQl equivalent of sql query

Body:
String SQL_QUERY = "SELECT count(*) FROM (SELECT * FROM Url as U where U.pageType=" + 1 + " group  by U.pageId having count(U.pageId) = 1)";
query = session.createQuery(SQL_QUERY);

I am getting an error

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 23 [ SELECT count() FROM (SELECT * FROM Url as U where U.pageType = 2 group by U.pageId having count(U.pageId) = 1)]

Body:
In HQL you cannot use subqueries in FROM clause.

In this particular case (with having count(U.pageId) = 1) the same result should be produced by the following query (though I'm not sure about performance):

SELECT count(u) FROM Url u WHERE u.pageType = 2 AND
    1 = (SELECT count(uu) FROM Url uu WHERE u.pageId = uu.pageId)

If it's not suitable, you can use session.createSQLQuery().


问:
Android Studio - CRLF vs LF for a Git-based multiplatform project
I'm working on an Android project involving multiple developers, some of which are on Windows, others Linux/MacOS. Since I'm on Windows, I've been instructed to configure Git as follows to avoid issues:

```<code>autocrlf = true
safecrlf = true
</code>```

This works mostly fine. Any .java/XML/etc files I create in Android Studio are in CRLF, get converted to LF when I push them into the repo, then back into CRLF when I pull changes into my local copy. Problem is, some types of files, like vector drawable assets, get generated in LF instead, for some reason. So when I try to add them to Git, I get the "irreversible conversion" error:

I know I could set safecrlf = warn, but from what I understand, this carries a risk of corrupting binary files if Git mistakes them for text files, so I'm looking for a safer solution. For now I'm manually editing vector assets into CRLF before I add them to Git, which avoids the above error message, but gets tedious having to repeat the process for every file. Any way to force Android Studio to generate all local files in CRLF?

答:
I would not set core.autocrlf to true (I advices against it since 2010): leave it to false.

Any file you want to be managed  in a .gitattributes file, especially since Git 2.10. See the release note

```<code>echo "*.java text=auto eol=crlf" >.gitattributes
</code>```

The  combination has been fixed to be equivalent to doing

```<code>$ git config core.autocrlf true
</code>```

With .gitattributes, you can limit that eol transformation to the precise set of files you want, instead of applying it blindly on all the repo files.

See more at "Checking-out and checking-in".

And with Git 2.16+, git add --renormalize . allows for converting all concerned files eol.

Body:
I'm working on an Android project involving multiple developers, some of which are on Windows, others Linux/MacOS. Since I'm on Windows, I've been instructed to configure Git as follows to avoid issues:

autocrlf = true
safecrlf = true

This works mostly fine. Any .java/XML/etc files I create in Android Studio are in CRLF, get converted to LF when I push them into the repo, then back into CRLF when I pull changes into my local copy. Problem is, some types of files, like vector drawable assets, get generated in LF instead, for some reason. So when I try to add them to Git, I get the "irreversible conversion" error:

I know I could set safecrlf = warn, but from what I understand, this carries a risk of corrupting binary files if Git mistakes them for text files, so I'm looking for a safer solution. For now I'm manually editing vector assets into CRLF before I add them to Git, which avoids the above error message, but gets tedious having to repeat the process for every file. Any way to force Android Studio to generate all local files in CRLF?

Body:
I would not set core.autocrlf to true (I advices against it since 2010): leave it to false.

Any file you want to be managed  in a .gitattributes file, especially since Git 2.10. See the release note

echo "*.java text=auto eol=crlf" >.gitattributes

The  combination has been fixed to be equivalent to doing

$ git config core.autocrlf true

With .gitattributes, you can limit that eol transformation to the precise set of files you want, instead of applying it blindly on all the repo files.

See more at "Checking-out and checking-in".

And with Git 2.16+, git add --renormalize . allows for converting all concerned files eol.

ContentLicense: CC BY-SA 4.0


问:
Artifactory Change Base URL through file system
Plenty of advice on how to change the Base URL the Artifactory Pro is running on, Custom Base URL via Rest API, etc.

However, We need to change all instances of Base URL while application is not running. So if any instance of Base URL exists in file system or Mysql db, need to update accordingly.

Thanks for any assistance.

答:
The answer to that is a bit tricky. You can have an 'artifactory.config.import.xml' file under your '$ARTIFACTORY_HOME/etc/' folder. By doing so Artifactory, upon starting will consume the file and import it as it's configuration file.

PLEASE READ THIS PART CAREFULLY: This is the tricky part, the import of this file will overwrite any existing configuration that you have on this Artifactory instance. Meaning that you have to hold the latest modified configuration before shutting down the instance.


问:
Visual studio code changes format (React-JSX)
I've the following snippet in my index.js

```<code>class App extends Component {
    render() {
        return ( <div style = { styles.app } >
            Welcome to React!
            </div>
        )
    }
}
</code>```

The code works, but every time I save (ctrl+s) visual studio format the jsx like that:

```<code>class App extends Component {
    render() {
        return ( < div style = { styles.app } >
            Welcome to React!
            <
            /div>
        )
    }
}
</code>```

How can I solve this? thanks

答:
You can install an extension like react-beautify that helps you format your jsx code.

It is found here

This extension wraps prettydiff/esformatter to format your javascript, JSX, typescript, TSX file.

Body:
I've the following snippet in my index.js

class App extends Component {
    render() {
        return (

            Welcome to React!

        )
    }
}

The code works, but every time I save (ctrl+s) visual studio format the jsx like that:

class App extends Component {
    render() {
        return (

            Welcome to React!
            <
            /div>
        )
    }
}

How can I solve this? thanks


问:
Is there a URL forwarding to the App Store review creator in iOS 11?
In iOS 10, I was able to forward directly from my app to its App Store ratings page by using the following link:

http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=app_id_here&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8

However, in iOS 11 with its all-new App Store where the review page doesn't exist any longer, this seems to be broken now.

Does anyone know an alternative url that opens up the review creator page directly? Or does Apple want us to stop using such links?

答:
What you should do is implement the SKStoreReviewController for IOS 10.3 and higher.

It's super simple,

```<code>import StoreKit
SKStoreReviewController.requestReview()
</code>```

It turns out that the system will automatically limit the display of the dialog to 3 times over a 365-day period, so there’s no logic required to check this.

There is however a recommendation that you show the prompts at ‘logical points’ when it is clear the user has made some sort of engagement within the app.

The guides also say you should allow a week or two between repeated displays of the prompt so users don’t feel like they’re being pestered(this will require some thoughtfulness and implementation on your part).

Jordan Holland

Body:
What you should do is implement the SKStoreReviewController for IOS 10.3 and higher.

It's super simple,

import StoreKit
SKStoreReviewController.requestReview()

It turns out that the system will automatically limit the display of the dialog to 3 times over a 365-day period, so there’s no logic required to check this.

There is however a recommendation that you show the prompts at ‘logical points’ when it is clear the user has made some sort of engagement within the app.

The guides also say you should allow a week or two between repeated displays of the prompt so users don’t feel like they’re being pestered(this will require some thoughtfulness and implementation on your part).

Jordan Holland


问:
palindrome or not what logical error in this
what is the logical error in this code.In this non palindrome are also showing palindrome like "java"is not palindrome but code shows it palindrome</p>

```<code>     package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        StringBuffer sbuffer1=new StringBuffer();
        sbuffer1=sbuffer.reverse();
        System.out.println(sbuffer1);
        if(sbuffer1.equals(sbuffer)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }

}
</code>```

答:
 as suggested in the comments i have modified your code, which will work fine

```<code>package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        String actual = sbuffer.toString();
        sbuffer.reverse();
        System.out.println(sbuffer);
        if(sbuffer.toString().equals(actual)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }
</code>```

Body:
what is the logical error in this code.In this non palindrome are also showing palindrome like "java"is not palindrome but code shows it palindrome

     package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        StringBuffer sbuffer1=new StringBuffer();
        sbuffer1=sbuffer.reverse();
        System.out.println(sbuffer1);
        if(sbuffer1.equals(sbuffer)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }

}

Body:
 as suggested in the comments i have modified your code, which will work fine

package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        String actual = sbuffer.toString();
        sbuffer.reverse();
        System.out.println(sbuffer);
        if(sbuffer.toString().equals(actual)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }


问:
Full width video background
I'm attempting my first web video project and am getting nowhere and need a little help with using a full width video header or background.

I found an example that does what I am trying to do using the below videos and it works just fine - no buffering, acceptable quality, etc.

The .mp4 file uses a 640x360 format @ 23 fps (613kbps) and this works fine on any display I view it - the whole frame is visible top to bottom, side to side.

The research I've done indicates the best video format to use is 720 x 24fps, which I have tried (actual dimension is 1280x720) but found it only works well on less than maximized browser resolutions, in which case, it looks great, otherwise, a small portion of the bottom, maybe the bottom 18% of the frame, is not visible until you scroll down, which is unacceptable.  I need the video to work as well as the 640x360 with the whole image visible. In addition, buffering occurs with the 720 format, whereas there is no buffering with the 640x360.

I am using Sony Vegas for the video editing and there is no option for a 640x360 format.  The closest is 640x480 but that produces the same result - to tall and the bottom is not visible.

There is a site that uses the 1280x720 format successfully (http://mazwai.com/#/) but I have no idea how.

Can someone point me in the right direction?

Thank You.

This is  the current code:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video test</title>

<script>
$(document).ready(function () {
$(".player").mb_YTPlayer();
});
</script>

<style>
body{ margin:0px; background:#000; max-width:1000; }
#bg_container{ height:800px; overflow:auto; }
#bg{ width:100%; }
</style>

</head>

<body>

<div id="bg_container">
  <video id="bg" src="www.parishpc.com/images/720.mp4" autoplay loop muted">    </video>
</div>

</body>
</html>
</code>```

This code worked a little bit better - only the bottom 5% was not visible:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video test</title>

<style>

body, html { margin: auto;
background:#fff;
height: 100%;
}

header {
height:100%;
width:100%;
overflow:hidden;
position:relative;
}

.video {
    position:fixed;
    top: 50%; left: 50%;
    z-index:1;
    min-width: 100%;
    min-height: 100%;
    width:auto;
    height:auto;
    transform: translate(-50%,-50%);
}
</style>

</head>

<body>
    <header>
        <video autoplay loop class="video">
            <source src="www.parishpc.com/images/720.mp4" type="video/mp4">
        </video>
    </header>
</body>
</html>
</code>```

答:
I'm not sure exactly what you want, but having a video background without stretching or cut off parts is impossible to do while accommodating to every user's window size.

This solution will make sure the video is 100% of the window's height. If they want to see the cut off parts they'd have to resize their window to fit the width.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Video test</title>

        <video autoplay loop class="video">
            <source src="http://www.parishpc.com/images/720.mp4" type="video/mp4">
        </video>

```

Title: Full width video background

Body:
I'm attempting my first web video project and am getting nowhere and need a little help with using a full width video header or background.

I found an example that does what I am trying to do using the below videos and it works just fine - no buffering, acceptable quality, etc.

The .mp4 file uses a 640x360 format @ 23 fps (613kbps) and this works fine on any display I view it - the whole frame is visible top to bottom, side to side.

The research I've done indicates the best video format to use is 720 x 24fps, which I have tried (actual dimension is 1280x720) but found it only works well on less than maximized browser resolutions, in which case, it looks great, otherwise, a small portion of the bottom, maybe the bottom 18% of the frame, is not visible until you scroll down, which is unacceptable.  I need the video to work as well as the 640x360 with the whole image visible. In addition, buffering occurs with the 720 format, whereas there is no buffering with the 640x360.

I am using Sony Vegas for the video editing and there is no option for a 640x360 format.  The closest is 640x480 but that produces the same result - to tall and the bottom is not visible.

There is a site that uses the 1280x720 format successfully (http://mazwai.com/#/) but I have no idea how.

Can someone point me in the right direction?

Thank You.

This is  the current code:

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Video test</title>

  <video id="bg" src="www.parishpc.com/images/720.mp4" autoplay loop muted">    </video>

This code worked a little bit better - only the bottom 5% was not visible:

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Video test</title>

        <video autoplay loop class="video">
            <source src="www.parishpc.com/images/720.mp4" type="video/mp4">
        </video>

Body:
I'm not sure exactly what you want, but having a video background without stretching or cut off parts is impossible to do while accommodating to every user's window size.

This solution will make sure the video is 100% of the window's height. If they want to see the cut off parts they'd have to resize their window to fit the width.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Video test</title>

    <style>
        body {
            margin: 0;
            padding: 0;
        }

        #container {
            height: 100%;
            width: auto;
        }

        .video {
            height: 100%;
        }

    </style>

</head>

<body>
    <div id="container">
        <video autoplay loop class="video">
            <source src="http://www.parishpc.com/images/720.mp4" type="video/mp4">
        </video>
    </div>
</body>

</html>


问:
InputBox Cancel different from vbNullString (null)
I want to use an InputBox for checking password.

If the user presses "OK" without data entry, the InputBox should run again, and if the user pressed "Cancel" or "ESC", corporate subroutine have exit.

How can I recognize "ESC" or "Cancel" input, different from just "null" or empty?

And how specially do that for my customize created Input box with API, so for changing key-pressed shown as "*" in password input, named as InputBoxDk:

```<code>'API functions to be used
Private Declare Function CallNextHookEx _
Lib "user32" ( _
ByVal hHook As Long, _
ByVal ncode As Long, _
ByVal wParam As Long, _
lParam As Any) _
As Long

Private Declare Function GetModuleHandle _
Lib "kernel32" _
Alias "GetModuleHandleA" ( _
ByVal lpModuleName As String) _
As Long

Private Declare Function SetWindowsHookEx _
Lib "user32" _
Alias "SetWindowsHookExA" ( _
ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) _
As Long

Private Declare Function UnhookWindowsHookEx _
Lib "user32" ( _
ByVal hHook As Long) _
As Long

Private Declare Function SendDlgItemMessage _
Lib "user32" Alias "SendDlgItemMessageA" ( _
ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) _
As Long

Private Declare Function GetClassName _
Lib "user32" _
Alias "GetClassNameA" ( _
ByVal hWnd As Long, _
ByVal lpClassName As String, _
ByVal nMaxCount As Long) _
As Long

Private Declare Function GetCurrentThreadId _
Lib "kernel32" () _
As Long

Private Declare Sub sapiSleep Lib "kernel32" _
    Alias "Sleep" _
    (ByVal dwMilliseconds As Long)
'Constants to be used in our API functions
Private Const EM_SETPASSWORDCHAR = &HCC
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
Private Const HC_ACTION = 0

Private hHook As Long

Public Function NewProc(ByVal lngCode As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long

Dim RetVal
Dim strClassName As String, lngBuffer As Long

If lngCode < HC_ACTION Then
    NewProc = CallNextHookEx(hHook, lngCode, wParam, lParam)
    Exit Function
End If

strClassName = String$(256, " ")
lngBuffer = 255

If lngCode = HCBT_ACTIVATE Then 'A window has been activated
    RetVal = GetClassName(wParam, strClassName, lngBuffer)
    If Left$(strClassName, RetVal) = "#32770" Then 'Class name of the Inputbox
         'This changes the edit control so that it display the password character *.
         'You can change the Asc("*") as you please.
        SendDlgItemMessage wParam, &H1324, EM_SETPASSWORDCHAR, Asc("*"), &H0
    End If
End If

 'This line will ensure that any other hooks that may be in place are
 'called correctly.
CallNextHookEx hHook, lngCode, wParam, lParam

End Function

'// Make it public = avail to ALL Modules
 '// Lets simulate the VBA Input Function
Public Function InputBoxDK(Prompt As String, Optional Title As String, _
Optional Default As String, _
Optional Xpos As Long, _
Optional Ypos As Long, _
Optional Helpfile As String, _
Optional Context As Long) As String

Dim lngModHwnd As Long, lngThreadID As Long

 '// Lets handle any Errors JIC! due to HookProc> App hang!
On Error GoTo ExitProperly
lngThreadID = GetCurrentThreadId
lngModHwnd = GetModuleHandle(vbNullString)

hHook = SetWindowsHookEx(WH_CBT, AddressOf NewProc, lngModHwnd, lngThreadID)
If Xpos Then
    InputBoxDK = InputBox(Prompt, Title, Default, Xpos, Ypos, Helpfile, Context)
Else
    InputBoxDK = InputBox(Prompt, Title, Default, , , Helpfile, Context)
End If

ExitProperly:
UnhookWindowsHookEx hHook

End Function

Sub TestDKInputBox()
Dim x

x = InputBoxDK("Type your password here.", "Password Required")
If x = "" Then End
If x <> "yourpassword" Then
    MsgBox "You didn't enter a correct password."
    End
End If

MsgBox "Welcome Creator!", vbExclamation

End Sub
</code>```

Code reference: http://www.ozgrid.com

答:
The Application.InputBox() returns False on Cancel or Esc, where InputBox() returns "".

```<code>Sub ProcedureName()

    Dim response As Variant
    Do Until Len(Trim(response)) > 0
        response = Application.InputBox("Type something: ", "InputBox")
    Loop

    If response = vbFalse Then ' in case the use press "Cancel"
        MsgBox "Pressed Cancel"
    End If
End Sub
</code>```

Body:
I want to use an InputBox for checking password.

If the user presses "OK" without data entry, the InputBox should run again, and if the user pressed "Cancel" or "ESC", corporate subroutine have exit.

How can I recognize "ESC" or "Cancel" input, different from just "null" or empty?

And how specially do that for my customize created Input box with API, so for changing key-pressed shown as "*" in password input, named as InputBoxDk:

'API functions to be used
Private Declare Function CallNextHookEx _
Lib "user32" ( _
ByVal hHook As Long, _
ByVal ncode As Long, _
ByVal wParam As Long, _
lParam As Any) _
As Long

Private Declare Function GetModuleHandle _
Lib "kernel32" _
Alias "GetModuleHandleA" ( _
ByVal lpModuleName As String) _
As Long

Private Declare Function SetWindowsHookEx _
Lib "user32" _
Alias "SetWindowsHookExA" ( _
ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) _
As Long

Private Declare Function UnhookWindowsHookEx _
Lib "user32" ( _
ByVal hHook As Long) _
As Long

Private Declare Function SendDlgItemMessage _
Lib "user32" Alias "SendDlgItemMessageA" ( _
ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) _
As Long

Private Declare Function GetClassName _
Lib "user32" _
Alias "GetClassNameA" ( _
ByVal hWnd As Long, _
ByVal lpClassName As String, _
ByVal nMaxCount As Long) _
As Long

Private Declare Function GetCurrentThreadId _
Lib "kernel32" () _
As Long

Private Declare Sub sapiSleep Lib "kernel32" _
    Alias "Sleep" _
    (ByVal dwMilliseconds As Long)
'Constants to be used in our API functions
Private Const EM_SETPASSWORDCHAR = &HCC
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
Private Const HC_ACTION = 0

Private hHook As Long

Public Function NewProc(ByVal lngCode As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long

Dim RetVal
Dim strClassName As String, lngBuffer As Long

If lngCode < HC_ACTION Then
    NewProc = CallNextHookEx(hHook, lngCode, wParam, lParam)
    Exit Function
End If

strClassName = String$(256, " ")
lngBuffer = 255

If lngCode = HCBT_ACTIVATE Then 'A window has been activated
    RetVal = GetClassName(wParam, strClassName, lngBuffer)
    If Left$(strClassName, RetVal) = "#32770" Then 'Class name of the Inputbox
         'This changes the edit control so that it display the password character *.
         'You can change the Asc("*") as you please.
        SendDlgItemMessage wParam, &H1324, EM_SETPASSWORDCHAR, Asc("*"), &H0
    End If
End If

 'This line will ensure that any other hooks that may be in place are
 'called correctly.
CallNextHookEx hHook, lngCode, wParam, lParam

End Function

'// Make it public = avail to ALL Modules
 '// Lets simulate the VBA Input Function
Public Function InputBoxDK(Prompt As String, Optional Title As String, _
Optional Default As String, _
Optional Xpos As Long, _
Optional Ypos As Long, _
Optional Helpfile As String, _
Optional Context As Long) As String

Dim lngModHwnd As Long, lngThreadID As Long

 '// Lets handle any Errors JIC! due to HookProc> App hang!
On Error GoTo ExitProperly
lngThreadID = GetCurrentThreadId
lngModHwnd = GetModuleHandle(vbNullString)

hHook = SetWindowsHookEx(WH_CBT, AddressOf NewProc, lngModHwnd, lngThreadID)
If Xpos Then
    InputBoxDK = InputBox(Prompt, Title, Default, Xpos, Ypos, Helpfile, Context)
Else
    InputBoxDK = InputBox(Prompt, Title, Default, , , Helpfile, Context)
End If

ExitProperly:
UnhookWindowsHookEx hHook

End Function

Sub TestDKInputBox()
Dim x

x = InputBoxDK("Type your password here.", "Password Required")
If x = "" Then End
If x <> "yourpassword" Then
    MsgBox "You didn't enter a correct password."
    End
End If

MsgBox "Welcome Creator!", vbExclamation

End Sub

Code reference: http://www.ozgrid.com

Body:
The Application.InputBox() returns False on Cancel or Esc, where InputBox() returns "".

Sub ProcedureName()

    Dim response As Variant
    Do Until Len(Trim(response)) > 0
        response = Application.InputBox("Type something: ", "InputBox")
    Loop

    If response = vbFalse Then ' in case the use press "Cancel"
        MsgBox "Pressed Cancel"
    End If
End Sub


问:
After file type validation using JS for an HTML Form, control should stay on the same page if invalid
I have an html form where for file types I want only pdf, docx and doc files. I am successfully able to validate, but on click of OK button, I do not want to post the form if it is invalid. Currently, it is going to connection.php. It should only go to connection.php when I have passed the validation successfully.

```<code><form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="function()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
    <script>
        $(document).ready(function () {
        $('input[type=file]').change(function () {
        var val = $(this).val().toLowerCase();
        var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
         if(!(regex.test(val))) {
        $(this).val('');
        alert('Please select correct file format');
        } }); });
    </script>
</code>```

答:
Use onsubmit event:

```<code><form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="return validate()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
<input type="submit" value="Upload book">
</form>
<script>
    function validate() {
    var val = document.getElementById('bookfile').value.toLowerCase();
    var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
        if(!(regex.test(val))) {
            document.getElementById('bookfile').value = '';
            alert('Please select correct file format');
            return false;
        }
        return true;
    }
</script>
</code>```

Body:
I have an html form where for file types I want only pdf, docx and doc files. I am successfully able to validate, but on click of OK button, I do not want to post the form if it is invalid. Currently, it is going to connection.php. It should only go to connection.php when I have passed the validation successfully.

<form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="function()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>

Body:
Use onsubmit event:

<form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="return validate()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
<input type="submit" value="Upload book">
</form>
<script>
    function validate() {
    var val = document.getElementById('bookfile').value.toLowerCase();
    var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
        if(!(regex.test(val))) {
            document.getElementById('bookfile').value = '';
            alert('Please select correct file format');
            return false;
        }
        return true;
    }
</script>


问:
how to open objects using id in django
I want to open objects using id, I have two classes one is foreign key to other now i am not sure how to change my view function this is what i am doing.

models.py

```<code>from django.db import models

class Movie(models.Model):
    name= models.CharField(max_length = 100)
    movie_poster = models.FileField()

    def __str__(self):
        return self.name

class Songs(models.Model):
    movie = models.ForeignKey(Movie, default= 1)
    song_title = models.CharField(max_length=20)
    song_list = models.FileField()

    def __str__(self):
        return self.song_title
</code>```

views.py

```<code>from django.shortcuts import render_to_response, get_object_or_404
from .models import Movie, Songs

def Movie_Songs(request, id):
    #movies = Movie.objects.all()
    #songs = Songs.objects.all()

    instance=get_object_or_404(Movie, id=id)
    context = {
        "name" : instance.name,
        "movie_poster" : instance.movie_poster,
        "movie" : instance.movie,
        "song_title": instance.song_title,
        "song_list": instance.song_list,
    }
    return render_to_response('profile_page.html', context)
</code>```

urls.py

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^profile/(?P<id>/d+)/$',views.Movie_Songs),
]
</code>```

html

```<code><h1>{{context.name}}</h1>

     {% for song in context %}
            <ol>
                <li>
                    <a href="{{song.song_list.url}}" target="_self"><h4>{{song.song_title}}</h4></a>
                </li>
            </ol>
            {% endfor %}
</code>```

above html will open when i click on an object,object has this

```<code><a href="profile/" target="new"><img width="170px" height="170px" src="{{ movie_item.movie_poster.url }}"></a>
            <h4>{{ movie_item.movie }}</h4>
</code>```

答:
Use django-rest framework to convert model data into proper JSON format using serializations.

Use ModelSerializers to code less and effectively.
Other useful links: for foreign key field ; for FileField/ ImageField

Title: how to open objects using id in django

Body:
I want to open objects using id, I have two classes one is foreign key to other now i am not sure how to change my view function this is what i am doing.

models.py

from django.db import models

class Movie(models.Model):
    name= models.CharField(max_length = 100)
    movie_poster = models.FileField()

    def __str__(self):
        return self.name

class Songs(models.Model):
    movie = models.ForeignKey(Movie, default= 1)
    song_title = models.CharField(max_length=20)
    song_list = models.FileField()

    def __str__(self):
        return self.song_title

views.py

from django.shortcuts import render_to_response, get_object_or_404
from .models import Movie, Songs

def Movie_Songs(request, id):
    #movies = Movie.objects.all()
    #songs = Songs.objects.all()

    instance=get_object_or_404(Movie, id=id)
    context = {
        "name" : instance.name,
        "movie_poster" : instance.movie_poster,
        "movie" : instance.movie,
        "song_title": instance.song_title,
        "song_list": instance.song_list,
    }
    return render_to_response('profile_page.html', context)

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^profile/(?P<id>/d+)/$',views.Movie_Songs),
]

html

{{context.name}}

     {% for song in context %}

{{song.song_title}}

            {% endfor %}

above html will open when i click on an object,object has this

{{ movie_item.movie }}


问:
replace line in a file C++
I'm trying to find a way to replace a line, containing a string, in a file with a new line.

If the string is not present in the file, then append it to the file.

Can someone give a sample code?

EDIT : is there anyway if the line that i need to replace is at the end of the file?

答:
Although I recognize that this is not the smartest way to do it, the following code reads demo.txt line by line and searches for the word cactus to replace it for oranges while writing the output to a secondary file named result.txt.

Don't worry, I saved some work for you. Read the comment:

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
  string search_string = "cactus";
  string replace_string = "oranges";
  string inbuf;
  fstream input_file("demo.txt", ios::in);
  ofstream output_file("result.txt");

  while (!input_file.eof())
  {
      getline(input_file, inbuf);

      int spot = inbuf.find(search_string);
      if(spot >= 0)
      {
         string tmpstring = inbuf.substr(0,spot);
         tmpstring += replace_string;
         tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
         inbuf = tmpstring;
      }

      output_file << inbuf << endl;
  }

  //TODO: delete demo.txt and rename result.txt to demo.txt
  // to achieve the REPLACE effect.
}
</code>```

Title: replace line in a file C++

Body:
Although I recognize that this is not the smartest way to do it, the following code reads demo.txt line by line and searches for the word cactus to replace it for oranges while writing the output to a secondary file named result.txt.

Don't worry, I saved some work for you. Read the comment:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
  string search_string = "cactus";
  string replace_string = "oranges";
  string inbuf;
  fstream input_file("demo.txt", ios::in);
  ofstream output_file("result.txt");

  while (!input_file.eof())
  {
      getline(input_file, inbuf);

      int spot = inbuf.find(search_string);
      if(spot >= 0)
      {
         string tmpstring = inbuf.substr(0,spot);
         tmpstring += replace_string;
         tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
         inbuf = tmpstring;
      }

      output_file << inbuf << endl;
  }

  //TODO: delete demo.txt and rename result.txt to demo.txt
  // to achieve the REPLACE effect.
}


问:
How to make match() work with date in excel vba?
I'm having problem making the match() work in excel VBA. The code is:

```<code>x = Application.Match("Sep 2008", Range("F1:F1"), 0)
</code>```

The value in cell F1 is 9/1/2008.

Even if I changed Sep 2008 to 9/1/2008, it still doesn't return any value.

Any idea how to fix it?

答:
Bottom line:

use WorksheetFunction.Match(CDbl(date), range, 0)

Alternatively, use a Date cell's Value2 property (which will also be a Double) instead of Value for the search key.

CLng suggested in other answers would discard the time part of the date.

The same problem exists for the Currency data type but you can't use CDbl for it (see below for options).

Range.Value2 Property (Excel) article suggests that Date and Currency types are "special" in that they have an "internal representation" that's in stark contrast with displayed value. Indeed:

Date is internally represented as IEEE 64-bit (8-byte) floating-point numbers where the integer part is the date and fractional part is the time

Currency is also 8-byte but is treated as a fixed-point number with 4 fractional digits (an integer scaled by 10'000)

Apparently, Match compares these internal values for performance reasons. So, we must ensure that they, rather than the readable representations, match exactly.

Since Date is already floating-point internally, CDbl(date) doesn't actually change the data.

For the Currency type, CDbl does change data, so it's out of question. So either

use the exact representation of the key (to 4 fractional digits) this way or another if you require exact match, or

make the cells in the range actually be formulas with Round) if the value to compare with comes from elsewhere and/or you only require equality to 2 fractional digits

Body:
I'm having problem making the match() work in excel VBA. The code is:

x = Application.Match("Sep 2008", Range("F1:F1"), 0)

The value in cell F1 is 9/1/2008.

Even if I changed Sep 2008 to 9/1/2008, it still doesn't return any value.

Any idea how to fix it?


问:
vis.js beforeAddNode handler
I'm adding dynamically nodes and edges to my network.
Before adding them I want to be sure they're not already present in the datasets.
I'm not sure manipulation is the way, I can't see that console.logs when I add nodes/edges.
http://visjs.org/docs/network/manipulation.html

```<code>manipulation: {
        enabled: false,
        addNode: function (data, callback) {
            console.log('add', data);
            callback(data);
        },
        editNode: function (data, callback) {
            console.log('edit', data);
            callback(data);
        },
        addEdge: function (data, callback) {
            console.log('add edge!', data);
            callback(data);
        }
}
</code>```

答:
i added a snippet to show you how you can do it.

there is a boolean there you can change and see the effect.

instead of this boolean you can run your function for checking if the node exist in the DataSet.

// create an array with nodes
  var nodes = new vis.DataSet([
    {id: 1, label: 'Node 1'},
    {id: 2, label: 'Node 2'},
    {id: 3, label: 'Node 3'},
    {id: 4, label: 'Node 4'},
    {id: 5, label: 'Node 5'}
  ]);

  // create an array with edges
  var edges = new vis.DataSet([
    {from: 1, to: 3},
    {from: 1, to: 2},
    {from: 2, to: 4},
    {from: 2, to: 5}
  ]);

  // create a network
  var container = document.getElementById('mynetwork');
  var data = {
    nodes: nodes,
    edges: edges
  };
  var options = {
    manipulation: {
        enabled: false,
        addNode: function (data, callback) {
            console.log('add', data);
            var idExist = true; // you can change it to false to see addition
            if(idExist){
              callback(null);
              console.log('node exist!!!, not added');
            }
            else{
              callback(data);
            }
        },
        editNode: function (data, callback) {
            console.log('edit', data);
            callback(data);
        },
        addEdge: function (data, callback) {
            console.log('add edge!', data);
            callback(data);
        }
    }
  };
  var network = new vis.Network(container, data, options);

  function addNode(){
    network.enableEditMode();
    network.addNodeMode();
    console.log('click on canvas to add node!');
  }

  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mynetwork {
      width: 600px;
      height: 400px;
      border: 1px solid lightgray;
    }

    p {
      max-width: 600px;
    }</code>```

<!doctype html>

  <title>Network | Basic usage</title>

  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.css" rel="stylesheet" type="text/css"/>

<button onclick="addNode()"> add node</button>

```

Title: vis.js beforeAddNode handler

Body:
I'm adding dynamically nodes and edges to my network.
Before adding them I want to be sure they're not already present in the datasets.
I'm not sure manipulation is the way, I can't see that console.logs when I add nodes/edges.
http://visjs.org/docs/network/manipulation.html

manipulation: {
        enabled: false,
        addNode: function (data, callback) {
            console.log('add', data);
            callback(data);
        },
        editNode: function (data, callback) {
            console.log('edit', data);
            callback(data);
        },
        addEdge: function (data, callback) {
            console.log('add edge!', data);
            callback(data);
        }
}

Body:
i added a snippet to show you how you can do it.

there is a boolean there you can change and see the effect.

instead of this boolean you can run your function for checking if the node exist in the DataSet.

// create an array with nodes
  var nodes = new vis.DataSet([
    {id: 1, label: 'Node 1'},
    {id: 2, label: 'Node 2'},
    {id: 3, label: 'Node 3'},
    {id: 4, label: 'Node 4'},
    {id: 5, label: 'Node 5'}
  ]);

  // create an array with edges
  var edges = new vis.DataSet([
    {from: 1, to: 3},
    {from: 1, to: 2},
    {from: 2, to: 4},
    {from: 2, to: 5}
  ]);

  // create a network
  var container = document.getElementById('mynetwork');
  var data = {
    nodes: nodes,
    edges: edges
  };
  var options = {
    manipulation: {
        enabled: false,
        addNode: function (data, callback) {
            console.log('add', data);
            var idExist = true; // you can change it to false to see addition
            if(idExist){
              callback(null);
              console.log('node exist!!!, not added');
            }
            else{
              callback(data);
            }
        },
        editNode: function (data, callback) {
            console.log('edit', data);
            callback(data);
        },
        addEdge: function (data, callback) {
            console.log('add edge!', data);
            callback(data);
        }
    }
  };
  var network = new vis.Network(container, data, options);

  function addNode(){
    network.enableEditMode();
    network.addNodeMode();
    console.log('click on canvas to add node!');
  }

#mynetwork {
      width: 600px;
      height: 400px;
      border: 1px solid lightgray;
    }

    p {
      max-width: 600px;
    }

<!doctype html>
<html>
<head>
  <title>Network | Basic usage</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<button onclick="addNode()"> add node</button>
<div id="mynetwork"></div>

</body>
</html>


问:
Assign string array to comboBox in java
I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.

```<code>import java.awt.EventQueue;

public class ExpenseManager {

private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName;
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ExpenseManager window = new ExpenseManager();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public ExpenseManager() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
//@SuppressWarnings("unchecked")
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnNewUser = new JButton("New User");
    btnNewUser.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            lblNewUserName.setVisible(true);
            txtUserName.setVisible(true);
            btnDone.setVisible(true);
        }
    });
    btnNewUser.setBounds(23, 34, 89, 23);
    frame.getContentPane().add(btnNewUser);

    txtUserName = new JTextField();
    txtUserName.setBounds(240, 63, 134, 20);
    frame.getContentPane().add(txtUserName);
    txtUserName.setVisible(false);
    txtUserName.setColumns(10);

    lblNewUserName = new JLabel("Enter New UserName");
    lblNewUserName.setBounds(240, 38, 134, 14);
    lblNewUserName.setVisible(false);
    frame.getContentPane().add(lblNewUserName);

    btnDone = new JButton("Done");
    btnDone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String newUserName = txtUserName.getText();
            if(!newUserName.isEmpty())
            {
                File f = new File("S:/Expense/" + newUserName);
                if (f.exists() && f.isDirectory()) {
                   JOptionPane.showMessageDialog(null, "User already exists");
                   txtUserName.setText(null);
                }
                else{
                    boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
                    if(!success){
                        JOptionPane.showMessageDialog(null, "Unable to register");
                    }else{
                        JOptionPane.showMessageDialog(null, "User registered Successfully");
                    }
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    btnDone.setBounds(240, 103, 89, 23);
    btnDone.setVisible(false);
    frame.getContentPane().add(btnDone);

    btnLogin = new JButton("Login");
    btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            File[] directories = new File("S:/Expense/").listFiles();

            for(int i = 0; i < directories.length; i++)
            {
                dir[i] = directories[i].getName();
            }

            comboBox.setVisible(true);

        }
    });
    btnLogin.setBounds(23, 68, 89, 23);
    frame.getContentPane().add(btnLogin);

    comboBox = new JComboBox<Object>(dir);
    comboBox.setBounds(24, 138, 72, 20);
    comboBox.setSelectedIndex(1);
    comboBox.setVisible(false);
    frame.getContentPane().add(comboBox);

     }
  }
</code>```

答:
You can use setModel with DefaultComboBoxModel which take an array instead like :

```<code>comboBox.setModel(new DefaultComboBoxModel(dir));
</code>```

Title: Assign string array to comboBox in java

Body:
I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.

import java.awt.EventQueue;

public class ExpenseManager {

private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName;
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ExpenseManager window = new ExpenseManager();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public ExpenseManager() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
//@SuppressWarnings("unchecked")
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnNewUser = new JButton("New User");
    btnNewUser.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            lblNewUserName.setVisible(true);
            txtUserName.setVisible(true);
            btnDone.setVisible(true);
        }
    });
    btnNewUser.setBounds(23, 34, 89, 23);
    frame.getContentPane().add(btnNewUser);

    txtUserName = new JTextField();
    txtUserName.setBounds(240, 63, 134, 20);
    frame.getContentPane().add(txtUserName);
    txtUserName.setVisible(false);
    txtUserName.setColumns(10);

    lblNewUserName = new JLabel("Enter New UserName");
    lblNewUserName.setBounds(240, 38, 134, 14);
    lblNewUserName.setVisible(false);
    frame.getContentPane().add(lblNewUserName);

    btnDone = new JButton("Done");
    btnDone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String newUserName = txtUserName.getText();
            if(!newUserName.isEmpty())
            {
                File f = new File("S:/Expense/" + newUserName);
                if (f.exists() && f.isDirectory()) {
                   JOptionPane.showMessageDialog(null, "User already exists");
                   txtUserName.setText(null);
                }
                else{
                    boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
                    if(!success){
                        JOptionPane.showMessageDialog(null, "Unable to register");
                    }else{
                        JOptionPane.showMessageDialog(null, "User registered Successfully");
                    }
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    btnDone.setBounds(240, 103, 89, 23);
    btnDone.setVisible(false);
    frame.getContentPane().add(btnDone);

    btnLogin = new JButton("Login");
    btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            File[] directories = new File("S:/Expense/").listFiles();

            for(int i = 0; i < directories.length; i++)
            {
                dir[i] = directories[i].getName();
            }

            comboBox.setVisible(true);

        }
    });
    btnLogin.setBounds(23, 68, 89, 23);
    frame.getContentPane().add(btnLogin);

    comboBox = new JComboBox<Object>(dir);
    comboBox.setBounds(24, 138, 72, 20);
    comboBox.setSelectedIndex(1);
    comboBox.setVisible(false);
    frame.getContentPane().add(comboBox);

     }
  }

Body:
You can use setModel with DefaultComboBoxModel which take an array instead like :

comboBox.setModel(new DefaultComboBoxModel(dir));


问:
how can i find the sum of all integers given in the string by using JavaScript?
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below. </p>

```<code>var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);
</code>```

答:
in the question you asked for an expected result of 2015

the given string is

```<code>var a = "weare20boysand15girls";
</code>```

the oneliner for this solution:

```<code>console.log([...a].filter( e => isFinite(e)).join(''));
</code>```

but you marked as correct answer an result of 8

the oneliner for this solution:

```<code>console.log([...a].filter( e => isFinite(e)).reduce((a, b)=>parseInt(a)+parseInt(b)));
</code>```

Use regex only when it is impossible to use an other way...

Body:
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below.

var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);

Body:
in the question you asked for an expected result of 2015

the given string is

var a = "weare20boysand15girls";

the oneliner for this solution:

console.log([...a].filter( e => isFinite(e)).join(''));

but you marked as correct answer an result of 8

the oneliner for this solution:

console.log([...a].filter( e => isFinite(e)).reduce((a, b)=>parseInt(a)+parseInt(b)));

Use regex only when it is impossible to use an other way...