问:
How can I show GET parameters as a new directory?
I am currently working on a website where pupils can create articles that can be commented by others.

I have a already developed a script that creates them and stores them in a mysql db.

Every one of these articles should be available under www.mydomain/articles/xyz/

but I don't want to create a new directory for everyone. So is it possible to pass the parameter article=xyz (www.maydomain/articles/articles.php&articles=xyz) to be shown as before mentioned?

I am sorry if my problem is too complex. If you have a question regarding it, do not hesitate to contact me! :)

答:
Maybe you can do something like this with .htaccess file.

You can redirect every page to your index.phppage

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    DirectoryIndex index.php
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule . /index.php [L]
</IfModule>
</code>```

And then you can handle your domain in your php file:

```<code><?php

/*
Example URL
$url = www.maydomain/articles/querystring/articles/xyz/param2/value2/param3/value3
$url = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
*/

$url = "www.maydomain/articles/querystring/articles/xyz/param2/value2/param3/value3";
$url = explode("/querystring/", $url);

/*
Where $url[0] is (www.maydomain/articles),
and $url[1] is the rest of it (queryqtring/articles/xyz/param2/value2/param3/value3)
*/

// If you need you can include your page articles on your index page like this
$page_name = explode("/", $url[0]);
$page_name = end($page_name);
include("/path to your directory/". $page_name .".php");

$query_string = $url[1];
// And one more explode for query string:
$query_params = explode("/", $query_string);

for($i=0; $i<count($query_params); $i++)
{
    // odd value is GET name
    $key = $query_params[$i];
    // even value is GET value
    $value = (isset($query_params[$i+1])) ? $query_params[$i+1] : "";
    $_GET[$key] = $value;
    $i++;
}

echo "```";
print_r($_GET);
echo "```";

/*
// GET Output
Array
(
    [articles] => xyz
    [param2] => value2
    [param3] => value3
)
*/

?>
</code>```

Body:
Maybe you can do something like this with .htaccess file.

You can redirect every page to your index.phppage

<IfModule mod_rewrite.c>
    RewriteEngine On
    DirectoryIndex index.php
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule . /index.php [L]
</IfModule>

And then you can handle your domain in your php file:

<?php

/*
Example URL
$url = www.maydomain/articles/querystring/articles/xyz/param2/value2/param3/value3
$url = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
*/

$url = "www.maydomain/articles/querystring/articles/xyz/param2/value2/param3/value3";
$url = explode("/querystring/", $url);

/*
Where $url[0] is (www.maydomain/articles),
and $url[1] is the rest of it (queryqtring/articles/xyz/param2/value2/param3/value3)
*/

// If you need you can include your page articles on your index page like this
$page_name = explode("/", $url[0]);
$page_name = end($page_name);
include("/path to your directory/". $page_name .".php");

$query_string = $url[1];
// And one more explode for query string:
$query_params = explode("/", $query_string);

for($i=0; $i<count($query_params); $i++)
{
    // odd value is GET name
    $key = $query_params[$i];
    // even value is GET value
    $value = (isset($query_params[$i+1])) ? $query_params[$i+1] : "";
    $_GET[$key] = $value;
    $i++;
}

echo "<pre>";
print_r($_GET);
echo "</pre>";

/*
// GET Output
Array
(
    [articles] => xyz
    [param2] => value2
    [param3] => value3
)
*/

?>


来源: stackexchange

问:
Mapping array of objects to array of arrays with headers using ES6
I want to map an array of objects, which I got from a json response of my backend, to an array of arrays, with the first row being an array of headers (titles). I'll use this array to make it downloadable in a csv file.

Also, I want to keep away a couple of headers / columns that are not really interesting for the end user to have in their csv file.

My code is working fine, but I have the idea that it can be done with more concise code. I'm fine with using ES6 / ES2015, but not really experienced with spread syntax and other ES6 goodies myself, so any suggestions for a better, more modern (functional / reactive?) approach are greatly appreciated.

const originalData = [
  {name: 'Gizmo', species: 'cat', age: '9', raw: 'G9e76rd', updated_at: '1318874398806', skill: 'sleeping'},
  {name: 'Benny', species: 'dog', age: '3', raw: '98HDo2h', updated_at: '1318874392417', skill: 'chasing tail'},
  {name: 'Oscar', species: 'cat', age: '2', raw: '9da8Ro1', updated_at: '1318874390283', skill: 'meowing'}
]

let headers = []
const firstRow = originalData[0]
for (var key in firstRow) {
  if (firstRow.hasOwnProperty(key)) {
    if (!['raw','updated_at'].includes(key)) {
      headers.push(key)
    }
  }
}

const d = originalData.map(function(_, i) {
  return headers.map(function(header) {
    return originalData[i][header]
  }.bind(this))
}.bind(this))

const result = [headers].concat(d)

console.log(result)```

答:
I'd like to point out that an object's keys order is not entirely "fixed" by spec.

If your first animal in your originalData starts with a species property, your whole table will be formatted in that column order...

Therefore I'd advice you to explicitly define your columns in an array, in which order does matter.

Note that in the example below I've swapped the property declaration order of Gizmo. Put this data in your own code and the first column will be species. (at least in my browser it is, I guess it can even differ between browsers?)

const data = [
  {species: 'cat', name: 'Gizmo', age: '9', raw: 'G9e76rd', updated_at: '1318874398806', skill: 'sleeping'},
  {name: 'Benny', species: 'dog', age: '3', raw: '98HDo2h', updated_at: '1318874392417', skill: 'chasing tail'},
  {name: 'Oscar', species: 'cat', age: '2', raw: '9da8Ro1', updated_at: '1318874390283', skill: 'meowing'}
]

const getProps = props => obj =>
  props.map(k => obj[k]);

const columns = ["name", "species", "age", "skill"];

console.log(
  [columns, ...data.map(getProps(columns))]
);```

ContentLicense: CC BY-SA 3.0


问:
How I can log all nodejs messages showed on console to syslog in ubuntu?
I am new to nodejs and syslog functionality.
The message generated by nodejs such as error, or info are not getting logged in syslog.
I want to log all the message generated by nodejs and displayed on the terminal to syslog.
For this what changes I need to do in syslog.conf file?
Note: I dont want to use Winston, loggly or log4s</p>

答: Not sure as to what Syslog is as I am not an Ubuntu user. But You may want to use Winston. Not only it will serve your purpose but also it's asynchronous.</p>


问:
jQuery's ajax not working on IE6 :(
I'm developing a website using asp.net mvc and I have this image that fire an Ajax event when clicked. It works just fine on FF and IE 7 & 8, but on IE 6 it doesn't even call the method on the controller (I did put a breakpoint there and ran it on debug mode to check). I'm on it for a few days now and can't find a solution. Here's my code:

```<code>    <img src="/Content/Images/img.png" onclick="HideAll(); GetMyVonparDiv(this);
         $.ajax({ url: '/<%= Html.ViewContext.RouteData.Values["language"] %>/myvonpar/AddContent/?idContent=<%= ViewData.Model.id_content.ToString() %>&static=<%= ViewData.Model.is_static %>',
         type: 'GET',
         success: function (msg) { if (msg == 'True') { $(parentDiv).prev('.ok').show(); } else { $(parentDiv).show(); } },
         error: function (msg) {  }
    });" />
</code>```

The url for the method is generated correctly (/pt/myvonpar/AddContent/?idContent=258&static=False) and, as i said before, it works on every other browser but IE6 :(

Edit: The same JS code formatted for better readability:

```<code>HideAll();
GetMyVonparDiv(this);

