问:
How to make other groups unselectable when you select an option of one group in md-select?
I am trying to implement a drop down list using

```<code><md-select>
</code>```

and

```<code><md-optgroup>.
</code>```

I am following the example "Option Groups" here: https://material.angularjs.org/latest/demo/select

But what I want to implement is a little bit complex. Once the user select an option under a group, then all the options in the other groups will be grey (cannot be selected). Only the options in the same group are still selectable.

For example, if the user select "Bacon" for the toppings first, then only "Pepperoni", "Sausage", "Ground Beef" are still selectable. Other options under VEGGIES are all disabled. Unless the user deselect "Bacon", then all the options under VEGGIES become available again.

Does anyone have a solution for this?
Thank you.

答:
You could disable an item by ng-disabled.
You should accomplish this by disabling all item which doesn't have the same category as the one already selected.

```<code>$scope.toppings = [
    { category: 'meat', name: 'Pepperoni' },
    { category: 'meat', name: 'Sausage' },
    { category: 'meat', name: 'Ground Beef' },
    { category: 'meat', name: 'Bacon' },
    { category: 'veg', name: 'Mushrooms' },
    { category: 'veg', name: 'Onion' },
    { category: 'veg', name: 'Green Pepper' },
    { category: 'veg', name: 'Green Olives' }
];
$scope.selectedToppings = [];
$scope.isDisabled = function(item) {
  return $scope.selectedToppings.length && (item.category !== $scope.selectedToppings[0].category);
};
</code>```

and your html:

```<code><md-option ng-disabled="isDisabled(topping)" ng-value="topping" ng-repeat="topping in toppings | filter: {category: 'meat' }">{{topping.name}}</md-option>
</code>```

Body:
I am trying to implement a drop down list using

<md-select>

and

<md-optgroup>.

I am following the example "Option Groups" here: https://material.angularjs.org/latest/demo/select

But what I want to implement is a little bit complex. Once the user select an option under a group, then all the options in the other groups will be grey (cannot be selected). Only the options in the same group are still selectable.

For example, if the user select "Bacon" for the toppings first, then only "Pepperoni", "Sausage", "Ground Beef" are still selectable. Other options under VEGGIES are all disabled. Unless the user deselect "Bacon", then all the options under VEGGIES become available again.

Does anyone have a solution for this?
Thank you.

Body:
You could disable an item by ng-disabled.
You should accomplish this by disabling all item which doesn't have the same category as the one already selected.

$scope.toppings = [
    { category: 'meat', name: 'Pepperoni' },
    { category: 'meat', name: 'Sausage' },
    { category: 'meat', name: 'Ground Beef' },
    { category: 'meat', name: 'Bacon' },
    { category: 'veg', name: 'Mushrooms' },
    { category: 'veg', name: 'Onion' },
    { category: 'veg', name: 'Green Pepper' },
    { category: 'veg', name: 'Green Olives' }
];
$scope.selectedToppings = [];
$scope.isDisabled = function(item) {
  return $scope.selectedToppings.length && (item.category !== $scope.selectedToppings[0].category);
};

and your html:

<md-option ng-disabled="isDisabled(topping)" ng-value="topping" ng-repeat="topping in toppings | filter: {category: 'meat' }">{{topping.name}}</md-option>


来源: stackexchange

问:
How to process standart html tags in xml file using xslt
I have not practiced XML in over a year.
My question is, using the samples below, why my for-each statement is only printing the first paragraph.

If you are wanting to know why my XML is using standard HTML "p" tags that I am trying to put back into "p" tags in my XSL file: the reason is I am batch processing several long writer documents from a word processor into HTML files. There are thousands (maybe tens of thousands) of paragraph tags. I cannot output XML files in any format I can use or manipulate the way I want.

I can however save the HTML file with an XML extension and work with that. I have already converted a few other files, but not tried to for-each the
 tags yet.

My XML file

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>

<Library>
    <Books>
        <MyBooks>

            <my_favorite_book>
                <title>the title of my favorite book</title>
                <p>paragraph 1</p>
                <p>paragraph 2</p>
                <p>paragraph 3</p>
                <p>paragraph 4</p>
                <p>paragraph 5</p>
                <p>paragraph 6</p>
                <p>paragraph 7</p>
                <p>paragraph 8</p>
                <p>paragraph 9</p>
           </my_favorite_book>

        </MyBooks>
    </Books>
</Library>
</code>```

My XSL file

```<code>    <?xml version="1.0"?>
    <xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

            <xsl:template match="/">

                <html>
                   <body>

                    <p align="center">
                        <span style="font-size: 5em;">
                            <b>
                                <xsl:value-of select="Library/Books/MyBooks/my_favorite_book/title" />
                            </b>
                        </span>
                        <br/>
                     </p>

                    <xsl:for-each select="Library/Books/MyBooks/my_favorite_book">
                        <p>
                            <xsl:value-of select="p" />
                        </p>
                    </xsl:for-each>

            </body>
        </html>

        </xsl:template>
    </xsl:stylesheet>
</code>```

The Web browser output (FireFox 54.0.1 (32-bit))

答:
I discovered the answer in another Stack Overflow post that worked.

That is, to change the above code to the code below:

```<code><xsl:for-each select="Library/Books/MyBooks/my_favorite_book/p">
                    <p>
                        <xsl:value-of select="." />
                    </p>
                </xsl:for-each>
</code>```

Also, while looking at some other projects I did, and reading other posts here, I now recall that using the "template" methods yielded a smoother and more flexible result, so I am going to radically modify my XSL file tomorrow and leave an update here.

ContentLicense: CC BY-SA 3.0

Body:
I have not practiced XML in over a year.
My question is, using the samples below, why my for-each statement is only printing the first paragraph.

If you are wanting to know why my XML is using standard HTML "p" tags that I am trying to put back into "p" tags in my XSL file: the reason is I am batch processing several long writer documents from a word processor into HTML files. There are thousands (maybe tens of thousands) of paragraph tags. I cannot output XML files in any format I can use or manipulate the way I want.

I can however save the HTML file with an XML extension and work with that. I have already converted a few other files, but not tried to for-each the
 tags yet.

My XML file

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>

<Library>
    <Books>
        <MyBooks>

            <my_favorite_book>
                <title>the title of my favorite book</title>

paragraph 1

paragraph 2

paragraph 3

paragraph 4

paragraph 5

paragraph 6

paragraph 7

paragraph 8

paragraph 9

           </my_favorite_book>

        </MyBooks>
    </Books>
</Library>

My XSL file

    <?xml version="1.0"?>
    <xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

            <xsl:template match="/">

                                <xsl:value-of select="Library/Books/MyBooks/my_favorite_book/title" />

                    <xsl:for-each select="Library/Books/MyBooks/my_favorite_book">

                            <xsl:value-of select="p" />

                    </xsl:for-each>

        </xsl:template>
    </xsl:stylesheet>

The Web browser output (FireFox 54.0.1 (32-bit))

Body:
I discovered the answer in another Stack Overflow post that worked.

That is, to change the above code to the code below:

<xsl:for-each select="Library/Books/MyBooks/my_favorite_book/p">
                    <p>
                        <xsl:value-of select="." />
                    </p>
                </xsl:for-each>

Also, while looking at some other projects I did, and reading other posts here, I now recall that using the "template" methods yielded a smoother and more flexible result, so I am going to radically modify my XSL file tomorrow and leave an update here.


问:
Calling a https WCF-Service from Silverlight 4 only works with fiddler and from VS2010
for days now, I try to get the following scenario running:

I have a Silverlight 4 Application that calls a WCF-Service via HTTPS. The WCF-Service is located on one of our servers, the Silverlight 4 app is also served from this server. After several hours of trial and error (well actually more error than try) I get it running when starting it from my VS2010 development environment on my local machine (see also SecurityError when calling a HTTPS-WCF Service from Silverlight 4).

But ...

The call to the https-WCF ONLY works when I start the SL-App from my VS2010 AND when fiddler is running and after I tell fiddler to ignore the Certificate Error (I use a self-signed certificate). When fiddler is not running, I get a security error. That applies, when my browser is the IE. When I copy the localhost address from the IE and paste it in my opera, it works without fiddler.

When I deploy the Silverlight app to the server and call it from the server, the WCF-call doesn't work, whether fiddler is running or not. I just get the standard Message, that an exception has occurred. This happens in both Opera and IE. Fiddler doesn't ask me to ignore the Certificate Error like it does in the VS2010 scenario, so maybe there is somewhere the key to my problem. Unfortunately, I have not much experiences with this stuff, so I have no idea, where to look or what to do.

I already found something about the fiddler issue here on stackoverflow ( Silverlight Requests, Failures & Fiddler), but it doesn't help me solving my problem.

I hope that some of you can shed some light in this issue, before all my hair is turned to gray.

Thanks in advance,

Frank

Edith has just installed the Certificate as a trusted Certificate in IE - but I still get the error, when calling the WCF when starting the deployed silverlight app from the server. At least I can call the Service when I start the SL app from VS2010 in the IE now (even when that doesn't help me, when some one else has to work with the app.

答: Does your SSL certificate has the same name as your service host? If not, that causes an error which can lead to the described behavior</p>

ContentLicense: CC BY-SA 2.5


问:
CastError: Cast to ObjectId failed for value " X" at path "_id" for model "Blog"
Hey guys could really use some help with a DELETE route. I'm working with RESTful routing, trying to follow the conventions and when adding the delete route I get the error:

CastError: Cast to ObjectId failed for value " X" at path "_id" for model "Blog"

I've searched for the issue on stackoverflow and the best I could come up with was the version of mongoose had a bug. I rolled it back to V 4.10.0 and am still getting the issue. My code follows:

```<code>var express    = require("express"),
app        = express(),
bodyParser = require("body-parser"),
mongoose   = require("mongoose"),
methodOverride = require("method-override");

           // APP CONFIG
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));

mongoose.connect("mongodb://localhost/restful_blog_app");

// Create a new Blog Schema defines what the object will be

var Blog = new mongoose.Schema ({
    title: String,
    image: String, //{type: String, default: "placeholder.jpg"} for a default image
    body: String,
    created: {type: Date, default: Date.now}
});

// Mongoose compiles the Schema into a model, useable object
var Blog = mongoose.model("Blog", Blog);

