问:
Recursive Methods with completion blocks
I call my method:

```<code>[self getBoundariesForFields:fields index:0 withCompletionBlock:^{
    DLog(@"completionBlock fields: %@", fields);
}];
</code>```

the method:

```<code>-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

if (index < fields.count) {
    NSMutableDictionary *field = [fields objectAtIndex:index];

    [self getBoundariesForField:field withCompletionBlock:^{
        [self getBoundariesForFields:fields index:index + 1 withCompletionBlock:^{
        }];
    }];
}
else {
    DLog(@"else statement fields: %@", fields);
    completionBlock();
}
</code>```

}

I get the "else statement fields:" log, but the "completionBlock Fields:" never runs.

I'm guessing it has to do with a retain issue; that the original method that calls this recursive loop is de-referenced so when the completionBlock is called, the code is gone.

How can I prevent this?

答:
The block is running, but the recursive calls to the method are passing ^{}, an empty block.  Fix by passing the original block parameter...

```<code>-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

    if (index < fields.count) {
        NSMutableDictionary *field = [fields objectAtIndex:index];

        [self getBoundariesForField:field withCompletionBlock:^{
            // NOTICE change here...
            [self getBoundariesForFields:fields index:index + 1 withCompletionBlock:completionBlock];
        }];
    }  else {
        DLog(@"else statement fields: %@", fields);
        completionBlock();
    }
}
</code>```

Body:
I call my method:

[self getBoundariesForFields:fields index:0 withCompletionBlock:^{
    DLog(@"completionBlock fields: %@", fields);
}];

the method:

-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

if (index < fields.count) {
    NSMutableDictionary *field = [fields objectAtIndex:index];

    [self getBoundariesForField:field withCompletionBlock:^{
        [self getBoundariesForFields:fields index:index + 1 withCompletionBlock:^{
        }];
    }];
}
else {
    DLog(@"else statement fields: %@", fields);
    completionBlock();
}

}

I get the "else statement fields:" log, but the "completionBlock Fields:" never runs.

I'm guessing it has to do with a retain issue; that the original method that calls this recursive loop is de-referenced so when the completionBlock is called, the code is gone.

How can I prevent this?

Body:
The block is running, but the recursive calls to the method are passing ^{}, an empty block.  Fix by passing the original block parameter...

-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

    if (index < fields.count) {
        NSMutableDictionary *field = [fields objectAtIndex:index];

        [self getBoundariesForField:field withCompletionBlock:^{
            // NOTICE change here...
            [self getBoundariesForFields:fields index:index + 1 withCompletionBlock:completionBlock];
        }];
    }  else {
        DLog(@"else statement fields: %@", fields);
        completionBlock();
    }
}


来源: stackexchange

问:
How can i detect if user is signed in anonumously with firebase auth?
I am using firebase auth for my login system and detect if user is signed in anonumously, how could i do it?
I know that with facebook is

```<code>for (UserInfo user: FirebaseAuth.getInstance().getCurrentUser().getProviderData()) { if (user.getProviderId().equals("facebook.com")) { System.out.println("User is signed in with Facebook"); } }
</code>```

But since there is no url to check I don't know if this is possible.
I would appreciate any help

答:
Use the isAnonymous() method on FirebaseUser.</p>

```<code>FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isAnonymous()) {
    // ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using firebase auth for my login system and detect if user is signed in anonumously, how could i do it?
I know that with facebook is

for (UserInfo user: FirebaseAuth.getInstance().getCurrentUser().getProviderData()) { if (user.getProviderId().equals("facebook.com")) { System.out.println("User is signed in with Facebook"); } }

But since there is no url to check I don't know if this is possible.
I would appreciate any help

Body:
Use the isAnonymous() method on FirebaseUser.

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isAnonymous()) {
    // ...
}


问:
Regex pattern for underscore or hyphen but not both
I have a regular expression that is allowing a string to be standalone, separated by hyphen and underscore.

I need help so the string only takes hyphen or underscore, but not both.

This is what I have so far.

```<code>^([a-z][a-z0-9]*)([-_]{1}[a-z0-9]+)*$

foo             = passed
foo-bar         = passed
foo_bar         = passed
foo-bar-baz     = passed
foo_bar_baz     = passed
foo-bar_baz_qux = passed # but I don't want it to
foo_bar-baz-quz = passed # but I don't want it to
</code>```

答:
Here's a nice clean solution:

```<code>^([a-zA-Z-]+|[a-zA-Z_]+)$
</code>```

Break it down!

^ start at the beginning of the text

[a-zA-Z-]+ match anything a-z or A-Z or -

| OR operator

[a-zA-Z_]+ match anything a-z or A-Z or _

$ end at the end of the text

Here's an example on regexr!

Body:
I have a regular expression that is allowing a string to be standalone, separated by hyphen and underscore.

I need help so the string only takes hyphen or underscore, but not both.

This is what I have so far.

^([a-z][a-z0-9]*)([-_]{1}[a-z0-9]+)*$

foo             = passed
foo-bar         = passed
foo_bar         = passed
foo-bar-baz     = passed
foo_bar_baz     = passed
foo-bar_baz_qux = passed # but I don't want it to
foo_bar-baz-quz = passed # but I don't want it to

Body:
Here's a nice clean solution:

^([a-zA-Z-]+|[a-zA-Z_]+)$

Break it down!

^ start at the beginning of the text

[a-zA-Z-]+ match anything a-z or A-Z or -

| OR operator

[a-zA-Z_]+ match anything a-z or A-Z or _

$ end at the end of the text

Here's an example on regexr!


问:
Getting error in HtmlHelper/Razor in asp.net mvc-5
I have created one cshtml file. When I run/build the solution in visual studio the solution builds fine and even the functionality wise (as far as I can tell) everything seems to be working but I see some errors in Visual Studio error window. Can someone guide me why I see those errors.

```<code>@if (Utils.IsCC)
{
    <div class="CC">
        <div class="form">
            @Html.LabelFor(model => model.CreditDetails.CreditCard, htmlAttributes: new { @class = "control-label col-md-2 required" })
             // Red squiggly comes in the entire line above
        </div>
    </div>
}
</code>```

Error :

The type arguments for method 'System.Web.Mvc.Html.LabelExtensions.LabelFor(System.Web.Mvc.HtmlHelper,
      System.Linq.Expressions.Expression>, System.Collections.Generic.IDictionary)'
      cannot be inferred from the usage. Try specifying the type arguments explicitly.

答:
Your model.CreditDetails.CreditCard has a type that is hard to reconize for MVC.

Try turning it into a normal type, OR specify the type you should use directly.

```<code>@Html.LabelFor<string>(model => model.CreditDetails.CreditCard, htmlAttributes: new { @class = "control-label col-md-2 required" })
</code>```

or

```<code>@Html.LabelFor<ComplexObject>(model => model.CreditDetails.CreditCard, htmlAttributes: new { @class = "control-label col-md-2 required" })
</code>```

That is what the error is trying to tell you, but i don't know if there is a better/perfect solution for this.

Body:
I have created one cshtml file. When I run/build the solution in visual studio the solution builds fine and even the functionality wise (as far as I can tell) everything seems to be working but I see some errors in Visual Studio error window. Can someone guide me why I see those errors.

@if (Utils.IsCC)
{

            @Html.LabelFor(model => model.CreditDetails.CreditCard, htmlAttributes: new { @class = "control-label col-md-2 required" })
             // Red squiggly comes in the entire line above

}

Error :

The type arguments for method 'System.Web.Mvc.Html.LabelExtensions.LabelFor(System.Web.Mvc.HtmlHelper,
      System.Linq.Expressions.Expression>, System.Collections.Generic.IDictionary)'
      cannot be inferred from the usage. Try specifying the type arguments explicitly.

Body:
Your model.CreditDetails.CreditCard has a type that is hard to reconize for MVC.

Try turning it into a normal type, OR specify the type you should use directly.

@Html.LabelFor<string>(model => model.CreditDetails.CreditCard, htmlAttributes: new { @class = "control-label col-md-2 required" })

or

@Html.LabelFor<ComplexObject>(model => model.CreditDetails.CreditCard, htmlAttributes: new { @class = "control-label col-md-2 required" })

That is what the error is trying to tell you, but i don't know if there is a better/perfect solution for this.


问:
Best practices if your Build is taking too long in Visual Studio
I have moderate size solution in Visual Studio which takes around 5 minutes to build (It take that long because of FxCop and other post build steps).
My problem is, Visual Studio stops responding while it's building. You can't continue working as VS almost hangs. I tried using two VS instances, just using one for build, but it keeps crashing every now and then.

My question is, How to not waste time looking at Visual Studio building your large/moderate project. Are there any best practices for this?

答: You might consider a dedicated build machine using MSBuild. From there, you'd be able to continue working while compiling.  It does make it more complicated, though, as you're introducing networking issues.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Charlie Salts


问:
Word VBA to extract Captions of Embedded Files
I'm trying to extract all the embedded Excel files in a Word docx. I know that I can do this quickly by changing filename of the docx to zip, and then find all the Excel files in word/embeddings folder.

The problem is that the Excel files in word/embeddings have very generic filenames (e.g., Microsoft_Excel_Macro-Enabled_Worksheet1.xlsm, Microsoft_Excel_Macro-Enabled_Worksheet2.xlsm) instead of the original filename. The original files, however, were actually csv not xlsm files.

I did not play any part in creating this document. I assume they used Insert -> Object -> Create From File. Also, I'm using Word 2010, but according to the Compatibility Checker the document was originally created with Word 97-2003, and the files were embedded later with Word 2007.

I can find the original filename if I go into the docx, right click on embedded file icon, and go to Macro-Enabled Worksheet Object -> Convert... -> Change Icon... -> Caption

However, I don't want to do this manually for a bunch of embedded Excel files.

So is there a way to use some vba code to extract a list of the original filenames for all embedded files? Then I can use this list as a key to rename the generically named files.

答:
Using vba I can get my code to print the caption of the selected file into immediate window (you can write it anywhere else). This is my code:

```<code> Sub Caption_Ex()

     If Selection.Type = wdSelectionShape Then
         Selection.ShapeRange(1).ConvertToInlineShape.Select
     End If

     Debug.Print Selection.InlineShapes(1).OLEFormat.IconLabel

 End Sub
