问:
Need Help Clearing elements in a dialog box AngularJS
I have an AngularJS SPA and one of the pages is a Search page, on the Search page there is a Button called Vendor(s) if I click on the Vendor(s) button a dialog box opens. So far so good.

In the dialog box there is an input field (input ng-model="vendorSearchBy") and a table that display a list of vendors based on what you enter in the input text field.  As soon as you start typing (after 2 characters), the table is loaded with results, with Vendors that match the letters you entered with the vendor name.  Still with me?

Now, the table has three columns; the first column is an input field (check box) to select the vendor (input type="checkbox" ng-init="action=hasVendor(rec_)" ng-model="action" ng-change="vendorSelected(action, rec_)"), the second column is the name of the vendor, and the third column is the description of the vendor.

On the dialog box there are also 3 buttons; OK, Close, and Clear.  On the Clear button is where I need help with.  When I click the Clear button I want this to happens:

Clear the input text field.

Clear the input check boxes from (if they were checked) checked to unchecked.

Clear the table and have no results.

Pretty much clear everything on the dialog box and have an empty input field and an empty table with no results.

Here is the HTML

```<code><div id="selectVendorsBox" title="Select Vendors" class="content">
    <div style="margin-bottom: 5px; font-size: 13px; float: left;">
        <label>Search for </label>
        <input ng-model="vendorSearchBy" class="dialog-input" placeholder="Vendor (min 3 letters)">
    </div>
    <div style="width: calc(100% - 270px); float: right;">
        <span style="font-size: 10px; line-height: normal;" ng-repeat="(k,v) in vendors">{{v.shortName}}, </span>
    </div>
    <div class="clear"></div>
    <div class="ui-jqgrid" style="border: solid 1px gray; border-radius: 5px; font-size: 13px;">
        <div class="header" style="text-align: left;">
            Search Results:
        </div>
        <div id="searchGridBox" style="display: block; visibility: visible; height: 450px;">
            <table cellpadding="0" cellspacing="0" style="width: 100%;">
                <thead style="width: 100%;">
                    <tr style="width: 100%;">
                        <th style="width: 50px;">Select</th>
                        <th style="width: 300px;">Vendor Name</th>
                        <th style="width: calc(100% - 350px);">Description</th>
                    </tr>
                </thead>
                <tbody style="width: 100%;">
                    <tr ng-repeat="rec_ in vsearchresults.content" style="width: 100%;">
                        <td>
                            <input type="checkbox" ng-init="action=hasVendor(rec_)" ng-model="action" ng-change="vendorSelected(action, rec_)"/>
                        </td>
                        <td style="overflow-x: hidden;">{{rec_.shortName}}</td>
                        <td style="overflow-x: hidden;">{{rec_.longDescription}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="cs-pagination">
            <div style="width: 200px; height: 20px; margin: 0px auto;">
                <div style="float: left; padding-right: 4px;">
                    <span class="ui-icon ui-icon-seek-first" ng-click="vpage=1" ng-class="{disabled:(vsearchresults.first)}"></span>
                    <span class="ui-icon ui-icon-seek-prev" ng-click="vpreviousPage()" ng-class="{disabled:(vsearchresults.first)}"></span>
                </div>
                <div style="float: left; padding: 0px 4px; border-left: solid 1px gray; border-right: solid 1px gray;">
                    Page: {{vpage}} of {{vsearchresults.totalPages}}
                </div>
                <div style="float: left; padding-left: 4px;">
                    <span class="ui-icon ui-icon-seek-next"
                        ng-click="vnextPage()" ng-class="{disabled:(vsearchresults.last)}"></span>
                    <span class="ui-icon ui-icon-seek-end"
                        ng-click="vpage=vsearchresults.totalPages" ng-class="{disabled:(vsearchresults.last)}"></span>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

And here is the JS

```<code>$scope.vendorSearchBy = null;
$scope.vsearchresults = null;
$scope.vpage = 1;
$scope.vendorsDialog = $('#selectVendorsBox');

/** this code is for the Vendor's dialog pop-up window **/
$scope.vendorsDialog.dialog({
    width: 1100,
    height: window.innerHeight * 0.71,
    resizable: false,
    autoOpen: false,
    modal: true,
    buttons: {
        "OK" : function() {
            $( this ).dialog( "close" );
        },
        "CANCEL" : function( ){
            $( this ).dialog( "close" );
        },
        "CLEAR" : function() {
            console.log('I am here and I need Help!!');
        }
    },
    close: function(e, ui) {
    }
});
/** this function opens the Vendor's dialog pop-up **/
$scope.selectVendors = function() {
    $scope.vendorsDialog.dialog('open');
};
$scope.vpreviousPage = function() {
    if( $scope.vsearchresults ) {
        if( !$scope.vsearchresults.first ) {
            $scope.vpage--;
        }
    }
};
$scope.vnextPage = function() {
    if( $scope.vsearchresults ) {
        if( !$scope.vsearchresults.last ) {
            $scope.vpage++;
        }
    }
};
$scope.vendorSearch = function() {
    if( $scope.vendorSearchBy && $scope.vendorSearchBy.length > 2 ) {
        var vendors = $lookupSvc.Vendors({shortName: $scope.vendorSearchBy}, 20, $scope.vpage-1);
        vendors.$promise.then(function(d) {
            if( d ) {
                $scope.vsearchresults = d;
            }
        });
    }
};
$scope.$watch('vendorSearchBy', function(nv, ov) {
    if( nv ) {
        $scope.vendorSearch();
    }
});
$scope.$watch('vpage', function(nv, ov) {
    if( $scope.vpage ) {
        if( $scope.vpage !== ov ) {
            if( $scope.vsearchresults ) {
                if( $scope.vpage < $scope.vsearchresults.totalPages + 1 ) {
                    $scope.vendorSearch();
                }
                else {
                    console.log('Page out of range.');
                }
            }
        }
    }
});
$scope.hasVendor = function(v) {
    let h = false;
    if( v ) {
        let keys = Object.keys($scope.vendors);
        h = keys.includes(v.shortName);
    }
    return h;
}
$scope.vendorSelected = function(a, v) {
    if( a ) {
        $scope.vendors[v.shortName] = v;
    }
    else {
        delete $scope.vendors[v.shortName];
    }
};
</code>```

I really hope that you guys can help me with this.

答:
```<code>"CLEAR" : function() {
            console.log('I am here and I need Help!!');
        }
</code>```

Something like this:

```<code>$scope.vendorSearchBy = "";
//If the vendor flag is being persisted then unset the flag for each one
//if it's not then this for loop is redundant

for(var i = 0; i < $scope.vsearchresults.content.length; i++){
var currentResult = $scope.vsearchresults.content[i];
//Ensure each listed vendor has its flag set to false
currentResult.action = false;
};

//Set the search results content to an empty object to clear the table
$scope.vsearchresults.content = {};
</code>```

Body:
I have an AngularJS SPA and one of the pages is a Search page, on the Search page there is a Button called Vendor(s) if I click on the Vendor(s) button a dialog box opens. So far so good.

In the dialog box there is an input field (input ng-model="vendorSearchBy") and a table that display a list of vendors based on what you enter in the input text field.  As soon as you start typing (after 2 characters), the table is loaded with results, with Vendors that match the letters you entered with the vendor name.  Still with me?

Now, the table has three columns; the first column is an input field (check box) to select the vendor (input type="checkbox" ng-init="action=hasVendor(rec_)" ng-model="action" ng-change="vendorSelected(action, rec_)"), the second column is the name of the vendor, and the third column is the description of the vendor.

On the dialog box there are also 3 buttons; OK, Close, and Clear.  On the Clear button is where I need help with.  When I click the Clear button I want this to happens:

Clear the input text field.

Clear the input check boxes from (if they were checked) checked to unchecked.

Clear the table and have no results.

Pretty much clear everything on the dialog box and have an empty input field and an empty table with no results.

Here is the HTML

        Search for
        <input ng-model="vendorSearchBy" class="dialog-input" placeholder="Vendor (min 3 letters)">

        {{v.shortName}},

            Search Results:

                        Select
                        Vendor Name
                        Description

                            <input type="checkbox" ng-init="action=hasVendor(rec_)" ng-model="action" ng-change="vendorSelected(action, rec_)"/>

                        {{rec_.shortName}}
                        {{rec_.longDescription}}

                    Page: {{vpage}} of {{vsearchresults.totalPages}}

And here is the JS

$scope.vendorSearchBy = null;
$scope.vsearchresults = null;
$scope.vpage = 1;
$scope.vendorsDialog = $('#selectVendorsBox');

/** this code is for the Vendor's dialog pop-up window **/
$scope.vendorsDialog.dialog({
    width: 1100,
    height: window.innerHeight * 0.71,
    resizable: false,
    autoOpen: false,
    modal: true,
    buttons: {
        "OK" : function() {
            $( this ).dialog( "close" );
        },
        "CANCEL" : function( ){
            $( this ).dialog( "close" );
        },
        "CLEAR" : function() {
            console.log('I am here and I need Help!!');
        }
    },
    close: function(e, ui) {
    }
});
/** this function opens the Vendor's dialog pop-up **/
$scope.selectVendors = function() {
    $scope.vendorsDialog.dialog('open');
};
$scope.vpreviousPage = function() {
    if( $scope.vsearchresults ) {
        if( !$scope.vsearchresults.first ) {
            $scope.vpage--;
        }
    }
};
$scope.vnextPage = function() {
    if( $scope.vsearchresults ) {
        if( !$scope.vsearchresults.last ) {
            $scope.vpage++;
        }
    }
};
$scope.vendorSearch = function() {
    if( $scope.vendorSearchBy && $scope.vendorSearchBy.length > 2 ) {
        var vendors = $lookupSvc.Vendors({shortName: $scope.vendorSearchBy}, 20, $scope.vpage-1);
        vendors.$promise.then(function(d) {
            if( d ) {
                $scope.vsearchresults = d;
            }
        });
    }
};
$scope.$watch('vendorSearchBy', function(nv, ov) {
    if( nv ) {
        $scope.vendorSearch();
    }
});
$scope.$watch('vpage', function(nv, ov) {
    if( $scope.vpage ) {
        if( $scope.vpage !== ov ) {
            if( $scope.vsearchresults ) {
                if( $scope.vpage < $scope.vsearchresults.totalPages + 1 ) {
                    $scope.vendorSearch();
                }
                else {
                    console.log('Page out of range.');
                }
            }
        }
    }
});
$scope.hasVendor = function(v) {
    let h = false;
    if( v ) {
        let keys = Object.keys($scope.vendors);
        h = keys.includes(v.shortName);
    }
    return h;
}
$scope.vendorSelected = function(a, v) {
    if( a ) {
        $scope.vendors[v.shortName] = v;
    }
    else {
        delete $scope.vendors[v.shortName];
    }
};

I really hope that you guys can help me with this.

Body:
"CLEAR" : function() {
            console.log('I am here and I need Help!!');
        }

Something like this:

$scope.vendorSearchBy = "";
//If the vendor flag is being persisted then unset the flag for each one
//if it's not then this for loop is redundant

for(var i = 0; i < $scope.vsearchresults.content.length; i++){
var currentResult = $scope.vsearchresults.content[i];
//Ensure each listed vendor has its flag set to false
currentResult.action = false;
};

//Set the search results content to an empty object to clear the table
$scope.vsearchresults.content = {};


来源: stackexchange

问:
Can't create share link using dropbox javascript sdk
I'm trying to create a shareable link using dropbox api, but the function that I used doesn't return anything.</p>

```<code> var ACCESS_TOKEN = "access_token";
 var SHARED_LINK = "/example/example.doc";
 var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
 var x = dbx.SharingCreateSharedLink({path: SHARED_LINK});
 alert(x);