// DELETE ROUTE

app.delete("/blogs/:id", function(req, res){
    Blog.findByIdAndRemove(req.params.id, function(err){
        if(err){
            console.log(err)
        }

    })
})
</code>```

答:
I think the id parameter that you get is not a valid ObjectId string, so it can't be casted to a ObjectId Object.

Here you have have some information about ObjectId, check you are passing a valid one.

Body:
Hey guys could really use some help with a DELETE route. I'm working with RESTful routing, trying to follow the conventions and when adding the delete route I get the error:

CastError: Cast to ObjectId failed for value " X" at path "_id" for model "Blog"

I've searched for the issue on stackoverflow and the best I could come up with was the version of mongoose had a bug. I rolled it back to V 4.10.0 and am still getting the issue. My code follows:

var express    = require("express"),
app        = express(),
bodyParser = require("body-parser"),
mongoose   = require("mongoose"),
methodOverride = require("method-override");

           // APP CONFIG
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));

mongoose.connect("mongodb://localhost/restful_blog_app");

// Create a new Blog Schema defines what the object will be

var Blog = new mongoose.Schema ({
    title: String,
    image: String, //{type: String, default: "placeholder.jpg"} for a default image
    body: String,
    created: {type: Date, default: Date.now}
});

// Mongoose compiles the Schema into a model, useable object
var Blog = mongoose.model("Blog", Blog);

// DELETE ROUTE

app.delete("/blogs/:id", function(req, res){
    Blog.findByIdAndRemove(req.params.id, function(err){
        if(err){
            console.log(err)
        }

    })
})


问:
Python 3: User input random numbers to see if multiples of 5. Then get the sum of all the numbers that were multiples of 5
I spent all day on this code. It failed.

```<code>def output (n):
  n = int(input('Enter a number: ')

while n != 0:
    if n % 5 == 0:
      print(n, 'Yes')
    n = int(input('Enter a number: ')
    if n == 0
      output = range(1, int(input('Enter a number: '))+1)
      print (output)
output (n)
</code>```

Question is:

let user enter integers to determine if multiple of 5.

If it is then keep count that will keep a sum of all numbers that are multiples of 5.

Task done using a loop in a function and the loop will terminate when a value of 0 is entered.

when the loop terminates, return the count of how many numbers that were multiple of 5s.

After complete, NEXT:
pass the variable sum_multiple_five to another function called print_result() and still
print the same message but now the print will be done in its own function.

答:
```<code>def sum_multiple_five(n):
  count = 0
  if n == 0: #initial check if the first input is 0 if it is return count as 0
    return count
  while n != 0: # not leaving this while loop until n is 0
    if n % 5 == 0: #if divisible by 5 increment count by 1 otherwise get new input
      count = count + 1
    n = int(input('Enter a number: ')) # Update n's value from user input. This is important because n is what the while loop is checking.

  return count #when the while loop exit as user input 0 we return count

def print_result(answer):
  # print(answer)
  print( str(answer) + " numbers were multiple of 5s")

def init():
  n = int(input('Enter a number: ')) #get user input and store it in variable n
  print_result(sum_multiple_five(n)) #call sum_multiple_five() function and use n as an input. then give the returned int to print_result function

init() #call the function init()
</code>```

result:

```<code>Enter a number:  10
Enter a number:  10
Enter a number:  100
Enter a number:  50
Enter a number:  5
Enter a number:  9
Enter a number:  7
Enter a number:  10
Enter a number:  4
Enter a number:  15
Enter a number:  5
Enter a number:  8
Enter a number:  2
Enter a number:  0
8 numbers were multiple of 5s
</code>```

Body:
I spent all day on this code. It failed.

def output (n):
  n = int(input('Enter a number: ')

while n != 0:
    if n % 5 == 0:
      print(n, 'Yes')
    n = int(input('Enter a number: ')
    if n == 0
      output = range(1, int(input('Enter a number: '))+1)
      print (output)
output (n)

Question is:

let user enter integers to determine if multiple of 5.

If it is then keep count that will keep a sum of all numbers that are multiples of 5.

Task done using a loop in a function and the loop will terminate when a value of 0 is entered.

when the loop terminates, return the count of how many numbers that were multiple of 5s.

After complete, NEXT:
pass the variable sum_multiple_five to another function called print_result() and still
print the same message but now the print will be done in its own function.

Body:
def sum_multiple_five(n):
  count = 0
  if n == 0: #initial check if the first input is 0 if it is return count as 0
    return count
  while n != 0: # not leaving this while loop until n is 0
    if n % 5 == 0: #if divisible by 5 increment count by 1 otherwise get new input
      count = count + 1
    n = int(input('Enter a number: ')) # Update n's value from user input. This is important because n is what the while loop is checking.

  return count #when the while loop exit as user input 0 we return count

def print_result(answer):
  # print(answer)
  print( str(answer) + " numbers were multiple of 5s")

def init():
  n = int(input('Enter a number: ')) #get user input and store it in variable n
  print_result(sum_multiple_five(n)) #call sum_multiple_five() function and use n as an input. then give the returned int to print_result function

init() #call the function init()

result:

Enter a number:  10
Enter a number:  10
Enter a number:  100
Enter a number:  50
Enter a number:  5
Enter a number:  9
Enter a number:  7
Enter a number:  10
Enter a number:  4
Enter a number:  15
Enter a number:  5
Enter a number:  8
Enter a number:  2
Enter a number:  0
8 numbers were multiple of 5s


问:
Checkboxes to generate letter
I am currently building a User form for some letters we use at work and I would like to design the userform to generate the letter with mostly just checkboxes. e.g.

Your application cannot be completed until the following is received:
A Statutory declaration providing a statement in regards to your: financial situation

In the above example I would need two checkboxes.

Checkbox 1:

A statutory declaration providing a statement in regards to your:

Checkbox2:

financial situation

I guess the question I am asking is in two parts:

1: How do I get checkboxes to generate text?

2: How do I get multiple checkboxes to generate text against the same bookmark/s?

I may not need a Statutory Declaration, I may need a "certified copy of:" ---"bank details, proof of identity, proof of citizenship"

As you can tell from the user form it's pretty extensive and all the checkboxes in the lower half of the form need to generate text.
Grateful for any advice or direction or resources or anything.

答:
In theory, you might store the text to be inserted in your letter in the Check box's caption property and use code to insert the text into your letter when the box is checked. I think this is cumbersome and recommend that you use the caption for a caption, for example, "Statutory declaration". If it is checked such a paragraph is inserted into the letter, else it is left out.

The required declaration may include one or several of many items. Since you are thinking of check boxes, you could have one for each "bank details", "proof of identity", "proof of citizenship". These selections are very short and could be placed in the caption property. But if the texts are longer or of greatly varying lengths I would recommend the use of text boxes instead. So, if Cbx1 is clicked, the text of Tbx1 is inserted etc.

Alternatively, if only one item is required you might consider a dropdown. Or you might use a list box with multiple choices. In principle, I think that using different systems for different levels of decision making helps the user to find his way through your form. For example, use check boxes to select paragraphs (the full text of which might be shown in adjacent text boxes), and then switch to list boxes, option buttons, dropdowns or check boxes which look completely different to specify the contents of the selected paragraph. All of that detail might as well be hidden until the user has checked its box.

Title: Checkboxes to generate letter


问:
A view that is moving
I've no experience in making something move in my app. And I observed this effect in Flickit Pro. The Tap for details view will shake for one or two second and then stop. It looks cute and very user-friendly.

So how can I make effects like this? A gif that is moving? Or some other methods with the help of Cocoa Touch?

Thanks in advance.

Di

答:
A high-level way would be [UIView beginAnimations: context:] (where both parameters can be NULL in this simple case). Then you can just change the properties that want to change of the view that should be animated, add some other "effects" like ease-in/out, etc. pp. When you are done with this, you just call [UIView commitAnimations] and it will animate everything for you.

However, in the case that you need more freedom, look into the CAAnimation class (its inside the QuartzCore framework).

Also: Look into the documentation for both ways (UIView / CAAnimation) and look into session 424 and 425 of the 2010 WWDC.

Title: A view that is moving


问:
Where can I find the full contents of the iOS root (/) directory?
I am an exploit developer/penetration tester for Maroon Penetration Testing based in Oklahoma (private organization) and I am currently looking for vulnerabilities in iOS, but I would either need the source code of iOS or the system files (root or / directory). I am running iOS 10.2.1 and it is nearly impossible to jailbreak the device, downgrading is not an option either. If there is anywhere I can download the source of iOS 10.2.1/ the root directory contents that would be awesome, or if there is any way to retrieve them myself that would be even better.

Regards,
 Noodles.

答:
I have not found any kind of source code for IOS version 10.2.1, and I don't think it's possible, but the closest I've found is

https://opensource.apple.com/release/ios-1021.html

Good luck with your exploitatious endeavors!


问:
How does one Print all WKWebView On AND Offscreen content OSX and iOS
This question is about printing ALL content (including off screen content) of WKWebView. Currently (still,  as of iOS 10.2 or OSX 10.12) there is NO working solution and none of the supposed solutions on Stackoverflow work. Only provide an answer here if you have verified for yourself that you can print OFF SCREEN CONTENT, and if you did then provide the working example code.

I'm trying to print ALL the content of a WKWebView or WebView on OSX 10.10 or above (Currently running on 10.11.2). For example, a wide html table where columns are out of view and off to the right. Earlier versions of OSX would automatically paginate and correctly print all the html.

I've tried using the solutions available here on Stackoverflow and elsewhere. All essentially say the same thing which is to print the documentView like so:

```<code>[[NSPrintOperation printOperationWithView:_webView.mainFrame.frameView.documentView printInfo:pInfo] runOperation];
</code>```

This stopped working for both WKWebView or WebView in 10.10. If you do this:

```<code>    [[NSPrintOperation printOperationWithView:_wkWebView printInfo:pInfo] runOperation];
</code>```

You get pagination but the printout includes scroll bars WebView, and the other WKWebView gives you blank pages.

I can't find any mention whatsoever in Apple documentation about printing for WKWebView on OSX. Nor can I find any answer that is OSX specific and not iOS.

Does anyone have ANY idea how to print these on OSX?

UPDATE: This is a bug in WebView [Radar:23159060] (still open 2/2018) and WKWebView does not even appear to address printing on OSX. After examining the Open Source for this class on the net, I see that all of the classes that have anything to do with printing are in a conditional compilation block that only supports platform: iOS.

UPDATE Part Deux: Amazingly this ridiculous bug exists in ALL implementations of this class including those on iOS! I find it ridiculous that this is still not fixed at this late date despite the documentation's statement to use this (and only this class) in Apps that support iOS 8 or above. It is now IMPOSSIBLE to print all the on screen and off screen content of a WebView on either iOS or OSX. Fail Apple. Time to FIX THIS! We all know what Steve would've said about it....

UPDATE Part THREE :)- Yet still more amazing is that this issue is NOT resolved as of 10.15.2 and coming up on 4+ YEARS!!! this issue has been floating around (Apple waaaaaake up up up up....). It's kind of amazing considering they're getting very pushy about using WKWebView and over in iOS land even rejecting Apps that don't (unless you're trying to support iOS 7).

UPDATE Part FOUR (2020... can you believe it?!?): As of Big Sur, this is still an issue. I solved it by writing a work around see accepted answer below:

```<code>printOperationWithPrintInfo:
</code>```

DOES NOT print all content which is off screen or scrolled out of view in either the Horizontal or vertical direction. It does however use your Print CSS which is a slight advantage over:

```<code>- (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration
                completionHandler:(void (^)(NSImage *snapshotImage, NSError *error))completionHandler;
</code>```

To get it to work I did:

```<code>NSPrintInfo *pInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
pInfo.horizontalPagination = NSPrintingPaginationModeAutomatic;
pInfo.verticalPagination = NSPrintingPaginationModeAutomatic;
pInfo.verticallyCentered = YES;
pInfo.horizontallyCentered = YES;
pInfo.orientation = NSPaperOrientationLandscape;
pInfo.leftMargin = 30;
pInfo.rightMargin = 30;
pInfo.topMargin = 30;
pInfo.bottomMargin = 30;

NSPrintOperation *po = [_webView printOperationWithPrintInfo:pInfo];
po.showsPrintPanel = YES;
po.showsProgressPanel = YES;

// Without the next line you get an exception. Also it seems to
// completely ignore the values in the rect. I tried changing them
// in both x and y direction to include content scrolled off screen.
// It had no effect whatsoever in either direction.
po.view.frame = _webView.bounds;

// [printOperation runOperation] DOES NOT WORK WITH WKWEBVIEW, use
[po runOperationModalForWindow:self.view.window delegate:self didRunSelector:@selector(printOperationDidRun:success:contextInfo:) contextInfo:nil];
</code>```

**Also there is something going on I don't fully understand. It doesn't seem to matter what size your wkWebView is. If I size the App to hide some of the content it still seems to grab as much that IS off screen as will fit on the page specified, but it doesn't seem to know how to paginate content that will not fit on the page size onto other pages. So that appears to be where the issue is. There may be some way around this and if anyone has a clue post it here!!

答:
In iOS, I pass UIView.viewPrintFormatter() to UIActivityViewController to allow users to print everything

```<code>let myShare = [webView.viewPrintFormatter()]
let avc = UIActivityViewController(activityItems: myShare, applicationActivities: nil)

present(avc, animated: true, completion: nil)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This question is about printing ALL content (including off screen content) of WKWebView. Currently (still,  as of iOS 10.2 or OSX 10.12) there is NO working solution and none of the supposed solutions on Stackoverflow work. Only provide an answer here if you have verified for yourself that you can print OFF SCREEN CONTENT, and if you did then provide the working example code.

I'm trying to print ALL the content of a WKWebView or WebView on OSX 10.10 or above (Currently running on 10.11.2). For example, a wide html table where columns are out of view and off to the right. Earlier versions of OSX would automatically paginate and correctly print all the html.

I've tried using the solutions available here on Stackoverflow and elsewhere. All essentially say the same thing which is to print the documentView like so:

[[NSPrintOperation printOperationWithView:_webView.mainFrame.frameView.documentView printInfo:pInfo] runOperation];

This stopped working for both WKWebView or WebView in 10.10. If you do this:

    [[NSPrintOperation printOperationWithView:_wkWebView printInfo:pInfo] runOperation];

You get pagination but the printout includes scroll bars WebView, and the other WKWebView gives you blank pages.

I can't find any mention whatsoever in Apple documentation about printing for WKWebView on OSX. Nor can I find any answer that is OSX specific and not iOS.

Does anyone have ANY idea how to print these on OSX?

UPDATE: This is a bug in WebView [Radar:23159060] (still open 2/2018) and WKWebView does not even appear to address printing on OSX. After examining the Open Source for this class on the net, I see that all of the classes that have anything to do with printing are in a conditional compilation block that only supports platform: iOS.

UPDATE Part Deux: Amazingly this ridiculous bug exists in ALL implementations of this class including those on iOS! I find it ridiculous that this is still not fixed at this late date despite the documentation's statement to use this (and only this class) in Apps that support iOS 8 or above. It is now IMPOSSIBLE to print all the on screen and off screen content of a WebView on either iOS or OSX. Fail Apple. Time to FIX THIS! We all know what Steve would've said about it....

UPDATE Part THREE :)- Yet still more amazing is that this issue is NOT resolved as of 10.15.2 and coming up on 4+ YEARS!!! this issue has been floating around (Apple waaaaaake up up up up....). It's kind of amazing considering they're getting very pushy about using WKWebView and over in iOS land even rejecting Apps that don't (unless you're trying to support iOS 7).

UPDATE Part FOUR (2020... can you believe it?!?): As of Big Sur, this is still an issue. I solved it by writing a work around see accepted answer below:

printOperationWithPrintInfo:

DOES NOT print all content which is off screen or scrolled out of view in either the Horizontal or vertical direction. It does however use your Print CSS which is a slight advantage over:

- (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration
                completionHandler:(void (^)(NSImage *snapshotImage, NSError *error))completionHandler;

To get it to work I did:

NSPrintInfo *pInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
pInfo.horizontalPagination = NSPrintingPaginationModeAutomatic;
pInfo.verticalPagination = NSPrintingPaginationModeAutomatic;
pInfo.verticallyCentered = YES;
pInfo.horizontallyCentered = YES;
pInfo.orientation = NSPaperOrientationLandscape;
pInfo.leftMargin = 30;
pInfo.rightMargin = 30;
pInfo.topMargin = 30;
pInfo.bottomMargin = 30;

NSPrintOperation *po = [_webView printOperationWithPrintInfo:pInfo];
po.showsPrintPanel = YES;
po.showsProgressPanel = YES;

// Without the next line you get an exception. Also it seems to
// completely ignore the values in the rect. I tried changing them
// in both x and y direction to include content scrolled off screen.
// It had no effect whatsoever in either direction.
po.view.frame = _webView.bounds;

// [printOperation runOperation] DOES NOT WORK WITH WKWEBVIEW, use
[po runOperationModalForWindow:self.view.window delegate:self didRunSelector:@selector(printOperationDidRun:success:contextInfo:) contextInfo:nil];

**Also there is something going on I don't fully understand. It doesn't seem to matter what size your wkWebView is. If I size the App to hide some of the content it still seems to grab as much that IS off screen as will fit on the page specified, but it doesn't seem to know how to paginate content that will not fit on the page size onto other pages. So that appears to be where the issue is. There may be some way around this and if anyone has a clue post it here!!

Body:
In iOS, I pass UIView.viewPrintFormatter() to UIActivityViewController to allow users to print everything

let myShare = [webView.viewPrintFormatter()]
let avc = UIActivityViewController(activityItems: myShare, applicationActivities: nil)

present(avc, animated: true, completion: nil)


问:
Asp.Net core modelbinder null value when POST
I have my action in Controller:

```<code>[HttpPost]
public JsonResult SignUp(DTOUser dtoUser)
{
    return Json(new string[] { "value1", "value2" } );
}
</code>```

and I have my formatters configured in Startup.cs

```<code> services.AddMvcCore(options => {
                options.InputFormatters.Insert(0, new JilInputFormatter());
                options.OutputFormatters.Insert(0, new JilOutputFormatter());
            });
</code>```

The problem here is my dtoUser has all variables null until I specify [FromBody]

Why do I have to specify FromBody everytime. This was never required in Asp.Net 4 older version.

How can I get around this issue. It's just an added overhead of adding FromBody to 100s of actions in my project that I will be developing. Any global place where I can add this thing to keep it happy?

Thanks!

答:
It was changed to deal with Cross Site Request Forgery (CSRF) issues. When you don't specify [FromBody] it will not automatically bind to a parameter passed in the body.

Andrew Lock did a great post about this subject: https://andrewlock.net/model-binding-json-posts-in-asp-net-core/

Body:
I have my action in Controller:

[HttpPost]
public JsonResult SignUp(DTOUser dtoUser)
{
    return Json(new string[] { "value1", "value2" } );
}

and I have my formatters configured in Startup.cs

 services.AddMvcCore(options => {
                options.InputFormatters.Insert(0, new JilInputFormatter());
                options.OutputFormatters.Insert(0, new JilOutputFormatter());
            });

The problem here is my dtoUser has all variables null until I specify [FromBody]

Why do I have to specify FromBody everytime. This was never required in Asp.Net 4 older version.

How can I get around this issue. It's just an added overhead of adding FromBody to 100s of actions in my project that I will be developing. Any global place where I can add this thing to keep it happy?

Thanks!


问:
Splitting data in SQL (separating a string of data)
I am looking to split up some data in SQL. We currently use databox's in SQL to store data. e.g. the following bit of information would be stored in a databox called: {Script.Details01}.

{Script.Details01} = Mr J Bloggs and Miss M Bloggs

What we are trying to do is validate our data, however due to other departments who enter it manually we need to pull through the two names and split them into two different databox's. For example {Script.Details02} and {Script.Details03}.

Because of the data we need to validate we have tried setting them into cols.

```<code>"SELECT '{Script.Details01}' as Col1,
'{Script.Details01}' as Col2,
'{Script.Details01}' as Col3"

Col1 Part1 = Item('Col1') Entry(1,'')
</code>```

Is there anyway we can split the data, so that Mr J Bloggs would go into details02 and Miss M Bloggs would go into 03? We can store the data entered and pull it through into questions, messages or ask it to go down a certain route depending on the answer.

Mr J Bloggs   and   Miss M Bloggs
{Script.Details02} {Script.Details03}

p.s. we do not care about "and" and want everything between this.
If I have confused anyone feel free to let me know and I will try and be clearer :)

答:
Here is a possible solution. This isn't the cleanest, most concise possible way of writing this, and you will need to modify this a bit to work with your table names, intended column names / databoxes etc. but it should give you a good starting point. Bear in mind that if your data entry folks aren't 100% consistent about how they input pairs of names, you're going to run into trouble. You may need to use more sophisticated techniques to clean up the remaining information.

```<code> SELECT
 LEFT({Script.Details01}, CHARINDEX(' and ', {Script.Details01})) AS FirstName,
 RIGHT({Script.Details01}, (CHARINDEX(' and ', {Script.Details01}) + 5)) AS SecondName
 FROM MyTable
</code>```

See these articles for more information regarding CharIndex and the Left and Right functions:

https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql

https://social.technet.microsoft.com/wiki/contents/articles/17948.t-sql-right-left-substring-and-charindex-functions.aspx

Body:
I am looking to split up some data in SQL. We currently use databox's in SQL to store data. e.g. the following bit of information would be stored in a databox called: {Script.Details01}.

{Script.Details01} = Mr J Bloggs and Miss M Bloggs

What we are trying to do is validate our data, however due to other departments who enter it manually we need to pull through the two names and split them into two different databox's. For example {Script.Details02} and {Script.Details03}.

Because of the data we need to validate we have tried setting them into cols.

"SELECT '{Script.Details01}' as Col1,
'{Script.Details01}' as Col2,
'{Script.Details01}' as Col3"

Col1 Part1 = Item('Col1') Entry(1,'')

Is there anyway we can split the data, so that Mr J Bloggs would go into details02 and Miss M Bloggs would go into 03? We can store the data entered and pull it through into questions, messages or ask it to go down a certain route depending on the answer.

Mr J Bloggs   and   Miss M Bloggs
{Script.Details02} {Script.Details03}

p.s. we do not care about "and" and want everything between this.
If I have confused anyone feel free to let me know and I will try and be clearer :)