</code>```

This is what @user1964692 had done for the whole document and I am including this in my edit for reference:

```<code> Option Explicit

 Dim num As Integer
 Dim AD As Document
 Dim ctr As Integer
 Dim caption_names() as variant
 Dim numObjects As Integer

 Sub Extract()

 Set AD = ActiveDocument

 numObjects = AD.InlineShapes.Count
        ctr = 1

 For num = 1 To numObjects
     If AD.InlineShapes(num).Type = 1 Then
         'it's an embedded OLE type so open it.
         Redim Preserve caption_names(1 to ctr)
         caption_names(ctr) = AD.InlineShapes(num).OLEFormat.IconLabel
         ctr=ctr+1
     End If
 Next num

 End Sub
</code>```

This is the solution that I would use by scripting:

Navigate to the folder that you *.docx is located and open cmd there. Make a copy of the word document with *.zip extension.

xcopy Doc1.docx *.zip

Then use 7zip for extracting the file in cmd. You should have the 7za.exe in the same folder as your document.

7za.exe x Doc1.zip -o *.xml.rels -r

xcopy document.xml.rels *.txt

Later you can search for the lines which have .xls in them (Assuming you are in C drive, change the path appropriately):

powershell Command "select-string -path "C:\document.txt" -Pattern ".xls" | select line | out-file C:\lines.txt -append"

You will find filename, line number and the whole line including the match (i.e .xls) in the lines.txt file. This will give you name of the files that you are looking for.

Body:
Using vba I can get my code to print the caption of the selected file into immediate window (you can write it anywhere else). This is my code:

 Sub Caption_Ex()

     If Selection.Type = wdSelectionShape Then
         Selection.ShapeRange(1).ConvertToInlineShape.Select
     End If

     Debug.Print Selection.InlineShapes(1).OLEFormat.IconLabel

 End Sub

This is what @user1964692 had done for the whole document and I am including this in my edit for reference:

 Option Explicit

 Dim num As Integer
 Dim AD As Document
 Dim ctr As Integer
 Dim caption_names() as variant
 Dim numObjects As Integer

 Sub Extract()

 Set AD = ActiveDocument

 numObjects = AD.InlineShapes.Count
        ctr = 1

 For num = 1 To numObjects
     If AD.InlineShapes(num).Type = 1 Then
         'it's an embedded OLE type so open it.
         Redim Preserve caption_names(1 to ctr)
         caption_names(ctr) = AD.InlineShapes(num).OLEFormat.IconLabel
         ctr=ctr+1
     End If
 Next num

 End Sub

This is the solution that I would use by scripting:

Navigate to the folder that you *.docx is located and open cmd there. Make a copy of the word document with *.zip extension.

xcopy Doc1.docx *.zip

Then use 7zip for extracting the file in cmd. You should have the 7za.exe in the same folder as your document.

7za.exe x Doc1.zip -o *.xml.rels -r

xcopy document.xml.rels *.txt

Later you can search for the lines which have .xls in them (Assuming you are in C drive, change the path appropriately):

powershell Command "select-string -path "C:\document.txt" -Pattern ".xls" | select line | out-file C:\lines.txt -append"

You will find filename, line number and the whole line including the match (i.e .xls) in the lines.txt file. This will give you name of the files that you are looking for.


问:
How to pass express errors message to Angular view?
I am asking because if javascript is disabled then server side validation will work. </p>

答:
I recommend you the next approaches:

Add a noscript tag in your html to manage a browser with javascript disabled. If you think a little, all Angular behaviour depends directly of JS, so, if it's disabled then your page won't starts nor function.

Check the express error handling docs

Add a custom ErrorHandler and ErrorExceptions to send in every particular case and a generic error when an unexpected situations happens and send it with next express function and to handle in promise catch

Always add frontend and backend validations, this is know like validation in deep, that means that you verify a valid, correct and permitted data.

Hope this can help you.

Regards.


问:
load image from url in tableview cell from alamofire swift
I am trying to load image from json using Alomofire and swiftyJSON. Json is dictionary:

```<code>{"name": {"image": "https://...",}}
</code>```

Alamorefire and SwiftyJSON

```<code>var imageLoad: String!

Alamofire.request(.GET, url).responseJSON { (response) -> Void in
    if let value = response.result.value {
    let json = JSON(value)

    if let jsonDict = json.dictionary {

        let image = jsonDict["name"]!["image"].stringValue
        print(image) // https://....
        self.imageLoad = image
    }
    self.tableView.reloadData()
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell

// Configure the cell...

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value"
</code>```

If anyone can help? If there is another way feel free to write.

答:
If you are using Alamofire, try AlamofireImage. But use the af_ shortcuts directly on uiimageview. Automatically you will get caching, placeholder images, and you can cancel outstanding requests if you are using a table view which could recycle the cells.

By specifying a placeholder image, the image view uses the placeholder image until the remote image is downloaded.

```<code>let imageView = UIImageView(frame: frame)
let url = URL(string: "https://httpbin.org/image/png")!
let placeholderImage = UIImage(named: "placeholder")!

imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)
</code>```

https://github.com/Alamofire/AlamofireImage

Body:
I am trying to load image from json using Alomofire and swiftyJSON. Json is dictionary:

{"name": {"image": "https://...",}}

Alamorefire and SwiftyJSON

var imageLoad: String!

Alamofire.request(.GET, url).responseJSON { (response) -> Void in
    if let value = response.result.value {
    let json = JSON(value)

    if let jsonDict = json.dictionary {

        let image = jsonDict["name"]!["image"].stringValue
        print(image) // https://....
        self.imageLoad = image
    }
    self.tableView.reloadData()
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell

// Configure the cell...

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value"

If anyone can help? If there is another way feel free to write.

Body:
If you are using Alamofire, try AlamofireImage. But use the af_ shortcuts directly on uiimageview. Automatically you will get caching, placeholder images, and you can cancel outstanding requests if you are using a table view which could recycle the cells.

By specifying a placeholder image, the image view uses the placeholder image until the remote image is downloaded.

let imageView = UIImageView(frame: frame)
let url = URL(string: "https://httpbin.org/image/png")!
let placeholderImage = UIImage(named: "placeholder")!

imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)

https://github.com/Alamofire/AlamofireImage


问:
Blur/Unblur function as a protocol extension
I have created Blurable protocol with extension that have blur function.

```<code>protocol Blurable {}

extension Blurable where Self: UIView {

    func blur(with effect:  UIBlurEffectStyle) {
        let blurEffect = UIBlurEffect(style: effect)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)

        blurEffectView.frame = bounds
        addSubview(blurEffectView)
    }
}
</code>```

Now I want to add unblur function.
If it would be a class I would make blurEffectView as a class property and create unblur function like this:

```<code>func unblur() {
    blurEffectView.removeFromSuperview
}
</code>```

Since protocol extensions don't allow for stored properties what is correct solution to this problem?

答:
You can keep variable in protocol declaration. </p>

```<code>protocol Blurable: class {
    var blurEffectView: UIVisualEffectView? { set get }

    func applyBlur(with effect: UIBlurEffectStyle)
    func removeBlur()
}

private var xoAssociationKey: UInt8 = 0

extension Blurable where Self: UIView {