</code>```

答:
The Dropbox JavaScript SDK returns the API call results asynchronously, not in the return value of the method call.

You can see an example of how to set up the callbacks for the result and error, using then and catch, respectively, here:

https://github.com/dropbox/dropbox-sdk-js/blob/master/examples/javascript/basic/index.html#L54

So, for example, your code should look something like this:

```<code>var ACCESS_TOKEN = "access_token";
var filePath = "/example/example.doc";

var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
dbx.sharingCreateSharedLinkWithSettings({path: filePath})
.then(function(response) {
   console.log(response);
 })
 .catch(function(error) {
   console.log(error);
 });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a shareable link using dropbox api, but the function that I used doesn't return anything.

 var ACCESS_TOKEN = "access_token";
 var SHARED_LINK = "/example/example.doc";
 var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
 var x = dbx.SharingCreateSharedLink({path: SHARED_LINK});
 alert(x);

Body:
The Dropbox JavaScript SDK returns the API call results asynchronously, not in the return value of the method call.

You can see an example of how to set up the callbacks for the result and error, using then and catch, respectively, here:

https://github.com/dropbox/dropbox-sdk-js/blob/master/examples/javascript/basic/index.html#L54

So, for example, your code should look something like this:

var ACCESS_TOKEN = "access_token";
var filePath = "/example/example.doc";

var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
dbx.sharingCreateSharedLinkWithSettings({path: filePath})
.then(function(response) {
   console.log(response);
 })
 .catch(function(error) {
   console.log(error);
 });


问:
Is there a way to identify what is Caching a particular file?
I am having a  prolonged issue with the Cart file, on an ecommerce website I am working on.  The WordPress powered website, is using WooCommerce as the preferred shopping platform.  Simply, the Cart file is being Cached by the Browser and I cannot seem to prevent this.

I have tried many avenues but to no success.  Is there a way to identify what is caching the 'cart.php' file, in a bid to narrow down my focus on where the problem(s) could lie?  I have no Caching Plugins, my hosting provider has stated there are no server side caching resources, there are no issues with the theme and I have not modified the '.htaccess' file, to cache any files.

Hopefully, knowing what is causing the Caching, will help resolve the problem.

答:
I have resolved the problem.  I totally forgot I placed the following Caching Code into my .htaccess file.  As soon as the below code was removed, the problem was resolved.

```<code>## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
</code>```

Body:
I have resolved the problem.  I totally forgot I placed the following Caching Code into my .htaccess file.  As soon as the below code was removed, the problem was resolved.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##


问:
Extract img tag source from string [Nodejs]
I have a string that looks like this

ANSA McAl sends 5 containers of relief items  Trinidad News
Full coverage

What I would like to do is extract the source of the image tag. Any suggestions as to where to start to accomplish this?

答:
You could use .split(), which is a very helpful method when trying to extract relevant data from a string:

```<code>'<table border="0" cellpadding="2" cellspacing="3"><tr><td><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRO8iLLBmxFL2lvSfboTwwmH3yGF12PdsJe56rTAzJtbsFfS07I1YM_ZzavbwJREe7bUmhFR3ATyA" border="1"></td><td><ol style="list-style: none; margin: 0; padding: 0;"><strong><li><a href="http://newsday.co.tt/2017/11/14/ansa-mcal-sends-5-containers-of-relief-items/" target="_blank">ANSA McAl sends 5 containers of relief items</a>  <font color="#6f6f6f">Trinidad News</font></li></strong><a href="https://news.google.com/story/?hl=en&ned=us" target="_blank">Full coverage</a></ol></td></tr></table>'
  .split('src="')[1]
  .split('"')[0]
</code>```

Essentially, this does the following:

Splits the string into an array based on the substring src="

Splits the second item in that array into a new array, based on the substring "

Returns the first element in that array.

There are certainly other ways to do this as well (for instance, regex).

Body:
You could use .split(), which is a very helpful method when trying to extract relevant data from a string:

'<table border="0" cellpadding="2" cellspacing="3"><tr><td><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRO8iLLBmxFL2lvSfboTwwmH3yGF12PdsJe56rTAzJtbsFfS07I1YM_ZzavbwJREe7bUmhFR3ATyA" border="1"></td><td><ol style="list-style: none; margin: 0; padding: 0;"><strong><li><a href="http://newsday.co.tt/2017/11/14/ansa-mcal-sends-5-containers-of-relief-items/" target="_blank">ANSA McAl sends 5 containers of relief items</a>&nbsp;&nbsp;<font color="#6f6f6f">Trinidad News</font></li></strong><a href="https://news.google.com/story/?hl=en&ned=us" target="_blank">Full coverage</a></ol></td></tr></table>'
  .split('src="')[1]
  .split('"')[0]

Essentially, this does the following:

Splits the string into an array based on the substring src="

Splits the second item in that array into a new array, based on the substring "

Returns the first element in that array.

There are certainly other ways to do this as well (for instance, regex).


问:
Adding elements to a collection during iteration
Is it possible to add elements to a collection while iterating over it?

More specifically, I would like to iterate over a collection, and if an element satisfies a certain condition I want to add some other elements to the collection, and make sure that these added elements are iterated over as well.  (I realise that this could lead to an unterminating loop, but I'm pretty sure it won't in my case.)

The Java Tutorial from Sun suggests this is not possible: "Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."

So if I can't do what I want to do using iterators, what do you suggest I do?

答:
Use ListIterator as follows:

```<code>List<String> l = new ArrayList<>();
l.add("Foo");
ListIterator<String> iter = l.listIterator(l.size());
while(iter.hasPrevious()){
    String prev=iter.previous();
    if(true /*You condition here*/){
        iter.add("Bah");
        iter.add("Etc");
    }
}
</code>```

The key is to iterate in reverse order - then the added elements appear on the next iteration.

ContentLicense: CC BY-SA 4.0

Body:
Use ListIterator as follows:

List<String> l = new ArrayList<>();
l.add("Foo");
ListIterator<String> iter = l.listIterator(l.size());
while(iter.hasPrevious()){
    String prev=iter.previous();
    if(true /*You condition here*/){
        iter.add("Bah");
        iter.add("Etc");
    }
}

The key is to iterate in reverse order - then the added elements appear on the next iteration.


问:
Dynamically change CSS flex order via JavaScript based on user event order
I have an application that has a  selection list of items that will dynamically open in an
 area.  Each item is defined as a
 in the
 area with display:none, until each is activated by a JavaScript function as the user clicks selections in the .  As they appear in the
 area, they show up in the sequence they are defined in the
.  The salient and somewhat pseudo parts of the code are shown below.

I would like each div to show up in the sequence that the user clicks, and not in the sequence the divs are laid out.  So if the user selects item002 then item001, the respective divs would show in the sequence item002, item001.

I've been trying to find a way to do this with flex column layout by dynamically changing the order of the article divs, something like:

```<code>document.getElementById(shID).order = myOrdervar;
</code>```

So far nothing I've tried has worked, and I can't find documentation on flex telling me if this is even possible.  Does anyone have a technique for changing the display sequence of the article divs, with or without flex?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <style>
        body {
            font: 1em Helvetica;
            background: #999999;
        }
        #main {
            min-height: 500px;
            margin: 0;
            padding: 0;
            display: flex;
            flex-flow: column;
        }
        #main > article {
            margin: 4px;
            padding: 5px;
            border: 1px solid #cccc33;
            border-radius: 7pt;
            background: #dddd88;
            height: 600px;
            flex: 3 1 60%;
            order: 2;
            flex-flow: column;
        }
        #main > nav {
            margin: 4px;
            padding: 5px;
            border: 1px solid #8888bb;
            border-radius: 7pt;
            background: #ccccff;
            height: 600px;
            flex: 1 6 20%;
            order: 1;
            overflow: auto;
        }
        header, footer {
            display: block;
            margin: 4px;
            padding: 5px;
            min-height: 100px;
            border: 1px solid #eebb55;
            border-radius: 7pt;
            background: #ffeebb;
            display: -webkit-flex;
            display: flex;
            -webkit-align-items: center;
            align-items: center;
            -webkit-justify-content: center;
            justify-content: center;
        }
        /* Too narrow to support three columns */
        @media all and (max-width: 640px) {
            #main, #page {
                flex-direction: column;
            }
            #main > article, #main > nav, #main > aside {
                /* Return them to document order */
                order: 0;
                flex-direction: column;
            }
            #main > nav, #main > aside, header, footer {
                min-height: 50px;
                max-height: 50px;
            }
        }
    </style>
    <script language="javascript" type="text/javascript">
        var globalOrder = 1;
        function showHide(shID) {
            if (document.getElementById(shID)) {
                if (document.getElementById(shID + '-show').style.display != 'none') {
                    document.getElementById(shID + '-show').style.display = 'none';
                    document.getElementById(shID).style.display = 'flex';
                    document.getElementById(shID).style.order = globalOrder;
                    globalOrder++;
                }
                else {
                    document.getElementById(shID + '-show').style.display = 'inline';
                    document.getElementById(shID).style.display = 'none';
                }
            }
        }
    </script>
    <style type="text/css">
        /* This CSS is used for the Show/Hide functionality. */
        .more {
            display: none;
            border-top: 0px solid #666;
            border-bottom: 0px solid #666;
        }
        .showSquid {
            display: block;
            border-top: 0px solid #666;
            border-bottom: 0px solid #666;
        }
        a.showLink, a.hideLink {
            text-decoration: none;
            font-size: 1.0em;
            font-family: 'MergeLight', Arial, Verdana, Helvetica, sans-serif;
            font-weight: bold;
            padding-left: 0px;
            border-top: 0px solid #666;
            border-bottom: 0px dotted #36f;
        }
        a.hideLink {
            background: transparent url(up.gif) no-repeat left;
        }
        a.showLink:hover, a.hideLink:hover {
            color: white;
        }
    </style>