Body:
Here is a possible solution. This isn't the cleanest, most concise possible way of writing this, and you will need to modify this a bit to work with your table names, intended column names / databoxes etc. but it should give you a good starting point. Bear in mind that if your data entry folks aren't 100% consistent about how they input pairs of names, you're going to run into trouble. You may need to use more sophisticated techniques to clean up the remaining information.

 SELECT
 LEFT({Script.Details01}, CHARINDEX(' and ', {Script.Details01})) AS FirstName,
 RIGHT({Script.Details01}, (CHARINDEX(' and ', {Script.Details01}) + 5)) AS SecondName
 FROM MyTable

See these articles for more information regarding CharIndex and the Left and Right functions:

https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql

https://social.technet.microsoft.com/wiki/contents/articles/17948.t-sql-right-left-substring-and-charindex-functions.aspx


问:
How to order a list of paragraphs
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

```<code>newList = (from a in list orderby a.Name ascending select a).ToList();
</code>```

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?

答:
```<code>... orderby int.Parse(a.Name.Split(" ")[1]) ...
</code>```

Title: How to order a list of paragraphs

Body:
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

newList = (from a in list orderby a.Name ascending select a).ToList();

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?


问:
Rewrite query string special characters to url?
I want my PHP file to pass: mysite.com/?id=ABC123abc to mysite.com/ABC123abc