    // If you want to avoid adding "blurEffectView" to each UIView class,
    // you can do it this way
    var blurEffectView: UIVisualEffectView? {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey) as? UIVisualEffectView
        }

        set(newBlurEffectView) {
            objc_setAssociatedObject(self, &xoAssociationKey, newBlurEffectView, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

    func applyBlur(with effect: UIBlurEffectStyle) {
        let blurEffect = UIBlurEffect(style: effect)
        blurEffectView = UIVisualEffectView(effect: blurEffect)

        blurEffectView?.frame = bounds

        if let blurEffectView = blurEffectView { addSubview(blurEffectView) }
    }

    func removeBlur() {
        if let blurEffectView = blurEffectView {
            blurEffectView.removeFromSuperview()
        }

        blurEffectView = nil
    }
}
</code>```

<p>This should works. You can keep a blurEffectView as non-optional variable but this solution is more safe and effective in future changes because you can check programatically if blur is applied. </p>

```<code>var someView = SomeView()

if let _ = someView.blurEffectView {
    print("YEAP")
} else {
    print("NOPE")
}
</code>```

Body:
I have created Blurable protocol with extension that have blur function.

protocol Blurable {}

extension Blurable where Self: UIView {

    func blur(with effect:  UIBlurEffectStyle) {
        let blurEffect = UIBlurEffect(style: effect)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)

        blurEffectView.frame = bounds
        addSubview(blurEffectView)
    }
}

Now I want to add unblur function.
If it would be a class I would make blurEffectView as a class property and create unblur function like this:

func unblur() {
    blurEffectView.removeFromSuperview
}

Since protocol extensions don't allow for stored properties what is correct solution to this problem?

Body:
You can keep variable in protocol declaration.

protocol Blurable: class {
    var blurEffectView: UIVisualEffectView? { set get }

    func applyBlur(with effect: UIBlurEffectStyle)
    func removeBlur()
}

private var xoAssociationKey: UInt8 = 0

extension Blurable where Self: UIView {

    // If you want to avoid adding "blurEffectView" to each UIView class,
    // you can do it this way
    var blurEffectView: UIVisualEffectView? {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey) as? UIVisualEffectView
        }

        set(newBlurEffectView) {
            objc_setAssociatedObject(self, &xoAssociationKey, newBlurEffectView, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

    func applyBlur(with effect: UIBlurEffectStyle) {
        let blurEffect = UIBlurEffect(style: effect)
        blurEffectView = UIVisualEffectView(effect: blurEffect)

        blurEffectView?.frame = bounds

        if let blurEffectView = blurEffectView { addSubview(blurEffectView) }
    }

    func removeBlur() {
        if let blurEffectView = blurEffectView {
            blurEffectView.removeFromSuperview()
        }

        blurEffectView = nil
    }
}

This should works. You can keep a blurEffectView as non-optional variable but this solution is more safe and effective in future changes because you can check programatically if blur is applied.

var someView = SomeView()

if let _ = someView.blurEffectView {
    print("YEAP")
} else {
    print("NOPE")
}


问:
How send parameter to a url without using form in php?
dear all,
I need to send parameters to a URL without using form in php and get value from that page.We can easily send parameters using form like this:

```<code><html>
    <form action="http://..../abc.php" method="get">
    <input name="id" type="text" />
    <input name="name" type="text"/>
    <input  type="submit" value="press" />
    </form>
</html>
</code>```

But i already have value like this

```<code>     <?php
       $id="123";
       $name="blahblah";
      ?>
</code>```

Now i need to send values to http://..../abc.php without using form.when the 2 value send to abc.php link then it's show a value OK.Now i have to collect the "OK" msg from abc.php and print on my current page.
i need to auto execute the code.when user enter into the page those value automatically send to a the url.So i can't use form or href. because form and href need extra one click.

Is their any kind heart who can help me to solve this issue?

答:
You can pass values via GET using a hyperlink:

```<code><a href='abc.php?id=123&name=blahblah' />
</code>```

print_r($_GET) would then give you the values, or you can use $_GET['id'] etc in abc.php

Other approaches, depending on your needs, include using AJAX to POST/GET the request asynchronously, or using include/require to pull in abc.php if it only includes specific functioanlity.eg:

```<code>   $id="123";
   $name="blahblah";
   require('abc.php');
</code>```

Body:
dear all,
I need to send parameters to a URL without using form in php and get value from that page.We can easily send parameters using form like this:

    <form action="http://..../abc.php" method="get">
    <input name="id" type="text" />
    <input name="name" type="text"/>
    <input  type="submit" value="press" />
    </form>

But i already have value like this

     <?php
       $id="123";
       $name="blahblah";
      ?>

Now i need to send values to http://..../abc.php without using form.when the 2 value send to abc.php link then it's show a value OK.Now i have to collect the "OK" msg from abc.php and print on my current page.
i need to auto execute the code.when user enter into the page those value automatically send to a the url.So i can't use form or href. because form and href need extra one click.

Is their any kind heart who can help me to solve this issue?

Body:
You can pass values via GET using a hyperlink:

<a href='abc.php?id=123&name=blahblah' />

print_r($_GET) would then give you the values, or you can use $_GET['id'] etc in abc.php

Other approaches, depending on your needs, include using AJAX to POST/GET the request asynchronously, or using include/require to pull in abc.php if it only includes specific functioanlity.eg:

   $id="123";
   $name="blahblah";
   require('abc.php');


问:
Trying to understand (function(func) { func(); } in JavaScript
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below. There is no name at all. So how does function(func) { func(); } calls the something.push(function() ?

Not to mention that something.push(function() doesn't even have an argument, which from C perspective, this is wrong

```<code>var something = [],
  object = {
    a: true,
    b: true,
    c: true
}

 for (let key in object){
   something.push(function() {
   console.log(key);
   });
 }

 something.forEach(function(func) { func(); }):
</code>```

答:
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below, there is no name at all.

Well in JavaScript, that's just not the case – functions can indeed be anonymous (nameless) functions. Sometimes you'll hear them called "lambdas" or redundantly called "lambda functions".

But more importantly, functions are first class data members in JavaScript, meaning:

They can be assigned to variables

```<code>let y = x => x + 5
y(3)
// 8
</code>```

They can be passed as arguments to other functions

```<code>let xs = [1,2,3]
let y = x => 2 * x
xs.map(y)
// [2,4,6]
</code>```

They can be returned from a function

```<code>let add = x => {
  return y => x + y
}
let f = add(1)
f(2)
// 3
</code>```

They can be included in data structures

```<code>let pikachu = {
  number: 25,
  shock: enemy => enemy.damage(30),
  growl: enemy => enemy.sadden(40)
}
pikachu.growl(meowth)
// "It's very effective!"
</code>```

So what's the take away here? Well, in JavaScript, you need to think of functions as being no different than any other value (eg) 1, "foo", or [{user: 'bob'}, {user: 'alice'}] – conceptually, they are just data and they're all first class

How to understand your code

Here's your code affectionally reformatted by me. Since you originally asked about ES6, I'm going to substitute your lambdas with ES6 arrow functions

let something = []
let object = { a: true, b: true, c: true }

for (let key in object) {
  something.push(() => console.log(key))
}

something.forEach(func => func())
// a
// b
// c```
</div>
</div>
</p>

<p>Using high level descriptors, the nature of this code is</p>

<ol>
<li>iterate thru each key of <code>object</code>, add <em>some value</em> to <code>something</code></li>
<li>iterate thru each value of <code>something</code>, do something with that value</li>
</ol>

<p>In your case, <em>some value</em> is a function, but I want to show you what your code would look like if we used another kind of value</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>let something = []
let object = { a: true, b: true, c: true }

for (let key in object) {
  // this time push a string, instead of an anonymous function
  something.push("the key is: " + key)
}

something.forEach(str => console.log(str))
// the key is: a
// the key is: b
// the key is: c</code>```

So now we can see how the code works when a different value type (String) is used. Aside from using a string, the only other thing we did was change

```<code>// from
func => func()

// to
str => console.log(str)
</code>```

The reasoning here is

in your original code, something is an array of functions, so for each of those functions, func, we call func()

in the modified code, something is an array of strings, so for each of those strings, str, we call console.log(str)

Dissection of Array.prototype.forEach

The last remaining bit to understand is the super-powered forEach function. Remember point number 2 in the first class capabilities: first class data members can be passed as arguments to other functions.

forEach expects its argument to be a function. So forEach is a function that accepts another function. This kind of function is called a higher-order function.

Don't let these fancy names distract you from their underlying simplicity. Making our own higher-order functions like forEach is actually really easy. Always just remember that functions are like any other value – below, we'll write our own version of forEach so you can see how it works

let something = []
let object = { a: true, b: true, c: true }

// forEach accepts an array and some function, f
let forEach = (arr, f) => {
  // iterate thru each value of arr
  for (let value of arr) {
    // call f on each value
    f(value)
  }
}

for (let key in object) {
  something.push("the key is: " + key)
}

forEach(something, str => console.log(str))
// the key is: a
// the key is: b
// the key is: c```
</div>
</div>
</p>

<p>So now we see the string array working with our own <code>forEach</code> function. Let's make sure it works with your original lambda array, too.</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>let something = []
let object = { a: true, b: true, c: true }

let forEach = (arr, f) => {
  for (let value of arr) {
    f(value)
  }
}

for (let key in object) {
  something.push(() => console.log(key))
}

forEach(something, func => { func() })
// a
// b
// c</code>```

Remarks

And that's it! Functions aren't special snowflakes in JavaScript. They're just like all the datums.

Coming from a C perspective, it might take awhile to think about functions in this way. But really, you should leave everything you understand about any language at the door when you're walking into the home of any new programming language. Each language has its own way of expressing itself yielding a unique set of strengths and weaknesses. By bringing in a "strength" of some language A to another language B, you might be substituting one of B's own strengths for one of it's weaknesses.

JavaScript is a multi-paradigm language making it rather suitable for imperative, object-oriented, and functional programming styles. Because of its jack-of-all-trades nature, it's probably not the best oop or fp language, but it's still rather impressive that it can express a particular solution to a problem in a wide variety of ways.

Body:
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below. There is no name at all. So how does function(func) { func(); } calls the something.push(function() ?

Not to mention that something.push(function() doesn't even have an argument, which from C perspective, this is wrong

var something = [],
  object = {
    a: true,
    b: true,
    c: true
}

 for (let key in object){
   something.push(function() {
   console.log(key);
   });
 }

 something.forEach(function(func) { func(); }):

Body:
Coming from C, every function needs a name that is used to call that specific function. but in the JavaScript code below, there is no name at all.

Well in JavaScript, that's just not the case – functions can indeed be anonymous (nameless) functions. Sometimes you'll hear them called "lambdas" or redundantly called "lambda functions".

But more importantly, functions are first class data members in JavaScript, meaning:

They can be assigned to variables

let y = x => x + 5
y(3)
// 8

They can be passed as arguments to other functions

let xs = [1,2,3]
let y = x => 2 * x
xs.map(y)
// [2,4,6]

They can be returned from a function

let add = x => {
  return y => x + y
}
let f = add(1)
f(2)
// 3

They can be included in data structures

let pikachu = {
  number: 25,
  shock: enemy => enemy.damage(30),
  growl: enemy => enemy.sadden(40)
}
pikachu.growl(meowth)
// "It's very effective!"

So what's the take away here? Well, in JavaScript, you need to think of functions as being no different than any other value (eg) 1, "foo", or [{user: 'bob'}, {user: 'alice'}] – conceptually, they are just data and they're all first class

How to understand your code

Here's your code affectionally reformatted by me. Since you originally asked about ES6, I'm going to substitute your lambdas with ES6 arrow functions

let something = []
let object = { a: true, b: true, c: true }

for (let key in object) {
  something.push(() => console.log(key))
}

something.forEach(func => func())
// a
// b
// c

Using high level descriptors, the nature of this code is

iterate thru each key of object, add some value to something

iterate thru each value of something, do something with that value

In your case, some value is a function, but I want to show you what your code would look like if we used another kind of value

let something = []
let object = { a: true, b: true, c: true }

for (let key in object) {
  // this time push a string, instead of an anonymous function
  something.push("the key is: " + key)
}

something.forEach(str => console.log(str))
// the key is: a
// the key is: b
// the key is: c

So now we can see how the code works when a different value type (String) is used. Aside from using a string, the only other thing we did was change

// from
func => func()

// to
str => console.log(str)

The reasoning here is

in your original code, something is an array of functions, so for each of those functions, func, we call func()

in the modified code, something is an array of strings, so for each of those strings, str, we call console.log(str)

Dissection of Array.prototype.forEach

The last remaining bit to understand is the super-powered forEach function. Remember point number 2 in the first class capabilities: first class data members can be passed as arguments to other functions.

forEach expects its argument to be a function. So forEach is a function that accepts another function. This kind of function is called a higher-order function.

Don't let these fancy names distract you from their underlying simplicity. Making our own higher-order functions like forEach is actually really easy. Always just remember that functions are like any other value – below, we'll write our own version of forEach so you can see how it works

let something = []
let object = { a: true, b: true, c: true }

// forEach accepts an array and some function, f
let forEach = (arr, f) => {
  // iterate thru each value of arr
  for (let value of arr) {
    // call f on each value
    f(value)
  }
}

for (let key in object) {
  something.push("the key is: " + key)
}

forEach(something, str => console.log(str))
// the key is: a
// the key is: b
// the key is: c

So now we see the string array working with our own forEach function. Let's make sure it works with your original lambda array, too.

let something = []
let object = { a: true, b: true, c: true }

let forEach = (arr, f) => {
  for (let value of arr) {
    f(value)
  }
}

for (let key in object) {
  something.push(() => console.log(key))
}

forEach(something, func => { func() })
// a
// b
// c

Remarks

And that's it! Functions aren't special snowflakes in JavaScript. They're just like all the datums.

Coming from a C perspective, it might take awhile to think about functions in this way. But really, you should leave everything you understand about any language at the door when you're walking into the home of any new programming language. Each language has its own way of expressing itself yielding a unique set of strengths and weaknesses. By bringing in a "strength" of some language A to another language B, you might be substituting one of B's own strengths for one of it's weaknesses.

JavaScript is a multi-paradigm language making it rather suitable for imperative, object-oriented, and functional programming styles. Because of its jack-of-all-trades nature, it's probably not the best oop or fp language, but it's still rather impressive that it can express a particular solution to a problem in a wide variety of ways.


问:
sharepoint 2013 & Excel: we can't show these features in a browser: text queries
I uploaded an Excel spreadsheet to Sharepoint 2013 & I'm getting this message "we can't show these features in a browser: text queries".  What text queries are they referring to?  I can't edit in the spreadsheet in the browser because of this</p>

答:
I found out what the issue was.

I followed the same steps as listed in the "Most Helpful Reply"  and the problem went away:

I was having this issue also and came across this post. I followed the suggestion of deleting the info in the connections tab and the problem continued. However, after that if you click on the properties tab under the connections tab, there is a choice in there about saving the query data. I un-checked that and at the moment I believe this has solved the problem.


问:
Packer - Windows Server 2012R2 - Install PowerShell 5
I'm having trouble with installing PowerShell 5 on Windows Server 2012 R2 using Packer.

To install PowerShell 5.1, I'm using chocolatey

powershell
iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
choco install PowerShell -y

I need to to do this for two packer builder:

Amazon Web Services EC2 AMI.

Hyper-V Vagrant.

With the Amazon Web Services EC2 AMI I've tried executing the above from the following locations

As part of the user_data_file script.

As an inline provision script.

I've added the windows-restart provision in the flow after the execution of the fragment.

Similarly I've tried the same with the Hyper-V Vagrant both as part of the Autounattend flow and as an inline provision.

In both cases the installation fails because the user profile is not created. At least I think that is the problem. As a reference, I've faced the exact same problem when installing sql server express.

Has anyone managed to accomplish this flow and what is your recommendation?

答:
PowerShell package uses MSU (Windows Update file). There are a couple of considerations here:

Ensure Windows Updates Service is turned on. Chocolatey doesn't do that yet, although there is an issue filed.

MSUs must be run locally from the machine. So if you are running over WinRM, you instead need to have it set up a scheduled task to call choco install and then run it that way.

Yes, that second point is accurate. No, it is not Chocolatey's fault. That's a Microsoft design decision with MSU files. It's a real PITA.

FYI - BoxStarter handles it appropriately, and it can be used with Packer. You will find less pain if you look there.

HTH


问:
Android finding source image files on the android device inside the app assets or resources
So, I am trying to place an image in a layout programmatically and I can do this, but only using the mipmap resources. I want to place the full image onto the layout. The answers I have come across mention bitmaps and file paths. What I am confused about is the file path part. Does this mean a file path on the computers source files, or does it mean a file path on the android device in which case, how can I find the image when it is part of the apps resources, not in gallery or to be taken from the camera. If i create a new directory in the project, I can't use R.XXX to find it as it is not there. Under Android the directory does not show up either and dragging an image to the directories under Android does nothing either.</p>

答: You should put images in res/drawable folder</p>


问:
How to remove(unregister) registered instance from Unity mapping?
I meet one problem that i can't solve now.
I have the following:

```<code>UnityHelper.DefaultContainer.RegisterInstance(typeof(IMyInterface), "test", instance);
</code>```

where UnityHelper.DefaultContainer is my helper for getting unity container with loaded configuration.

here I registered instance as an instance of IMyInterface.

So anywhere( some time after using) I want to remove this mapping. Remove it at all. How I can do it?

I have tried:

```<code>UnityHelper.DefaultContainer.Teardown(instance)
</code>```

but is was unsuccessful and the following code returns instance anyway:

```<code>UnityHelper.DefaultContainer.ResolveAll<IMyInterface>()
</code>```

答:
This is an old question, but some answers are misleading, so I will provide my own.
You can´t do that with Unity. End of the story.
Calling RemoveValue on registrations lifetime managers does not achieve unregistration (more information about lifetime managers), and that method is not intended to unregister anything. So the final behaviour is unexpected and not convenient. Of course, RemoveValue makes even less sense if you register an implementation or a factory method, although the question is about unregistering instances.
Consider the next piece of code

```<code>    public interface SomeInterface
    {
        int Foo { get; set; }
    }

    public class SomeImplementation: SomeInterface
    {
        public int Foo { get; set; }
    }

    static void Main(string[] args)
    {
        UnityContainer iocContainer = new UnityContainer();
        string registerName = "instance";
        //before any registration
        Resolve<SomeInterface>(iocContainer, registerName);

        iocContainer.RegisterInstance<SomeInterface>(registerName, new SomeImplementation());

        //after registration
        Resolve<SomeInterface>(iocContainer, registerName);

        ClearValue<SomeInterface>(iocContainer, registerName);

        //after clear value
        Resolve<SomeInterface>(iocContainer, registerName);

    }

    private static void Resolve<T>(UnityContainer iocContainer,string name)
    {
        if (iocContainer.IsRegistered<T>(name))
            iocContainer.Resolve<T>(name);

        iocContainer.ResolveAll<T>();
    }
    private static void ClearValue<T>(UnityContainer iocContainer, string name)
    {
        foreach (var registration in iocContainer.Registrations.Where(p => p.RegisteredType == typeof(T)
            && p.Name==name))
        {
            registration.LifetimeManager.RemoveValue();
        }
    }
</code>```

If you debug it, you will see that after the call to ClearValue, the container still says it is registered, but if you try to resolve that instance it will throw an exception. What is even worse, calls to ResolveAll<T> will fail too.

To Sum up, no matter if you do ClearValue, wrap around your register instance with another IoC or a custom class, or provide your own LifeTimeManager, ResolveAll<T> and IsRegistered<T> won´t behave as expected, and the registration will still be there. So don't try it because it won´t work and it will cause problems down the road.

ContentLicense: CC BY-SA 4.0

Body:
I meet one problem that i can't solve now.
I have the following:

UnityHelper.DefaultContainer.RegisterInstance(typeof(IMyInterface), "test", instance);

where UnityHelper.DefaultContainer is my helper for getting unity container with loaded configuration.

here I registered instance as an instance of IMyInterface.

So anywhere( some time after using) I want to remove this mapping. Remove it at all. How I can do it?

I have tried:

UnityHelper.DefaultContainer.Teardown(instance)

but is was unsuccessful and the following code returns instance anyway:

UnityHelper.DefaultContainer.ResolveAll<IMyInterface>()

Body:
This is an old question, but some answers are misleading, so I will provide my own.
You can´t do that with Unity. End of the story.
Calling RemoveValue on registrations lifetime managers does not achieve unregistration (more information about lifetime managers), and that method is not intended to unregister anything. So the final behaviour is unexpected and not convenient. Of course, RemoveValue makes even less sense if you register an implementation or a factory method, although the question is about unregistering instances.
Consider the next piece of code

    public interface SomeInterface
    {
        int Foo { get; set; }
    }

    public class SomeImplementation: SomeInterface
    {
        public int Foo { get; set; }
    }

    static void Main(string[] args)
    {
        UnityContainer iocContainer = new UnityContainer();
        string registerName = "instance";
        //before any registration
        Resolve<SomeInterface>(iocContainer, registerName);

        iocContainer.RegisterInstance<SomeInterface>(registerName, new SomeImplementation());

        //after registration
        Resolve<SomeInterface>(iocContainer, registerName);

        ClearValue<SomeInterface>(iocContainer, registerName);

        //after clear value
        Resolve<SomeInterface>(iocContainer, registerName);

    }

    private static void Resolve<T>(UnityContainer iocContainer,string name)
    {
        if (iocContainer.IsRegistered<T>(name))
            iocContainer.Resolve<T>(name);

        iocContainer.ResolveAll<T>();
    }
    private static void ClearValue<T>(UnityContainer iocContainer, string name)
    {
        foreach (var registration in iocContainer.Registrations.Where(p => p.RegisteredType == typeof(T)
            && p.Name==name))
        {
            registration.LifetimeManager.RemoveValue();
        }
    }

If you debug it, you will see that after the call to ClearValue, the container still says it is registered, but if you try to resolve that instance it will throw an exception. What is even worse, calls to ResolveAll<T> will fail too.

To Sum up, no matter if you do ClearValue, wrap around your register instance with another IoC or a custom class, or provide your own LifeTimeManager, ResolveAll<T> and IsRegistered<T> won´t behave as expected, and the registration will still be there. So don't try it because it won´t work and it will cause problems down the road.


问:
How to join YEARS from 2 tables with different format
I am trying to create a custom view in excel for a pivot,  I cant join the YEARSF because the tb1 format is 2016-17 and tb2 is 2016/17, how can i join these, see code below... what is the appropriate way of doing this

```<code>TB1.YEARF = TB2.YEARF
</code>```

Seems to be the issue

```<code>     SELECT TB1.YEARF,
TB1.MC,
TB1.CATEG,
TB1.ID,
TB1.TY,
TB1.CAT,
TB1.LOC,
TB2.HD0_NAME,
TB2.HD1_NAME,
TB2.HD2_NAME,
TB2.HD3_NAME,
TB2.HD4_NAME
FROM DB.TB2 TB2, DB.TB1 TB1
WHERE TB2.CAT = TB1.CAT AND TB2.LOC = TB1.LOC AND TB1.TY = TB2.TY AND TB1.YEARF = TB2.YEARF AND TB1.ID = TB2.ID
</code>```

答:
```<code>WHERE Format(TB1.YEARF, "yyyy-dd") = Format(TB2.YEARF, "yyyy-dd")
</code>```

Body:
I am trying to create a custom view in excel for a pivot,  I cant join the YEARSF because the tb1 format is 2016-17 and tb2 is 2016/17, how can i join these, see code below... what is the appropriate way of doing this

TB1.YEARF = TB2.YEARF

Seems to be the issue

     SELECT TB1.YEARF,
TB1.MC,
TB1.CATEG,
TB1.ID,
TB1.TY,
TB1.CAT,
TB1.LOC,
TB2.HD0_NAME,
TB2.HD1_NAME,
TB2.HD2_NAME,
TB2.HD3_NAME,
TB2.HD4_NAME
FROM DB.TB2 TB2, DB.TB1 TB1
WHERE TB2.CAT = TB1.CAT AND TB2.LOC = TB1.LOC AND TB1.TY = TB2.TY AND TB1.YEARF = TB2.YEARF AND TB1.ID = TB2.ID


问:
c++ graphical programming
I'm new to c++ 3D, so I may just be missing something obvious, but how do I convert from 3D to 2D and (for a given z location) from 2D to 3D?</p>

答: You map 3D to 2D via projection. You map 2D to 3D by inserting the appropriate value in the Z element of the vector.</p>

Title: c++ graphical programming


问:
Sequelize query for the following SQL:
I have a SQL query that I want to write as a Sequelize query.

```<code>SELECT users.username, players.points, tournaments.date
FROM USERS
JOIN players ON users.id = players.UserId
JOIN Tournaments ON tournaments.id = players.TournamentId
WHERE players.player_checkedin_flag = 1 AND users.role = "user";
</code>```

I have the following association in Players table:

```<code>classMethods: {
    associate: function(models) {
      // Foreign key to user_id
      Player.belongsTo(models.User, {
        foreignKey: {
          allowNull: false
        }
      });
      // Foreign key to tournament_id
      Player.belongsTo(models.Tournament, {
        foreignKey: {
          allowNull: false
        }
      });
</code>```

In Users table,

```<code>{
  classMethods: {
    associate: function(models) {
      // User has many Player data
      User.hasMany(models.Player);
    }
  }
}
</code>```

And in Tournaments table:

```<code>{
  classMethods: {
    associate: function(models) {
      // Tournament is connected to many player rows
      Tournament.hasMany(models.Player);
    }
  }
}
</code>```

What is the corresponding sequelize query for it?

答:
In this case you need to perform eager loading on those three models

User.all({
    attributes: ['username'], // return only 'username' column from 'users' table
    include: [
        {
            model: Player, // eager load players on players.userId = users.id
            attributes: ['points'], // return only 'points' column from 'players' table
            include: [{ model: Tournament, attributes: ['date'] }] // nested eager load of 'tournaments' table on tournaments.playerId = players.id
        }
    ],
    where: {
        playerCheckedinFlag: sequelize.where(sequelize.col('Player.player_checkedin_flag', '=', 1),
        role: 'user'
    },
    raw: true // used the raw attribute to prevent creating User instances from the query result due to the fact that we return 3 fields from 3 different tables
}).(result => {
    console.log(result);
});
```

sequelize in the code above is the instance of Sequelize in which the models were defined. You can also check the documentation of sequelize.where() method.

Title: Sequelize query for the following SQL:

Body:
I have a SQL query that I want to write as a Sequelize query.

SELECT users.username, players.points, tournaments.date
FROM USERS
JOIN players ON users.id = players.UserId
JOIN Tournaments ON tournaments.id = players.TournamentId
WHERE players.player_checkedin_flag = 1 AND users.role = "user";

I have the following association in Players table:

classMethods: {
    associate: function(models) {
      // Foreign key to user_id
      Player.belongsTo(models.User, {
        foreignKey: {
          allowNull: false
        }
      });
      // Foreign key to tournament_id
      Player.belongsTo(models.Tournament, {
        foreignKey: {
          allowNull: false
        }
      });

In Users table,

{
  classMethods: {
    associate: function(models) {
      // User has many Player data
      User.hasMany(models.Player);
    }
  }
}

And in Tournaments table:

{
  classMethods: {
    associate: function(models) {
      // Tournament is connected to many player rows
      Tournament.hasMany(models.Player);
    }
  }
}

What is the corresponding sequelize query for it?

Body:
In this case you need to perform eager loading on those three models

User.all({
    attributes: ['username'], // return only 'username' column from 'users' table
    include: [
        {
            model: Player, // eager load players on players.userId = users.id
            attributes: ['points'], // return only 'points' column from 'players' table
            include: [{ model: Tournament, attributes: ['date'] }] // nested eager load of 'tournaments' table on tournaments.playerId = players.id
        }
    ],
    where: {
        playerCheckedinFlag: sequelize.where(sequelize.col('Player.player_checkedin_flag', '=', 1),
        role: 'user'
    },
    raw: true // used the raw attribute to prevent creating User instances from the query result due to the fact that we return 3 fields from 3 different tables
}).(result => {
    console.log(result);
});

sequelize in the code above is the instance of Sequelize in which the models were defined. You can also check the documentation of sequelize.where() method.


问:
Why fatal error “LNK1104: cannot open file 'cryptlib.lib' occur when I compile a C++ project in Visual Studio?
I am getting the error mentioned above when compiling a project on Visual Studio. What is strange and different about my situation is that this works on my personal laptop, but not at work.

I have the entire project saved in Dropbox, because I sometimes work on my projects from work and I like this automatic sync that way I don't worry about loosing anything. Having said that, I use relative paths for my libraries, that way the folder is the same for both computers, i.e. "..\cryptopp\x64\Output\Debug\cryptlib.lib"

My question is, why does it work at home, but not at work? I made sure the property sheet has the correct path as well. The linker and VC++ directories are both relative paths.

This cryptlib.lib has some namespaces like CryptoPP and variable types such as byte, it won't give me an error on this. It knows it exists (I get the correct font color)

Is there something that I am missing?

P.S. Added screenshots per request. Can't add more than 2 links, so I merged 2 screenshots into 1. That ECE427Projects is where the solution file is located. I don't want to go any further back than that.

Screenshot 1

Screenshot 2

答:
You've put the directory for the library in the wrong field.

There's two places you could use to specify the directory where your libraries are supposed to be. I prefer to use the Library Directories section in Configuration Properties→VC++ Directories, but the alternate is Additional Library Directories in Configuration Properties→Linker→General. There's no need to specify it in both locations, though I doubt anything bad will happen if you do. Bear in mind that this is supposed to be a directory, not a file, so delete the trailing cryptlib.lib file name from this directory string.

If you haven't, in Configuration Properties→Linker→Input, for Additional Dependencies, you should be putting the name of the library object (cryptlib.lib), in your case.

For all of these, make sure the default values inherited by the project property pages are still there, after the stuff you add.

Let me know if this doesn't resolve the issue.


问:
Bootstrap datepicker in popover clear other inputs when event show fired
I have a form in popover window, in this form I have input with datepicker bootstrap. I fill all inputs before input with datepicker, but when I open datepicker all inputs clear.
Can anyone help?

    $('.datepicker').datepicker({
        format: 'dd.mm.yyyy',
        language: 'ru',
        autoclose: true
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modal fade" id="taskform" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
 <div class="modal-dialog" role="document">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    <h4 class="modal-title" id="myModalLabel">Создать задачу</h4>
   </div>
   @using (Html.BeginForm(Model.ActionName, Model.ControllerName, FormMethod.Post, new { id = "task_form" }))
   {
    <div class="modal-body">
     <div class="form-group">
      @Html.HiddenFor(m => m.CampaignId)
      @Html.HiddenFor(m => m.AuthorId)

      @Html.LabelFor(x => x.Title)
      @Html.TextBoxFor(x => x.Title, new { @class = "form-control form-input" })
     </div>

     <div class="form-group">
      <br />
      @Html.LabelFor(x => x.Description)
      @Html.TextAreaFor(x => x.Description, new { @class = "ckeditor form-control form-input", rows = "3" })
      <br />
     </div>
     <div class="form-group">
      @Html.LabelFor(x => x.DeadLine)
      @Html.TextBoxFor(x => x.DeadLine, new { @class = "form-control form-input datepicker", placeholder = "Дедлайн" })
      <br />
     </div>
    </div>
    <div class="modal-footer" style="text-align: left;">
     <button type="button" id="task-submit" class="btn btn-primary" style="float: right;">Создать</button>
     @Html.DropDownListFor(m => m.Performers, Model.AllPerformers.Select(item => new SelectListItem()
     {
      Text = item.FullName,
      Value = Convert.ToString(item.Id)
     }), new { @class = "form-control select2 ", style = "", multiple = "multiple", placeholder = "Добавьте исполнителей" })
    </div>
   }
  </div>
 </div>
</div></code>```

答:
In case someone still need it :

Using shown and hidden events instead of show and hide is not always possible. A better workaround is to check the event namespace:

```<code>modal.on('show.bs.modal', function(e) {
    if (e.namespace === 'bs.modal') {
        //
    }
});
</code>```

from https://github.com/uxsolutions/bootstrap-datepicker/issues/978

Body:
I have a form in popover window, in this form I have input with datepicker bootstrap. I fill all inputs before input with datepicker, but when I open datepicker all inputs clear.
Can anyone help?

    $('.datepicker').datepicker({
        format: 'dd.mm.yyyy',
        language: 'ru',
        autoclose: true
    });

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Создать задачу

   @using (Html.BeginForm(Model.ActionName, Model.ControllerName, FormMethod.Post, new { id = "task_form" }))
   {

      @Html.HiddenFor(m => m.CampaignId)
      @Html.HiddenFor(m => m.AuthorId)

      @Html.LabelFor(x => x.Title)
      @Html.TextBoxFor(x => x.Title, new { @class = "form-control form-input" })

      @Html.LabelFor(x => x.Description)
      @Html.TextAreaFor(x => x.Description, new { @class = "ckeditor form-control form-input", rows = "3" })

      @Html.LabelFor(x => x.DeadLine)
      @Html.TextBoxFor(x => x.DeadLine, new { @class = "form-control form-input datepicker", placeholder = "Дедлайн" })

     <button type="button" id="task-submit" class="btn btn-primary" style="float: right;">Создать</button>
     @Html.DropDownListFor(m => m.Performers, Model.AllPerformers.Select(item => new SelectListItem()
     {
      Text = item.FullName,
      Value = Convert.ToString(item.Id)
     }), new { @class = "form-control select2 ", style = "", multiple = "multiple", placeholder = "Добавьте исполнителей" })

   }

Body:
In case someone still need it :

Using shown and hidden events instead of show and hide is not always possible. A better workaround is to check the event namespace:

modal.on('show.bs.modal', function(e) {
    if (e.namespace === 'bs.modal') {
        //
    }
});

from https://github.com/uxsolutions/bootstrap-datepicker/issues/978


问:
Database Design: name-value pairs - good or bad?
Say I have an online store wherein each product has a single category (and there are hundreds of categories to choose from) assigned to it (e.g. "book", "portable DVD player", etc.). If I needed to provide descriptive fields for each category (e.g. "author" would be a field for the "book" category), what is the best way to represent this in a database?

Option 1 (name value pairs):

```<code>===========================
 field
===========================
- field_id
- category_id (FK, referring to category like "book")
- name
- value
</code>```

This means I can rely on one table for any category. I'm concerned that the pivoting required to display this data side by side with other books might be a potential problem.

Option 2 (individual tables):

```<code>===========================
 book_field
===========================
- book_field_id
- book_id (FK, referring to the actual book)
- author
- title
- publisher
- date_published
...
</code>```

This means I need a table for each category.

NOTE: not that I think it matters, but the category would be coming from a hierarchy of categories (e.g. Electronics ->  DVD Players -> Portable DVD Players).

答:
My $0.02 - one table per category.  If things are truely different, then embrace that and set up your tables accordingly.

Naturally if some of the entities have common data, that can be abstracted/normalized out, but I think the name/value pair option you have up there could lead to some nasty readability/query performance issues down the road.

Body:
Say I have an online store wherein each product has a single category (and there are hundreds of categories to choose from) assigned to it (e.g. "book", "portable DVD player", etc.). If I needed to provide descriptive fields for each category (e.g. "author" would be a field for the "book" category), what is the best way to represent this in a database?

Option 1 (name value pairs):

===========================
 field
===========================
- field_id
- category_id (FK, referring to category like "book")
- name
- value

This means I can rely on one table for any category. I'm concerned that the pivoting required to display this data side by side with other books might be a potential problem.

Option 2 (individual tables):

===========================
 book_field
===========================
- book_field_id
- book_id (FK, referring to the actual book)
- author
- title
- publisher
- date_published
...

This means I need a table for each category.

NOTE: not that I think it matters, but the category would be coming from a hierarchy of categories (e.g. Electronics ->  DVD Players -> Portable DVD Players).


问:
how to change title of aspx page dynamically on page load
I had set of ASPX pages in which each page had different titles, but I want to put default title for pages which don't have a title. The default title must be configurable.</p>

答:
I had a similar problem and none of these solutions worked well for me. The problem stems from the order control events fire for a page. In my case, I had some code that needed to be in the Page_load event (this was because that is the first event where we have a Request object to work with). That code also needed to run before the title could be set. Other pages in my site were able to simply set the desired Title in the page Ctor but because this page needed to interrogate the response object for information first, it was a problem. The problem with this is that the master page has already created the page header section by the time we get to the Page_load event and I didn't want junk in my Master page that was only required for a single page on my site. My simple hack to overcome this issue was to insert a bit of javascript inline in the content portion of the page:

```<code><asp:Content ID=BodyContent ContentPlaceHolderID=MainContent RunAt=Server>
    <script type="text/javascript">
        document.title='<%=Title%>';
    </script>

    ... the rest of the content page goes here ...

</asp:Content>
</code>```

With this in place, you are free to set the Title in the Page_Load event and it'll be set as soon as this line of code has downloaded. Of course, my site already has a JS requirement so if you're trying to avoid that then this is not going to work for you.

Body:
I had a similar problem and none of these solutions worked well for me. The problem stems from the order control events fire for a page. In my case, I had some code that needed to be in the Page_load event (this was because that is the first event where we have a Request object to work with). That code also needed to run before the title could be set. Other pages in my site were able to simply set the desired Title in the page Ctor but because this page needed to interrogate the response object for information first, it was a problem. The problem with this is that the master page has already created the page header section by the time we get to the Page_load event and I didn't want junk in my Master page that was only required for a single page on my site. My simple hack to overcome this issue was to insert a bit of javascript inline in the content portion of the page:

<asp:Content ID=BodyContent ContentPlaceHolderID=MainContent RunAt=Server>
    <script type="text/javascript">
        document.title='<%=Title%>';
    </script>

    ... the rest of the content page goes here ...

</asp:Content>

With this in place, you are free to set the Title in the Page_Load event and it'll be set as soon as this line of code has downloaded. Of course, my site already has a JS requirement so if you're trying to avoid that then this is not going to work for you.


问:
Having trouble to loop through a file containing XPaths
I am having trouble to loop through a file day.txt containing XPaths.

For example: I already tried to triple quote in the file like this:

```<code>"""//[@id="frm"]/div[4]/div/div[1]/div[1]/div[2]/div/div[1]/div/div[2]"""
</code>```

but it's not working.

The error is

SyntaxError:

    Failed to execute 'evaluate' on 'Document':

    The string '"""//*[@id="frm"]/div[4]/div/div[1]/div[1]/div[2]/div/div[2]/div[2]/div[3]/div/div/div[2]/table/tbody/tr[1]/td[7]/span"""
  '

  is not a valid XPath expression.

Any help is welcome!

```<code>dates = open("days.txt")
for date in dates:
 date.strip()
 driver.find_element_by_xpath(date).click()
</code>```

答:
You shouldn't need any quotes around the lines in the txt file. If your XPath locators contain double quotes ("), you will need to replace them all with single quotes (') before using them. If you google replacing characters in a string in python, you'll find some example code.

NOTE: Locators that contain that many levels are very brittle. You really need to handcraft those locators to make them much shorter.

Body:
I am having trouble to loop through a file day.txt containing XPaths.

For example: I already tried to triple quote in the file like this:

"""//[@id="frm"]/div[4]/div/div[1]/div[1]/div[2]/div/div[1]/div/div[2]"""

but it's not working.

The error is

SyntaxError:

    Failed to execute 'evaluate' on 'Document':

    The string '"""//*[@id="frm"]/div[4]/div/div[1]/div[1]/div[2]/div/div[2]/div[2]/div[3]/div/div/div[2]/table/tbody/tr[1]/td[7]/span"""
  '

  is not a valid XPath expression.

Any help is welcome!

dates = open("days.txt")
for date in dates:
 date.strip()
 driver.find_element_by_xpath(date).click()


问:
Hook on Windows Installer messages
I wonder if there is any win32 API regarding the user install software on his machine ?

Is there is any event the windows fire when a user start to install software ?

I need to write an application that listen to this event and cancel the operation for some software.

答:
You don't need an app to disable installs based on MSI setups. See DisableMsi policy:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa369784(v=vs.85).aspx

Setups built with other tools (that build non-MSI setups) can't really be detected because they're just applications that do things to the system, just like any other application, so there isn't really a way to stop them.

Title: Hook on Windows Installer messages


问:
Semantic UI menu - disappearing on click
I have a semantic-UI lefside menu that I want to be persistent. I am trying to make 2 states -  a wide one with type for each item, and a compact one with an image for each item.
Currently there are a few issues that I am totally stumped on!

1) Why does the menu completely go away on click?

2) How can I make the page NOT do dim?

3) Can the page collapse in width instead of getting pushed to the right?