</head>
<body>
    <header>
        Sources
    </header>
    <div id='main'>
        <nav>
            <a href='#' id='Wilmington Wind-show' class='showLink' onclick='showHide("Wilmington Wind");return false;'>
                Wilmington Wind
            </a><br>
            <a href='#' id='ArtMachine.mp3-show' class='showLink' onclick='showHide("ArtMachine.mp3");return false;'>
                Art Machine
            </a><br>
            <a href='#' id='Breathing-original.mp3-show' class='showLink' onclick='showHide("Breathing-original.mp3");return false;'>
                Breathing
            </a><br>
            <a href='#' id='ToroidMachine-show' class='showLink' onclick='showHide("ToroidMachine");return false;'>
            </a>
        </nav>
        <article>
            <div id='Wilmington Wind' class='more' style="flex-direction: column;">
                Wilmington Wind<br>
            </div>
            <div id='ArtMachine.mp3' class='more' style="flex-direction: column;">
                Art Machine<br>
            </div>
            <div id='Breathing-original.mp3' class='more' style="flex-direction: column;">
                Breathing
            </div> <!-- Breathing-original.mp3 -->
        </article>
        <footer>© 2017</footer>
    </div>
</body>
</html>
</code>```

答:
You miss the .style part in document.getElementById(shID).order=myOrdervar;:

```<code>document.getElementById(shID).style.order=myOrdervar;
</code>```

Body:
I have an application that has a  selection list of items that will dynamically open in an
 area.  Each item is defined as a
 in the
 area with display:none, until each is activated by a JavaScript function as the user clicks selections in the .  As they appear in the
 area, they show up in the sequence they are defined in the
.  The salient and somewhat pseudo parts of the code are shown below.

I would like each div to show up in the sequence that the user clicks, and not in the sequence the divs are laid out.  So if the user selects item002 then item001, the respective divs would show in the sequence item002, item001.

I've been trying to find a way to do this with flex column layout by dynamically changing the order of the article divs, something like:

document.getElementById(shID).order = myOrdervar;

So far nothing I've tried has worked, and I can't find documentation on flex telling me if this is even possible.  Does anyone have a technique for changing the display sequence of the article divs, with or without flex?

<!DOCTYPE html>

        Sources

                Wilmington Wind

                Art Machine

                Breathing

                Wilmington Wind

                Art Machine

                Breathing

        © 2017

Body:
You miss the .style part in document.getElementById(shID).order=myOrdervar;:

document.getElementById(shID).style.order=myOrdervar;


问:
Worst Case Analysis for Regular Expressions
Are there any tools that will take a particular regular expression and return the worst case scenario in terms of the number of operations required for a certain number of characters that the regular expression is matched against?

So for example, given a (f|a)oo.*[ ]baz, how many steps might the engine possibly go though through to match 100 characters?

I would also be interested if there is a tool that can take a bunch of text samples and show the average operations for each run.

I realize this will depend a lot on the engine used and the implementation -- but I am ignorant as to how common this is. So if it is common for many languages (making my question too vague) I would be particularly interested in Perl and Python.

答:
Regexbuddy's debugger shows how many steps engine would take to conclude match or not on a given sample. More information on catastrophic backtracking and debugging regular expressions.

PS: It is not free but they offer a 3-month money-back guarantee.

ContentLicense: CC BY-SA 2.5


问:
GeckoWebBrowser how to mark the Captcha checkbox (C# Windows forms)?
I'm working on a Windows application with GeckoWebBrowser and I'm trying to check the checkbox of a Captcha via code. Programmaticaly I already can get and set html elements, but this checkbox I can't reach. I can't find it in any place in the page.
I'm not trying to decifrate or solve the captcha, just check the checkbox element and after that verify if it is checked. Simple like that.

What I know at the moment:

In the FireFox inspector I can see

Some obvious informations: the captcha is in a iframe with title="widget recaptcha", width=304 and height=78.

The checkbox element is in this point (inside the iframe):

Now, this is how I'm trying to get the checkbox, looking for id, span, div and class in different ways with no success...

First, in the main Document

```<code>            //looking all elements into main Document (around 1300 elements)
            GeckoElementCollection collection = geckoWebBrowser1.Document.GetElementsByTagName("*");
        foreach (GeckoHtmlElement elem in collection)
        {
            string id = elem.Id;
            if (id == "recaptcha-anchor")
            {
                string myId = "this is my ID";         //never find this ID!
            }
            //just for debug
            string LocalName = elem.LocalName;
            string OuterHtml = elem.OuterHtml;
            string TagName = elem.TagName;
            string TextContent = elem.TextContent;
            string role = elem.GetAttribute("role");
            string value = elem.GetAttribute("value");
        }
</code>```

So, in the main Document I can't find anything by ID.

Next, looking into iframe:

```<code>        //get the iframe works well
        foreach (GeckoIFrameElement iframe in geckoWebBrowser1.Document.GetElementsByTagName("iframe"))
        {
            //get main info about the iframe - ok
            string title = iframe.GetAttribute("title");
            if (title != null && title.ToLower().Contains("captcha"))   //got "recaptcha widget"
            {
                int x = iframe.OffsetLeft;
                int y = iframe.OffsetTop;
                int width = Convert.ToInt32(iframe.Width);
                int height = Convert.ToInt32(iframe.Height);
            }

            //inside the iframe, get all elements --> but always return null
            Gecko.Collections.IDomHtmlCollection<GeckoElement> collection2 = iframe.GetElementsByTagName("*");
            foreach (GeckoHtmlElement elem in collection2)
            {
                string id = elem.Id;
                string LocalName = elem.LocalName;
                string OuterHtml = elem.OuterHtml;
                string TagName = elem.TagName;
                string TextContent = elem.TextContent;
                string role = elem.GetAttribute("role");
                string value = elem.GetAttribute("value");
            }

            //foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("*"))             //get no elements
            //foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("input"))         //get no elements
            //foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("div"))           //get no elements
            foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("span"))           //get no elements
            {
                string id = elem.Id;
                string LocalName = elem.LocalName;
                string OuterHtml = elem.OuterHtml;
                string TagName = elem.TagName;
                string TextContent = elem.TextContent;
                string role = elem.GetAttribute("role");
            }
        }