I've tried this code but probably is wrong:

```<code>$request = parse_url($_SERVER['REQUEST_URI']);
$path = $request["path"];
$_GET['id'] = $path; //my server returns error 404 - not found
</code>```

Googled it about and haven't found anything, sorry if is duplicated question.

答:
In your site,you can use the .htaccess file (he is used to make commands to Apache) on the folder of your project, inside him, put the code to Rewrite your URL:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([0-9]+)/?$ index.php?id=$1 [NC,L]
</code>```

The RewriteEngine is a mechanism where each write of the url, the request is rewritten otherwise, which you specify.

On documentation of Apache you can look more of the RewriteEngine.

Body:
I want my PHP file to pass: mysite.com/?id=ABC123abc to mysite.com/ABC123abc

I've tried this code but probably is wrong:

$request = parse_url($_SERVER['REQUEST_URI']);
$path = $request["path"];
$_GET['id'] = $path; //my server returns error 404 - not found

Googled it about and haven't found anything, sorry if is duplicated question.

Body:
In your site,you can use the .htaccess file (he is used to make commands to Apache) on the folder of your project, inside him, put the code to Rewrite your URL:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([0-9]+)/?$ index.php?id=$1 [NC,L]

The RewriteEngine is a mechanism where each write of the url, the request is rewritten otherwise, which you specify.

On documentation of Apache you can look more of the RewriteEngine.


问:
Sorry, that page does not exist code 34
```<code>    $consumerkey = 'HGJHGJHBJHGUYjhvbjhvGUYG';
    $consumersecret = 'HGFHGFhghgHGFHGhgvchGHGVhgvcHG';
    $accesstoken = 'gvHGHGVHGVhgVHGVhgvhgvhv';
    $accesstokensecret = 'hgHGJHGVHJGVjhgvGVhgvHGVhjgvHGVhgVj';

    $twitter = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

    $tweets = $twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Sunshine&count=10');

print_r($tweets);
</code>```

Gives me this error:

```<code>stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [message] => Sorry, that page does not exist [code] => 34 ) ) )
</code>```

How do I resolve this? Since everything I throw at to this script gives me an error.

答:
The library you're using, TwitterOAuth, doesn't take a full URL in its get() method. Instead you need to pass in the path as well as an array of parameters.

Per the documentation, this:

```<code>$twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Sunshine&count=10');
</code>```

Should be:

```<code>$twitter->get('statuses/user_timeline', ['screen_name' => 'Sunshine', 'count' => 10]);
</code>```

Documentation: https://twitteroauth.com/

Title: Sorry, that page does not exist code 34

Body:
    $consumerkey = 'HGJHGJHBJHGUYjhvbjhvGUYG';
    $consumersecret = 'HGFHGFhghgHGFHGhgvchGHGVhgvcHG';
    $accesstoken = 'gvHGHGVHGVhgVHGVhgvhgvhv';
    $accesstokensecret = 'hgHGJHGVHJGVjhgvGVhgvHGVhjgvHGVhgVj';

    $twitter = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

    $tweets = $twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Sunshine&count=10');

print_r($tweets);

Gives me this error:

stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [message] => Sorry, that page does not exist [code] => 34 ) ) )

How do I resolve this? Since everything I throw at to this script gives me an error.

Body:
The library you're using, TwitterOAuth, doesn't take a full URL in its get() method. Instead you need to pass in the path as well as an array of parameters.

Per the documentation, this:

$twitter->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Sunshine&count=10');

Should be:

$twitter->get('statuses/user_timeline', ['screen_name' => 'Sunshine', 'count' => 10]);

Documentation: https://twitteroauth.com/


问:
How to make a generic enum Equatable in Swift?
Having a generic enum Result<T>

enum Result<T> {
    case success(T)
    case error
}
```

<p>How to make it conform to the <code>Equatable</code> protocol in Swift version 3 or higher?</p>

<hr>

<p>I've tried the following:</p>

<pre class="lang-swift prettyprint-override"><code>extension Result: Equatable {
    static func ==<T: Equatable>(lhs: Result<T>, rhs: Result<T>) -> Bool {
        switch (lhs, rhs) {
        case let (.success(lhsVal), .success(rhsVal)):
            return lhsVal == rhsVal
        case (.error, .error):
            return true
        default:
            return false
        }
    }
}
</code>```

However, this produces a compiler error: Type 'Result<T>' does not conform to protocol 'Equatable'

I've also tried the following:

extension Result: Equatable {
    static func ==(lhs: Result, rhs: Result) -> Bool {
        switch (lhs, rhs) {
        case let (.success(lhsVal), .success(rhsVal)):
            return lhsVal == rhsVal
        case (.error, .error):
            return true
        default:
            return false
        }
    }
}
```

However, this produces a compiler error: Binary operator '==' cannot be applied to two 'T' operands

答:
Does it help to constrain the generic type to Equatable?

```<code>enum Result<T : Equatable> {
    case success(T)
    case error
}
</code>```

Body:
Having a generic enum Result<T>

enum Result<T> {
    case success(T)
    case error
}

How to make it conform to the Equatable protocol in Swift version 3 or higher?

I've tried the following:

extension Result: Equatable {
    static func ==<T: Equatable>(lhs: Result<T>, rhs: Result<T>) -> Bool {
        switch (lhs, rhs) {
        case let (.success(lhsVal), .success(rhsVal)):
            return lhsVal == rhsVal
        case (.error, .error):
            return true
        default:
            return false
        }
    }
}

However, this produces a compiler error: Type 'Result<T>' does not conform to protocol 'Equatable'

I've also tried the following:

extension Result: Equatable {
    static func ==(lhs: Result, rhs: Result) -> Bool {
        switch (lhs, rhs) {
        case let (.success(lhsVal), .success(rhsVal)):
            return lhsVal == rhsVal
        case (.error, .error):
            return true
        default:
            return false
        }
    }
}

However, this produces a compiler error: Binary operator '==' cannot be applied to two 'T' operands

Body:
Does it help to constrain the generic type to Equatable?

enum Result<T : Equatable> {
    case success(T)
    case error
}


问:
Javascript return value from asynchronous function

I know it's a very popular and many times answered topics, but I

 couldn't fully understand it's application in my case.