4) is it possible to have two menu states, as described, and toggle between them on click?

Thank you very much!
My site is here: http://itp.evejweinberg.com/left/

And my html:

```<code>    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="semantic/semantic.min.css">

        <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js"></script>
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">

        <script src="https://code.jquery.com/jquery-3.1.1.min.js"
          integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
          crossorigin="anonymous"></script>

          <!-- my json of content -->
          <script type="text/javascript" src="list.js"></script>
          <!-- jQuery to build that content -->
          <script type="text/javascript" src="buildScene.js"></script>

        <script src="semantic/semantic.min.js"></script>

      </head>
<!--//do I need this class? -->
      <body class="pushable">

    <!-- semantic says to put everything in pusher -->
    <div class="pusher">

      <div class="all">

          <div id="main"></div>

          <div class="title-holder">
            <div class="animatedDiv"></div>
          </div>

            <div class='container'>
                <div class='header'></div>
                <div class="all-books"></div>
            </div>
      </div>

      </div>

    <!-- menu -->
    <div class="ui vertical left labeled menu fixed small sidebar">
        <div class="header link item" onclick="scrollTo(captology)">Intro</div>
      <div class="item">
        <div class="header link item">Emotions</div>
        <div class="menu">
          <a class="item link" onclick="scrollTo(hope)">Hope</a>
          <a class="item link" onclick="scrollTo(anxiety)">Anxiety</a>
          <a class="item link" onclick="scrollTo(fear)">Fear</a>
        </div>
      </div>
      <div class="item">
        <div class="header link item">Psychology</div>
        <div class="menu">
          <a class="item link" onclick="scrollTo(transparency)">Transparency</a>
          <a class="item link" onclick="scrollTo(loss)">Loss Aversion</a>
          <a class="item link" onclick="scrollTo(dark)">Dark Patterns</a>
          <a class="item link" onclick="scrollTo(social)">Social Pressure</a>
        </div>
      </div>
      <div class="item">
        <div class="header link" onclick="scrollTo(fogg)">Fogg</div>
        <div class="menu">
          <a class="item link" onclick="scrollTo(motivation)">Motivation</a>
          <a class="item link" onclick="scrollTo(ability)">Ability</a>
          <a class="item link" onclick="scrollTo(trigger)">Trigger</a>
        </div>
      </div>
      <div class="item">
        <div class="header link" onclick="scrollTo(flow)">Flow</div>
        <div class="menu">
          <a class="item link" onclick="scrollTo(chunking)">Chunking</a>
          <!-- <a class="item">FAQs</a> -->
        </div>
      </div>
      <div class="item">
        <div class="header">Ethics</div>
        <div class="menu">
          <div class="nav-rect" id="e"></div>
          <div class="nav-rect" id="e"></div>
          <div class="nav-rect" id="e"></div>
          <div class="nav-rect" id="e"></div>
        </div>
        <div class="header link" onclick="scrollTo(sources)">Sources</div>

      </div>
        <div class="header">About</div>
        <div class="ui category search item">
          <div class="ui transparent icon input">
            <input class="prompt" type="text" placeholder="Search...">
            <i class="search link icon"></i>
          </div>
          <div class="results"></div>
        </div>
      </div>

    </div>

        <script type="text/javascript" src="content.js"></script>

        <script type="text/javascript" src="sketch.js"></script>
        <script type="text/javascript" src="js/intro.js"></script>
        <script type="text/javascript" src="js/hope.js"></script>
        <script type="text/javascript" src="js/lossAversion.js"></script>

        <script type="text/javascript">

        $('.sidebar').sidebar('show');

      //   $('.sidebar')
      // .visibility({
      //   type   : 'fixed',
      //   offset : 45 // give some space from top of screen
      // });

        // $('.menu').click(function(){
        //   $('.ui.labeled.icon.sidebar').sidebar('toggle');
        //
        // })

        // $('.ui.sidebar').click(function(){
        //   sidebar('toggle');
        // })

        </script>

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

答: Mystery solved! Semantic-UI was dynamically adding to my html on build. I removed the class 'sidebar' and all pusher and dimmer css went away. That solves #1 and #2. For the rest, i'm just going to go back to jQuery animations to slide the left nav to the left and collapse it's width. Thx All!</p>

Body:
I have a semantic-UI lefside menu that I want to be persistent. I am trying to make 2 states -  a wide one with type for each item, and a compact one with an image for each item.
Currently there are a few issues that I am totally stumped on!

1) Why does the menu completely go away on click?

2) How can I make the page NOT do dim?

3) Can the page collapse in width instead of getting pushed to the right?

4) is it possible to have two menu states, as described, and toggle between them on click?

Thank you very much!
My site is here: http://itp.evejweinberg.com/left/

And my html:

        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="semantic/semantic.min.css">

        <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">

Intro

Emotions

          Hope
          Anxiety
          Fear

Psychology

          Transparency
          Loss Aversion
          Dark Patterns
          Social Pressure

Fogg

          Motivation
          Ability
          Trigger

Flow

          Chunking

Ethics

Sources

About

            <input class="prompt" type="text" placeholder="Search...">


问:
How to import data from csv to models using django-import-export?
I've  made some researches about django-import-export, but the most of example I have found are using django admin..
I'm trying  to import  data to a django model from my template (when clicking on a button a modal appears to choose file location and then submit ),

I feel lost and I don't know how to start..

This is the model I have :

```<code>class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)
</code>```

could someone guide me by giving the steps to follow ?

Thanks in advance !

答:
I have not used django-import-export but writing a view for CSV generation is not difficult using python's built-in csv module.

Django docs also have a section on outputting csv.

Following is a snippet based on example provided in docs:

```<code>import csv
from django.http import HttpResponse
from django.views.generic import View