</code>```

So, after a lot of try and error I can't get the checkbox element, but I can get some info about the captcha box, like position and size, although the title is not 100% as I expected: in Firefox the title = "widget recaptcha" and in the GeckoWebbrowser title = "recaptcha widget"... a litle bizarre.

This is driving me crazy... :-(

Anybody has some sugestion what I'm missing or what I'm doing wrong?
There are a way to get all the html elements even in iframes, or the complete element tree?

Is possible to do what I'm trying to do?

Thanks in advance!

答:
To find all iframe elements at the current page use the Frames property of GeckoWindow:

```<code>// this will return a collecton of all frames
var iframes = Browser.Window.Frames;
</code>```

I recomend you to do this in the handler of DocumentCompleted event of your browser.
Then iterate through this frames. Each frame has its own Document element, which is actually a container for all elements inside it. Your captcha should be there. Then you probably want to find the div with checkbox, and click it, so the code will looke like this:

```<code>foreach (var iframe in iframes)
{
    var doc = iframe.Document;
    if (doc == null)
        continue;

    var elements = doc.GetElementsByClassName("your_name");

    foreach (var element in elements)
    {
        // get the div and validate it
        var myDiv = element as GeckoDivElement;
        if(myDiv == null || !myDiv.Id.Equals("your_checkbox_id", StringComparison.InvariantCultureIgnoreCase))
            continue;

        myDiv.Click(); // click your checkbox
        break;
    }
}
</code>```

Body:
I'm working on a Windows application with GeckoWebBrowser and I'm trying to check the checkbox of a Captcha via code. Programmaticaly I already can get and set html elements, but this checkbox I can't reach. I can't find it in any place in the page.
I'm not trying to decifrate or solve the captcha, just check the checkbox element and after that verify if it is checked. Simple like that.

What I know at the moment:

In the FireFox inspector I can see

Some obvious informations: the captcha is in a iframe with title="widget recaptcha", width=304 and height=78.

The checkbox element is in this point (inside the iframe):

Now, this is how I'm trying to get the checkbox, looking for id, span, div and class in different ways with no success...

First, in the main Document

            //looking all elements into main Document (around 1300 elements)
            GeckoElementCollection collection = geckoWebBrowser1.Document.GetElementsByTagName("*");
        foreach (GeckoHtmlElement elem in collection)
        {
            string id = elem.Id;
            if (id == "recaptcha-anchor")
            {
                string myId = "this is my ID";         //never find this ID!
            }
            //just for debug
            string LocalName = elem.LocalName;
            string OuterHtml = elem.OuterHtml;
            string TagName = elem.TagName;
            string TextContent = elem.TextContent;
            string role = elem.GetAttribute("role");
            string value = elem.GetAttribute("value");
        }

So, in the main Document I can't find anything by ID.

Next, looking into iframe:

        //get the iframe works well
        foreach (GeckoIFrameElement iframe in geckoWebBrowser1.Document.GetElementsByTagName("iframe"))
        {
            //get main info about the iframe - ok
            string title = iframe.GetAttribute("title");
            if (title != null && title.ToLower().Contains("captcha"))   //got "recaptcha widget"
            {
                int x = iframe.OffsetLeft;
                int y = iframe.OffsetTop;
                int width = Convert.ToInt32(iframe.Width);
                int height = Convert.ToInt32(iframe.Height);
            }

            //inside the iframe, get all elements --> but always return null
            Gecko.Collections.IDomHtmlCollection<GeckoElement> collection2 = iframe.GetElementsByTagName("*");
            foreach (GeckoHtmlElement elem in collection2)
            {
                string id = elem.Id;
                string LocalName = elem.LocalName;
                string OuterHtml = elem.OuterHtml;
                string TagName = elem.TagName;
                string TextContent = elem.TextContent;
                string role = elem.GetAttribute("role");
                string value = elem.GetAttribute("value");
            }

            //foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("*"))             //get no elements
            //foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("input"))         //get no elements
            //foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("div"))           //get no elements
            foreach (GeckoHtmlElement elem in iframe.GetElementsByTagName("span"))           //get no elements
            {
                string id = elem.Id;
                string LocalName = elem.LocalName;
                string OuterHtml = elem.OuterHtml;
                string TagName = elem.TagName;
                string TextContent = elem.TextContent;
                string role = elem.GetAttribute("role");
            }
        }

So, after a lot of try and error I can't get the checkbox element, but I can get some info about the captcha box, like position and size, although the title is not 100% as I expected: in Firefox the title = "widget recaptcha" and in the GeckoWebbrowser title = "recaptcha widget"... a litle bizarre.

This is driving me crazy... :-(

Anybody has some sugestion what I'm missing or what I'm doing wrong?
There are a way to get all the html elements even in iframes, or the complete element tree?

Is possible to do what I'm trying to do?

Thanks in advance!

Body:
To find all iframe elements at the current page use the Frames property of GeckoWindow:

// this will return a collecton of all frames
var iframes = Browser.Window.Frames;

I recomend you to do this in the handler of DocumentCompleted event of your browser.
Then iterate through this frames. Each frame has its own Document element, which is actually a container for all elements inside it. Your captcha should be there. Then you probably want to find the div with checkbox, and click it, so the code will looke like this:

foreach (var iframe in iframes)
{
    var doc = iframe.Document;
    if (doc == null)
        continue;

    var elements = doc.GetElementsByClassName("your_name");

    foreach (var element in elements)
    {
        // get the div and validate it
        var myDiv = element as GeckoDivElement;
        if(myDiv == null || !myDiv.Id.Equals("your_checkbox_id", StringComparison.InvariantCultureIgnoreCase))
            continue;

        myDiv.Click(); // click your checkbox
        break;
    }
}


问:
Playing sounds sequentially on android's google chrome (given the new restrictions on playing sound)
I have a small app that plays sequential sounds (a teaching app playing the sillables of a word)

This could be accomplished by firing an event right after each sound stopped playing. Something like:

```<code>var sounds = new Array(new Audio("1.mp3"), new Audio("2.mp3"));
var i = -1;
playSnd();