I am learning my way through Javascript, and I am stuck trying to return a value from async function. Essentially, I want my function to take a city name and return its current temperature from APIXU Weather API (https://www.apixu.com).

Then, I wanted to use this function inside my other Google API function. This function takes id of the clicked marker, finds it's city name in the array of places, and displays information in an infowindow, such as title of the place, weather of a city and  Google Streetview. My initial plan was to use getWeather function inside populateInfoWindow to find the weather of a city. Is it possible to achieve it? Because from what I understand using asynchronous function inside synchronous, will make the latest one asynchronous. Another possible route I was going to choose is to get the weather of all places in the array on document load and just take the information from the array in populateInfoWindow function. But I am afraid that this will be repetitive and unnecessary.

To your opinion, what would be the best way to accomplish it and how to avoid similar problems?

Here is the code:

```<code>//Get current forecast from weather API
        function getWeather(city) {
            var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXXXXX&q=" + city;
            $.getJSON(weatherAPIXU, function(data) {
                var forecast = data.current.temp_c;
                var curWeather = forecast + '° C';
                 return curWeather
            });
        }

// Return a city name that matches a marker id
function getCityName(locations, marker) {
    for (var i = 0, iLen = locations.length; i < iLen; i++) {
        if (locations[i].id == marker.id) return locations[i].city;
    }
}

// This function populates the infowindow when the marker is clicked. It'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
    // Check to make sure the infowindow is not already opened on this marker.
    if (infowindow.marker != marker) {
        // Clear the infowindow content to give the streetview time to load.
        infowindow.setContent('');
        infowindow.marker = marker;
        // Make sure the marker property is cleared if the infowindow is closed.
        infowindow.addListener('closeclick', function() {
            infowindow.marker = null;
        });
        var streetViewService = new google.maps.StreetViewService();
        var radius = 50;
        var city = getCityName(locations, marker);
        console.log(city);
        var weatherInCity = getWeather(city);
        console.log(weatherInCity);
        // In case the status is OK, which means the pano was found, compute the
        // position of the streetview image, then calculate the heading, then get a
        // panorama from that and set the options
        var getStreetView = function(data, status) {
            if (status == google.maps.StreetViewStatus.OK) {
                var nearStreetViewLocation = data.location.latLng;
                var heading = google.maps.geometry.spherical.computeHeading(
                    nearStreetViewLocation, marker.position);
                infowindow.setContent('<div>' + marker.title + '' + weatherInCity +
                    '</div><div id="pano"></div>');
                var panoramaOptions = {
                    position: nearStreetViewLocation,
                    pov: {
                        heading: heading,
                        pitch: 30
                    }
                };
                var panorama = new google.maps.StreetViewPanorama(
                    document.getElementById('pano'),
                    panoramaOptions);
            } else {
                infowindow.setContent('<div>' + marker.title +
                    '</div>' +
                    '<div>No Street View Found</div>');
            }
        };
        // Use streetview service to get the closest streetview image within
        // 50 meters of the markers position
        streetViewService.getPanoramaByLocation(marker.position,
            radius, getStreetView);
        // Open the infowindow on the correct marker.
        infowindow.open(map, marker);
    }
}
</code>```

答: Your function probably returns a value, my guess would be that you are trying to use the value before the function returns. </p>

Body:
I know it's a very popular and many times answered topics, but I

 couldn't fully understand it's application in my case.

I am learning my way through Javascript, and I am stuck trying to return a value from async function. Essentially, I want my function to take a city name and return its current temperature from APIXU Weather API (https://www.apixu.com).

Then, I wanted to use this function inside my other Google API function. This function takes id of the clicked marker, finds it's city name in the array of places, and displays information in an infowindow, such as title of the place, weather of a city and  Google Streetview. My initial plan was to use getWeather function inside populateInfoWindow to find the weather of a city. Is it possible to achieve it? Because from what I understand using asynchronous function inside synchronous, will make the latest one asynchronous. Another possible route I was going to choose is to get the weather of all places in the array on document load and just take the information from the array in populateInfoWindow function. But I am afraid that this will be repetitive and unnecessary.

To your opinion, what would be the best way to accomplish it and how to avoid similar problems?

Here is the code:

//Get current forecast from weather API
        function getWeather(city) {
            var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXXXXX&q=" + city;
            $.getJSON(weatherAPIXU, function(data) {
                var forecast = data.current.temp_c;
                var curWeather = forecast + '° C';
                 return curWeather
            });
        }

// Return a city name that matches a marker id
function getCityName(locations, marker) {
    for (var i = 0, iLen = locations.length; i < iLen; i++) {
        if (locations[i].id == marker.id) return locations[i].city;
    }
}

// This function populates the infowindow when the marker is clicked. It'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
    // Check to make sure the infowindow is not already opened on this marker.
    if (infowindow.marker != marker) {
        // Clear the infowindow content to give the streetview time to load.
        infowindow.setContent('');
        infowindow.marker = marker;
        // Make sure the marker property is cleared if the infowindow is closed.
        infowindow.addListener('closeclick', function() {
            infowindow.marker = null;
        });
        var streetViewService = new google.maps.StreetViewService();
        var radius = 50;
        var city = getCityName(locations, marker);
        console.log(city);
        var weatherInCity = getWeather(city);
        console.log(weatherInCity);
        // In case the status is OK, which means the pano was found, compute the
        // position of the streetview image, then calculate the heading, then get a
        // panorama from that and set the options
        var getStreetView = function(data, status) {
            if (status == google.maps.StreetViewStatus.OK) {
                var nearStreetViewLocation = data.location.latLng;
                var heading = google.maps.geometry.spherical.computeHeading(
                    nearStreetViewLocation, marker.position);
                infowindow.setContent('
' + marker.title + '' + weatherInCity +
                    '

');
                var panoramaOptions = {
                    position: nearStreetViewLocation,
                    pov: {
                        heading: heading,
                        pitch: 30
                    }
                };
                var panorama = new google.maps.StreetViewPanorama(
                    document.getElementById('pano'),
                    panoramaOptions);
            } else {
                infowindow.setContent('
' + marker.title +
                    '
' +
                    '
No Street View Found
');
            }
        };
        // Use streetview service to get the closest streetview image within
        // 50 meters of the markers position
        streetViewService.getPanoramaByLocation(marker.position,
            radius, getStreetView);
        // Open the infowindow on the correct marker.
        infowindow.open(map, marker);
    }
}


问:
Azure WebJob using a Cron Expression is not executing
I have read the documentation.

The CRON expression is composed of 6 fields: {second} {minute} {hour}
  {day} {month} {day of the week}.

Cron expressions such as 0/15 * * * * * work. This indicates that the job should run every 15 seconds.

Additionally, a cron expression such as  works.

Now, I want to have my job run at, for example,  22:25... every day.
I tried: 0 25 22 * * * as well as * 25 22 * * *, but neither of them work, both showing n/a under the SCHEDULE.

Even 0 0 11 * * * fails to execute.

The only cron expression I have made work is 0/15 * * * * *.

Why do my cron expressions not work and how can I fix them to run ever day at 22:25?

答:
Why do my cron expressions not work and how can I fix them to run ever day at 22:25?

I just test following format CRON and it works good on my side.

```<code>0 25 22 * * *
</code>```

You could create a scheduled WebJob by creating a file named settings.job under the root folder of your WebJob or by setting the CRON in Azure portal when creating a WebJob.

If your WebJob didn't executed at 22:25. It maybe caused by the timezone on Azure WebJob is UTC±00:00. You could modify your scheduled time to meet your requirement.

Body:
Why do my cron expressions not work and how can I fix them to run ever day at 22:25?

I just test following format CRON and it works good on my side.

0 25 22 * * *

You could create a scheduled WebJob by creating a file named settings.job under the root folder of your WebJob or by setting the CRON in Azure portal when creating a WebJob.

If your WebJob didn't executed at 22:25. It maybe caused by the timezone on Azure WebJob is UTC±00:00. You could modify your scheduled time to meet your requirement.


答:
you can done this things using htaccess

Create SEO Friendly URLs With Htaccess Mod Rewrite

Example : http://parthmy007.in/user/123

Now you want to access 123n as parameter using id
so for this you have to wright htaccess file

Creating .htaccess file

Open NotePad (yes, the windows notepad) > File > Save As > Change the “Save as Type” to “All Files” > enter “.htaccess” as the name and press Save. You’ve created a htacces file.

Create your own rewrite rule

RewriteEngine On

RewriteRule ^user/([0-9]+) user.php?id=$1 [NC, L]

Title: Rewrite query string special characters to url?


问:
Split a String Into Multiple Strings Using a Regex With Different Capture Groups
I am trying to split a string into multiple strings but rather than using a string just one simple regex pattern, I am trying to use a regex pattern that will split a string into different strings if it detects certain characters, but the characters are different. Instead of splitting the string into different strings, it's giving me each and every individual characters in said string.

```<code>String[] splitstr = line.split("([&]{2})?([|]{2})?(!=)?");
</code>```

Using the above line, I have a variable called line which, as an example, I am putting this line from a file:

```<code>:if[input=right || input=Right]:
</code>```

I am just wondering if there is a way to make this split into

```<code>":if[input=right", "input=Right]:"
</code>```

And if I put in a line like this:

```<code>:if[input=right || input=Right && input != null]:
</code>```

So that it splits into

```<code>":if[input=right", "input=Right", "input != null]:"
</code>```

I was using String#split(regex) for the || symbol and it worked just fine, but now that I want it to split wherever that are || or && or != and I want my code to be efficient and clean and easy to read.

答:
The java class below will split your example string into the parts you are interested in.  The code will split the original string at all '||' and '&&' delimeters, globally.  I.e, if you have more than one '||' or '&&' operator in your original string, each part will be split out.

One thing to note is the need to escape (\) the special characters.  In Java you also need to escape the escape, so you need 2 backslashes in order to have a literal in your string.

Here's a great site to test out regEx code ... Regular Expressions 101

```<code>public class splitStrRegex {

    public static void main(String[] args) {

        String myStr = ":if[input=right || input=Right && input != null]:";
        String[] myStrings = myStr.split("\\|\\||&&");
        for(int i = 0; i < myStrings.length; i++) {
            System.out.println(myStrings[i].trim());
        }
    }
}
</code>```

Output:

```<code>:if[input=right
input=Right
input != null]:
</code>```

Body:
I am trying to split a string into multiple strings but rather than using a string just one simple regex pattern, I am trying to use a regex pattern that will split a string into different strings if it detects certain characters, but the characters are different. Instead of splitting the string into different strings, it's giving me each and every individual characters in said string.

String[] splitstr = line.split("([&]{2})?([|]{2})?(!=)?");

Using the above line, I have a variable called line which, as an example, I am putting this line from a file:

:if[input=right || input=Right]:

I am just wondering if there is a way to make this split into

":if[input=right", "input=Right]:"

And if I put in a line like this:

:if[input=right || input=Right && input != null]:

So that it splits into

":if[input=right", "input=Right", "input != null]:"

I was using String#split(regex) for the || symbol and it worked just fine, but now that I want it to split wherever that are || or && or != and I want my code to be efficient and clean and easy to read.

Body:
The java class below will split your example string into the parts you are interested in.  The code will split the original string at all '||' and '&&' delimeters, globally.  I.e, if you have more than one '||' or '&&' operator in your original string, each part will be split out.

One thing to note is the need to escape (\) the special characters.  In Java you also need to escape the escape, so you need 2 backslashes in order to have a literal in your string.

Here's a great site to test out regEx code ... Regular Expressions 101

public class splitStrRegex {

    public static void main(String[] args) {

        String myStr = ":if[input=right || input=Right && input != null]:";
        String[] myStrings = myStr.split("\\|\\||&&");
        for(int i = 0; i < myStrings.length; i++) {
            System.out.println(myStrings[i].trim());
        }
    }
}

Output:

:if[input=right
input=Right
input != null]:


问:
How to use Docker link in Ansible when link var defined
I want playbook that will start an container (in a task) and only link it to another container if the link is provided in a variable. For example:

```<code>- name: Start container
  docker_container:
    image: somerepo/app-server:{{ var_tag }}
    name: odoo-server
    state: started
    log_opt: "tag=app-server-{{ var_tag }}"
    expose:
      - 8080
    links:
      - "{{ var_db_link }}"
        when: var_db_link is defined
</code>```

But of course this does not work.  (I know - without a value is invalid ~ this is just pseudo code)

The whole task is actually quite a bit larger because it includes other directives so I really don't to have 2 versions of the task defined, one for starting with a link and another without.

答:
when use '-',  it means there is certain value , so I have a way to avoid it.

```<code>---
- hosts: localhost
  tasks:
    - name: Start container
      docker_container:
        image: centos
        name: odoo-server
        state: started
        expose:
          - 8080
        links: "{{ var_db_link | default([]) }}"
</code>```

then test it use

```<code>ansible-playbook  ha.yml -e var_db_link="redis-master:centos"
ansible-playbook  ha.yml
</code>```

It runs normally!

Body:
I want playbook that will start an container (in a task) and only link it to another container if the link is provided in a variable. For example:

- name: Start container
  docker_container:
    image: somerepo/app-server:{{ var_tag }}
    name: odoo-server
    state: started
    log_opt: "tag=app-server-{{ var_tag }}"
    expose:
      - 8080
    links:
      - "{{ var_db_link }}"
        when: var_db_link is defined

But of course this does not work.  (I know - without a value is invalid ~ this is just pseudo code)

The whole task is actually quite a bit larger because it includes other directives so I really don't to have 2 versions of the task defined, one for starting with a link and another without.

Body:
when use '-',  it means there is certain value , so I have a way to avoid it.

---
- hosts: localhost
  tasks:
    - name: Start container
      docker_container:
        image: centos
        name: odoo-server
        state: started
        expose:
          - 8080
        links: "{{ var_db_link | default([]) }}"

then test it use

ansible-playbook  ha.yml -e var_db_link="redis-master:centos"
ansible-playbook  ha.yml

It runs normally!


问:
div not scrolling to bottom (css, js)
ok so have some code that I've cobbled together to make some kind of chat room, it's a hack job tbh but learning as I go along. Been through a number of answers here but nothing seems to work.

I want a javascript function to run when the page loads. there is another part of the code that does the same thing when run (it is run when a button is pressed) that does work, so this is confusing me. anyway.

the css:

```<code>#result{max-width:1024px; width:100%; padding:10px; background: #0000A0; overflow:auto;}
</code>```

the function im trying in the  part of index.php:

```<code> function scrollbottom(){
    document.getElementById('result').scrollTop=document.getElementById('result').scrollHeight;
}
</code>```

I have tried calling the function in the body, calling with window on load, and calling before and after the function within the script tag.

this code does run (also with script tag), and does scroll the div to the bottom, I didn't write this code btw:

```<code>function submitchat(){
    if($('#chat').val()=='1' || $('#chatbox').val()==' ') return false;
    $.ajax({
        url:'chat.php',
        data:{chat:$('#chatbox').val(),ajaxsend:true},
        method:'post',
        success:function(data){
            $('#result').html(data); // Get the chat records and add it to result div
            document.getElementById('result').scrollTop=document.getElementById('result').scrollHeight; // Bring the scrollbar to bottom of the chat resultbox in case of long chatbox
        }
    })
    return false;
</code>```

};

and that is run from

```<code><form method="post" onsubmit="return submitchat();">
</code>```

help appreciated and can post more code if needed. With the exception of the CSS file, all the above is in index.php.

答:
onLoad should work. Make sure it's not a dumb mistake like capitalization errors (I accidentally do that all the time!), and other simple problems.

If you find nothing, trying an external way of loading on page load would work. See if this post below will help you:

https://stackoverflow.com/a/4722710/6911064

Title: div not scrolling to bottom (css, js)

Body:
ok so have some code that I've cobbled together to make some kind of chat room, it's a hack job tbh but learning as I go along. Been through a number of answers here but nothing seems to work.

I want a javascript function to run when the page loads. there is another part of the code that does the same thing when run (it is run when a button is pressed) that does work, so this is confusing me. anyway.

the css:

#result{max-width:1024px; width:100%; padding:10px; background: #0000A0; overflow:auto;}

the function im trying in the  part of index.php:

 function scrollbottom(){
    document.getElementById('result').scrollTop=document.getElementById('result').scrollHeight;
}

I have tried calling the function in the body, calling with window on load, and calling before and after the function within the script tag.

this code does run (also with script tag), and does scroll the div to the bottom, I didn't write this code btw:

function submitchat(){
    if($('#chat').val()=='1' || $('#chatbox').val()==' ') return false;
    $.ajax({
        url:'chat.php',
        data:{chat:$('#chatbox').val(),ajaxsend:true},
        method:'post',
        success:function(data){
            $('#result').html(data); // Get the chat records and add it to result div
            document.getElementById('result').scrollTop=document.getElementById('result').scrollHeight; // Bring the scrollbar to bottom of the chat resultbox in case of long chatbox
        }
    })
    return false;

};

and that is run from

<form method="post" onsubmit="return submitchat();">

help appreciated and can post more code if needed. With the exception of the CSS file, all the above is in index.php.


问:
Image at wrong location on canvas
I am trying to make a game that is based on cursor movement(like agar.io) but when the image is rendered on the canvas it is put about 4 times farther away from the origin than I want it to be.

Javascript, CSS, HTML:

function combined() {
    movechar(direction())
    draw()
}
function draw() {
    //context.save()
    context.clearRect(0, 0, canvas.width, canvas.height);
    //cont.restore()
    context.drawImage(img, xChar, yChar)
    //context.drawImage(img,1,1)
}
function direction() {
    var delX = xCor - xChar
    var delY = yCor - yChar
    var delta = Math.sqrt(delX * delX + delY * delY)
    var dirX = delX / delta
    var dirY = delY / delta
    return [dirX, dirY]
}
function movechar(dirArr) {
    xChar += dirArr[0]
    yChar += dirArr[1]
}
var d = new Date()
var sTime = d.getTime()
console.log(sTime)
var canvas = document.getElementById("playerCanvas")
var context = canvas.getContext('2d')
context.im
var img = new Image()
img.src = "char.bmp", img.width = 8, img.height = 8
var xCor = 0
var yCor = 0
var xChar = canvas.clientWidth / 2
var yChar = canvas.clientHeight / 2
$("canvas").on("mousemove", function (e) { xCor = e.clientX; yCor = e.clientY; })
function docload() { setInterval(combined,30) }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 0px;
    overflow: hidden;
}
canvas#playerCanvas {
    width : 100%;
    height : 100%;
    margin : 0%;
    background-image : url("floor2.bmp");
    background-repeat : repeat;
}</code>```

    <title>wizard.io</title>

    <link rel="stylesheet" href="koolLooks.css">
    Ur browser sux

    <canvas id="playerCanvas"></canvas>

```