class CsvExportView(View):

    def get(self, request):
        # create a response object
        response = HttpResponse(content_type='text/csv')
        # assign a filename for csv
        response['Content-Disposition'] = 'attachment; filename="{}"'.format("filename.csv")
        wr = csv.writer(response, dialect='excel')
        # get queryset
        queryset = Musician.objects.all()
        # write every queryset to response object
        for obj in queryset:
            row = [obj.first_name, obj.last_name, obj.instrument]
            wr.writerow(row)
        # return response object
        return response
</code>```

Body:
I've  made some researches about django-import-export, but the most of example I have found are using django admin..
I'm trying  to import  data to a django model from my template (when clicking on a button a modal appears to choose file location and then submit ),

I feel lost and I don't know how to start..

This is the model I have :

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

could someone guide me by giving the steps to follow ?

Thanks in advance !

Body:
I have not used django-import-export but writing a view for CSV generation is not difficult using python's built-in csv module.

Django docs also have a section on outputting csv.

Following is a snippet based on example provided in docs:

import csv
from django.http import HttpResponse
from django.views.generic import View

class CsvExportView(View):

    def get(self, request):
        # create a response object
        response = HttpResponse(content_type='text/csv')
        # assign a filename for csv
        response['Content-Disposition'] = 'attachment; filename="{}"'.format("filename.csv")
        wr = csv.writer(response, dialect='excel')
        # get queryset
        queryset = Musician.objects.all()
        # write every queryset to response object
        for obj in queryset:
            row = [obj.first_name, obj.last_name, obj.instrument]
            wr.writerow(row)
        # return response object
        return response


问:
How to get database value not related to the event in Cloud Functions for Firebase?
I have a firebase database and I am currently trying to use cloud functions to perform an operation when a value in my database changes. So far, it successfully triggers code to run when the value in my database changes. However, when the database value changes, I now need to check another value to determine it's status, and then perform an action after that. The problem is that I have ~0 experience with JS and I have no way of debugging my code other than deploying, changing the value in my database, and looking at the console log.

Is there any way to look up another value in the database and read it? How about look up a value and then set a value for it? Here is the code:

exports.determineCompletion =

```<code>functions.database.ref('/Jobs/{pushId}/client_job_complete')
    .onWrite(event => {

        const status = event.data.val();
        const other = functions.database.ref('/Jobs/' + event.params.pushId + '/other_job_complete');
        console.log('Status', status, other);

        if(status == true && **other.getValueSomehow** == true) {
            return **setAnotherValue**;
        }

    });