function playSnd() {
   i++;
   if (i == sounds.length) return;
   sounds[i].addEventListener('ended', playSnd);
   sounds[i].play();
}
</code>```

(source)

However, now android chrome has implemented some new restrictions on how to play sound: Sound events must all be fired by a user action.

So, when I run code very similar to the above, the first sound plays, and then I get

```<code>Uncaught (in promise) DOMException: play() can only be initiated by a user gesture.
</code>```

How can a sequence of sounds, determined at run time, be played on Android's Chrome?

答:
To start with, Google Chrome on Android has been having the limitation of not allowing applications to play HTML audio(s) without an explicit action by the user. However, it is different than how stock browser(s), in most cases, handles it.

The reason, as Chromium Org puts it, is that, Autoplay is not honored on android as it will cost data usage.

You may find more details on the same here.

Apart from the fact that this results in wastage of bandwidth, this also makes some sense, since mobile devices are used in public and in houses, where unsolicited sound from random Web sites could be a nuisance.

However, in the later versions, this idea was over ruled and Chrome on Android started allowing autoplay of HTML audios and videos on it. Again after a set of reviews and discussions, this feature was reverted to what it was, making it mandatory for a user action to invoke HTML audios and videos on the Chrome for Android.

Here is something that I found more on the same. As it says, the reason stated was that "We're going to gather some data about how users react to autoplaying videos in order to decide whether to keep this restriction". And hence the playing option without a user action was reverted back.

You can also find more about the blocking of _autoplay of audio(s) and video(s) here on Forbes and The Verge.

However, this is something that I can suggest you to try which will help you achieve what you intend to. All you have to do is copy this code and paste in your Chrome for Android. This helps you reset the flag which is default set to not allowing to play HTML audios and videos without user interaction:

chrome://flags/#disable-gesture-requirement-for-media-playback

OR

about:flags/#disable-gesture-requirement-for-media-playback

If the above procedure doesn't help/work for you, you can do this:

Go into chrome://flags OR about:flags (this will direct you to chrome://flags) and Enable the "Disable gesture requirement for media playback" option (which is actually the same as the above URL specified).

Body:
I have a small app that plays sequential sounds (a teaching app playing the sillables of a word)

This could be accomplished by firing an event right after each sound stopped playing. Something like:

var sounds = new Array(new Audio("1.mp3"), new Audio("2.mp3"));
var i = -1;
playSnd();

function playSnd() {
   i++;
   if (i == sounds.length) return;
   sounds[i].addEventListener('ended', playSnd);
   sounds[i].play();
}

(source)

However, now android chrome has implemented some new restrictions on how to play sound: Sound events must all be fired by a user action.

So, when I run code very similar to the above, the first sound plays, and then I get

Uncaught (in promise) DOMException: play() can only be initiated by a user gesture.

How can a sequence of sounds, determined at run time, be played on Android's Chrome?


问:
custom application form as write mode for normal users in service now
In serviceNow, how to change custom application form as write mode for normal users after i used extended my table from task table

答:
Your question doesn't make a lot of sense, so I'm having a lot of trouble understanding what you're asking.

I don't want to be presumptuous, but it sounds like you're asking about how to change the security on your table so certain users can access it and write to it.

If I'm right, you need to right-click on your form's header, go to Configure->Security Rules, then create ACLs to allow the right users to write to your form. Information on ACLs can be found on the servicenow docs site.


问:
How to write Regex to find stock and Price
```<code>var rawItemInfo={"stock":"In Stock","shipping":"<em>Free Shipping</em>","finalPrice":"56.99","itemInfo":"<div class=\"grpPricing\"><div class=\"wrapper\"><div class=\"current\" id=\"singleFinalPrice\"><span class=\"label\">Now:  </span><span>$</span>56<sup>.99</sup></div></div><div
</code>```

I want to extract two information from above string

1: Stock Status "In Stock" which will come always after "Stock":

2 Price $56.99 which is there

some before....$56.99 some code after....

Please help me out to write regex for these two information.

答:
You can extract these value using this code</p>

```<code>var regPattern = "stock\":\"(.*?)\",\".*?finalPrice\":\"(.*?)\"";
Regex regex = new Regex(regPattern);
var data = regex.Match(contact.Name);
data.Groups[1].Value ///"In stock. Limit 1 per customer."
data.Groups[2].Value ///"549.99"
</code>```

Body:
var rawItemInfo={"stock":"In Stock","shipping":"Free Shipping","finalPrice":"56.99","itemInfo":"

Now:  $56.99

<div

I want to extract two information from above string

1: Stock Status "In Stock" which will come always after "Stock":

2 Price $56.99 which is there

some before....$56.99 some code after....

Please help me out to write regex for these two information.

Body:
You can extract these value using this code

var regPattern = "stock\":\"(.*?)\",\".*?finalPrice\":\"(.*?)\"";
Regex regex = new Regex(regPattern);
var data = regex.Match(contact.Name);
data.Groups[1].Value ///"In stock. Limit 1 per customer."
data.Groups[2].Value ///"549.99"


问:
jQuery - Append() is not working to add a button on Clicking an element
jsfiddle: https://jsfiddle.net/gkmuhfqt/1/

As you can see on jsfiddle, I made a Readmore text that can be clicked and it's for some functions.

Using jQuery, I tried to add a button through clicking the Readmore text that uses the append() function.

But it did not work.

Why does my Readmore text click not work at all in append()- to add some button?

I want to add hello button through clicking readmore text.

Where is my problem? How can I fix it?

-Edit-

html :

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-xs-12 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 col-lg-4 col-lg-offset-4"  style="border:0.5px; border-style: solid;">
              <div class="media">
                <div class="media-left media-top" style="">
                  <img src="https://6dbaudio.files.wordpress.com/2013/08/imgp0746.jpg" class="media-object pull-left img-circle" style="width:70px; height:70px;">
                </div>
                <div class="media-body" style="">
                  <p><h4 class="media-heading">hello</h4></p>
                  <p class="readmore_as_p">Lorem ipsum dolor sit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consectetur.
                  </p>
                 </div>
                </div>
        </div>
</code>```

javascript:

```<code>$(".readmore_as_p").each(function () {

    var original_str = $(this).text();
    console.log("hi");
    if (original_str.length>20) {
        var subtracted_str = original_str.substr(0, 20);
        var p_plus_readmore_str = '<p class="readmore_before" data="' + original_str + '">' + subtracted_str + '...</p>';
        var link_read_more = '<a class="read_more"><p>Read more</p></a>';
        $(this).parent().children('p.readmore_as_p').html(p_plus_readmore_str+link_read_more);

        $('.read_more').click(function () {
            var originaltext = $(this).parent().children('p.readmore_before').attr('data');
            $(this).parent().html(originaltext);

            //Here is problem starting. What i ask is here.
            var text = '<div class="media" style="">\n' +
    '                    <div class="media-body text-center" style="">\n' +
    '                        <button class="btn btn-warning" style="">hello</button>' +
    '                    </div>\n' +
    '                </div>\n';
            $(this).parent().parent().append(text);
                             //To here
        });
    }
    else {
    }
});
</code>```

答:
```<code>$(this).parent().parent().append(text);
</code>```

Parent element is not defined, because original $(this) (which is after debugging - a Read more link) is overwritten by your text, so there is no parent for not existing element in DOM.

Updated fiddle

It is better to create an anchor for original container:

```<code>var _t = $(this);
</code>```

and use it later for appending of elements:

```<code>_t.append(text)
</code>```

Nesting of parent().parent() is not very good practice.

Body:
jsfiddle: https://jsfiddle.net/gkmuhfqt/1/

As you can see on jsfiddle, I made a Readmore text that can be clicked and it's for some functions.

Using jQuery, I tried to add a button through clicking the Readmore text that uses the append() function.

But it did not work.

Why does my Readmore text click not work at all in append()- to add some button?

I want to add hello button through clicking readmore text.

Where is my problem? How can I fix it?

-Edit-

html :

hello

Lorem ipsum dolor sit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consesit amet, consectetur.

javascript:

$(".readmore_as_p").each(function () {

    var original_str = $(this).text();
    console.log("hi");
    if (original_str.length>20) {
        var subtracted_str = original_str.substr(0, 20);
        var p_plus_readmore_str = '
' + subtracted_str + '...
';
        var link_read_more = '
Read more
';
        $(this).parent().children('p.readmore_as_p').html(p_plus_readmore_str+link_read_more);

        $('.read_more').click(function () {
            var originaltext = $(this).parent().children('p.readmore_before').attr('data');
            $(this).parent().html(originaltext);

            //Here is problem starting. What i ask is here.
            var text = '
\n' +
    '
\n' +
    '                        <button class="btn btn-warning" style="">hello</button>' +
    '
\n' +
    '
\n';
            $(this).parent().parent().append(text);
                             //To here
        });
    }
    else {
    }
});

Body:
$(this).parent().parent().append(text);

Parent element is not defined, because original $(this) (which is after debugging - a Read more link) is overwritten by your text, so there is no parent for not existing element in DOM.

Updated fiddle

It is better to create an anchor for original container:

var _t = $(this);

and use it later for appending of elements:

_t.append(text)

Nesting of parent().parent() is not very good practice.


问:
Half transparent circle in another half circle
I have to make such contruction like this one on the picture. There is a bubble with some fancy ending and I don't know, how to make this half transparent circle inside it.
How can I do that?
I have some image as a background.

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.circle {
  background-color: #34bc74;
  border-bottom-right-radius: 140px;
  border-top-right-radius: 140px;
  border-left-color: transparent;
  width: 70px;
  height: 140px;
  position: absolute;
  z-index: 1;
  top: -70px;
  right: -70px;
  overflow: hidden;
}
.circle:after {
    height: 70px;
    width: 35px;
    left: -35px;
    z-index: 2;
    content: '';
    border-radius: 70px;
    position: absolute;
    // border: 35px solid $green;
    // box-shadow: 0px 300px 0px 300px #448CCB;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bubble">
  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id
  <div class="circle"></div>
</div></code>```

答:
You could try create the shape using svg masking.

Here's some more info from MDN

(poor) example...

body {
  background: url(https://unsplash.it/1000x1000);
}

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.bubble svg {
  position: absolute;
  right: -4em;
  top: -1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bubble">
  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id
  <svg width="100" height="100">
  <defs>
    <mask id="inner-circle">
      <rect width="100%" height="100%" fill="white"/>
      <circle r="28" cx="40" cy="20" fill="black"/>
    </mask>
  </defs>
  <circle id="curve" r="50" cx="50" cy="50" fill="#34bc74" mask="url(#inner-circle)" />
</svg>
</div></code>```

Body:
I have to make such contruction like this one on the picture. There is a bubble with some fancy ending and I don't know, how to make this half transparent circle inside it.
How can I do that?
I have some image as a background.

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.circle {
  background-color: #34bc74;
  border-bottom-right-radius: 140px;
  border-top-right-radius: 140px;
  border-left-color: transparent;
  width: 70px;
  height: 140px;
  position: absolute;
  z-index: 1;
  top: -70px;
  right: -70px;
  overflow: hidden;
}
.circle:after {
    height: 70px;
    width: 35px;
    left: -35px;
    z-index: 2;
    content: '';
    border-radius: 70px;
    position: absolute;
    // border: 35px solid $green;
    // box-shadow: 0px 300px 0px 300px #448CCB;
  }

  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id

Body:
You could try create the shape using svg masking.

Here's some more info from MDN

(poor) example...

body {
  background: url(https://unsplash.it/1000x1000);
}

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.bubble svg {
  position: absolute;
  right: -4em;
  top: -1em;
}

<div class="bubble">
  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id
  <svg width="100" height="100">
  <defs>
    <mask id="inner-circle">
      <rect width="100%" height="100%" fill="white"/>
      <circle r="28" cx="40" cy="20" fill="black"/>
    </mask>
  </defs>
  <circle id="curve" r="50" cx="50" cy="50" fill="#34bc74" mask="url(#inner-circle)" />
</svg>
</div>


问:
Word Interop does not save file
I have this snippet of code that should open a docx file and I would like to save it as pdf.

Unfortunately no error is thrown but the PDF is not saved.

Any hint on how to save it?

```<code>var wordApplication = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDocument = null;

try
{
    wordDocument = wordApplication.Documents.Open(docPath + ".docx");

    if (wordDocument != null)
        wordDocument.SaveAs2(docPath + ".pdf", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
        //wordDocument.ExportAsFixedFormat(docPath + ".pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
    else throw new Exception("CUSTOM ERROR: Cannot Open Word Application");
}
catch (Exception ex)
{
    new Exception("CUSTOM ERROR" + ex.Message);
}
</code>```

答:
having the same problem with server 2008r2 and now with server 2012r2 and office 2010/2016

try to create a "Desktop" folder in C:\Windows\SysWOW64\config\systemprofile

this is work for me

find another article about this

office interop does not work in windows service

Title: Word Interop does not save file

Body:
I have this snippet of code that should open a docx file and I would like to save it as pdf.

Unfortunately no error is thrown but the PDF is not saved.

Any hint on how to save it?

var wordApplication = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDocument = null;

try
{
    wordDocument = wordApplication.Documents.Open(docPath + ".docx");

    if (wordDocument != null)
        wordDocument.SaveAs2(docPath + ".pdf", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
        //wordDocument.ExportAsFixedFormat(docPath + ".pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
    else throw new Exception("CUSTOM ERROR: Cannot Open Word Application");
}
catch (Exception ex)
{
    new Exception("CUSTOM ERROR" + ex.Message);
}


问:
Application hangs on wait async method
I've got two combobox controls on my page, binded to a ObservableCollection<Vendor> and ObservableCollection<Driver>.

When the page is loaded the OnWindowLoaded() is executed.
When the setter of the property Vendor is triggered, OnVendorPropertyChanged is executed.
When OnWindowLoaded() finishes, Vendor and Driver is being set correctly.

However when I change the Vendor, the application waits on the line

```<code>LoadDriversAsync(Vendor.DCP).Wait();
</code>```

How can I fix this?

```<code>    private async void OnWindowLoaded()
    {
        Debug.WriteLine("Enter OnWindowLoaded");
        await LoadVendorsAsync();
        await System.Threading.Tasks.Task.Run(() => { Vendor = Vendors.FirstOrDefault(); });
        await System.Threading.Tasks.Task.Run(() => { Driver = Drivers.FirstOrDefault(); });
        Debug.WriteLine("Leave OnWindowLoaded");
    }

     private Vendor _vendor;
     public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

    /// <summary>
    /// Raised when Vendor property is changed
    /// </summary>
    /// <param name="vendor"></param>
    private void OnVendorPropertyChanged(PropertyChangedMessage<Vendor> vendor)
    {
         Debug.WriteLine("Enter OnVendorPropertyChanged");

            //application hangs when vendor is changed
            LoadDriversAsync(Vendor.DCP).Wait();
            Debug.WriteLine("Leave OnVendorPropertyChanged");
    }

    private async System.Threading.Tasks.Task LoadVendorsAsync()
    {
            Debug.WriteLine("Enter LoadVendorsAsync");
            //load the vendors, don't return data
            Debug.WriteLine("Leave LoadVendorsAsync");

    }

      private Vendor _vendor;
    public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

   ObservableCollection<Vendor> _vendors = new ObservableCollection<Vendor>();
    public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

        set
        {
            if (_vendors != value)
            {
                var oldVendors = _vendors;
                _vendors = value;
                RaisePropertyChanged(nameof(Vendors), oldVendors, Vendors, true);
            }

        }
    }

private async System.Threading.Tasks.Tas LoadDriversAsync(Objects.Vendor Vendor)
    {

            Debug.WriteLine("Enter LoadDriversAsync");
//load data, don't return

            Debug.WriteLine("Leave LoadDriversAsync");
            RaisePropertyChanged(nameof(Drivers), oldDrivers, Drivers, true);
        }

    }
</code>```

Output

```<code>Enter OnWindowLoaded
Enter LoadVendorsAsync
Leave LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave LoadDriversAsync
Leave OnVendorPropertyChanged
Leave OnWindowLoaded
</code>```

Edited

Following Boo advice did not help. Application still blocks when changing vendor.

Following @Frederik Gheysels advice did not help.

Output

```<code>Enter OnWindowLoaded
Enter LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave OnWindowLoaded
Leave LoadDriversAsync
Leave OnVendorPropertyChanged
</code>```

答:
You're experiencing a deadlock.

Why do you use .Wait() on that method call ?

You should make your calling method async and await the Task.

```<code>    private async void OnVendorPropertyChanged(PropertyChangedMessage<Vendor> vendor)
    {
         Debug.WriteLine("Enter OnVendorPropertyChanged");

         //application hangs when vendor is changed
         await LoadDriversAsync(Vendor.DCP);
         Debug.WriteLine("Leave OnVendorPropertyChanged");
    }
</code>```

Title: Application hangs on wait async method

Body:
I've got two combobox controls on my page, binded to a ObservableCollection<Vendor> and ObservableCollection<Driver>.

When the page is loaded the OnWindowLoaded() is executed.
When the setter of the property Vendor is triggered, OnVendorPropertyChanged is executed.
When OnWindowLoaded() finishes, Vendor and Driver is being set correctly.

However when I change the Vendor, the application waits on the line

LoadDriversAsync(Vendor.DCP).Wait();

How can I fix this?

    private async void OnWindowLoaded()
    {
        Debug.WriteLine("Enter OnWindowLoaded");
        await LoadVendorsAsync();
        await System.Threading.Tasks.Task.Run(() => { Vendor = Vendors.FirstOrDefault(); });
        await System.Threading.Tasks.Task.Run(() => { Driver = Drivers.FirstOrDefault(); });
        Debug.WriteLine("Leave OnWindowLoaded");
    }

     private Vendor _vendor;
     public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

    ///
    /// Raised when Vendor property is changed
    ///
    /// <param name="vendor"></param>
    private void OnVendorPropertyChanged(PropertyChangedMessage<Vendor> vendor)
    {
         Debug.WriteLine("Enter OnVendorPropertyChanged");

            //application hangs when vendor is changed
            LoadDriversAsync(Vendor.DCP).Wait();
            Debug.WriteLine("Leave OnVendorPropertyChanged");
    }

    private async System.Threading.Tasks.Task LoadVendorsAsync()
    {
            Debug.WriteLine("Enter LoadVendorsAsync");
            //load the vendors, don't return data
            Debug.WriteLine("Leave LoadVendorsAsync");

    }

      private Vendor _vendor;
    public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

   ObservableCollection<Vendor> _vendors = new ObservableCollection<Vendor>();
    public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

        set
        {
            if (_vendors != value)
            {
                var oldVendors = _vendors;
                _vendors = value;
                RaisePropertyChanged(nameof(Vendors), oldVendors, Vendors, true);
            }

        }
    }

private async System.Threading.Tasks.Tas LoadDriversAsync(Objects.Vendor Vendor)
    {

            Debug.WriteLine("Enter LoadDriversAsync");
//load data, don't return

            Debug.WriteLine("Leave LoadDriversAsync");
            RaisePropertyChanged(nameof(Drivers), oldDrivers, Drivers, true);
        }

    }

Output

Enter OnWindowLoaded
Enter LoadVendorsAsync
Leave LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave LoadDriversAsync
Leave OnVendorPropertyChanged
Leave OnWindowLoaded

Edited

Following Boo advice did not help. Application still blocks when changing vendor.

Following @Frederik Gheysels advice did not help.

Output

Enter OnWindowLoaded
Enter LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave OnWindowLoaded
Leave LoadDriversAsync
Leave OnVendorPropertyChanged

Body:
You're experiencing a deadlock.

Why do you use .Wait() on that method call ?

You should make your calling method async and await the Task.

    private async void OnVendorPropertyChanged(PropertyChangedMessage<Vendor> vendor)
    {
         Debug.WriteLine("Enter OnVendorPropertyChanged");

         //application hangs when vendor is changed
         await LoadDriversAsync(Vendor.DCP);
         Debug.WriteLine("Leave OnVendorPropertyChanged");
    }


问:
Best Practices for SPA calling multiple APIs?
My team is trying to figure out the best architecture for the problem below. I'd like to be able to find any existing recommendations for our situation, but it's difficult to search.

We have an application A with a SPA, ASP.NET WebAPI backend, and a database.

We have another in-house WebAPI B for storing and serving files and application-agnostic metadata. B has its own database. This API belongs to our team too, but is meant to eventually be consumed by other applications.

A has a table of A-specific document metadata. These records represent attachments of files to other things in A and contain the IDs of the document records in B

To list attachments for a given item, A frontend gets A document records, then uses the result of the call to A to fetch the rest of the metadata (filename, size, etc) from B

We had an idea to eliminate the second call by duplicating the data returned from an upload to B in A's metadata.

So, my questions are:

Is there any reason not to duplicate the data?

I've had trouble googling it so far—I feel like I'm missing jargon or some term that will get me what I need. Is there a name for this specific architecture topic that will aid me in my searches?

Thanks

答:
I think we can speak of micro service.

For data duplication that's depending how you want to treat it. Your data must always be up to date?

If it's a kind of data, you can duplicate the data into A backend. E.g: A row in invoice

Otherwise, from A backend you call B backend to merge data and you send to your clients (frontend) only useful information.

Your clients must know only one endpoint.

Because, if you have 3 clients (e.g .: website, mobile app, tab app) which have the same feature. Tomorrow, B changes, you have to check your frontend code everywhere.

Whereas, if only A knows B, you change the connection into A. Generally, it's transparent for your clients

Some reads: http://microservices.io/patterns/data/event-sourcing


问:
Link to an anchor AND force reload current page
When I click a link with an href=# the browser scrolls to the div instead of reloading the page. How can I force a reload?

To clarify, I do not want to just reload the page, but I want to reload the page AND go to the associated div designated with the #X. For example href=#153> should reload the page and go to that div.

All current questions in this regards talk about simply reloading the page; not reloading and redirecting to the div.

Yes, I am quite aware this is easily done with JavaScript. But with a task so simply, I'm sure there is a way of doing this without JavaScript.

答:
This worked for me:

```<code><a href="?reload=1#153">Reload</a>
</code>```

I used a trick. When you use the same address then page won't reload.
But when you change address simply by adding fake param "reload=1" then page will be reloaded and navigated to specified anchor.

Btw. reloading with javascript can be tricky or misleading when you want to execute php script again with reload, cos javascript reloads only contents of page but php script is not executed.

Body:
When I click a link with an href=# the browser scrolls to the div instead of reloading the page. How can I force a reload?

To clarify, I do not want to just reload the page, but I want to reload the page AND go to the associated div designated with the #X. For example  should reload the page and go to that div.

All current questions in this regards talk about simply reloading the page; not reloading and redirecting to the div.

Yes, I am quite aware this is easily done with JavaScript. But with a task so simply, I'm sure there is a way of doing this without JavaScript.

Body:
This worked for me:

<a href="?reload=1#153">Reload</a>

I used a trick. When you use the same address then page won't reload.
But when you change address simply by adding fake param "reload=1" then page will be reloaded and navigated to specified anchor.

Btw. reloading with javascript can be tricky or misleading when you want to execute php script again with reload, cos javascript reloads only contents of page but php script is not executed.


问:
Invert a dictionary inplace
I have a dictionary with unique values and I want to invert it (i.e. swap keys with values) inplace.
Is there any way doing it without using another dictionary?

I would prefer to just manipulate the items inside the dict than use a new dictionary, so that id(my_dict) would remain the same.

答:
If you are trying to swap keys and values and do not mind duplicate values creating key conflicts, you can "reverse" the dictionary rather easily with a single line of code:

```<code>dictionary = dict(map(reversed, dictionary.items()))
</code>```

If you would rather use the dictionary comprehension syntax instead, you can write this line:

```<code>dictionary = {value: key for key, value in dictionary.items()}
</code>```

If you do not want to use the items method of the dictionary, it is rather easy to avoid:

```<code>dictionary = {dictionary[key]: key for key in dictionary}
</code>```

If you can afford creating a copy of the dictionary, you can reverse it in place if needed:

```<code>def reverse_in_place(dictionary):
    reference = dictionary.copy()
    dictionary.clear()
    dictionary.update(map(reversed, reference.items()))
</code>```

Title: Invert a dictionary inplace

Body:
If you are trying to swap keys and values and do not mind duplicate values creating key conflicts, you can "reverse" the dictionary rather easily with a single line of code:

dictionary = dict(map(reversed, dictionary.items()))

If you would rather use the dictionary comprehension syntax instead, you can write this line:

dictionary = {value: key for key, value in dictionary.items()}

If you do not want to use the items method of the dictionary, it is rather easy to avoid:

dictionary = {dictionary[key]: key for key in dictionary}

If you can afford creating a copy of the dictionary, you can reverse it in place if needed:

def reverse_in_place(dictionary):
    reference = dictionary.copy()
    dictionary.clear()
    dictionary.update(map(reversed, reference.items()))


问:
Filtering Include values in Linq
With Linq, is there a way to consolidate these two lines into one method chain?

```<code>Group group = await _database.Groups.AsQueryable()
    .Include(g => g.Children)
    .Include(g => g.Documents)
    .SingleOrDefaultAsync(g => g.Pk == id);

group.Children = @group.Children.Where(c => c.Active).AsEnumerable().ToList();
</code>```

Edit to explain structure:

group is of type Group

the Children property on a Group is a List<Group>

答:
You could just make the database do the filtering for you instead of bringing back all the children records:</p>

```<code>var group = await _database.Groups.AsQueryable()
    .Where(g => g.Pk == id)
    .Select(g => new {
          Children = g.Children.Where(c => c.Active).ToList(),
          Documents = g.Documents.ToList() } )
    .SingleOrDefaultAsync();
</code>```

Title: Filtering Include values in Linq

Body:
With Linq, is there a way to consolidate these two lines into one method chain?

Group group = await _database.Groups.AsQueryable()
    .Include(g => g.Children)
    .Include(g => g.Documents)
    .SingleOrDefaultAsync(g => g.Pk == id);

group.Children = @group.Children.Where(c => c.Active).AsEnumerable().ToList();

Edit to explain structure:

group is of type Group

the Children property on a Group is a List<Group>

Body:
You could just make the database do the filtering for you instead of bringing back all the children records:

var group = await _database.Groups.AsQueryable()
    .Where(g => g.Pk == id)
    .Select(g => new {
          Children = g.Children.Where(c => c.Active).ToList(),
          Documents = g.Documents.ToList() } )
    .SingleOrDefaultAsync();


问:
When validating data in Laravel 5.5, Update returns "unknown column in field list" error where Create does not
Laravel 5.5 introduces a new streamlined request validation. The idea being that:

```<code>$validData = $request->validate($rules)
</code>```

will return only those fields that are present in the $rules. This is beneficial so that one can then simply User::create($validData) or User::update($validData).

However, I noticed that when I have additional data, which I do validate, but that doesn't exist in the model's (this case User) table, the create method inserts the record, but that the update method returns this error:

```<code>Column not found: 1054 Unknown column 'column_name' in 'field list'
</code>```

I can of course write the relevant field lists out, or use other workaround, but I wonder why are the two methods are behaving differently?

e.g. passing

```<code>array:4 [▼
  "first_name" => "Pedro"
  "last_name" => "Taco"
  "email" => "taco@example.org"
  "operators" => array:1 [▼
    0 => "1"
  ]
]
</code>```

to User::create() inserts the record. Passing the same to User::update() returns an error.
User has $fillable = 'first_name', 'last_name', 'email'

答:
I believe they behave the same but in update method you have some extra fields that are not in table in database, so you should verify what exactly you send and what exactly you validate to make sure there are no additional fields in $validData when you are updating user.

If you think that's not the case, please show us exactly how the validation looks like for creating and updating user.

Body:
Laravel 5.5 introduces a new streamlined request validation. The idea being that:

$validData = $request->validate($rules)

will return only those fields that are present in the $rules. This is beneficial so that one can then simply User::create($validData) or User::update($validData).

However, I noticed that when I have additional data, which I do validate, but that doesn't exist in the model's (this case User) table, the create method inserts the record, but that the update method returns this error:

Column not found: 1054 Unknown column 'column_name' in 'field list'

I can of course write the relevant field lists out, or use other workaround, but I wonder why are the two methods are behaving differently?

e.g. passing

array:4 [▼
  "first_name" => "Pedro"
  "last_name" => "Taco"
  "email" => "taco@example.org"
  "operators" => array:1 [▼
    0 => "1"
  ]
]

to User::create() inserts the record. Passing the same to User::update() returns an error.
User has $fillable = 'first_name', 'last_name', 'email'


问:
PHP can (should) I array_map filter_var to $_POST
I just stumbled on this neat bit of code to filter $_POST data quickly:

```<code>$post=array_map("filter_data",$_POST);
</code>```

I've updated it to the new version (after PHP 5.2) and I've got

```<code>$post=array_map("filter_var",$_POST,array(516));  // 516 == 'unsafe_raw'
</code>```

Now I'm paranoid; this seems too easy.  So

Should I not do this for all post data? (shifty nervous eyes)

Is unsafe_raw the correct filter for generic post, get, or cookie data?

I should add I'm just trying for a general sanitizer, mainly to remove SQL injections.  If I have an email address or something I can filter again later.  Any ideas / suggestions / horrified stares?

答:
To avoid SQL injection, always use the appropriate functions for your database just before plugging the value into the query string, e.g. mysql_real_escape_string. A general filter not specific to your database doesn't guarantee anything and will probably only filter too much.

For anything else, like email validation, use the specific filter on the specific variable that holds the email address.

Also, use the constant FILTER_UNSAFE_RAW, not its numeric value.

Body:
I just stumbled on this neat bit of code to filter $_POST data quickly:

$post=array_map("filter_data",$_POST);

I've updated it to the new version (after PHP 5.2) and I've got

$post=array_map("filter_var",$_POST,array(516));  // 516 == 'unsafe_raw'

Now I'm paranoid; this seems too easy.  So

Should I not do this for all post data? (shifty nervous eyes)

Is unsafe_raw the correct filter for generic post, get, or cookie data?

I should add I'm just trying for a general sanitizer, mainly to remove SQL injections.  If I have an email address or something I can filter again later.  Any ideas / suggestions / horrified stares?


问:
Haskell converting string to binary number
I need to convert a string of chars to a list of binary numbers in Haskell. I've written two functions to do this, but I'm not sure how to combine them into one. So far I have

```<code>dec[]=[]
dec(x:xs) = ord(x): dec xs
</code>```

to convert every char in the list into a decimal number. The next function

```<code>bin 0 = [0]
bin n| n `mod` 2 == 1 = bin (n `div` 2) ++ [1]
     | n `mod` 2 == 0 = bin (n `div` 2) ++ [0]
</code>```

converts a decimal number to its binary equivalent. I'm not sure how to apply the second function to every element in the list, in order to convert every char to its equivalent in binary. I tried to use the where clause:

where n = dec(x:xs) = ord(x): dec xs

but this is not valid as there are two equals signs on the same line. How can I achieve the correct functionality?

答:
You can be pretty certain that an Int will be stored in binary.  It only appears to be in decimal because it is converted to decimal when you print it.  So, the name dec is a misnomer, that function is converting a String into a sequence of numbers that represent the Unicode value of each character.  You can avoid explicit recursion by using map:

```<code>toUnicode :: String -> [Int]
toUnicode = map ord
</code>```

Note that this function uses so-called point-free style.  The expected argument is missing, but will be passed to map when supplied by the caller.

The Bin function will not compile because it starts with an upper case character, making it a data constructor.  You should name the function starting with a lower case character.  According to your example output, you want leading zeros in your binary representations, so you can't stop conversion when the value becomes zero.  You need to continue until you have converted the desired number of digits, which appears to be 8.  It is also inefficient to keep appending to a list.  It is better to prepend, and then reverse the result.

```<code>toBinary :: Int -> [Int]
toBinary = go 8 [] where
    go 0 acc _ = reverse acc
    go n acc x = go (n-1) (bit:acc) x' where
        (x', bit) = x `divMod` 2
</code>```

Here, we use a helper function, go which counts down the number of remaining digits as it builds up the list of 1's and 0's.

So, now we have a function to convert a String into a list of Ints, and a function to convert an Int into a list of 0/1 Ints, and we want to glue them together to make a function that converts a String to a list of 0/1 Ints.  If we map our toBinary function over the result of toUnicode, we will get a list of lists, which must be concatenated to form a single list.  This is such a common pattern that there's a function for that called, concatMap:

```<code>stringToBinary :: String -> [Int]
stringToBinary = concatMap toBinary . toUnicode
</code>```

Here we use function composition to first apply toUnicode to the String, and then concatMap the toBinary over the result.

Body:
I need to convert a string of chars to a list of binary numbers in Haskell. I've written two functions to do this, but I'm not sure how to combine them into one. So far I have

dec[]=[]
dec(x:xs) = ord(x): dec xs

to convert every char in the list into a decimal number. The next function

bin 0 = [0]
bin n| n `mod` 2 == 1 = bin (n `div` 2) ++ [1]
     | n `mod` 2 == 0 = bin (n `div` 2) ++ [0]

converts a decimal number to its binary equivalent. I'm not sure how to apply the second function to every element in the list, in order to convert every char to its equivalent in binary. I tried to use the where clause:

where n = dec(x:xs) = ord(x): dec xs

but this is not valid as there are two equals signs on the same line. How can I achieve the correct functionality?

Body:
You can be pretty certain that an Int will be stored in binary.  It only appears to be in decimal because it is converted to decimal when you print it.  So, the name dec is a misnomer, that function is converting a String into a sequence of numbers that represent the Unicode value of each character.  You can avoid explicit recursion by using map:

toUnicode :: String -> [Int]
toUnicode = map ord

Note that this function uses so-called point-free style.  The expected argument is missing, but will be passed to map when supplied by the caller.

The Bin function will not compile because it starts with an upper case character, making it a data constructor.  You should name the function starting with a lower case character.  According to your example output, you want leading zeros in your binary representations, so you can't stop conversion when the value becomes zero.  You need to continue until you have converted the desired number of digits, which appears to be 8.  It is also inefficient to keep appending to a list.  It is better to prepend, and then reverse the result.

toBinary :: Int -> [Int]
toBinary = go 8 [] where
    go 0 acc _ = reverse acc
    go n acc x = go (n-1) (bit:acc) x' where
        (x', bit) = x `divMod` 2

Here, we use a helper function, go which counts down the number of remaining digits as it builds up the list of 1's and 0's.

So, now we have a function to convert a String into a list of Ints, and a function to convert an Int into a list of 0/1 Ints, and we want to glue them together to make a function that converts a String to a list of 0/1 Ints.  If we map our toBinary function over the result of toUnicode, we will get a list of lists, which must be concatenated to form a single list.  This is such a common pattern that there's a function for that called, concatMap:

stringToBinary :: String -> [Int]
stringToBinary = concatMap toBinary . toUnicode

Here we use function composition to first apply toUnicode to the String, and then concatMap the toBinary over the result.


问:
Altering a View to add a column as bit not null
I'm trying to add a column to a view using ALTER VIEW but it keeps saying 'The column is invalid'. I need the column to be BIT NOT NULL. How would I go about doing this?  Thank you all!

```<code>SELECT dbo.tbl_skins.skinName, dbo.tbl_prefs.PersonID, dbo.tbl_prefs[columnName] etc...
FROM dbo.tbl_prefs
INNER JOIN dbo.tbl_skins
   ON dbo.tbl_prefs.skinId = dbo.tbl_skins.skinId
</code>```

I didn't add the rest of the columns because the rest are all from dbo.tbl_prefs. The only one that is different is that first one that reads dbo.tbl_skins.skinName.

Upon opening the table I see,

```<code>SELECT TOP (1000) [column1],[column2], etc... FROM [table_name].
</code>```

All I'm trying to do is add a new column of type BIT, NOT NULL to the table (dbo.tbl_prefs) and the same to the view (dbo.qry_prefs).

答:
Yeah I tried casting the column to make it a bit not null, but I think I wrote the syntax wrong. Sorry, I haven't used SQL in a while
  let alone worked with views. I deleted the query but I think I wrote
  it like ALTER VIEW [dbo].[qry_prefs] AS SELECT CAST(bit, not null)
  [newColumn] FROM [projects].[dbo].[qry_prefs] But i'm pretty certain
  that's wrong.

You are trying to add a column to a view that you then want to retrieve again from that view. That makes no sense.

Try something like this

Assuming that your view is called qry_prefs and you want to add a blank bit column.

```<code>ALTER VIEW [dbo].[qry_prefs] AS
  SELECT dbo.tbl_skins.skinName,
         dbo.tbl_prefs.PersonID,
         dbo.tbl_prefs.[columnName],
         etc...
         convert(bit, null) as newColumn
  FROM dbo.tbl_prefs
    INNER JOIN dbo.tbl_skins ON dbo.tbl_prefs.skinId = dbo.tbl_skins.skinId
</code>```

Make it some easier for yourself by using aliases

```<code>ALTER VIEW [dbo].[qry_prefs] AS
  SELECT s.skinName,
         p.PersonID,
         p.[columnName],
         etc...
         convert(bit, null) as newColumn
  FROM dbo.tbl_prefs p
    INNER JOIN dbo.tbl_skins s ON p.skinId = s.skinId
</code>```

EDIT: from the comments it seems you need to add the field to the table and to the view

That can be done like this

```<code>alter table [dbo].[tbl_prefs]
add newColumn bit null
</code>```

now add this field to the view like this

```<code>ALTER VIEW [dbo].[qry_prefs] AS
  SELECT s.skinName,
         p.PersonID,
         p.[columnName],
         etc...
         p.newColumn
  FROM dbo.tbl_prefs p
    INNER JOIN dbo.tbl_skins s ON p.skinId = s.skinId
</code>```

Body:
I'm trying to add a column to a view using ALTER VIEW but it keeps saying 'The column is invalid'. I need the column to be BIT NOT NULL. How would I go about doing this?  Thank you all!

SELECT dbo.tbl_skins.skinName, dbo.tbl_prefs.PersonID, dbo.tbl_prefs[columnName] etc...
FROM dbo.tbl_prefs
INNER JOIN dbo.tbl_skins
   ON dbo.tbl_prefs.skinId = dbo.tbl_skins.skinId

I didn't add the rest of the columns because the rest are all from dbo.tbl_prefs. The only one that is different is that first one that reads dbo.tbl_skins.skinName.

Upon opening the table I see,

SELECT TOP (1000) [column1],[column2], etc... FROM [table_name].

All I'm trying to do is add a new column of type BIT, NOT NULL to the table (dbo.tbl_prefs) and the same to the view (dbo.qry_prefs).

Body:
Yeah I tried casting the column to make it a bit not null, but I think I wrote the syntax wrong. Sorry, I haven't used SQL in a while
  let alone worked with views. I deleted the query but I think I wrote
  it like ALTER VIEW [dbo].[qry_prefs] AS SELECT CAST(bit, not null)
  [newColumn] FROM [projects].[dbo].[qry_prefs] But i'm pretty certain
  that's wrong.

You are trying to add a column to a view that you then want to retrieve again from that view. That makes no sense.

Try something like this

Assuming that your view is called qry_prefs and you want to add a blank bit column.

ALTER VIEW [dbo].[qry_prefs] AS
  SELECT dbo.tbl_skins.skinName,
         dbo.tbl_prefs.PersonID,
         dbo.tbl_prefs.[columnName],
         etc...
         convert(bit, null) as newColumn
  FROM dbo.tbl_prefs
    INNER JOIN dbo.tbl_skins ON dbo.tbl_prefs.skinId = dbo.tbl_skins.skinId

Make it some easier for yourself by using aliases

ALTER VIEW [dbo].[qry_prefs] AS
  SELECT s.skinName,
         p.PersonID,
         p.[columnName],
         etc...
         convert(bit, null) as newColumn
  FROM dbo.tbl_prefs p
    INNER JOIN dbo.tbl_skins s ON p.skinId = s.skinId

EDIT: from the comments it seems you need to add the field to the table and to the view

That can be done like this

alter table [dbo].[tbl_prefs]
add newColumn bit null

now add this field to the view like this

ALTER VIEW [dbo].[qry_prefs] AS
  SELECT s.skinName,
         p.PersonID,
         p.[columnName],
         etc...
         p.newColumn
  FROM dbo.tbl_prefs p
    INNER JOIN dbo.tbl_skins s ON p.skinId = s.skinId


问:
AJAX in Django - Clicking an element updates all counters tied to the update script. How can I prevent this?
I'm doing a small project, learning how to use AJAX and it turned out to be a little uncomfortable. When I press the like button, the counter increases or decreases in all the elements. For example if I like question 1, in the question 2 and 3 the like counter also changes and uses the same counter as the one in question 1. How can I avoid it?

This is my script:

```<code>  $(".like-button").click(function(e){
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: "/like/",
    data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
    dataType: "json",
    success: function(response){
      sl = $(".show-likes");
      sl.html(response.likes_count);
    },
    error: function(rs, r){
      alert(rs.responseText);
    }
  });
});
</code>```

This is my html template:

```<code>{% for tweet in tweets %}
  <!--Card-->
  <div class="card col">
      <!--Card content-->
      <div class="card-body">
          <!--Title-->
          <h4 class="card-title">{{tweet.title}}</h4>
          <!--Text-->
          <p class="card-text">{{tweet.text}}</p>
        <button
          type="button"
          name="{{tweet.slug}}"
          class="btn btn-primary like-button">Likes
          <span
          class="show-likes">
            {{tweet.total_likes}}
          </span>
        </button>
      </div>
  </div>
  <hr>

{% endfor %}
</code>```

Inside of the like button's code, I have a  for showing "total_likes".

And how could I add a little more real-time updating to this? I'm using Django as the Backend.

Thank you very much for your time and have an excellent day.

答:
You need to descend from the clicked like button (this within the handler) to find the likes counter for that button only. Otherwise your '.show-likes' query will yield all counters on the page.

```<code>$(".like-button").click(function(e){
  var $btn = $(this);

  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: "/like/",
    data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
    dataType: "json",
    success: function(response){
      var sl = $btn.find(".show-likes");
      sl.html(response.likes_count);
    },
    error: function(rs, r){
      alert(rs.responseText);
    }
  });
});
</code>```

Also, not sure what you mean by adding "more" real-time updating. You might be referring to what's known as an "optimistic update". In this case you would update the likes counter immediately (increment by one), and then call your ajax function. Your handler would remain the same and update with the actual, trusted value from the server once complete. If other users have clicked like during that time, the final value from the server may be higher.

Body:
I'm doing a small project, learning how to use AJAX and it turned out to be a little uncomfortable. When I press the like button, the counter increases or decreases in all the elements. For example if I like question 1, in the question 2 and 3 the like counter also changes and uses the same counter as the one in question 1. How can I avoid it?

This is my script:

  $(".like-button").click(function(e){
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: "/like/",
    data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
    dataType: "json",
    success: function(response){
      sl = $(".show-likes");
      sl.html(response.likes_count);
    },
    error: function(rs, r){
      alert(rs.responseText);
    }
  });
});

This is my html template:

{% for tweet in tweets %}

{{tweet.title}}

{{tweet.text}}

        <button
          type="button"
          name="{{tweet.slug}}"
          class="btn btn-primary like-button">Likes

            {{tweet.total_likes}}

        </button>

{% endfor %}

Inside of the like button's code, I have a  for showing "total_likes".

And how could I add a little more real-time updating to this? I'm using Django as the Backend.

Thank you very much for your time and have an excellent day.

Body:
You need to descend from the clicked like button (this within the handler) to find the likes counter for that button only. Otherwise your '.show-likes' query will yield all counters on the page.

$(".like-button").click(function(e){
  var $btn = $(this);

  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: "/like/",
    data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
    dataType: "json",
    success: function(response){
      var sl = $btn.find(".show-likes");
      sl.html(response.likes_count);
    },
    error: function(rs, r){
      alert(rs.responseText);
    }
  });
});