$.ajax({
    url: '/<%= Html.ViewContext.RouteData.Values["language"] %>/myvonpar/AddContent/?idContent=<%= ViewData.Model.id_content.ToString() %>&static=<%= ViewData.Model.is_static %>',
    type: 'GET',
    success: function (msg) {
        if (msg == 'True') {
            $(parentDiv).prev('.ok').show();
        } else {
            $(parentDiv).show();
        }
    },
    error: function (msg) {  }
});
</code>```

答: I've run into a similar problem and it turned out that IE was caching the get query.  see this link here</p>

ContentLicense: CC BY-SA 2.5

Title: jQuery's ajax not working on IE6 :(

Body:
I'm developing a website using asp.net mvc and I have this image that fire an Ajax event when clicked. It works just fine on FF and IE 7 & 8, but on IE 6 it doesn't even call the method on the controller (I did put a breakpoint there and ran it on debug mode to check). I'm on it for a few days now and can't find a solution. Here's my code:

    <img src="/Content/Images/img.png" onclick="HideAll(); GetMyVonparDiv(this);
         $.ajax({ url: '/<%= Html.ViewContext.RouteData.Values["language"] %>/myvonpar/AddContent/?idContent=<%= ViewData.Model.id_content.ToString() %>&static=<%= ViewData.Model.is_static %>',
         type: 'GET',
         success: function (msg) { if (msg == 'True') { $(parentDiv).prev('.ok').show(); } else { $(parentDiv).show(); } },
         error: function (msg) {  }
    });" />

The url for the method is generated correctly (/pt/myvonpar/AddContent/?idContent=258&static=False) and, as i said before, it works on every other browser but IE6 :(

Edit: The same JS code formatted for better readability:

HideAll();
GetMyVonparDiv(this);

$.ajax({
    url: '/<%= Html.ViewContext.RouteData.Values["language"] %>/myvonpar/AddContent/?idContent=<%= ViewData.Model.id_content.ToString() %>&static=<%= ViewData.Model.is_static %>',
    type: 'GET',
    success: function (msg) {
        if (msg == 'True') {
            $(parentDiv).prev('.ok').show();
        } else {
            $(parentDiv).show();
        }
    },
    error: function (msg) {  }
});


问:
Dynamo Db vs Elastic Search
I was just reading about elastic search and found that it indexes each and every term in the document as well as all fields. Although it has some disadvantages like it cannot provide transactions, etc. But for the application, where I only need to read data from DB and there is no write, is there any advantage to using Dynamo Db instead of Elastic Search. Earlier, I was thinking to use the Dynamo Db, but now after seeing that it indexes each and every field, so why not use Elastic Search itself. Till now, the only use case defined for my project is to search by an id. But in future, more use cases come, then it would be very difficult to add more indexes in Dynamo Db but would already be there in Elastic Search.

Can someone tell me of some advantages of Dynamo Db against Elastic Search.

Please give your suggestions.

答:
I have used elasticsearch and MongoDB but not much Dynamodb. MongoDB works very well regarding indexing and strong consistency.

Few things I know about elasticsearch and DynamoDB;

elasticsearch
is a search-engine, where you can search by any terms, or aggregate records based on certain criteria, but it also serves as a document-store, though was not primary purpose. And definitely great for less writes and more reads.

some elasticsearch advantages

max size of each document it allows is 2G -> 2G at lucene level

you can have partitions(called Shards) to distribute your documents based on _id field by default

supports strong consistency - configurable

supports atomic writes with versioning on each document.

supports only document level Atomicity

you can aggregate documents based on criterias - JSON based queries

elasticsearch disadvantages

has no Atomicity (A in ACID) between multiple documents

you might want to check security options, last time I used it maybe version 3, did not have good option

Dynamodb on the other hand is a datastore(technically called document-store/ Amazon's version of MongoDB).

advantages

fully managed by AWS, as you won't have to worry about server going down or etc.

secured by Amazon IAM roles

you can have partitions(called Shards) to distribute your documents based on primary key on each document

supports multi item/document level Atomicity (A in ACID)

supports atomic writes - https://github.com/awslabs/dynamodb-transactions
lock attribute on each document which refers to current transactionId

supports Eventually Consistent and Strongly Consistent Reads :

When a document is written to DynamoDB table and receives an HTTP 200
  response, all copies of the document are updated. The document will
  eventually be consistent across all storage locations, usually within
  one second or less.

When you request a strongly consistent read, DynamoDB returns a
  response with the most up-to-date data, reflecting the updates from
  all prior write operations that were successful. A strongly consistent
  read might not be available in the case of a network delay or outage.

But has some limitations,

only supports max 40K writes for 1KB sized documents/sec per table = which would be 400 writes for 100K sized docs/sec (in us-east region)

supports only 10K writes for 1KB sized docs/per table in other regions

max 40K reads for 4KB sized documents/sec per table (in us-east region)

supports only 10K reads for 4KB sized docs/per table in other regions

so calculate your throughput based on your average document size and see DynamoDB fits in

the max document/item size in dynamodb is 400KB (reference to s3 might do the trick if document size is more than 400KB, but still depends if you really want to go that route )/ MongoDB might be alternative which allows upto 16M of document.

you can only fetch 1000 KB of documents from DynamoDB in one request

So, basically,

desired throughput,

ACID-compliancy (DynamoDB +1),

each document size (elasticsearch +1, MongoDB +1 ) and

security might be the deciding factor.

I would also consider looking into MongoDB vs DynamoDB as MongoDB is open source, has all the features other than A in Atomicity, and is also supported by AWS.

Title: Dynamo Db vs Elastic Search


问:
Add hyphen automatically in text field but not able to edit the textfield (Phone number masking)
Using the below code, I am able to add hyphen automatically, but not able to do editing in the textfield properly.

For example when I click to insert any number between the already entered numbers in the textfield, this will insert the number at the end of the textfield and further not delete that number properly. Can anyone help me out?

```<code>-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
  {
     if(textField == txtUserName)
     {
         if (range.location == 12)
         {
             return NO;
         }
         if (range.length == 0 && ![[NSCharacterSet decimalDigitCharacterSet]   characterIsMember:[string characterAtIndex:0]])
         {
             return NO;
         }
        if (range.length == 0 && (range.location == 3 || range.location == 7))
         {
             txtUserName.text = [NSString stringWithFormat:@"%@-  %@",txtUserName.text,string];
             return NO;
         }
         if (range.length == 1 &&(range.location==4 ||range.location ==7))
         {
             range.location--;
             range.length = 2;
              txtUserName.text = [txtUserName.text  stringByReplacingCharactersInRange:range withString:@""];
             NSLog(@"Nisha..%@",txtUserName.text);
             return NO;
          }
    }
    return YES;
}
</code>```

答:
Even this question is too old but in case you need help you can use VMaskTextField library

https://github.com/viniciusmo/VMaskTextField

Body:
Using the below code, I am able to add hyphen automatically, but not able to do editing in the textfield properly.

For example when I click to insert any number between the already entered numbers in the textfield, this will insert the number at the end of the textfield and further not delete that number properly. Can anyone help me out?

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
  {
     if(textField == txtUserName)
     {
         if (range.location == 12)
         {
             return NO;
         }
         if (range.length == 0 && ![[NSCharacterSet decimalDigitCharacterSet]   characterIsMember:[string characterAtIndex:0]])
         {
             return NO;
         }
        if (range.length == 0 && (range.location == 3 || range.location == 7))
         {
             txtUserName.text = [NSString stringWithFormat:@"%@-  %@",txtUserName.text,string];
             return NO;
         }
         if (range.length == 1 &&(range.location==4 ||range.location ==7))
         {
             range.location--;
             range.length = 2;
              txtUserName.text = [txtUserName.text  stringByReplacingCharactersInRange:range withString:@""];
             NSLog(@"Nisha..%@",txtUserName.text);
             return NO;
          }
    }
    return YES;
}


问:
how to work delete query in wordpress 4.7
Im trying to work delete query in wordpress.
im list all values from table(test)and create delete link to all view values.id;?>">Delete

and Im create anew page delete.php.
Code is :
<?php global $wpdb;
$id=$_POST['id'];
$r=$wpdb->query($wpdb->prepare("DELETE FROM test WHERE id=$id"));?>

after running page not found error message is display??

答:
Why not using wp_delet_post?

Like it says here
https://codex.wordpress.org/Function_Reference/wp_delete_post

Body:
Im trying to work delete query in wordpress.
im list all values from table(test)and create delete link to all view values.<a href="http://localhost/wordpress/delete?id=<?php echo $user->id;?>">Delete

and Im create anew page delete.php.
Code is :
<?php global $wpdb;
$id=$_POST['id'];
$r=$wpdb->query($wpdb->prepare("DELETE FROM test WHERE id=$id"));?>

after running page not found error message is display??


问:
Horizontal UIScrollView using auto layout
I have been trying this for quite sometime now and went through a lot of posts on SO and some video tutorials. What I want to create is a horizontal scroll view with some buttons in it, like this:

My view hierarchy is as follows:

View Controller

View

Scroll View

View

Buttons

I have set top, leading, trailing, bottom constraints to the scroll view. I have set it's width equal to it's superview, and have set it's height to 200. So far so good, for the view inside the scroll view, I have set it's constraints leading, trailing, top and bottom to zero with respect to it's superview i.e. scroll view. I have made it's width equals to the View controllers view, since that was the solution here on SO to the ambiguous width issue. It solved the issue. Now I added all the buttons and set up their constraints to their parent view. Now when I run the app, a screen like the above added screenshot appears, however I cant scroll to the last element.Any help is greatly appretiated.

答:
It's so simple.

Take a scrollView(Draw top left bottom right and hight constraint)

Take a UIView which will act like as a container View.(Draw top left bottom right constraint with scrollView).

Make your View Controller 1000px so that you can make your scrollView bigger and easy to watch.later on you can minimize it.

Now keep your button inside of it. keep in mind that, Every button will have top leading width , height and trailing if necessary. Width & height is important for scrollView because how big it will be depends on it.

Pictures worth a thousand word.

here is my hierarchy

And here is the Storyboard layout design.White background is basically containerView.

And here is the output.I have given some color for better understanding.


问:
Amcharts responsive issue with Pie chart
When we are checking the chart in mobile view, it was showing like in the attached. As a result it is too small to view in mobile.

答:
There's very little you can do since a lot of those slices are very small. Just like my answer to a previous question with a similar issue, you can try tweaking the labelRadius, pullOutRadius and startAngle to see if that helps, but you're better off setting a hideLabelsPercent to hide those other slices and use a legend for those smaller slices instead. Since you have a lot of slices, you'll want to place the legend in an external div so so it doesn't take up the chart's area by using the legend's divId property:

HTML

```<code><div id="chartdiv"></div>
<div id="legenddiv"></div>
</code>```

JS

```<code>AmCharts.makeChart("chartdiv", {
  // ...
  "legend": {
    "divId": "legenddiv",
     // ...
   },
  // ...
});
</code>```

You can find an example of this in action here.

You can also try including and enabling AmCharts' responsive plugin, which comes with some default rules that dynamically change the chart settings in smaller resolutions. You can also add your own rules as well.

Body:
There's very little you can do since a lot of those slices are very small. Just like my answer to a previous question with a similar issue, you can try tweaking the labelRadius, pullOutRadius and startAngle to see if that helps, but you're better off setting a hideLabelsPercent to hide those other slices and use a legend for those smaller slices instead. Since you have a lot of slices, you'll want to place the legend in an external div so so it doesn't take up the chart's area by using the legend's divId property:

HTML

<div id="chartdiv"></div>
<div id="legenddiv"></div>

JS

AmCharts.makeChart("chartdiv", {
  // ...
  "legend": {
    "divId": "legenddiv",
     // ...
   },
  // ...
});

You can find an example of this in action here.

You can also try including and enabling AmCharts' responsive plugin, which comes with some default rules that dynamically change the chart settings in smaller resolutions. You can also add your own rules as well.


问:
sqoop import failing with no command found error
I am trying to import SQL Server tables directly to HBase, below is the sqoop import syntax

```<code>sqoop import --connect "jdbc:sqlserver://server_IP:port;databaseName=xxx" --username xxx --password xxx --table sqoop_HBase--hbase-table employeeHBase --column-family amitesh --hbase-row-key empid --hbase-create-table -m 1
</code>```

Here I am facing two issues

1) If I am taking jdbc:sqlserver://server_IP:port;databaseName=xxx in double quotes, I am getting below error

```<code>5 06:02:05 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6_IBM_27
17/06/05 06:02:05 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Error parsing arguments for import:
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: employeeHBase
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: --column-family
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: amitesh
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: --hbase-row-key
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: empid
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: --hbase-create-table
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: -m
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: 1
</code>```

2) when I undo the double quotes, and execute the command , I get below error

```<code>--table or --query is required for import. (Or use sqoop import-all-tables.)
Try --help for usage instructions.
-bash: --username: command not found
</code>```

I pretty sure that I am mistyping command syntax.May be I am wrong though.

答: There must be space between --table sqoop_HBase and --hbase-table employeeHBase

Body:
I am trying to import SQL Server tables directly to HBase, below is the sqoop import syntax

sqoop import --connect "jdbc:sqlserver://server_IP:port;databaseName=xxx" --username xxx --password xxx --table sqoop_HBase--hbase-table employeeHBase --column-family amitesh --hbase-row-key empid --hbase-create-table -m 1

Here I am facing two issues

1) If I am taking jdbc:sqlserver://server_IP:port;databaseName=xxx in double quotes, I am getting below error

5 06:02:05 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6_IBM_27
17/06/05 06:02:05 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Error parsing arguments for import:
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: employeeHBase
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: --column-family
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: amitesh
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: --hbase-row-key
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: empid
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: --hbase-create-table
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: -m
17/06/05 06:02:05 ERROR tool.BaseSqoopTool: Unrecognized argument: 1

2) when I undo the double quotes, and execute the command , I get below error

--table or --query is required for import. (Or use sqoop import-all-tables.)
Try --help for usage instructions.
-bash: --username: command not found

I pretty sure that I am mistyping command syntax.May be I am wrong though.


问:
Why does my loop iterate only twice?
I have defined two structs and when I loop to set their values, it only loop twice as printf return. Any ideas?

```<code>typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[];
} World;