</code>```

This code partially works, it successfully gets the value associated with client_job_complete and stores it in status. But how do I get the other value?

Additionally, if anyone has any JS or firebase documentation that they think would help me, please share! I have read a bunch on firebase here : https://firebase.google.com/docs/functions/database-events but it only talks about events and is very brief

Thank you for your help!

答:
You have to wait on the promise from a once() on the new ref, something like:

```<code>exports.processJob = functions.database.ref('/Jobs/{pushId}/client_job_complete')
  .onWrite(event => {

    const status = event.data.val();
    const ref = event.data.adminRef.root.child('Jobs/'+event.params.pushId+'/other_job_complete');
    ref.once('value').then(function(snap){
      const other = snap.val();
      console.log('Status', status, other);
      if(status && other) {
        return other;
      }
    });
  });
</code>```

Edit to fix the error that @Doug Stevenson noticed (I did say "something like")

Body:
I have a firebase database and I am currently trying to use cloud functions to perform an operation when a value in my database changes. So far, it successfully triggers code to run when the value in my database changes. However, when the database value changes, I now need to check another value to determine it's status, and then perform an action after that. The problem is that I have ~0 experience with JS and I have no way of debugging my code other than deploying, changing the value in my database, and looking at the console log.

Is there any way to look up another value in the database and read it? How about look up a value and then set a value for it? Here is the code:

exports.determineCompletion =

functions.database.ref('/Jobs/{pushId}/client_job_complete')
    .onWrite(event => {

        const status = event.data.val();
        const other = functions.database.ref('/Jobs/' + event.params.pushId + '/other_job_complete');
        console.log('Status', status, other);

        if(status == true && **other.getValueSomehow** == true) {
            return **setAnotherValue**;
        }

    });

This code partially works, it successfully gets the value associated with client_job_complete and stores it in status. But how do I get the other value?

Additionally, if anyone has any JS or firebase documentation that they think would help me, please share! I have read a bunch on firebase here : https://firebase.google.com/docs/functions/database-events but it only talks about events and is very brief

Thank you for your help!

Body:
You have to wait on the promise from a once() on the new ref, something like:

exports.processJob = functions.database.ref('/Jobs/{pushId}/client_job_complete')
  .onWrite(event => {

    const status = event.data.val();
    const ref = event.data.adminRef.root.child('Jobs/'+event.params.pushId+'/other_job_complete');
    ref.once('value').then(function(snap){
      const other = snap.val();
      console.log('Status', status, other);
      if(status && other) {
        return other;
      }
    });
  });

Edit to fix the error that @Doug Stevenson noticed (I did say "something like")


问:
How to print an equation in Ruby
I've got a question.

```<code>1.0X + 1.0Y + -7.0 = 0
</code>```

How can I print an equation better?

For example, instead of +- 7.0 I'd like to print -7.0; or in a case with zero coefficients.

Thanks

答:
With a few substitutions, you could achieve a much cleaner equation :

```<code>equation = "1.0X + 1.0Y - -0.0Z + -7.0 = 0"