答:
When canvas resolution does not match the display size.

When you render to the canvas it is usually in canvas pixels. The number of pixels in the canvas is set via the width and height properties and defines the canvas resolution.

When the canvas is displayed and you set the display size via the canvas.style with and height this does not change the canvas resolution, just the size. The result is that you stretch the canvas pixels to cover many CSS pixels. Then when you try to draw at a mouse coord which is in CSS pixels it does not match the pixel on the canvas under the mouse.

To make sure you do get a mismatch it is best to avoid using the canvas.style.width and canvas.style.height properties at all and just set the canvas.width and height properties directly. NOTE these values are always pixels and are not postfixed ie canvas.width = "100%" will not work

The problem is simple to fix.

Below I have made changes to your snippet and marked them with comments

function combined() {
    movechar(direction())
    draw()
}
function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "red";
    //--------------------------------------------------------------------
    // as your images had bad URL I put boxes in there place

    context.strokeRect(xChar, yChar,50,50)
     context.fillRect(xCor-10, yCor-10,20,20)
}
function direction() {
    var delX = xCor - xChar
    var delY = yCor - yChar
    var delta = Math.sqrt(delX * delX + delY * delY)
    var dirX = delX / delta
    var dirY = delY / delta
    return [dirX, dirY]
}
function movechar(dirArr) {
    xChar += dirArr[0]
    yChar += dirArr[1]
}
var d = new Date()
var sTime = d.getTime()

var canvas = document.getElementById("playerCanvas")
var context = canvas.getContext('2d')

//====================================================================
// IMPORTANT BIT
//--------------------------------------------------------------------
// set the canvas size to the window size

canvas.width = innerWidth;
canvas.height = innerHeight;
//--------------------------------------------------------------------

context.im
var xCor = 0
var yCor = 0

//--------------------------------------------------------------------
// use the canvas height and width rather than clientWidth height

var xChar = canvas.width / 2
var yChar = canvas.height / 2
//--------------------------------------------------------------------