Also, not sure what you mean by adding "more" real-time updating. You might be referring to what's known as an "optimistic update". In this case you would update the likes counter immediately (increment by one), and then call your ajax function. Your handler would remain the same and update with the actual, trusted value from the server once complete. If other users have clicked like during that time, the final value from the server may be higher.


问:
DbxRequestConfig is deprecated in API V2?
project Details:

version = android studio 3.0 dropbox api v2 = dropbox-core-sdk-2.0.6
  and dropbox-core-sdk-3.0.5 (I tried both). compileSdkVersion =  26
  buildToolsVersion = '26.0.2'

```<code>DbxRequestConfig config = new DbxRequestConfig("MyApp/1.0", "en_US");
</code>```

Image shows the deprecated call of DbxRequestConfig

It is in the Dropbox jar file.

答:
Per the documentation, the DbxRequestConfig(String clientIdentifier, String userLocale) constructor is deprecated, in favor of using DbxRequestConfig.newBuilder.

There's an example of using it here.

Body:
project Details:

version = android studio 3.0 dropbox api v2 = dropbox-core-sdk-2.0.6
  and dropbox-core-sdk-3.0.5 (I tried both). compileSdkVersion =  26
  buildToolsVersion = '26.0.2'

DbxRequestConfig config = new DbxRequestConfig("MyApp/1.0", "en_US");