new_equation = equation.gsub('+ -', '- ')
                       .gsub('- -', '+ ')
                       .gsub(/^\s*\+/, '')             # Remove leading +
                       .gsub(/(?<=\d)\.0+(?=\D)/, '')  # Remove trailing zeroes
                       .gsub(/\b1(?=[a-z])/i, '')      # Remove 1 in 1X
                       .gsub(/[+-]? ?0[a-z] ?/i, '')   # Remove 0Z

p new_equation

# "X + Y - 7 = 0"
</code>```

By the way, as much as I love Ruby, I must say that Sympy is an awesome project. This library alone makes it worthwhile to learn the basic Python syntax.

Title: How to print an equation in Ruby

Body:
I've got a question.

1.0X + 1.0Y + -7.0 = 0

How can I print an equation better?

For example, instead of +- 7.0 I'd like to print -7.0; or in a case with zero coefficients.

Thanks

Body:
With a few substitutions, you could achieve a much cleaner equation :

equation = "1.0X + 1.0Y - -0.0Z + -7.0 = 0"

new_equation = equation.gsub('+ -', '- ')
                       .gsub('- -', '+ ')
                       .gsub(/^\s*\+/, '')             # Remove leading +
                       .gsub(/(?<=\d)\.0+(?=\D)/, '')  # Remove trailing zeroes
                       .gsub(/\b1(?=[a-z])/i, '')      # Remove 1 in 1X
                       .gsub(/[+-]? ?0[a-z] ?/i, '')   # Remove 0Z

p new_equation

# "X + Y - 7 = 0"

By the way, as much as I love Ruby, I must say that Sympy is an awesome project. This library alone makes it worthwhile to learn the basic Python syntax.


问:
Detect resizing in Widget-window resized signal
I create a simple UI with Qt Designer and convert it to Python codes. I searched for any method to detect changing window size.

This is the generated code :

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def onResize(event):
        print(event)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowTitle("MainWindow")
        MainWindow.resize(200, 200)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)

        MainWindow.resized.connect(self.someFunction)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

I found a similar question QWidget resize signal? and this tutorial to handle size that recommended overriding resizeEvent method of QMainWindow.

But any of them doesn't solve my problem. Is there any resized function to detect window resizing like below:

```<code>MainWindow.resized.connect(self.someFunction)
</code>```

答:
There is no such signal by default, but you can create the resized signal, we emit it in the resizeEvent function.

For Example:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowTitle("MainWindow")
        MainWindow.resize(200, 200)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

class Window(QtWidgets.QMainWindow):
    resized = QtCore.pyqtSignal()
    def  __init__(self, parent=None):
        super(Window, self).__init__(parent=parent)
        ui = Ui_MainWindow()
        ui.setupUi(self)
        self.resized.connect(self.someFunction)

    def resizeEvent(self, event):
        self.resized.emit()
        return super(Window, self).resizeEvent(event)

    def someFunction(self):
        print("someFunction")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())
</code>```