// change listener just to make it work no JQuery
canvas.addEventListener("mousemove", function (e) { xCor = e.clientX; yCor = e.clientY; })
function docload() { setInterval(combined,30) }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 0px;
    overflow: hidden;
}
canvas#playerCanvas {

    /* not needed as they are stretching the canvas
    width : 100%;
    height : 100%;

    */

    margin : 0%;
    background-image : url("floor2.bmp");
    background-repeat : repeat;
}</code>```

    <title>wizard.io</title>

    <link rel="stylesheet" href="koolLooks.css">
    Ur browser sux

    <canvas id="playerCanvas"></canvas>

```

Title: Image at wrong location on canvas

Body:
I am trying to make a game that is based on cursor movement(like agar.io) but when the image is rendered on the canvas it is put about 4 times farther away from the origin than I want it to be.

Javascript, CSS, HTML:

function combined() {
    movechar(direction())
    draw()
}
function draw() {
    //context.save()
    context.clearRect(0, 0, canvas.width, canvas.height);
    //cont.restore()
    context.drawImage(img, xChar, yChar)
    //context.drawImage(img,1,1)
}
function direction() {
    var delX = xCor - xChar
    var delY = yCor - yChar
    var delta = Math.sqrt(delX * delX + delY * delY)
    var dirX = delX / delta
    var dirY = delY / delta
    return [dirX, dirY]
}
function movechar(dirArr) {
    xChar += dirArr[0]
    yChar += dirArr[1]
}
var d = new Date()
var sTime = d.getTime()
console.log(sTime)
var canvas = document.getElementById("playerCanvas")
var context = canvas.getContext('2d')
context.im
var img = new Image()
img.src = "char.bmp", img.width = 8, img.height = 8
var xCor = 0
var yCor = 0
var xChar = canvas.clientWidth / 2
var yChar = canvas.clientHeight / 2
$("canvas").on("mousemove", function (e) { xCor = e.clientX; yCor = e.clientY; })
function docload() { setInterval(combined,30) }

body {
    margin: 0px;
    overflow: hidden;
}
canvas#playerCanvas {
    width : 100%;
    height : 100%;
    margin : 0%;
    background-image : url("floor2.bmp");
    background-repeat : repeat;
}

    <title>wizard.io</title>

    <link rel="stylesheet" href="koolLooks.css">
    Ur browser sux

    <canvas id="playerCanvas"></canvas>

Body:
When canvas resolution does not match the display size.

When you render to the canvas it is usually in canvas pixels. The number of pixels in the canvas is set via the width and height properties and defines the canvas resolution.

When the canvas is displayed and you set the display size via the canvas.style with and height this does not change the canvas resolution, just the size. The result is that you stretch the canvas pixels to cover many CSS pixels. Then when you try to draw at a mouse coord which is in CSS pixels it does not match the pixel on the canvas under the mouse.

To make sure you do get a mismatch it is best to avoid using the canvas.style.width and canvas.style.height properties at all and just set the canvas.width and height properties directly. NOTE these values are always pixels and are not postfixed ie canvas.width = "100%" will not work

The problem is simple to fix.

Below I have made changes to your snippet and marked them with comments

function combined() {
    movechar(direction())
    draw()
}
function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "red";
    //--------------------------------------------------------------------
    // as your images had bad URL I put boxes in there place

    context.strokeRect(xChar, yChar,50,50)
     context.fillRect(xCor-10, yCor-10,20,20)
}
function direction() {
    var delX = xCor - xChar
    var delY = yCor - yChar
    var delta = Math.sqrt(delX * delX + delY * delY)
    var dirX = delX / delta
    var dirY = delY / delta
    return [dirX, dirY]
}
function movechar(dirArr) {
    xChar += dirArr[0]
    yChar += dirArr[1]
}
var d = new Date()
var sTime = d.getTime()

var canvas = document.getElementById("playerCanvas")
var context = canvas.getContext('2d')

//====================================================================
// IMPORTANT BIT
//--------------------------------------------------------------------
// set the canvas size to the window size

canvas.width = innerWidth;
canvas.height = innerHeight;
//--------------------------------------------------------------------

context.im
var xCor = 0
var yCor = 0

//--------------------------------------------------------------------
// use the canvas height and width rather than clientWidth height

var xChar = canvas.width / 2
var yChar = canvas.height / 2
//--------------------------------------------------------------------

// change listener just to make it work no JQuery
canvas.addEventListener("mousemove", function (e) { xCor = e.clientX; yCor = e.clientY; })
function docload() { setInterval(combined,30) }

body {
    margin: 0px;
    overflow: hidden;
}
canvas#playerCanvas {

    /* not needed as they are stretching the canvas
    width : 100%;
    height : 100%;

    */

    margin : 0%;
    background-image : url("floor2.bmp");
    background-repeat : repeat;
}

<html>
<head>
    <title>wizard.io</title>
    <script src="jquery.js"></script>
    <link rel="stylesheet" href="koolLooks.css">
    <noscript>Ur browser sux</noscript>
</head>
<body onload="docload()">
    <canvas id="playerCanvas"></canvas>
    <script src="ok2hax.js"></script>
    <script src="eligal2hax.js"></script>
</body>
</html>


问:
From multiple filter to single filter
Hi I am new to Rails and currently working on a project my teacher gave me.
I have this code which filters my card via checkboxes. The only problem is, that you can select multiple categories meaning that you can filter through multiple things.

But I only want this code to be able to filter one category each time.
It should only show me the cards for this category and if i select another category it should show me the corresponding cards.

Those are my filters:

    <form id="filters">
      <% @categories.each do |categ| %>

          <input type="checkbox" name='<%= categ %>' id='<%= categ %>'>
          <label class="index-category" for='<%= categ %>'>
            <% if categ == "Social Media" %>

            <% elsif categ == "Content" %>

            <% elsif categ == "Research" %>

            <% else %>

            <% end %>
          <%= categ %>

      <% end %>
    </form>

  ```
</div>
</div>
</p>

<p>My cards are divs with the class .selectable-cards</p>

```
My Cards

```

<p>And this is my Javascript for the filter</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
  $('#filters input:checkbox').change(function () {
    var selectedCategoryNames = $('#filters input:checkbox:checked').map(function () {
      return $(this).attr('name')
    }).toArray();

    cards = $('.selectable-card');
    cards.hide()
    cards.each(function() {
      if (selectedCategoryNames.includes($(this).attr('data-category'))) $(this).delay(100).fadeIn(300);
    });

    if (selectedCategoryNames.length === 0) cards.show();
  });
});</code>```

答:
You could use

<input type="radio" name='category' data-category='<%=categ%> id='<%= categ %>' onclick="$('.selectable-card').hide(); $('.selectable-card[data-category=<%=categ%>]').show();">

with the same name attribute instead of

<input type="checkbox" name='<%= categ %>' id='<%= categ %>'>

Instead of the onclick attribute, you can still use your jquery script with minor changes.

Title: From multiple filter to single filter

Body:
Hi I am new to Rails and currently working on a project my teacher gave me.
I have this code which filters my card via checkboxes. The only problem is, that you can select multiple categories meaning that you can filter through multiple things.

But I only want this code to be able to filter one category each time.
It should only show me the cards for this category and if i select another category it should show me the corresponding cards.

Those are my filters:

    <form id="filters">
      <% @categories.each do |categ| %>

          <input type="checkbox" name='<%= categ %>' id='<%= categ %>'>
          <label class="index-category" for='<%= categ %>'>
            <% if categ == "Social Media" %>

            <% elsif categ == "Content" %>

            <% elsif categ == "Research" %>

            <% else %>

            <% end %>
          <%= categ %>

      <% end %>
    </form>

My cards are divs with the class .selectable-cards

My Cards

And this is my Javascript for the filter

$(document).ready(function() {
  $('#filters input:checkbox').change(function () {
    var selectedCategoryNames = $('#filters input:checkbox:checked').map(function () {
      return $(this).attr('name')
    }).toArray();

    cards = $('.selectable-card');
    cards.hide()
    cards.each(function() {
      if (selectedCategoryNames.includes($(this).attr('data-category'))) $(this).delay(100).fadeIn(300);
    });

    if (selectedCategoryNames.length === 0) cards.show();
  });
});


问:
PHP set value of text box equal to form variable
I am simply trying to enter a word or number into the first text box and upon clicking submit have that word stored in a variable and then echoed into the second text box. This is the code I have but it is not working.</p>

```<code><html>
<head>
    <?php
        $one = "";
        if (isset($_POST["Submit"])){
            $one = $_POST["inputOne"];
        }
    ?>
</head>

<body>
    <form method="post" action="index.php">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>
</body>
</html>
</code>```

答:
Try:

```<code>if(isset($_POST["inputOne"])){ $one = $_POST["inputOne"];
}else{$one = 'No value was sent for inputOne';}
</code>```

...with this your php will let you know if a value for inputOne was never received in the first place.

Honestly.. for what you are trying to achieve, your code should look more like this:

```<code><html>
<head>
    <?php
        $one = "";
        if (isset($_POST["inputOne"])){
            $one = $_POST["inputOne"];
        }else{$one = 'No value received for one';}
    ?>
</head>
<body>
    <form method="post" action="">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>
</body>
</html>
</code>```

Body:
I am simply trying to enter a word or number into the first text box and upon clicking submit have that word stored in a variable and then echoed into the second text box. This is the code I have but it is not working.

    <?php
        $one = "";
        if (isset($_POST["Submit"])){
            $one = $_POST["inputOne"];
        }
    ?>

    <form method="post" action="index.php">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>

Body:
Try:

if(isset($_POST["inputOne"])){ $one = $_POST["inputOne"];
}else{$one = 'No value was sent for inputOne';}

...with this your php will let you know if a value for inputOne was never received in the first place.

Honestly.. for what you are trying to achieve, your code should look more like this:

<html>
<head>
    <?php
        $one = "";
        if (isset($_POST["inputOne"])){
            $one = $_POST["inputOne"];
        }else{$one = 'No value received for one';}
    ?>
</head>
<body>
    <form method="post" action="">
        <input type="text" name="inputOne">
        <input type="submit" name="Submit">
        <input type="text" name="output" value="<?php echo $one; ?>">
    </form>
</body>
</html>


问:
Interactive transition: navigation bar appearance issue
Lets's say, I have 3 view controllers: A, B, C, all embedded into a navigation controller. A and B have a navigation bar, C doesn't.

I have a custom interactive transition between B and C. Since I need my navigation bar to disappear on C, I implemented this function of UINavigationControllerDelegate:

```<code>func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    if viewController is C {
        navigationController.setNavigationBarHidden(true, animated: animated)
    }
    else {
        navigationController.setNavigationBarHidden(false, animated: animated)
    }
}
</code>```

Everything works perfectly in an common scenario, when I only make push-pop transitions.

But when I cancel transition B->C by calling cancel() on my UIPercentDrivenInteractiveTransition, the navigation bar doesn't show up on B. Here I have to call setNavigationBarHidden(false, ...), but I haven't managed to find the correct place to do it.

If I call it in B's viewWillAppear, navigation bar appears, but looks really strange - it contains elements which the C would have if it had navigation bar. If I pop back to the A, it will blink for a moment with expected contents, but immediately after transition the A navigation bar gets replaced by the B navigation bar!

So, it seems like the navigation bars stack is somehow broken after B->C transition cancellation, it appears to be shifted relatively to viewcontrollers like that:

```<code>                      has
-----------------------------------------------
|    ViewController    |   Navigation bar of  |
-----------------------------------------------
|           A          |           B          |
-----------------------------------------------
|           B          |           C          |
-----------------------------------------------
</code>```

So, my question is what's the correct place to call navigationController.setNavigationBarHidden(false, animated: true) in this case?

答:
Well, I've managed to find an ugly hack to fix it by myself. Maybe someone in this world would find it helpful.

In my custom UIPercentDrivenInteractiveTransition I override cancel function like that:

```<code>class CustomTransitionManager: UIPercentDrivenInteractiveTransition {

    /// Indicates transition direction. Must be set before each transition.
    var forward: Bool = true

    /// Current navigation controller used for transition. Must be set before transition starts
    var nc: UINavigationController?

    /**
     * Hack #1 with UINavigationController here
     */
    override func cancel() {
        super.cancel()

        if forward {
            self.nc?.setNavigationBarHidden(false, animated: false)
        }
        self.nc?.setNavigationBarHidden(forward, animated: false)
    }
}
</code>```

In each of the view controllers (A, B, C) I make the following hack:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Hide and immediately show navigation bar: this will restore it's correct state
    self.navigationController?.setNavigationBarHidden(true, animated: false)
    self.navigationController?.setNavigationBarHidden(false, animated: true)
}
</code>```

The best solution probably would be a modal fullscreen presentation of C, but in my case I am working with a project already having corrupted navigation hierarchy and I had no time to fix it properly. Basically, that's the reason why I faced this issue.

Body:
Lets's say, I have 3 view controllers: A, B, C, all embedded into a navigation controller. A and B have a navigation bar, C doesn't.

I have a custom interactive transition between B and C. Since I need my navigation bar to disappear on C, I implemented this function of UINavigationControllerDelegate:

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    if viewController is C {
        navigationController.setNavigationBarHidden(true, animated: animated)
    }
    else {
        navigationController.setNavigationBarHidden(false, animated: animated)
    }
}

Everything works perfectly in an common scenario, when I only make push-pop transitions.

But when I cancel transition B->C by calling cancel() on my UIPercentDrivenInteractiveTransition, the navigation bar doesn't show up on B. Here I have to call setNavigationBarHidden(false, ...), but I haven't managed to find the correct place to do it.

If I call it in B's viewWillAppear, navigation bar appears, but looks really strange - it contains elements which the C would have if it had navigation bar. If I pop back to the A, it will blink for a moment with expected contents, but immediately after transition the A navigation bar gets replaced by the B navigation bar!

So, it seems like the navigation bars stack is somehow broken after B->C transition cancellation, it appears to be shifted relatively to viewcontrollers like that:

                      has
-----------------------------------------------
|    ViewController    |   Navigation bar of  |
-----------------------------------------------
|           A          |           B          |
-----------------------------------------------
|           B          |           C          |
-----------------------------------------------

So, my question is what's the correct place to call navigationController.setNavigationBarHidden(false, animated: true) in this case?

Body:
Well, I've managed to find an ugly hack to fix it by myself. Maybe someone in this world would find it helpful.

In my custom UIPercentDrivenInteractiveTransition I override cancel function like that:

class CustomTransitionManager: UIPercentDrivenInteractiveTransition {

    /// Indicates transition direction. Must be set before each transition.
    var forward: Bool = true

    /// Current navigation controller used for transition. Must be set before transition starts
    var nc: UINavigationController?

    /**
     * Hack #1 with UINavigationController here
     */
    override func cancel() {
        super.cancel()

        if forward {
            self.nc?.setNavigationBarHidden(false, animated: false)
        }
        self.nc?.setNavigationBarHidden(forward, animated: false)
    }
}

In each of the view controllers (A, B, C) I make the following hack:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Hide and immediately show navigation bar: this will restore it's correct state
    self.navigationController?.setNavigationBarHidden(true, animated: false)
    self.navigationController?.setNavigationBarHidden(false, animated: true)
}

The best solution probably would be a modal fullscreen presentation of C, but in my case I am working with a project already having corrupted navigation hierarchy and I had no time to fix it properly. Basically, that's the reason why I faced this issue.


问:
Cannot implicitly convert type 'string' to 'System.DateTime'
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

```<code>DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);
</code>```

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.

答: Try DateTime.Parse(...) or DateTime.ParseExact(...) if you need to specify the format.

Body:
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.


问:
How to groupby by a column and return the values of other columns as lists in pandas?
I am facing trouble clubbing the values of a column together and retaining the respective values of other columns. I would like to do something similar to this: grouping rows in list in pandas groupby

But instead, I want the list/dictionary (preferably latter) to contain values of multiple columns.
Example for this dataframe:

df:

```<code>Col1   Col2   Col3
A      xyz     1
A      pqr     2
B      xyz     2
B      pqr     3
B      lmn     1
C      pqr     2
</code>```

I want something like-

```<code>A {'xyz':1, 'pqr': 2}
B {'xyz':2, 'pqr': 3, 'lmn': 1}
C {'pqr':2}
</code>```

I tried doing

```<code>df.groupby('Col1')[['Col2', 'Col3']].apply(list)
</code>```

which is a variant of the solution mentioned in the linked post, but isn't giving me the result I need.

From that point on, I would also like to transform it into a dataframe of the form:

```<code>  xyz  pqr  lmn
A  1    2    NaN
B  2    3    1
C  NaN  2    NaN
</code>```

答:
What you want in the end is a pivot table.

df.pivot_table(index='Col1',columns='Col2',values='Col3')

look up the documentation for more options.

Body:
I am facing trouble clubbing the values of a column together and retaining the respective values of other columns. I would like to do something similar to this: grouping rows in list in pandas groupby

But instead, I want the list/dictionary (preferably latter) to contain values of multiple columns.
Example for this dataframe:

df:

Col1   Col2   Col3
A      xyz     1
A      pqr     2
B      xyz     2
B      pqr     3
B      lmn     1
C      pqr     2

I want something like-

A {'xyz':1, 'pqr': 2}
B {'xyz':2, 'pqr': 3, 'lmn': 1}
C {'pqr':2}

I tried doing

df.groupby('Col1')[['Col2', 'Col3']].apply(list)

which is a variant of the solution mentioned in the linked post, but isn't giving me the result I need.

From that point on, I would also like to transform it into a dataframe of the form:

  xyz  pqr  lmn
A  1    2    NaN
B  2    3    1
C  NaN  2    NaN


问:
error copy file that was created in C#
I have this problem when I try to copy a file that was created in C#:

"System.IO.IOException: 'The process can not access the file' d:\las.txt 'because it is being used in another process.'"

my code:

```
using System;

namespace modulo1
{
    class Program
    {
        static void Main(string[] args)
        {
           string folderName = @"c:\lasss";

           System.IO.Directory.CreateDirectory(folderName);

           string archivo = @"d:\las.txt";

           System.IO.File.Create(archivo);

            string dest = @"d:\soft";

           //here is the problem
            System.IO.File.Copy(archivo, dest, true);
        }
    }
}
```

How can i solve this problem???

答:
Thank you for your answers
This worked for me:</p>

```
...
 var fileStream = System.IO.File.Create(archivo);
 fileStream.Close();
...
```

Title: error copy file that was created in C#

Body:
I have this problem when I try to copy a file that was created in C#:

"System.IO.IOException: 'The process can not access the file' d:\las.txt 'because it is being used in another process.'"

my code:

using System;

namespace modulo1
{
    class Program
    {
        static void Main(string[] args)
        {
           string folderName = @"c:\lasss";

           System.IO.Directory.CreateDirectory(folderName);

           string archivo = @"d:\las.txt";

           System.IO.File.Create(archivo);

            string dest = @"d:\soft";

           //here is the problem
            System.IO.File.Copy(archivo, dest, true);
        }
    }
}

How can i solve this problem???

Body:
Thank you for your answers
This worked for me:

...
 var fileStream = System.IO.File.Create(archivo);
 fileStream.Close();
...


问:
preventing hardcoded url to delete in django
I have a link and button inside it that deletes a record associated with the button

```<code><a href="{% url 'parts:stock_delete' stock.id  %}">
  <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button>
</a>
</code>```

but I want the record to be deleted only when the button is pressed but not when URL is typed in the address bar like:

http://127.0.0.1:8000/parts/stock_delete/16/

what can be done for this?

答:
You should really use DeleteView!

It's a generic class-based view that - when viewed (GET) will display a confirmation page asking if you really want to delete the record. When you confirm (POST) the record will be deleted.

@sasuke's answer doesn't take into consideration another large security hole, CSRF. You'll want to study this page very closely if you want to ensure that your application is secure.

Body:
I have a link and button inside it that deletes a record associated with the button

  <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button>

but I want the record to be deleted only when the button is pressed but not when URL is typed in the address bar like:

http://127.0.0.1:8000/parts/stock_delete/16/

what can be done for this?


问:
If you dont include an image does it use bandwidth
If I was making a static website and it had a folder called images which stored all the images. Assume I only included 2/10 of the images in that folder on the website in my html. If someone views the website are all the images downloaded or just them 2?

If it is only the 2 images use bandwidth, what happens if I use jquery to change the src of one of the images, is another image downloaded from the server?

答: Only the images that are called will take up bandwidth. If you had 1000 images in your folder and only displayed 2, then it would only consume the bandwidth of 2 images plus the HTML, etc.</p>