Image shows the deprecated call of DbxRequestConfig

It is in the Dropbox jar file.


问:
Quit Application when press logout button
When I press back button in my android application or close the app, it terminates and I want my app to be terminated when I press the logout button.
I only want my app to be terminated when I press the logout button, otherwise not, whether I press back button or close it by minimizing the app.

What should I do?

For the back button, I used this simple code

```<code>@Override
public void onBackPressed()
{
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    moveTaskToBack(true);

    if (drawer.isDrawerOpen(GravityCompat.START))
    {
        drawer.closeIrawer(GravityCompat.START);
    }
    else
    {
        super.onBackPressed();
    }
}
</code>```

Should I do something with these lines?

Or should make any web services for this?

答:
Just use finishAffinity

I will do your work but requires SDK>16

Now your code of onBackPressed() should be

```<code>@Override public void onBackPressed() {
  finishAffinity();
 }
</code>```

Body:
When I press back button in my android application or close the app, it terminates and I want my app to be terminated when I press the logout button.
I only want my app to be terminated when I press the logout button, otherwise not, whether I press back button or close it by minimizing the app.

What should I do?

For the back button, I used this simple code

@Override
public void onBackPressed()
{
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    moveTaskToBack(true);

    if (drawer.isDrawerOpen(GravityCompat.START))
    {
        drawer.closeIrawer(GravityCompat.START);
    }
    else
    {
        super.onBackPressed();
    }
}

Should I do something with these lines?

Or should make any web services for this?

Body:
Just use finishAffinity

I will do your work but requires SDK>16

Now your code of onBackPressed() should be

@Override public void onBackPressed() {
  finishAffinity();
 }