Body:
I create a simple UI with Qt Designer and convert it to Python codes. I searched for any method to detect changing window size.

This is the generated code :

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def onResize(event):
        print(event)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowTitle("MainWindow")
        MainWindow.resize(200, 200)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)

        MainWindow.resized.connect(self.someFunction)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

I found a similar question QWidget resize signal? and this tutorial to handle size that recommended overriding resizeEvent method of QMainWindow.

But any of them doesn't solve my problem. Is there any resized function to detect window resizing like below:

MainWindow.resized.connect(self.someFunction)

Body:
There is no such signal by default, but you can create the resized signal, we emit it in the resizeEvent function.

For Example:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowTitle("MainWindow")
        MainWindow.resize(200, 200)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

class Window(QtWidgets.QMainWindow):
    resized = QtCore.pyqtSignal()
    def  __init__(self, parent=None):
        super(Window, self).__init__(parent=parent)
        ui = Ui_MainWindow()
        ui.setupUi(self)
        self.resized.connect(self.someFunction)

    def resizeEvent(self, event):
        self.resized.emit()
        return super(Window, self).resizeEvent(event)

    def someFunction(self):
        print("someFunction")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())


问:
mb_strtolower not working
I have the following string:

```<code>$var = "RUA TANGARA"
</code>```

And I'm doing:

```<code>echo mb_strtolower(preg_replace('/[^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $var)), 'UTF-8');
</code>```

But this still returning "RUA TANGARA".

I use the preg_replace() because $var can be "RÜÁ TÃNAGARA".

Can someone help me?

答:
PHP's functions work very well, take a look at this simple demonstration:

```<code><?php
$data = "RUA TANGARA";
$result = mb_strtolower($data);
var_dump($result);
</code>```

The obvious output is:

string(11) "rua tangara"

The same works with non ascii characters:

```<code><?php
$data = 'RÜÁ TÃNAGARA';
$result = mb_strtolower($data);
var_dump($result);
</code>```

The output of that is:

string(15) "rüá tãnagara"

Title: mb_strtolower not working

Body:
I have the following string:

$var = "RUA TANGARA"

And I'm doing:

echo mb_strtolower(preg_replace('/[^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $var)), 'UTF-8');

But this still returning "RUA TANGARA".

I use the preg_replace() because $var can be "RÜÁ TÃNAGARA".

Can someone help me?

Body:
PHP's functions work very well, take a look at this simple demonstration:

<?php
$data = "RUA TANGARA";
$result = mb_strtolower($data);
var_dump($result);

The obvious output is:

string(11) "rua tangara"

The same works with non ascii characters:

<?php
$data = 'RÜÁ TÃNAGARA';
$result = mb_strtolower($data);
var_dump($result);

The output of that is:

string(15) "rüá tãnagara"


问:
how can I select only all done Task in MYSQL?
I am doing a simple task in MYSQL . As Example , There is Jib(jobId) and subjid(subJobId) and UL. SubJobId is a Id refereed to JOBID and each SubJID has a ul field , I Only need those  JID(JobId) whose UL is 1, if there is even 1 UL is 0. then it'll ignore.

please check the image
enter image description here

答:
You can do this easily with a sub query.  These two will to the trick.

```<code>select *
  from your_schema.your_table a
  left join (select *
               from your_schema.your_table
              where ul = 0) b
    on b.jid = a.jid
 where b.jid is null;
</code>```

OR

```<code>select *
  from your_schema.your_table
 where jid not in (select jid
                     from your_schema.your_table
                    where ul = 0);
</code>```

Body:
You can do this easily with a sub query.  These two will to the trick.

select *
  from your_schema.your_table a
  left join (select *
               from your_schema.your_table
              where ul = 0) b
    on b.jid = a.jid
 where b.jid is null;

OR

select *
  from your_schema.your_table
 where jid not in (select jid
                     from your_schema.your_table
                    where ul = 0);