int main() {
  int i, x, y;
  i = 0;
  World grid;
  grid.sizeX = 10;
  grid.sizeY = 10;

  for (x = 0; x < grid.sizeX; x++) {
    for (y = 0; y < grid.sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;

      printf("%d,%d: ", cell.x, cell.y);

      grid.cell[i] = cell;
      i++;
    }
  }

    return 0;
}
</code>```

EDIT :

Correct answer given below, thanks for comments and your patience for a C noob !

答:
Here is the results : </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#define LIVE 1
#define DEAD 0
#define xSize 10
#define ySize 10

typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[1];
} World;

int main() {
  int i, x, y;
  i = 0;
  World *grid = malloc(sizeof(World) + xSize * ySize * sizeof(Cell));;
  grid->sizeX = xSize;
  grid->sizeY = ySize;

  for (x = 0; x < grid->sizeX; x++) {
    for (y = 0; y < grid->sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;
      cell.status = DEAD;

      printf("%d,%d: ", cell.x, cell.y);

      grid->cell[i] = cell;
      i++;
    }
  }

    return 0;
}
</code>```

Title: Why does my loop iterate only twice?

Body:
I have defined two structs and when I loop to set their values, it only loop twice as printf return. Any ideas?

typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[];
} World;

int main() {
  int i, x, y;
  i = 0;
  World grid;
  grid.sizeX = 10;
  grid.sizeY = 10;

  for (x = 0; x < grid.sizeX; x++) {
    for (y = 0; y < grid.sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;

      printf("%d,%d: ", cell.x, cell.y);

      grid.cell[i] = cell;
      i++;
    }
  }

    return 0;
}

EDIT :

Correct answer given below, thanks for comments and your patience for a C noob !

Body:
Here is the results :

#include <stdio.h>
#include <stdlib.h>
#define LIVE 1
#define DEAD 0
#define xSize 10
#define ySize 10

typedef struct {
  int x;
  int y;
  unsigned char status;
} Cell;

typedef struct {
  int sizeX;
  int sizeY;
  Cell cell[1];
} World;

int main() {
  int i, x, y;
  i = 0;
  World *grid = malloc(sizeof(World) + xSize * ySize * sizeof(Cell));;
  grid->sizeX = xSize;
  grid->sizeY = ySize;

  for (x = 0; x < grid->sizeX; x++) {
    for (y = 0; y < grid->sizeY; y++) {
      Cell cell;
      cell.x = x;
      cell.y = y;
      cell.status = DEAD;

      printf("%d,%d: ", cell.x, cell.y);

      grid->cell[i] = cell;
      i++;
    }
  }

    return 0;
}


问:
How to add click listener in List View, If ListView have already button in xml?
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

```<code>      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>
</code>```

activity_wash_detail

```<code>    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>
</code>```

WashDetailActivity.java

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}
</code>```

答: Means you want button click inside listview, Right?</p>

Body:
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>

activity_wash_detail

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>

WashDetailActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}


问:
tr td jquery each previous td value is not saving in variable
In debit note if i alert sales invoice value alert("sales" + si ); then it says:-

undefined

why is that?

Why it is not saving value in si?

Any help?

My code

```<code>$('input[type=button]' ).click(function() {

    var trid = $(this).closest('tr').attr('id'); // table row ID
    var grossProfit = 0;

    $("tr#"+trid).each(function( i ) { // row.

        $("td", this).each(function( j ) { // col.
            console.log("".concat("row: ", i, ", col: ", j, ", value: ", $(this).text()));

            //Sales Invoice.

            if ( j == 2) {
                var si =  $(this).find("input").val();
                // if sales invoice not found/undefined.
                if (typeof si === "undefined") {
                    si = 0; // if sales invoice is not defined.
                }
                alert("sales" + si );
            }
            // Debit Note.
            if ( j == 3) {
                var dn =  $(this).find("input").val(); // Debit note input value.
                //if debit note not found/undefined.
                if (typeof dn === "undefined") {
                    dn = 0; // if Debit Note is not defined.
                }
                alert("sales" + si );
            }
        });
    });
});
</code>```

Single html row with input fields tr and td
share code with html
https://codeshare.io/21q4zj

答:
UPDATE

To clarify who are thinking its a scope issue its not

JavaScript does variable hoisting and all variable definition are brought to the top inside your function.

what JavaScript  does it initializes a variable to undefined when it assigns a memory to it.

If a variable is undefined it means the variable is not initialized.

A undefined (Never defined) variable in Javascript will give you reference error

https://jsfiddle.net/b5cbwufx/3/

Solution

Here the problem is that you are assigning the value si = 0

only if the condition if (j == 2) { is met that means when the condition  if(j == 3){ is met the above condition will obliviously fail hence your si is never initialized to 0

This code never executes

```<code>if ( j == 2) {
  var si =  $(this).find("input").val();
  // if sales invoice not found/undefined.
  if (typeof si === "undefined") {
    si = 0; // if sales invoice is not defined.
  }
   alert("sales" + si );
}
</code>```

so, your are getting undefined in the code

```<code>// Debit Note.
if (j == 3) {
  var dn = $(this).find("input").val();

  if (typeof dn === "undefined") {
    dn = 0; // if Debit Note is not defined.
  }
  alert("sales" + si); // not defined as j==3 and not 2
}
</code>```

try declaring them outside the if blocks at the top

```<code>var si=0,dn=0; //declare here

// // Sales Invoice.
if (j == 2) {

  si = $(this).find("input").val();
  // if sales invoice not found/undefined.
  if (typeof si === "undefined") {
    si = 0; // if sales invoice is not defined.
  }
  alert("sales" + si);

} // scope ends

// Debit Note.
if (j == 3) {
  dn = $(this).find("input").val(); // Debit note input value.

  if (typeof dn === "undefined") {
    dn = 0; // if Debit Note is not defined.
  }
  alert("sales" + si);
}
</code>```

Body:
In debit note if i alert sales invoice value alert("sales" + si ); then it says:-

undefined

why is that?

Why it is not saving value in si?

Any help?

My code

$('input[type=button]' ).click(function() {

    var trid = $(this).closest('tr').attr('id'); // table row ID
    var grossProfit = 0;

    $("tr#"+trid).each(function( i ) { // row.

        $("td", this).each(function( j ) { // col.
            console.log("".concat("row: ", i, ", col: ", j, ", value: ", $(this).text()));

            //Sales Invoice.

            if ( j == 2) {
                var si =  $(this).find("input").val();
                // if sales invoice not found/undefined.
                if (typeof si === "undefined") {
                    si = 0; // if sales invoice is not defined.
                }
                alert("sales" + si );
            }
            // Debit Note.
            if ( j == 3) {
                var dn =  $(this).find("input").val(); // Debit note input value.
                //if debit note not found/undefined.
                if (typeof dn === "undefined") {
                    dn = 0; // if Debit Note is not defined.
                }
                alert("sales" + si );
            }
        });
    });
});

Single html row with input fields tr and td
share code with html
https://codeshare.io/21q4zj

Body:
UPDATE

To clarify who are thinking its a scope issue its not

JavaScript does variable hoisting and all variable definition are brought to the top inside your function.

what JavaScript  does it initializes a variable to undefined when it assigns a memory to it.

If a variable is undefined it means the variable is not initialized.

A undefined (Never defined) variable in Javascript will give you reference error

https://jsfiddle.net/b5cbwufx/3/

Solution

Here the problem is that you are assigning the value si = 0

only if the condition if (j == 2) { is met that means when the condition  if(j == 3){ is met the above condition will obliviously fail hence your si is never initialized to 0

This code never executes

if ( j == 2) {
  var si =  $(this).find("input").val();
  // if sales invoice not found/undefined.
  if (typeof si === "undefined") {
    si = 0; // if sales invoice is not defined.
  }
   alert("sales" + si );
}

so, your are getting undefined in the code

// Debit Note.
if (j == 3) {
  var dn = $(this).find("input").val();

  if (typeof dn === "undefined") {
    dn = 0; // if Debit Note is not defined.
  }
  alert("sales" + si); // not defined as j==3 and not 2
}

try declaring them outside the if blocks at the top

var si=0,dn=0; //declare here

// // Sales Invoice.
if (j == 2) {

  si = $(this).find("input").val();
  // if sales invoice not found/undefined.
  if (typeof si === "undefined") {
    si = 0; // if sales invoice is not defined.
  }
  alert("sales" + si);

} // scope ends

// Debit Note.
if (j == 3) {
  dn = $(this).find("input").val(); // Debit note input value.

  if (typeof dn === "undefined") {
    dn = 0; // if Debit Note is not defined.
  }
  alert("sales" + si);
}


问:
Excel Interop freeze panes fails when splitrow is >0
I am trying to freeze panes in an excel worksheet created in a vb.net project. I have created the following test code:

```<code>Dim xlApp = New Microsoft.Office.Interop.Excel.Application
Dim xlBook = xlApp.Workbooks.Add
Dim xlSheet = xlBook.Worksheets(1)
Dim xlWindow = xlApp.Windows(1)

With xlApp.ActiveWindow
  .SplitColumn = 1
  .SplitRow = 0
End With

xlApp.ActiveWindow.FreezePanes = True
</code>```

The problem is that this works fine as written, but if I alter the .SplitRow to anything greater then 0 I get an error on the freezepanes line -

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Unable to set the FreezePanes property of the Window class

I have also tried replacing the with block completely with the single line:

```<code>xlSheet.Cells(6, 2).Select()
</code>```

This doesn't throw an error, but it also only freezes column 6.

I would add that this is an older program that I use once a year and it worked fine last year but I have since upgraded to office 365 (64 bit version). I am still using the interop assembly for office 15 but have not been able to find an updated version.

答:
Since no-one has been able to answer this question and I have found a workaround I thought I would post an answer for anyone else who is having this problem. I am not accepting this answer though because there ought to be a solution using microsoft's own dll.

I have found a free dll called spire office by e-iceblue which will allow excel files to be manipulated without office being installed (which makes it version agnostic). There are limitations on the free version but they don't seem to apply to xls files only conversion tasks. This is able to split the panes.

Body:
I am trying to freeze panes in an excel worksheet created in a vb.net project. I have created the following test code:

Dim xlApp = New Microsoft.Office.Interop.Excel.Application
Dim xlBook = xlApp.Workbooks.Add
Dim xlSheet = xlBook.Worksheets(1)
Dim xlWindow = xlApp.Windows(1)

With xlApp.ActiveWindow
  .SplitColumn = 1
  .SplitRow = 0
End With

xlApp.ActiveWindow.FreezePanes = True

The problem is that this works fine as written, but if I alter the .SplitRow to anything greater then 0 I get an error on the freezepanes line -

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Unable to set the FreezePanes property of the Window class

I have also tried replacing the with block completely with the single line:

xlSheet.Cells(6, 2).Select()

This doesn't throw an error, but it also only freezes column 6.

I would add that this is an older program that I use once a year and it worked fine last year but I have since upgraded to office 365 (64 bit version). I am still using the interop assembly for office 15 but have not been able to find an updated version.


问:
MySQL Error 1215: Cannot add foreign key constraint between Parent and Children
I am utterly disappointed as I failed to pinpoint to the exact reason, why my table creation is failing when I am trying to create a Foreign Key relation between my two tables. The SQL queries that I am using to create the 2 tables are as under:

```<code>CREATE TABLE `OneMD_DEA_EMEA_STG_CUSTOMER` (
  `Customer_Pkey` int(11) NOT NULL AUTO_INCREMENT,
  `CustomerID` varchar(15) NOT NULL,
  `DataType` varchar(10) NOT NULL,
  `SourceSystemName` varchar(10) NOT NULL,
  `SourceCountry` varchar(2) NOT NULL,
  `SrcDataRfrshDt` date NOT NULL,
  `StartDt` date NOT NULL,
  `EndDt` date NOT NULL,
  `Category` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Customer_Pkey`,`CustomerID`),
  UNIQUE KEY `CustomerID_UNIQUE` (`CustomerID`),
  KEY `idx_OneMD_DEA_EMEA_STG_CUSTOMER` (`DataType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `STG_RELATION` (
      `Relation_Pkey` int(11) NOT NULL AUTO_INCREMENT,
      `RelationType` varchar(15) NOT NULL,
      `SourceDataType` varchar(5) NOT NULL,
      `SourceID` varchar(15) NOT NULL,
      `TargetDataType` varchar(5) NOT NULL,
      `TargetID` varchar(15) NOT NULL,
      `RltnPrmryID` varchar(50) NOT NULL,
      `SourceSystemName` varchar(10) DEFAULT NULL,
      `SourceCountry` varchar(2) NOT NULL,
      `SrcDataRfrshDt` date NOT NULL,
      `StartDt` date NOT NULL,
      `EndDt` date NOT NULL,
      `HCPHCOSubType` varchar(10) DEFAULT NULL,
      `HCPHCOLinkType` varchar(10) DEFAULT NULL,
      `HCOHCOSubType` varchar(10) DEFAULT NULL,
      `HCOHCOLinkType` varchar(10) DEFAULT NULL,
      PRIMARY KEY (`Relation_Pkey`,`SourceID`,`TargetID`,`RltnPrmryID`),
      UNIQUE KEY `Relation_Pkey_UNIQUE` (`Relation_Pkey`),
      KEY `idx_STG_RELATION` (`RelationType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`),
      KEY `Source_ID_idx` (`SourceID`),
      KEY `Target_ID_idx` (`TargetID`),
      CONSTRAINT `Source_ID` FOREIGN KEY (`SourceID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION,
      CONSTRAINT `Target_ID` FOREIGN KEY (`TargetID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    CREATE TABLE `STG_RELATION_ROLE` (
          `RltnRole_PKey` int(11) NOT NULL AUTO_INCREMENT,
          `SourceSystemName` varchar(10) NOT NULL,
          `ActivityID` varchar(15) NOT NULL,
          `RltnFrgnID` varchar(50) NOT NULL,
          `SrcDataRfrshDt` date NOT NULL,
          `StartDt` date NOT NULL,
          `EndDt` date NOT NULL,
          `SourceCountry` varchar(2) NOT NULL,
          `HCPHCORoleType` varchar(10) DEFAULT NULL,
          `HCPHCORoleField` varchar(10) DEFAULT NULL,
          `HCPHCORole` varchar(10) DEFAULT NULL,
          `HCPHCORoleStatus` varchar(20) DEFAULT NULL,
          PRIMARY KEY (`RltnRole_PKey`,`SourceSystemName`,`ActivityID`,`RltnFrgnID`),
          KEY `idx_STG_RELATION_ROLE` (`SrcDataRfrshDt`,`SourceSystemName`,`SourceCountry`,`EndDt`),
          KEY `Rltn_Frgn_ID_idx` (`RltnFrgnID`),
          CONSTRAINT `RltnFrgnID` FOREIGN KEY (`RltnFrgnID`) REFERENCES `STG_RELATION` (`RltnPrmryID`) ON DELETE CASCADE ON UPDATE NO ACTION
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

The Table RELATION got created successfully, but whenver I am trying to create the child table (RELATION_ROLE with parent as RELATION), the table creation is failing with the

Error 1215: Cannot Add Foreign Key Constraint

error message.

Am I missing something here?

Please note that CUSTOMER is the main table with child as RELATION (Customer_ID acting as Primary and Foreign Key) which further has a child RELATION_ROLE (RltnPrmryID is the Primary Key while RltnFrgnID is the foreign key.

Please help me to get the issue resolved.

答:
Uh, there are quite a few problems there - in particular with your table designs.

First of all, the STG_RELATION.RltnPrmryID is not the left most field of any indexes. MySQL requires both endpoints of a foreign key to be the leftmost fields of an index. The leftmost fields are the ones that can be used for lookups. This is the direct reason of the error.

Secondly, the primary key of STG_RELATION table is a mess. The child table should reference the primary key or a unique key from the parent table. STG_RELATION.RltnPrmryID is neither, it is only part of the primary key. Relation_Pkey field being auto increment already uniquely identifies records within the STG_RELATION table, therefore this should be the PK and STG_RELATION_ROLE table should reference this column in the foreign key (obviously, you need to adjust the field type for this to work in STG_RELATION_ROLE). Indexes on integers are a lot more efficient than indexes on strings from a performance point of view.

Body:
I am utterly disappointed as I failed to pinpoint to the exact reason, why my table creation is failing when I am trying to create a Foreign Key relation between my two tables. The SQL queries that I am using to create the 2 tables are as under:

CREATE TABLE `OneMD_DEA_EMEA_STG_CUSTOMER` (
  `Customer_Pkey` int(11) NOT NULL AUTO_INCREMENT,
  `CustomerID` varchar(15) NOT NULL,
  `DataType` varchar(10) NOT NULL,
  `SourceSystemName` varchar(10) NOT NULL,
  `SourceCountry` varchar(2) NOT NULL,
  `SrcDataRfrshDt` date NOT NULL,
  `StartDt` date NOT NULL,
  `EndDt` date NOT NULL,
  `Category` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Customer_Pkey`,`CustomerID`),
  UNIQUE KEY `CustomerID_UNIQUE` (`CustomerID`),
  KEY `idx_OneMD_DEA_EMEA_STG_CUSTOMER` (`DataType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `STG_RELATION` (
      `Relation_Pkey` int(11) NOT NULL AUTO_INCREMENT,
      `RelationType` varchar(15) NOT NULL,
      `SourceDataType` varchar(5) NOT NULL,
      `SourceID` varchar(15) NOT NULL,
      `TargetDataType` varchar(5) NOT NULL,
      `TargetID` varchar(15) NOT NULL,
      `RltnPrmryID` varchar(50) NOT NULL,
      `SourceSystemName` varchar(10) DEFAULT NULL,
      `SourceCountry` varchar(2) NOT NULL,
      `SrcDataRfrshDt` date NOT NULL,
      `StartDt` date NOT NULL,
      `EndDt` date NOT NULL,
      `HCPHCOSubType` varchar(10) DEFAULT NULL,
      `HCPHCOLinkType` varchar(10) DEFAULT NULL,
      `HCOHCOSubType` varchar(10) DEFAULT NULL,
      `HCOHCOLinkType` varchar(10) DEFAULT NULL,
      PRIMARY KEY (`Relation_Pkey`,`SourceID`,`TargetID`,`RltnPrmryID`),
      UNIQUE KEY `Relation_Pkey_UNIQUE` (`Relation_Pkey`),
      KEY `idx_STG_RELATION` (`RelationType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`),
      KEY `Source_ID_idx` (`SourceID`),
      KEY `Target_ID_idx` (`TargetID`),
      CONSTRAINT `Source_ID` FOREIGN KEY (`SourceID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION,
      CONSTRAINT `Target_ID` FOREIGN KEY (`TargetID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    CREATE TABLE `STG_RELATION_ROLE` (
          `RltnRole_PKey` int(11) NOT NULL AUTO_INCREMENT,
          `SourceSystemName` varchar(10) NOT NULL,
          `ActivityID` varchar(15) NOT NULL,
          `RltnFrgnID` varchar(50) NOT NULL,
          `SrcDataRfrshDt` date NOT NULL,
          `StartDt` date NOT NULL,
          `EndDt` date NOT NULL,
          `SourceCountry` varchar(2) NOT NULL,
          `HCPHCORoleType` varchar(10) DEFAULT NULL,
          `HCPHCORoleField` varchar(10) DEFAULT NULL,
          `HCPHCORole` varchar(10) DEFAULT NULL,
          `HCPHCORoleStatus` varchar(20) DEFAULT NULL,
          PRIMARY KEY (`RltnRole_PKey`,`SourceSystemName`,`ActivityID`,`RltnFrgnID`),
          KEY `idx_STG_RELATION_ROLE` (`SrcDataRfrshDt`,`SourceSystemName`,`SourceCountry`,`EndDt`),
          KEY `Rltn_Frgn_ID_idx` (`RltnFrgnID`),
          CONSTRAINT `RltnFrgnID` FOREIGN KEY (`RltnFrgnID`) REFERENCES `STG_RELATION` (`RltnPrmryID`) ON DELETE CASCADE ON UPDATE NO ACTION
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The Table RELATION got created successfully, but whenver I am trying to create the child table (RELATION_ROLE with parent as RELATION), the table creation is failing with the

Error 1215: Cannot Add Foreign Key Constraint

error message.

Am I missing something here?

Please note that CUSTOMER is the main table with child as RELATION (Customer_ID acting as Primary and Foreign Key) which further has a child RELATION_ROLE (RltnPrmryID is the Primary Key while RltnFrgnID is the foreign key.

Please help me to get the issue resolved.


问:
Is there a way to crack the password on an Excel VBA Project?
I've been asked to update some Excel 2003 macros, but the VBA projects are password protected, and it seems there's a lack of documentation... no-one knows the passwords.

Is there a way of removing or cracking the password on a VBA project?

答:
your excel file's extension change to xml.
And open it in notepad.
password text find in xml file.

you see like below line;

```<code>Sheets("Sheet1").Unprotect Password:="blabla"
</code>```

(sorry for my bad english)

Body:
your excel file's extension change to xml.
And open it in notepad.
password text find in xml file.

you see like below line;

Sheets("Sheet1").Unprotect Password:="blabla"

(sorry for my bad english)


问:
Automatically close PuTTY when connection is lost
I have a script in bash, running multiple PuTTY sessions.
For example, I open the connection to run a couple of commands, when it finishes it saves the values, closes the session, opens a new session and runs a couple more.

This script is supposed to run for 60 hours, more or less, so i need to have everything automated.

My issue is, when the PuTTY session is open, and connected to the device i need, if at some point the device reboots (don't know why it reboots, it just does), a window in putty appears saying the connection was terminated (obviously). The problem is that the window stays open until I press the "ok" button. So my script just stops there until some manual interaction with the PuTTY session.

Is there a way to automatically terminate the PuTTY session if a disconnection happens?

Thank you for your help, if you need some more information just let me know!
regards

答:
See the "Close Window on Exit" option in the Session panel.

Documentation


问:
PHPUnit generated test skeleton path
Is it possible to tell phpunit where to put generated test skeleton file by the --skeleton-test command? Even is it possible to tell phpunit to repeat directory structure?
Lest say i have file for testing in lib/model/SomeClass.php and i want phpstorm to generate unit test class and put it in test/lib/model/SomeClassTest.php without creation of all neccessary directory structure.

Thanks in advance!

答:
Yeah that is possible in netbeans IDE. if you configure PHPUnit(Xdebug required) with netbeans then it automatically creates file/folder structure for your framework

Netbeans link

Also it creates the skeleton for each class of Controller and module

Title: PHPUnit generated test skeleton path


问:
Create new array from existing one only with elements that contain specific value
I create a new array from an existing one (big array with 100.000 objects). In the new array I want only elements where the value of "city" is for example New York City.

```<code>    var newData = [];

    for (var i = 0; i < data.length; i++) {

        if(data[i].city === "New York City") {

            newData[i] = {"city": data[i].city, "longitude":
            data[i].longitude, "latitude": data[i].latitude, "state":
            data[i].state};

        }
     }
</code>```

I must be doing something wrong since a lot of elements in the new array are null …

The new array then looks something like this:

```<code>[null,null,null,null,null, {"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"},
null,null,null,null,null,null,"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"}]
</code>```

What am I doing wrong? How could I achieve my goal?

Thanks in advance guys!

答:
The elements won't be null, they'll be missing (which shows up as undefined when you try to access them). The reason is that you're increasing i every time, even when you skip an entry.

To fix it, use push instead:

```<code>var newData = [];

for (var i = 0; i < data.length; i++) {

    if (data[i].city === "New York City") {
        newData.push({
            "city": data[i].city,
            "longitude": data[i].longitude,
            "latitude": data[i].latitude,
            "state": data[i].state
        });
    }
}
</code>```

If you want the two arrays to share objects, you could use filter instead:

```<code>var newData = data.filter(function(entry) {
    return entry.city === "New York City";
});
</code>```

but if you want the new array to have new objects that are different from the originals, your for loop is fine.

Body:
I create a new array from an existing one (big array with 100.000 objects). In the new array I want only elements where the value of "city" is for example New York City.

    var newData = [];

    for (var i = 0; i < data.length; i++) {

        if(data[i].city === "New York City") {

            newData[i] = {"city": data[i].city, "longitude":
            data[i].longitude, "latitude": data[i].latitude, "state":
            data[i].state};

        }
     }

I must be doing something wrong since a lot of elements in the new array are null …

The new array then looks something like this:

[null,null,null,null,null, {"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"},
null,null,null,null,null,null,"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"}]

What am I doing wrong? How could I achieve my goal?

Thanks in advance guys!

Body:
The elements won't be null, they'll be missing (which shows up as undefined when you try to access them). The reason is that you're increasing i every time, even when you skip an entry.

To fix it, use push instead:

var newData = [];

for (var i = 0; i < data.length; i++) {

    if (data[i].city === "New York City") {
        newData.push({
            "city": data[i].city,
            "longitude": data[i].longitude,
            "latitude": data[i].latitude,
            "state": data[i].state
        });
    }
}

If you want the two arrays to share objects, you could use filter instead:

var newData = data.filter(function(entry) {
    return entry.city === "New York City";
});

but if you want the new array to have new objects that are different from the originals, your for loop is fine.


问:
How to prevent style propagation to the next LI element?
I have an article with a list (ol) of sentences, one per line. A user can hit Enter to create another sentence on a new line, which appends a new li. A user can also emphasize some text in a sentence (using a button, but it's irrelevant for the sake of the question). The problem is that when hitting Enter after an emphasized text, the next li also "inherits" the emphasis. How can I make the new lis vanilla?

HTML

```<code><article id="xml" contenteditable="true">
  <ol>
    <li>hello</li>
    <li><em>world</em></li>
  </ol>
</article>
</code>```

CSS

```<code>body {
  counter-reset: item !important;
}

article#xml ol {
  list-style: none;
}

article#xml ol li {
  line-height: 1.5;
  font-family: sans-serif;
  margin-top: 14px;
  counter-increment: item;
}

#xml ol li:before {
  content: counter(item);
  color: #888;
  border-right: solid 1px #c4c4c4;
  margin-right: 14px;
  text-align: center;
  font-size: 12px;
  display: inline-block;
}
</code>```

E.g. adding an item after 'hello' creates a vanilla li, while doing so after 'world' creates an emphasized one.

Demo

答:
you want one of these i think.

only style the first one.

CSS

```<code>ol li:first {
....
}
</code>```

HTML

```<code><ol>
    <li></li> /*styling from the above*/
    <li></li> /* NO styling from the above rule */
</ol>
</code>```

prevent style propagation to the next LI element

CSS

```<code>ol > li {
....
}
</code>```

HTML

```<code><ol>
    <li> /*styling from the above*/
        <li></li> /* NO styling from the above rule*/
    </li>
</ol>
</code>```

know that you can combined them, i was just showing for ease of illustration.
so this is also valid.

```<code>ol > li: first {
....
}
</code>```

try apply as you need:

```<code>ol li:before {
   //only rules for before
}
ol li:first {
   //only rules for before
}
ol li {
   //rules for all li within ol
}
</code>```

Body:
I have an article with a list (ol) of sentences, one per line. A user can hit Enter to create another sentence on a new line, which appends a new li. A user can also emphasize some text in a sentence (using a button, but it's irrelevant for the sake of the question). The problem is that when hitting Enter after an emphasized text, the next li also "inherits" the emphasis. How can I make the new lis vanilla?

HTML

hello

world

CSS

body {
  counter-reset: item !important;
}

article#xml ol {
  list-style: none;
}

article#xml ol li {
  line-height: 1.5;
  font-family: sans-serif;
  margin-top: 14px;
  counter-increment: item;
}

#xml ol li:before {
  content: counter(item);
  color: #888;
  border-right: solid 1px #c4c4c4;
  margin-right: 14px;
  text-align: center;
  font-size: 12px;
  display: inline-block;
}

E.g. adding an item after 'hello' creates a vanilla li, while doing so after 'world' creates an emphasized one.

Demo

Body:
you want one of these i think.

only style the first one.

CSS

ol li:first {
....
}

HTML

<ol>
    <li></li> /*styling from the above*/
    <li></li> /* NO styling from the above rule */
</ol>

prevent style propagation to the next LI element

CSS

ol > li {
....
}

HTML

<ol>
    <li> /*styling from the above*/
        <li></li> /* NO styling from the above rule*/
    </li>
</ol>

know that you can combined them, i was just showing for ease of illustration.
so this is also valid.

ol > li: first {
....
}

try apply as you need:

ol li:before {
   //only rules for before
}
ol li:first {
   //only rules for before
}
ol li {
   //rules for all li within ol
}


问:
Using pointer to channel
Is it good practice to use pointer to channel? For example I read the data concurrently and pass those data map[string]sting using channel  and process this channel inside getSameValues().

```<code>func getSameValues(results *chan map[string]string) []string {
    var datas = make([]map[string]string, len(*results))
    i := 0
    for values := range *results {
        datas[i] = values
        i++
    }
}
</code>```

The reason I do this is because the chan map[string]string there will be around millions of data inside the map and it will be more than one map.

So I think it would be a good approach if I can pass pointer to the function so that it will not copy the data to save some resource of memory.

I didn't find a good practice in effective go. So I'm kinda doubt about my approach here.

答:
In Go, there are six categories of value that are passed by reference rather than by value. These are pointers, slices, maps, channels, interfaces and functions.

Copying a reference value and copying a pointer should be considered equal in terms of what the CPU has to actually do (at least as a good approximation).

So it is almost never useful to use pointers to channels, just like it is rarely useful to use pointers to maps.

Because your channel carries maps, the channel is a reference type and so are the maps, so all the CPU is doing is copying pointers around the heap. In the case of the channel, it also does goroutine synchronisation too.

For further reading, open Effective Go and search the page for the word 'reference'.

Title: Using pointer to channel

Body:
Is it good practice to use pointer to channel? For example I read the data concurrently and pass those data map[string]sting using channel  and process this channel inside getSameValues().

func getSameValues(results *chan map[string]string) []string {
    var datas = make([]map[string]string, len(*results))
    i := 0
    for values := range *results {
        datas[i] = values
        i++
    }
}

The reason I do this is because the chan map[string]string there will be around millions of data inside the map and it will be more than one map.

So I think it would be a good approach if I can pass pointer to the function so that it will not copy the data to save some resource of memory.

I didn't find a good practice in effective go. So I'm kinda doubt about my approach here.

ContentLicense: CC BY-SA 4.0


问:
How to get tooltip on chart.js v1.x?
I have tried
Chart JS custom tooltip option?
and
How to show tooltips in Chart.js?

One among many attempts of mine are:

```<code>    new Chart(document.getElementById("location").getContext("2d")).Bar(barChartData2,{
    showTooltip: true,
    tooltipTemplate: "<%= value %>",
     //Option for title font size in pixels
     tooltipTitleFontSize: 14,

     //Option for tooltip title color
     tooltipTitleFontColor: "#eee",
     });
</code>```

but both of no use to me I have tried every possibility and I'm not able to know what is stopping the tooltip from working.
Nothing there in the console to debug so any suggestion would be thankful

答:
```<code> new Chart(document.getElementById("location").getContext("2d")).Bar(barChartData2**)**,{
showTooltip: true,
tooltipTemplate: "<%= value %>",
 //Option for title font size in pixels
 tooltipTitleFontSize: 14,

 //Option for tooltip title color
 tooltipTitleFontColor: "#eee",
 });
</code>```

<p>See the above code....are you missing a parenthesis after barChartData2? </p>

Title: How to get tooltip on chart.js v1.x?

Body:
I have tried
Chart JS custom tooltip option?
and
How to show tooltips in Chart.js?

One among many attempts of mine are:

    new Chart(document.getElementById("location").getContext("2d")).Bar(barChartData2,{
    showTooltip: true,
    tooltipTemplate: "<%= value %>",
     //Option for title font size in pixels
     tooltipTitleFontSize: 14,

     //Option for tooltip title color
     tooltipTitleFontColor: "#eee",
     });

but both of no use to me I have tried every possibility and I'm not able to know what is stopping the tooltip from working.
Nothing there in the console to debug so any suggestion would be thankful

Body:
 new Chart(document.getElementById("location").getContext("2d")).Bar(barChartData2**)**,{
showTooltip: true,
tooltipTemplate: "<%= value %>",
 //Option for title font size in pixels
 tooltipTitleFontSize: 14,

 //Option for tooltip title color
 tooltipTitleFontColor: "#eee",
 });

See the above code....are you missing a parenthesis after barChartData2?


问:
Create a New Laravel Project Using Homestead
I have already setup Laravel using homestead before, and I have an existing project that already works. However, i want to add another new project.

I have added a new folder and mapped it in the homestead.yaml file. But I want to know how to setup the project itself because the folder is empty and all the documentation I found is on the new site mapping. How about the new site configuration and files.

Please assist me in this as i am very new to Laravel. I am using Windows by the way

答:
The mappings are installed only at the creation of virtual machine.
To refresh them run the machine with homestead up --provision


问:
Virtual keyboard changes my page height
I'm developing a web app for mobile phones and i got a strange problem.
I have a simple page with a background image and an input field centered in the middle of the page.
The problem is whenever i click the input box and the virtual keyboard comes up, the background image and input field dimensions are recalculated according to the remaining page space.

The desired behavior is that the whole page will be pushed up.

relevant code (i'm developing with react, hence the weird names)

```<code><html>
<head>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <style type="text/css">.location_input__LocationInputStyle___2cLQ9 {
        position: absolute;
        width: 85%;
        height: 10%;
        top: 45%;
        left: 50%;
        transform: translate(-50%);
        background-color: transparent;
        border-radius: 50px;
        border: 3px solid #ffffff;
        text-align: center;
        font-size: 22px;
        color: #ffffff;

    }
    </style>
    <style type="text/css">.home_page_container__HomePageStyle___2f5vW {
        position: relative;
        width: 100%;
        height: 100%;
        background-image: url(86349e48855062e70072f79443fe0af6.jpg);
        background-repeat: no-repeat;
        background-size: cover;
        background-position: 40% 0;
    }
    </style>
</head>
<body>
<div id="app">
    <div class="home_page_container__HomePageStyle___2f5vW">
        <input type="text" class="location_input__LocationInputStyle___2cLQ9" placeholder="Address">
    </div>
</div>
</body>
</html>
</code>```

Related Images:

The problem, when keyboard pops up

Desired result

P.S: after playing with the debugger a bit, i found out that if i set the height of my app container/body/html to a fixed pixel height it doesn't happen.
Yet it's not a good solution, because i want the height to be 100% of the viewport (so it will be compatible with all devices).

How do i fix it properly?

答:
You can specify min-height for the keyboard div.

You can also try giving the dividing the text part and keyboard part  in  vh (viewport height, like for input div : 50vh,keyboard :50vh ) instead of giving height:100%;.Please remove all other heights.

Title: Virtual keyboard changes my page height

Body:
I'm developing a web app for mobile phones and i got a strange problem.
I have a simple page with a background image and an input field centered in the middle of the page.
The problem is whenever i click the input box and the virtual keyboard comes up, the background image and input field dimensions are recalculated according to the remaining page space.

The desired behavior is that the whole page will be pushed up.

relevant code (i'm developing with react, hence the weird names)

    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, minimum-scale=1, maximum-scale=1">

        <input type="text" class="location_input__LocationInputStyle___2cLQ9" placeholder="Address">

Related Images:

The problem, when keyboard pops up

Desired result

P.S: after playing with the debugger a bit, i found out that if i set the height of my app container/body/html to a fixed pixel height it doesn't happen.
Yet it's not a good solution, because i want the height to be 100% of the viewport (so it will be compatible with all devices).

How do i fix it properly?


问:
W3C HTML validation for React JSX files
When working on front-end projects I always like to work with linting tools. They prevent from dumb mistakes to serious smelly code pieces. Linting tools also suggest improvements and optimisations.

Validating and linting HTML means using the W3C Validator. When working with vanilla JavaScript projects I use the grunt-html Grunt NPM module. And when working with Angular 1.x I use the grunt-html-angular-validate module, which is the same validator but adapted to Angular requirements (non standard attributes or incomplete HTML documents will not fire errors or warnings). However I have tried to find some similar tool for React JSX documents either for Grunt or Gulp but with not luck.

Does it exist W3C HTML validators for React JSX files? In case it does not, any reason for it?

NOTE: I am not interested on checking the JavaScript part of the JSX with tools like JSXHint but just the HTML part and its compliance with W3C specifications.

答:
Does it exist W3C HTML validators for React JSX files?

No.

In case it does not, any reason for it?

Because they aren't HTML.

The closest you could come would be to execute the JavaScript to generate a DOM, then serialize that DOM to HTML (e.g. with .innerHTML), and then add a DOCTYPE declaration and validate the result.

This, of course, only gives you a snapshot of the output for a given state of the application.

Server-side rendering tools (such as Next.js) are probably helpful here.

Title: W3C HTML validation for React JSX files


问:
How to delay Picasso image loading?
I have implemented a shared element activity transition animation between MainActivity (GridView) and DetailActivity. When item is clicked, the image in Grid item will zoom-in to become the background image in DetailActivity. I have made the transition very smooth by saving the image on the MainActivity into a file, then use it as placeholder image in DetailActivity before the higher quality image is downloaded via picasso. When picasso finished its task the higher quality image will replace the placeholder one very neatly.

Code from onCreateView() in DetailActivityFragment.java

```<code>ImageView iv = (ImageView) mRootview.findViewById(R.id.movie_poster);
try {
    // Prepare "InterimPoster" jpeg file to be placeholder image
    Bitmap bitmap = BitmapFactory.decodeStream(c.openFileInput("InterimPoster"));
    Picasso.with(c).load("http://image.tmdb.org/t/p/w780" + mMovieInfo[2])
            .placeholder(new BitmapDrawable(getResources(), bitmap))
            .fit()
            .centerCrop()
            .noFade()
            .into(iv);

} catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

As for animation, I implement it like in the link here step 1-3 https://guides.codepath.com/android/Shared-Element-Activity-Transition

However, sometimes there's flicker when the higher quality image finished download before the transition animation is completed. The zooming-in image will be replaced with new image while moving which is an unpleasant animation.

So I wonder how can I fix this flicker? One thing I can think of is to delay the image download because I already have lower quality image as a placeholder. How can I do that?

Here the video.
Usually, on my test device it's smooth 80% of the time, but luckily in this video it flicker most of the time.

答:
To delay some process, you can use Handler(). </p>

<p>Example. </p>

```<code>new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            // write your codes here.. this  will delay 2 seconds...
           startActivity(new Intent(this,MySecondActivity.class);

        }
    },2000);
</code>```

Title: How to delay Picasso image loading?

Body:
I have implemented a shared element activity transition animation between MainActivity (GridView) and DetailActivity. When item is clicked, the image in Grid item will zoom-in to become the background image in DetailActivity. I have made the transition very smooth by saving the image on the MainActivity into a file, then use it as placeholder image in DetailActivity before the higher quality image is downloaded via picasso. When picasso finished its task the higher quality image will replace the placeholder one very neatly.

Code from onCreateView() in DetailActivityFragment.java

ImageView iv = (ImageView) mRootview.findViewById(R.id.movie_poster);
try {
    // Prepare "InterimPoster" jpeg file to be placeholder image
    Bitmap bitmap = BitmapFactory.decodeStream(c.openFileInput("InterimPoster"));
    Picasso.with(c).load("http://image.tmdb.org/t/p/w780" + mMovieInfo[2])
            .placeholder(new BitmapDrawable(getResources(), bitmap))
            .fit()
            .centerCrop()
            .noFade()
            .into(iv);

} catch (FileNotFoundException e) {
    e.printStackTrace();
}

As for animation, I implement it like in the link here step 1-3 https://guides.codepath.com/android/Shared-Element-Activity-Transition

However, sometimes there's flicker when the higher quality image finished download before the transition animation is completed. The zooming-in image will be replaced with new image while moving which is an unpleasant animation.

So I wonder how can I fix this flicker? One thing I can think of is to delay the image download because I already have lower quality image as a placeholder. How can I do that?

Here the video.
Usually, on my test device it's smooth 80% of the time, but luckily in this video it flicker most of the time.

Body:
To delay some process, you can use Handler().

Example.

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            // write your codes here.. this  will delay 2 seconds...
           startActivity(new Intent(this,MySecondActivity.class);

        }
    },2000);


答:
We can use max.col

```<code>df1$near_column <- names(df1)[-1][ max.col(-abs(df1[-1]- df1[,1]))]
df1$near_column
#[1] "A" "A" "B" "D" "D" "C"
</code>```

Title: how to compare single value with multiple value in a row

Body:
Hi I have a df as below

**name    | min_date     | max_date      | act_val    | A     | B    | C     | D
 sam    2016-06-01   2016-06-27    30724     38115  635   2541    26

fred    2016-06-01   2016-06-27    29270     38115  635   2541    26

hays    2016-06-01   2016-06-27    29270      38115  635   2541   26

prem    2016-06-01   2016-06-27    700       38115  635   2541    26

cains   2016-06-01   2016-06-27    24        38115  635   2541    26

alan    2016-06-01   2016-06-27    28        38115  635   2541    26

vincy   2016-06-01   2016-06-27    3000      38115  635   2541    26

i want compare "act_val" with all other columns in order to get nearest >variable name i.e in row 1 , 30724 is near to value in A (30724 ~= 38115)

| name     | min_date    | max_date    |  act_val    | A     | B    | C    |  D  | near_column

 sam    2016-06-01   2016-06-27    30724     38115  635   2541    26   A

fred    2016-06-01   2016-06-27    29270     38115  635   2541    26   A

hays    2016-06-01   2016-06-27    29270      38115  635   2541   26   A

prem    2016-06-01   2016-06-27    700       38115  635   2541    26   B

cains   2016-06-01   2016-06-27    24        38115  635   2541    26   D

alan    2016-06-01   2016-06-27    28        38115  635   2541    26   D

vincy   2016-06-01   2016-06-27    3000      38115  635   2541    26   C

Thanks in advance

Body:
We can use max.col

df1$near_column <- names(df1)[-1][ max.col(-abs(df1[-1]- df1[,1]))]
df1$near_column
#[1] "A" "A" "B" "D" "D" "C"


问:
Log for a powershell script
I have a powershell script which has the following contents:-

```<code>$Dir = "Drive:\"
$Exe = "Any.exe"
$Args = '/quiet /norestart'
Start-Process "$Directory\$Exe" $Args -NoNewWindow -Wait
</code>```

This does not make any log.

I want to have a log of all the tasks being done by this powershell script, that is why i tried this:-

```<code>$Args = '/quiet /norestart /L*V C:\Log.txt'
</code>```

and i have created this file ( Log.txt ) in my C  drive explicitly.

But, this doesn't work.
If anyone knows how to do it, please help.

Thanx in advance.

答:
I suppose you Any.exe use this file for log, it isn't?

May by try to add quote to your path log like it:

```<code>$Args = '/quiet /norestart /L*V "C:\Log.txt"'
</code>```

Otherwise check if you have permission to write to c:\ (try to write in c:\temp\Log.txt by example)

Title: Log for a powershell script

Body:
I have a powershell script which has the following contents:-

$Dir = "Drive:\"
$Exe = "Any.exe"
$Args = '/quiet /norestart'
Start-Process "$Directory\$Exe" $Args -NoNewWindow -Wait

This does not make any log.

I want to have a log of all the tasks being done by this powershell script, that is why i tried this:-

$Args = '/quiet /norestart /L*V C:\Log.txt'

and i have created this file ( Log.txt ) in my C  drive explicitly.

But, this doesn't work.
If anyone knows how to do it, please help.

Thanx in advance.

Body:
I suppose you Any.exe use this file for log, it isn't?

May by try to add quote to your path log like it:

$Args = '/quiet /norestart /L*V "C:\Log.txt"'

Otherwise check if you have permission to write to c:\ (try to write in c:\temp\Log.txt by example)


问:
Extract a specific XML message from a log file
i have a log file which contains hundreds/thousands of seperate XML messages and need to find a way to extract a complete xml message depending on the parameters given (values of nodes).

My biggest problem is that even though i program a fair amount i have had very little contact with XML or the XML libraries of the languages i use and didnt think that a simple text parsing would be an elegant solution!

I am going to attempt this in C# or VB.net any help would be much appreciated and any attempt at a solution even better!

thanks in advance!

答:
For LINQ to XML, something similar to this:

```<code>Dim xml As XDocument = XDocument.Load("Messages.xml")
Dim messages = From msg In xml.<Messages>.<Message> Select msg

For Each m In messages
  Console.WriteLine(m.Value.ToString)
Next
</code>```

Of course, this will have to modified to fit the structure of your XML.

OwnerDisplayName: Gigglymesh

Body:
For LINQ to XML, something similar to this:

Dim xml As XDocument = XDocument.Load("Messages.xml")
Dim messages = From msg In xml.<Messages>.<Message> Select msg

For Each m In messages
  Console.WriteLine(m.Value.ToString)
Next

Of course, this will have to modified to fit the structure of your XML.

OwnerDisplayName: aphoria


问:
Doing a commit togehter with all the submodules
Is it possible to make a commit which recursively or automatically does commits to the submodules as well?</p>

答: Does git submodule for each git commit; git commit help?


问:
.NET Scheduling many operations: single timer vs one timer for operation
I am developing a Windows Service application, in .NET, which executes many functions (it is a WCF service host), and one of the targets is running scheduled tasks.

I chose to create a System.Threading.Timer for every operation, with a dueTime set to the next execution and no period to avoid reentrancy.

Every time the operation ends, it changes the dueTime to match the next scheduled execution.

Most of the operations are scheduled to run every minute, not all toghether but delayed by some seconds each other.

Now, after adding a number of operations, about 30, it seems that the timers start to be inaccurate, starting the operations many seconds late, or even minutes late.

I am running the operation logic directly in the callback method of the timer, so the running thread should be the same as the timer.

Should I create a Task to run the operation instead of running it in the callback method to improve accuracy?

Or should I use a single timer with a fixed (1 second) dueTime to check which operations need to be started?

I don't like this last option because it would be more difficult to handle reentrancy..

答:
Timers fire on a thread pool thread, so you are probably finding that as you add lots of timers that you are exhausting the thread pool.

You could increase the size of the thread pool, or alternatively ensure you have fewer timers than the thread pool size.

Firing off Tasks from the callback likely won't help - since you are going to be fighting for threads from the same thread pool. Unless you use long-running tasks.


问:
Android dotted underline is staying in middle of textview
I want to show a dotted underline below the textview, following are my codes

```<code><TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />
</code>```

dashed_line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>
</code>```

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

```<code>android:drawableBottom="@drawable/dashed_line"
</code>```

答:
You can use something like this.</p>

```<code>TextView tv = (TextView) findViewById(R.id.mytext);
tv.setText("This is strike-thru");
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
</code>```

Body:
I want to show a dotted underline below the textview, following are my codes

<TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />

dashed_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

android:drawableBottom="@drawable/dashed_line"

Body:
You can use something like this.

TextView tv = (TextView) findViewById(R.id.mytext);
tv.setText("This is strike-thru");
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);


问:
Removing the [''] format from a file
I have to rip my cd library in Flac to archive them and long story short the filename when ripped doesn't include the track number, which is throwing off the playlist order when played on my audio player.

To save the trouble to rename them manually I wrote this morning a little script:

```<code>import os
from mutagen.flac import FLAC

chemin= r'E:\CD\CdName'

for titre in os.listdir(chemin):
    track= FLAC(os.path.join(chemin, titre))
    tracknumber = track.tags["tracknumber"]
    tracktitle= track.tags["title"]
    newtitle= str(tracknumber) + " " + str(tracktitle)
    os.rename(os.path.join(chemin,titre),os.path.join(chemin,str(newtitle)))
</code>```

Sorry it's not the cleanest code, I am still a newbie in python.

It works fine for its purpose except that it has the format ['text'] in the track title which results in something like this ['01']  ['TrackName'] for the filename which is not convenient.

As a consequence I was wondering if there was a possibility to remove this unwanted formating in the track name.

答:
Simply just replace the strings.

```<code>tracktitle = "['01'] ['TrackName']"
tracktitle = tracktitle.replace("[","").replace("]","")
tracktitle = tracktitle.replace("'", "")
</code>```

This will output "01 TrackName"

Edit:

Edited to suit comments

```<code>tracktitle = "['01'] ['TrackName']"
tracktitle = tracktitle.replace("'] ['", " ")
tracktitle = tracktitle[2:]
tracktitle = tracktitle[0:-2]
</code>```

Title: Removing the [''] format from a file

Body:
I have to rip my cd library in Flac to archive them and long story short the filename when ripped doesn't include the track number, which is throwing off the playlist order when played on my audio player.

To save the trouble to rename them manually I wrote this morning a little script:

import os
from mutagen.flac import FLAC

chemin= r'E:\CD\CdName'

for titre in os.listdir(chemin):
    track= FLAC(os.path.join(chemin, titre))
    tracknumber = track.tags["tracknumber"]
    tracktitle= track.tags["title"]
    newtitle= str(tracknumber) + " " + str(tracktitle)
    os.rename(os.path.join(chemin,titre),os.path.join(chemin,str(newtitle)))

Sorry it's not the cleanest code, I am still a newbie in python.

It works fine for its purpose except that it has the format ['text'] in the track title which results in something like this ['01']  ['TrackName'] for the filename which is not convenient.

As a consequence I was wondering if there was a possibility to remove this unwanted formating in the track name.

Body:
Simply just replace the strings.

tracktitle = "['01'] ['TrackName']"
tracktitle = tracktitle.replace("[","").replace("]","")
tracktitle = tracktitle.replace("'", "")

This will output "01 TrackName"

Edit:

Edited to suit comments

tracktitle = "['01'] ['TrackName']"
tracktitle = tracktitle.replace("'] ['", " ")
tracktitle = tracktitle[2:]
tracktitle = tracktitle[0:-2]


问:
Set Minimum date to UIDatePicker
I have a date in UILabel(like 'Dec 14, 2010). This date i want to set as minimum date of my UIDatepicker. How can i do this please reply?

Thanks
Nishant

答:
Convert your UILabel text in to date format using NSDateFormatter and put that value replacing "Date" in following example:

```<code>UIDatepicker *datePicker;

NSDate *Date=[NSDate date];

datePicker.minimumDate=Date;
</code>```

Title: Set Minimum date to UIDatePicker

Body:
Convert your UILabel text in to date format using NSDateFormatter and put that value replacing "Date" in following example:

UIDatepicker *datePicker;

NSDate *Date=[NSDate date];

datePicker.minimumDate=Date;


问:
Fetching a Call Instance with Twilio (Node Helper Library 3.x)
Twilio is deprecating Node Helper Library 2.x on 8/31/2017 and has made some changes with their 3.x version. I used to get the details of a single call with:

```<code>client.calls(sid).get(function(err, call) {
    if(!err) {
        console.log(call);
    }
});
</code>```

With 2.x, the get() method returned valid JSON:

{"sid": "xxxx", "date_created": "xxxx", "date_updated": "xxxx",...

With 3.x, the fetch() method replaces get() (and promises are now used). With fetch(), rather than receive a valid JSON response, I'm now getting a JavaScript CallInstance object:

```<code>CallInstance {
  _version:
   V2010 {
     _domain:
      Api {
        twilio: [Object],
        baseUrl: 'https://api.twilio.com',
        _v2010: [Circular] },
     _version: '2010-04-01',
     _accounts: undefined,
     _account:
      AccountContext {
        _version: [Circular],
        _solution: [Object],
        ...
</code>```

If I piece together the baseUrl plus the uri from the CallInstance (https://api.twilio.com/2010-04-01/Accounts/xxx/Calls/xxx.json), then I can get the old JSON response that I'm looking for.

Question: Is there a way for the Twilio Node Helper Library 3.x to return the old, valid JSON format instead of a CallInstance object?

答:
Twilio developer evangelist here.

The version 3 Twilio Node library doesn't return a plain JavaScript object and as far as I can see, looking through the code, you can't simply access the plain JSON response from the API using the library.

You could create the URLs yourself and make the request to the API to return the raw response, with something like this (using the same request library that Twilio uses under the hood):

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

var accountSid = YOUR_ACCOUNT_SID;
var authToken = YOUR_AUTH_TOKEN;

var callSid = CALL_SID;

var url = 'https://api.twilio.com/2010-04-01/Accounts/'+ accountSid +'/Calls/'+ callSid +'.json';

request.get(url, {
  'auth': {
    'user': accountSid,
    'pass': authToken,
    'sendImmediately': true
  }
}, function (error, response, body) {
  console.log(body);
});
</code>```

As an aside, I'd like to understand what you need the raw JavaScript object for? All the same data is provided in the CallInstance object as well as further methods for loading more or related data about the instance.

Body:
Twilio is deprecating Node Helper Library 2.x on 8/31/2017 and has made some changes with their 3.x version. I used to get the details of a single call with:

client.calls(sid).get(function(err, call) {
    if(!err) {
        console.log(call);
    }
});

With 2.x, the get() method returned valid JSON:

{"sid": "xxxx", "date_created": "xxxx", "date_updated": "xxxx",...

With 3.x, the fetch() method replaces get() (and promises are now used). With fetch(), rather than receive a valid JSON response, I'm now getting a JavaScript CallInstance object:

CallInstance {
  _version:
   V2010 {
     _domain:
      Api {
        twilio: [Object],
        baseUrl: 'https://api.twilio.com',
        _v2010: [Circular] },
     _version: '2010-04-01',
     _accounts: undefined,
     _account:
      AccountContext {
        _version: [Circular],
        _solution: [Object],
        ...

If I piece together the baseUrl plus the uri from the CallInstance (https://api.twilio.com/2010-04-01/Accounts/xxx/Calls/xxx.json), then I can get the old JSON response that I'm looking for.

Question: Is there a way for the Twilio Node Helper Library 3.x to return the old, valid JSON format instead of a CallInstance object?

Body:
Twilio developer evangelist here.

The version 3 Twilio Node library doesn't return a plain JavaScript object and as far as I can see, looking through the code, you can't simply access the plain JSON response from the API using the library.

You could create the URLs yourself and make the request to the API to return the raw response, with something like this (using the same request library that Twilio uses under the hood):

var request = require('request');

var accountSid = YOUR_ACCOUNT_SID;
var authToken = YOUR_AUTH_TOKEN;

var callSid = CALL_SID;

var url = 'https://api.twilio.com/2010-04-01/Accounts/'+ accountSid +'/Calls/'+ callSid +'.json';

request.get(url, {
  'auth': {
    'user': accountSid,
    'pass': authToken,
    'sendImmediately': true
  }
}, function (error, response, body) {
  console.log(body);
});

As an aside, I'd like to understand what you need the raw JavaScript object for? All the same data is provided in the CallInstance object as well as further methods for loading more or related data about the instance.


问:
Display XML format data in html div
I need to display a XML format data fetched from the database to be displayed in a division. But its not displaying with the xml tags on. Is there any way to get xml data as such with the tags in the div?

The xml which i need is given below:

```<code><Name>public</name><Number>848065065639AuthDemoClient:STGKSITM01:20140109052539707</Number><Ret>y</Ret><Tmestamp>2014-01-09T17:22:15.318+05:30GCSD017263</timestamp>
</code>```

But its getting displayed as follows:

public848065065639AuthDemoClient:STGKSITM01:20140109052539707y2014-01-09T17:22:15.318+05:30GCSD017263

Please suggest a solution

答:
Try creating a style like this

```<code><head>
  #xml   { padding-left: 20pt; background-color: #ffffb3; color: #990000; font-size: 14px; font-family: Courier New, Lucida Sans Typewriter, Lucida Typewriter, monospace; font-weight: 600; white-space: pre; }
</head>
</code>```

Then referencing in the

```<code><textarea id=xml rows="20" cols="40" style="border:none;" disabled>
</code>```

It's the 'white-space: pre' that's the important bit...

Title: Display XML format data in html div

Body:
I need to display a XML format data fetched from the database to be displayed in a division. But its not displaying with the xml tags on. Is there any way to get xml data as such with the tags in the div?

The xml which i need is given below:

<Name>public</name><Number>848065065639AuthDemoClient:STGKSITM01:20140109052539707</Number><Ret>y</Ret><Tmestamp>2014-01-09T17:22:15.318+05:30GCSD017263</timestamp>

But its getting displayed as follows:

public848065065639AuthDemoClient:STGKSITM01:20140109052539707y2014-01-09T17:22:15.318+05:30GCSD017263

Please suggest a solution

Body:
Try creating a style like this

<head>
  #xml   { padding-left: 20pt; background-color: #ffffb3; color: #990000; font-size: 14px; font-family: Courier New, Lucida Sans Typewriter, Lucida Typewriter, monospace; font-weight: 600; white-space: pre; }
</head>

Then referencing in the

<textarea id=xml rows="20" cols="40" style="border:none;" disabled>

It's the 'white-space: pre' that's the important bit...