问:
How to add custom font family in ionic2 app
I want to add new font family from Google fonts in my ionic2 app. I need to change the default font family and add my custom font family. Please help! Thanks</p>

答:
It is important to make sure the 'font-family' name matches the native fonts name.To check the font's name in Windows you can just double click the .ttf file and see what value 'Font name' has.

Lets say I have a font I want to use in my Ionic app and I check it's .ttf file and it's font name is 'Flouc Font'. I would make sure the .ttf is in the correct folder (assets/fonts) in my case. Then edit the /src/theme/variables.scss file to include the following definition:

@font-face {
  font-family: "Flouc Font";
  src: url("../assets/fonts/floucFont.ttf")
}

*{
  font-family: "Flouc Font";
}
```


来源: stackexchange

问:
Removing punctuation and placing it at the end of a string
I'm trying to write a function that upon execution will remove punctuation marks from a word and place the mark at the end. The removal bit was working fine until I appended the part which adds that same mark at the end; now instead of removing the punc. inside of the string, it leaves it there and adds it to the end, which is not what I want. My code is the following:

```<code>function containsPunctuation(word) {
    var new_word;
    new_word = word.replace(".", "");
    new_word = word.replace("!", "");
    new_word = word.replace(";", "");
    new_word = word.replace(",", "");
    new_word = word.replace("?", "");
    if (word.includes(".") === true) {
        new_word = new_word + ".";
    }
    return new_word;
}
</code>```

答:
Why not use a regular expression for replacing unwanted characters?

var string = 'a,b;c!d.e?f';

string = string.replace(/[.,;!?]/g, '') + '.';

console.log(string);```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a function that upon execution will remove punctuation marks from a word and place the mark at the end. The removal bit was working fine until I appended the part which adds that same mark at the end; now instead of removing the punc. inside of the string, it leaves it there and adds it to the end, which is not what I want. My code is the following:

function containsPunctuation(word) {
    var new_word;
    new_word = word.replace(".", "");
    new_word = word.replace("!", "");
    new_word = word.replace(";", "");
    new_word = word.replace(",", "");
    new_word = word.replace("?", "");
    if (word.includes(".") === true) {
        new_word = new_word + ".";
    }
    return new_word;
}


问:
Scrapy commandline tool not installed by pip
I installed scrapy via sudo pip install scrapy. It installed the python modules into site-packages and I can import scrapy in my python environment. However, attempting to use the command line tool throws an error:

```<code>scrapy startproject demo
</code>```

has error The program 'scrapy' is not currently installed. and tells me to install python-scrapy.

whereis scrapy has no output. Got tired of trying to track down the install path, so I ran find -name "*crap*", which also turned up nothing useful. It seems that the commandline tool wasn't installed by pip. What am I missing with this pip install?

答:
The problem is sudo pip install scrapy installs scrapy in a directory not accessible by the current user, if you are not root.

You need to remove scrapy first sudo pip uninstall scrapy then reinstall with the -H sudo flag sudo -H pip install scrapy this will make it such that your command line can detect the scrapy installation.

Body:
I installed scrapy via sudo pip install scrapy. It installed the python modules into site-packages and I can import scrapy in my python environment. However, attempting to use the command line tool throws an error:

scrapy startproject demo

has error The program 'scrapy' is not currently installed. and tells me to install python-scrapy.

whereis scrapy has no output. Got tired of trying to track down the install path, so I ran find -name "*crap*", which also turned up nothing useful. It seems that the commandline tool wasn't installed by pip. What am I missing with this pip install?


问:
Nginx - Forwarding a request to the Server-App if 'alias' fails
For a project I implemented automatic serverside thumbnail-generation. If you request an Image with '_thumb' in its filename the server checks if there already is a thumbnail for the original image, if not it generates it and sends it back. Works fine.

Now I'd like to bring Nginx into the mix to serve the images directly from the harddrive without involving the server-app (the url itself would work fine and return the image if requested from the server-app itself).

The following Block works fine, if the thumbnail already exists. If there is no thumbnail already generated it just responds 404 - unsurprisingly.

How would I modify the following Nginx-Block to make another request to the server in case the thumbnail cant be found to create it?

Request

```<code>http://www.proj.com/files/images/234782348234/bunny_thumb.jpg
</code>```

Nginx-Block

```<code>location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   alias /srv/proj/data/uploads/images/temp/$1_thumb.$2;
   // No image found? Request it from the server directly on "files/images/234782348234/bunny_thumb.jpg"
}
</code>```

Actual File-Path

```<code>/srv/proj/data/uploads/images/temp/234782348234_thumb.jpg
</code>```

答:
Sometimes it helps to read the excellent blog of the nginx company.

What you search for is called named location with try_files.

https://www.nginx.com/resources/admin-guide/nginx-web-server/

https://www.nginx.com/resources/admin-guide/serving-static-content/

```<code>location / {
    try_files $uri $uri/ @backend;
}

location @backend {
    proxy_pass http://backend.example.com;
}
</code>```

For your case I would try the following

```<code>location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   try_files /srv/proj/data/uploads/images/temp/$1_thumb.$2 @callapp;
   // No image found? Request it from the server directly
   // on "files/images/234782348234/bunny_thumb.jpg"
}

location @callapp {
...
}
</code>```

Body:
For a project I implemented automatic serverside thumbnail-generation. If you request an Image with '_thumb' in its filename the server checks if there already is a thumbnail for the original image, if not it generates it and sends it back. Works fine.

Now I'd like to bring Nginx into the mix to serve the images directly from the harddrive without involving the server-app (the url itself would work fine and return the image if requested from the server-app itself).

The following Block works fine, if the thumbnail already exists. If there is no thumbnail already generated it just responds 404 - unsurprisingly.

How would I modify the following Nginx-Block to make another request to the server in case the thumbnail cant be found to create it?

Request

http://www.proj.com/files/images/234782348234/bunny_thumb.jpg

Nginx-Block

location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   alias /srv/proj/data/uploads/images/temp/$1_thumb.$2;
   // No image found? Request it from the server directly on "files/images/234782348234/bunny_thumb.jpg"
}

Actual File-Path

/srv/proj/data/uploads/images/temp/234782348234_thumb.jpg

Body:
Sometimes it helps to read the excellent blog of the nginx company.

What you search for is called named location with try_files.

https://www.nginx.com/resources/admin-guide/nginx-web-server/

https://www.nginx.com/resources/admin-guide/serving-static-content/

location / {
    try_files $uri $uri/ @backend;
}

location @backend {
    proxy_pass http://backend.example.com;
}

For your case I would try the following

location ~* ^/files/images/(\w+)/.+_thumb\.(jpg|png|gif)$ {
   try_files /srv/proj/data/uploads/images/temp/$1_thumb.$2 @callapp;
   // No image found? Request it from the server directly
   // on "files/images/234782348234/bunny_thumb.jpg"
}

location @callapp {
...
}


问:
Patterns in Python without using lists / only range function
Trying to create the following patterns in Python without using lists and only range function or nested loops.

Patterns are like the following.

```<code>*******
*  *  *
*  *  *
*******
*  *  *
*  *  *
*******
</code>```

And,

```<code>**  **
**  **
  **  *
  **  *
**  **
**  **
  **  *
</code>```

A big thanks.

答:
So you want to fill 7 x 7 grids with different patterns of asterisks? Cool.  I'll bite.

Let's analyze the first one:

(0,0) through (0,6) are filled

(1,0), (1,3), (1,6) are filled

(2,0), (2,3), (2,6) are filled

(3,0) through (3,6) are filled

(4,0), (4,3), (4,6) are filled

(5,0), (5,3), (5,6) are filled

(6,0) through (6,6) are filled

If y is divisible by 3 (or y % 3 == 0), then fill all x with *
else fill only the x that are divisible by 3 (x % 3 == 0)

In Python:

```<code>for y in range(0, 7):
    for x in range(0, 8): # an extra column for newline
        if (x == 7):
            print("\n", end='')
        elif (y % 3 == 0):
            print("*", end='')
        elif (x % 3 == 0):
            print("*", end='')
        else:
            print(" ", end='')
</code>```

Output is:

```<code>*******
*  *  *
*  *  *
*******
*  *  *
*  *  *
*******
</code>```

Do the same exercise for the second one.

EDIT:

Might as well post the second one:

```<code>for y in range(0, 7):
    for x in range(0, 8):
        if (x == 7):
            print("\n", end='')
        elif ((x - y) % 4 == 0) or ((x + y) % 4 == 1):
            print("x", end='')
        else:
            print(" ", end='')
</code>```

Results in:

```<code>xx  xx
xx  xx
  xx  x
  xx  x
xx  xx
xx  xx
  xx  x
</code>```

Body:
Trying to create the following patterns in Python without using lists and only range function or nested loops.

Patterns are like the following.

*******
*  *  *
*  *  *
*******
*  *  *
*  *  *
*******

And,

**  **
**  **
  **  *
  **  *
**  **
**  **
  **  *

A big thanks.

Body:
So you want to fill 7 x 7 grids with different patterns of asterisks? Cool.  I'll bite.

Let's analyze the first one:

(0,0) through (0,6) are filled

(1,0), (1,3), (1,6) are filled

(2,0), (2,3), (2,6) are filled

(3,0) through (3,6) are filled

(4,0), (4,3), (4,6) are filled

(5,0), (5,3), (5,6) are filled

(6,0) through (6,6) are filled

If y is divisible by 3 (or y % 3 == 0), then fill all x with *
else fill only the x that are divisible by 3 (x % 3 == 0)

In Python:

for y in range(0, 7):
    for x in range(0, 8): # an extra column for newline
        if (x == 7):
            print("\n", end='')
        elif (y % 3 == 0):
            print("*", end='')
        elif (x % 3 == 0):
            print("*", end='')
        else:
            print(" ", end='')

Output is:

*******
*  *  *
*  *  *
*******
*  *  *
*  *  *
*******

Do the same exercise for the second one.

EDIT:

Might as well post the second one:

for y in range(0, 7):
    for x in range(0, 8):
        if (x == 7):
            print("\n", end='')
        elif ((x - y) % 4 == 0) or ((x + y) % 4 == 1):
            print("x", end='')
        else:
            print(" ", end='')

Results in:

xx  xx
xx  xx
  xx  x
  xx  x
xx  xx
xx  xx
  xx  x


问:
spring-kafka snapshot builds exist somewhere?
I'm in need of code that only exists in the master at the moment, and the docs specifically mention a version called 2.0.0.BUILD-SNAPSHOT, but I'll be damned if I can figure out which repository is hosting such a build.  Anyone have any clues?

Also, is there any information published about release schedules?  I'm loath to develop against the 1.x API because I want the retry and recovery functionality (which doesn't work in either of the 2.0.0 milestone builds, hence my need for a snapshot), but I don't want to commit to an unreleased library without some sense of when a release might happen.

答:
The BUILD-SNAPSHOT you can find in the https://repo.spring.io/snapshot. So, you should configure that for your project.

The next Spring Kafka 2.0.0.RC1 is scheduled for this June 28.

You can find that info on the project page as well: https://github.com/spring-projects/spring-kafka/milestone/20


问:
angularjs - apply filter on dynamic property of object
what i'm trying to do is ask user to choose the property on which they want to apply filter. the data is shown in table format using ng-repeat.
enter image description here

my code looks like this:
the form to add data:-

```<code><form name="myform">
                        <div class="form-group">
                            <input type="text" class="form-control" id="name" placeholder="Name" ng-model="data.name" required>
                        </div>
                        <div class="form-group">
                            <input type="email" class="form-control" id="email" placeholder="Email" ng-model="data.email" required>
                        </div>
                        <div class="form-group">
                            <textarea class="form-control" id="comment" placeholder="Comment" ng-model="data.comment" required></textarea>
                        </div>
                        <div class="row">
                            <div class="col-xs-6">
                                <button type="submit" class="btn btn-primary" ng-disabled="myform.$invalid" ng-click="add(data)">Submit</button>
                            </div>
                            <div class="col-xs-6">.
                                <button type="submit" class="btn btn-default" ng-click="reset()" ng-disabled="myform.$invalid">Reset</button>
                            </div>
                        </div>
                    </form>
</code>```

the table to show data:-

```<code><div class="col-sm-6 col-sm-offset-3" style="overflow-x:auto;">
            <div class="row">
                <div class="col-xs-6">
                    <select ng-options="key as value for (key, value) in keys" class="form-control" ng-model="filtercolumn">
                         <option value="">Select column</option>
                    </select>
                </div>
                <div class="col-xs-6">
                    <input type="text" class="form-control" ng-model="filtertxt" placeholder="filter">
                </div>
            </div>
            <br><br>
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Sr</th>
                        <th>Date</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Comment</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="x in data | filter: {filtercolumn: filtertxt}">
                        <td>{{x.sr}}</td>
                        <td>{{x.date}}</td>
                        <td>{{x.name}}</td>
                        <td>{{x.email}}</td>
                        <td>{{x.comment}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
</code>```

and here is the controller:

```<code>app.controller("ctrl", ["$scope", function($scope){
    var i = 0;
    $scope.keys =  {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    $scope.data = [];

    $scope.add = function(data){
        $scope.data.push({
            "sr": i++,
            "date": new Date().toDateString(),
            "name": data.name,
            "email": data.email,
            "comment": data.comment
        });
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };

    $scope.reset = function(){
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
}]);
</code>```

as i'm new to angular, may be i'm missing some concept.

Thanks in advance

答:
So there's a couple issues with the controller code and HTML.

First (and most important)

Don't use $scope variables. Assign the variables to your controller and use controllerAs syntax, e.g. ng-controller="myController as myCtrl". The rest of my answer is predicated on using myCtrl as your controller object in the HTML. Here's updated controller code using controller-assigned variables instead of $scope (note: I renamed your controller to myController to avoid ambiguity in ng-controller using as syntax):

```<code>app.controller("myController", function($scope)
{
    // need a reference to 'this' to use inside functions
    var self = this;
    var i = 0;

    self.keys =   {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    self.data = [];

... the rest of your controller
</code>```

Second

You're using the same $scope.data as both an Array AND an Object for your Form. This isn't easy to see because you're using $scope assignments. Add another input variable to your controller:

self.formInput = {}

Then in your form, change all your ng-model directives to ng-model="myCtrl.formInput.whatever"

Third

Now update your add function - again, assigning as a Controller variable, not $scope:

```<code>self.add = function(data)
{
    self.data.push({
        "sr": i++,
        "date": new Date().toDateString(),
        "name": self.formInput.name,
        "email": self.formInput.email,
        "comment": self.formInput.comment
    });

    // now clear the inputs on the form
    self.formInput.name = "";
    self.formInput.email = "";
    self.formInput.comment = "";
};
</code>```

Fourth

Now update your HTML to use the myCtrl variables instead of $scope. So for your ng-options statement in the Select object:

ng-options="key as value for (key, value) in myCtrl.keys"

And for your repeater:

And finally your Form's "Add" button:

ng-click="myCtrl.add(data)"

It's OK that your filtercolumn and filtertxt variables are accessed in the current scope since they're only used in the HTML and are automatically bound with ng-model. If you ever needed access to those in your controller, it'd be advisable to add them as controller variables like the new self.formInput variable. Personally I would do that anyway since using ng-if, for example, would make those model-bound variables inaccessible to the rest of the page. Just good practice to put your variables in the controller.

Body:
what i'm trying to do is ask user to choose the property on which they want to apply filter. the data is shown in table format using ng-repeat.
enter image description here

my code looks like this:
the form to add data:-

<form name="myform">

                            <input type="text" class="form-control" id="name" placeholder="Name" ng-model="data.name" required>

                            <input type="email" class="form-control" id="email" placeholder="Email" ng-model="data.email" required>

                            <textarea class="form-control" id="comment" placeholder="Comment" ng-model="data.comment" required></textarea>

                                <button type="submit" class="btn btn-primary" ng-disabled="myform.$invalid" ng-click="add(data)">Submit</button>

.
                                <button type="submit" class="btn btn-default" ng-click="reset()" ng-disabled="myform.$invalid">Reset</button>

                    </form>

the table to show data:-

                    <select ng-options="key as value for (key, value) in keys" class="form-control" ng-model="filtercolumn">
                         <option value="">Select column</option>
                    </select>

                    <input type="text" class="form-control" ng-model="filtertxt" placeholder="filter">

                        Sr
                        Date
                        Name
                        Email
                        Comment

                        {{x.sr}}
                        {{x.date}}
                        {{x.name}}
                        {{x.email}}
                        {{x.comment}}

and here is the controller:

app.controller("ctrl", ["$scope", function($scope){
    var i = 0;
    $scope.keys =  {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    $scope.data = [];

    $scope.add = function(data){
        $scope.data.push({
            "sr": i++,
            "date": new Date().toDateString(),
            "name": data.name,
            "email": data.email,
            "comment": data.comment
        });
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };

    $scope.reset = function(){
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
}]);

as i'm new to angular, may be i'm missing some concept.

Thanks in advance

Body:
So there's a couple issues with the controller code and HTML.

First (and most important)

Don't use $scope variables. Assign the variables to your controller and use controllerAs syntax, e.g. ng-controller="myController as myCtrl". The rest of my answer is predicated on using myCtrl as your controller object in the HTML. Here's updated controller code using controller-assigned variables instead of $scope (note: I renamed your controller to myController to avoid ambiguity in ng-controller using as syntax):

app.controller("myController", function($scope)
{
    // need a reference to 'this' to use inside functions
    var self = this;
    var i = 0;

    self.keys =   {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    self.data = [];

... the rest of your controller

Second

You're using the same $scope.data as both an Array AND an Object for your Form. This isn't easy to see because you're using $scope assignments. Add another input variable to your controller:

self.formInput = {}

Then in your form, change all your ng-model directives to ng-model="myCtrl.formInput.whatever"

Third

Now update your add function - again, assigning as a Controller variable, not $scope:

self.add = function(data)
{
    self.data.push({
        "sr": i++,
        "date": new Date().toDateString(),
        "name": self.formInput.name,
        "email": self.formInput.email,
        "comment": self.formInput.comment
    });

    // now clear the inputs on the form
    self.formInput.name = "";
    self.formInput.email = "";
    self.formInput.comment = "";
};

Fourth

Now update your HTML to use the myCtrl variables instead of $scope. So for your ng-options statement in the Select object:

ng-options="key as value for (key, value) in myCtrl.keys"

And for your repeater:

<tr ng-repeat="x in myCtrl.data | filter: {filtercolumn: filtertxt}">

And finally your Form's "Add" button:

ng-click="myCtrl.add(data)"

It's OK that your filtercolumn and filtertxt variables are accessed in the current scope since they're only used in the HTML and are automatically bound with ng-model. If you ever needed access to those in your controller, it'd be advisable to add them as controller variables like the new self.formInput variable. Personally I would do that anyway since using ng-if, for example, would make those model-bound variables inaccessible to the rest of the page. Just good practice to put your variables in the controller.


问:
Application Logic (Proper place for Authentication/Authorization)
I am developing a CMS like application using MVC 3 (RC2) and I am in crossroads at this point. I am unable to convince myself if my proposed approach is appropriate or not. I guess it is because I am aware that I am trying to cut some corners which will cost me heavily later down the line.

I will get right down to describing my problem:

1) I have a resource (lets call it A) which has to be made editable.

2) I have a custom permission system implemented which has 2 (of many) permissions:

Can Edit Own Resource

Can Edit Other Resource

3) Creator of resource A is free to edit it if they have 'Can Edit Own Resource' permission.

4) A separate user can only edit A if they have permission 'Can Edit Other Resource'

Now that the requirement is described, let me tell you my approach so far:

1) I have a controller called 'ResourceController'

2) I have a action called 'Edit'

3) The action has a attribute on it: [CustomerAuthorize(Perm.CanEditOwnResource, Perm.CanEditOtherResource, Any = true)]

4) I have a service class which takes care of domain validation.

So a user get call the action method if they have either the 'Can Edit Own Resource' or 'Can Edit Other Resource' permission.

How do I decide (and where should this decision be made) on whether the user has the right permission or not (depending on whether they own the resource?) Should it be in the controller action, in the resource service class, in a separate service class?

Waiting to hear different views...

答:
Because of the nature of MVC, you will want to have your authentication checks at a variety of points.

For one, you'll need to be able to display visual cues on the UI (i.e. show the edit button or not show it), so the logic will have to be made available to your Views.

Of course, that's only for UI purposes.  You'll want authentication/authorization on your controller actions as well, just in case someone goes around your UI to access it.

Finally, the most secure place to authenticate and authorize an action is right before you perform it.  If you have a handler, for example, I would place some authorization logic there.  You want to make sure that no one can write around your security logic by calling the service from somewhere else, and not knowing that there were restrictions on that service. This helps make the security options more granular as well.

ContentLicense: CC BY-SA 2.5


问:
Excel: Counting number of male and female employees
It might be a basic question but I'm struggling to come up with a function. I have two columns on a spreadsheet: Employee ID and Sex (Male=1). A sample data is as follows: CAPTURE IMAGE

Each data entry is an unique observation, and I want to count the number of males and females. For example, there are 2 females and 1 male employee out of 32 observations. What forumula can I use to calculate the numbers?

答:
Use these array formulas:

Female:

```<code>=SUM(IF($B$2:$B$32=0,1/COUNTIFS($A$2:$A$32,$A$2:$A$32,$B$2:$B$32,0)))
</code>```

Male:

```<code>=SUM(IF($B$2:$B$32=1,1/COUNTIFS($A$2:$A$32,$A$2:$A$32,$B$2:$B$32,1)))
</code>```

being array formulas they need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

Body:
Use these array formulas:

Female:

=SUM(IF($B$2:$B$32=0,1/COUNTIFS($A$2:$A$32,$A$2:$A$32,$B$2:$B$32,0)))

Male:

=SUM(IF($B$2:$B$32=1,1/COUNTIFS($A$2:$A$32,$A$2:$A$32,$B$2:$B$32,1)))

being array formulas they need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.


问:
Pyspark: Is there an equivalent method to pandas info()?
Is there an equivalent method to pandas info() method in PySpark?

I am trying to gain basic statistics about a dataframe in PySpark, such as:
Number of columns and rows
Number of nulls
Size of dataframe

Info() method in pandas provides all these statistics.

答:
To figure out type information about data frame you could try df.schema

```<code>spark.read.csv('matchCount.csv',header=True).printSchema()

StructType(List(StructField(categ,StringType,true),StructField(minv,StringType,true),StructField(maxv,StringType,true),StructField(counts,StringType,true),StructField(cutoff,StringType,true)))
</code>```

For Summary stats you could also have a look at describe method from the documentation.

Body:
To figure out type information about data frame you could try df.schema

spark.read.csv('matchCount.csv',header=True).printSchema()

StructType(List(StructField(categ,StringType,true),StructField(minv,StringType,true),StructField(maxv,StringType,true),StructField(counts,StringType,true),StructField(cutoff,StringType,true)))

For Summary stats you could also have a look at describe method from the documentation.

ContentLicense: CC BY-SA 4.0


问:
In AWS Cognito - how to allow only specific email addresses from signing up?
I am using AWS Cognito in javascript with the amazon-cognito-identity-js package and it has been great.

I am wondering, how is it possible to only allow users with certain email address endings to go through the signup flow?

For example, only people who enter email address ending with ....@companyABC.com will be allowed to sign up and get the confirmation code sent to that email address. This will prevent people outside the company from accessing the application. The app does not have any top secret information, but we want only users within our company to access it.

I look to User Pool Settings and online but haven't been able to find a solution.

Thanks!

答:
if using angular 2

```<code><input
        type="text" class="form-control" id="loginEmail"
        required
        pattern="^[a-zA-Z0-9]*(@companyABC.com)$"
        [(ngModel)]="email" name="loginEmail"
        #loginEmail="ngModel">
</code>```

https://regex101.com/r/Y6P47P/3

Body:
if using angular 2

<input
        type="text" class="form-control" id="loginEmail"
        required
        pattern="^[a-zA-Z0-9]*(@companyABC.com)$"
        [(ngModel)]="email" name="loginEmail"
        #loginEmail="ngModel">

https://regex101.com/r/Y6P47P/3


问:
Referencing data package current version in guest executable
I'm deploying Lightstreamer Moderato (free for production use) as a stateless guest executable in Service Fabric.

I extracted Java in a jdk folder and Lightstreamer to a ls folder in a CodePackage called lib. Everything is working perfectly. The maintenance problem is that the config package version has to be specified in the ExeHost Arguments element:

ServiceManifest.xml:

```<code>  <CodePackage Name="lib" Version="1.2.3">
    <EntryPoint>
      <ExeHost>
        <Program>jdk\bin\java.exe</Program>
        <Arguments>-server -XX:MaxGCPauseMillis=1000 -Dcom.lightstreamer.kernel_lib_path=".\ls\lightstreamer.jar" -Dcom.lightstreamer.internal_lib_path=".\ls\ls-monitor.jar";".\ls\core\*" -Dcom.lightstreamer.logging_lib_path=".\ls\ls-logging-utilities.jar";".\ls\log\*" -cp ".\ls\ls-bootstrap.jar";".\ls\ls-adapter-interface.jar" com.lightstreamer.LS "..\Lightstreamer-Main.conf.2.0\lightstreamer_conf.xml"</Arguments>
    <WorkingFolder>CodePackage</WorkingFolder>
        <ConsoleRedirection FileRetentionCount="5" FileMaxSizeInKb="2048"/>
      </ExeHost>
    </EntryPoint>
  </CodePackage>

  <ConfigPackage Name="conf" Version="2.0" />
</code>```

How can a Service Fabric guest executable ServiceManifest.xml reference the correct ConfigPackage deployment in the command-line arguments?

答: Use SetupEntryPoint to find the latest cfg version folder, create a symlink,  and change the command-line arguments to use the symlink instead of the versioned cfg package path.

Body:
I'm deploying Lightstreamer Moderato (free for production use) as a stateless guest executable in Service Fabric.

I extracted Java in a jdk folder and Lightstreamer to a ls folder in a CodePackage called lib. Everything is working perfectly. The maintenance problem is that the config package version has to be specified in the ExeHost Arguments element:

ServiceManifest.xml:

  <CodePackage Name="lib" Version="1.2.3">
    <EntryPoint>
      <ExeHost>
        <Program>jdk\bin\java.exe</Program>
        <Arguments>-server -XX:MaxGCPauseMillis=1000 -Dcom.lightstreamer.kernel_lib_path=".\ls\lightstreamer.jar" -Dcom.lightstreamer.internal_lib_path=".\ls\ls-monitor.jar";".\ls\core\*" -Dcom.lightstreamer.logging_lib_path=".\ls\ls-logging-utilities.jar";".\ls\log\*" -cp ".\ls\ls-bootstrap.jar";".\ls\ls-adapter-interface.jar" com.lightstreamer.LS "..\Lightstreamer-Main.conf.2.0\lightstreamer_conf.xml"</Arguments>
    <WorkingFolder>CodePackage</WorkingFolder>
        <ConsoleRedirection FileRetentionCount="5" FileMaxSizeInKb="2048"/>
      </ExeHost>
    </EntryPoint>
  </CodePackage>

  <ConfigPackage Name="conf" Version="2.0" />

How can a Service Fabric guest executable ServiceManifest.xml reference the correct ConfigPackage deployment in the command-line arguments?


问:
An error occurred while closing the provider connection…OCI invalid handle
I searched a lot trying to find why am I getting this error but no help, can you please advise.

I am getting the following error when executing a linq query

```<code>    var test = (Linq query).ToList<Testdata>();
</code>```

System.Data.EntityException: An error occurred while closing the
  provider connection. See the inner exception for details. --->
  Devart.Data.Oracle.OracleException: OCI invalid handle.

at Devart.Data.Oracle.a1.c(Int32 A_0) at Devart.Data.Oracle.aq.d()

at Devart.Data.Oracle.OracleInternalConnection.a(Boolean A_0)

at Devart.Common.DbConnectionInternal.CloseInternalConnection()

at
  Devart.Data.Oracle.OracleInternalConnection.CloseInternalConnection()

at Devart.Common.DbConnectionInternal.Close()

at Devart.Data.Oracle.OracleInternalConnection.Close()

at Devart.Common.DbConnectionBase.Close()

at Devart.Data.Oracle.OracleConnection.Close()

at System.Data.EntityClient.EntityConnection.StoreCloseHelper() ---
  End of inner exception stack trace ---

at System.Data.EntityClient.EntityConnection.StoreCloseHelper()

at System.Data.EntityClient.EntityConnection.CloseHelper()

at System.Data.EntityClient.EntityConnection.Close()

at System.Data.Objects.ObjectContext.ReleaseConnection()

at System.Data.Common.Internal.Materialization.Shaper`1.Finally()

at
  ystem.Data.Common.Internal.Materialization.Shaper`1.ObjectQueryNestedEnumerator.Dispose()

at System.Collections.Generic.List1..ctor(IEnumerable1 collection)

at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

答: Please send us a small test project and DDL/DML script for reproducing the issue in our environment. Also specify the versions of your Oracle Server and Oracle Client.</p>

Body:
I searched a lot trying to find why am I getting this error but no help, can you please advise.

I am getting the following error when executing a linq query

    var test = (Linq query).ToList<Testdata>();

System.Data.EntityException: An error occurred while closing the
  provider connection. See the inner exception for details. --->
  Devart.Data.Oracle.OracleException: OCI invalid handle.

at Devart.Data.Oracle.a1.c(Int32 A_0) at Devart.Data.Oracle.aq.d()

at Devart.Data.Oracle.OracleInternalConnection.a(Boolean A_0)

at Devart.Common.DbConnectionInternal.CloseInternalConnection()

at
  Devart.Data.Oracle.OracleInternalConnection.CloseInternalConnection()

at Devart.Common.DbConnectionInternal.Close()

at Devart.Data.Oracle.OracleInternalConnection.Close()

at Devart.Common.DbConnectionBase.Close()

at Devart.Data.Oracle.OracleConnection.Close()

at System.Data.EntityClient.EntityConnection.StoreCloseHelper() ---
  End of inner exception stack trace ---

at System.Data.EntityClient.EntityConnection.StoreCloseHelper()

at System.Data.EntityClient.EntityConnection.CloseHelper()

at System.Data.EntityClient.EntityConnection.Close()

at System.Data.Objects.ObjectContext.ReleaseConnection()

at System.Data.Common.Internal.Materialization.Shaper`1.Finally()

at
  ystem.Data.Common.Internal.Materialization.Shaper`1.ObjectQueryNestedEnumerator.Dispose()

at System.Collections.Generic.List1..ctor(IEnumerable1 collection)

at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)


问:
Why is this conversion allowed?
So I have this code(stolen from cplusplus.com):

```<code>class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}
</code>```

So the conversion constructor can only be called explicitly and thereby fn(foo); is not allowed. This made me confused, because why can you do B bar (foo); if you cannot do fn(foo);, I mean doesn't fn(foo) also end up in initializing an object of type B to an object of type A, like in the statement B bar (foo);, so what are they both not generating an error? What is particularly explicit in B bar (foo); that is not explicit in the function call?

答: Doing B bar(foo) means that you are calling the constructor of B with foo as the argument, this is an explicit construction.  Whereas when you call fn(foo) the compiler tries to implicitly convert foo to match the function argument type, and this is an implicit conversion and is therefore not allowed since your convert constructor is marked explicit.

Title: Why is this conversion allowed?

Body:
So I have this code(stolen from cplusplus.com):

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}

So the conversion constructor can only be called explicitly and thereby fn(foo); is not allowed. This made me confused, because why can you do B bar (foo); if you cannot do fn(foo);, I mean doesn't fn(foo) also end up in initializing an object of type B to an object of type A, like in the statement B bar (foo);, so what are they both not generating an error? What is particularly explicit in B bar (foo); that is not explicit in the function call?


问:
Object expected error on node.js
When I run the below code on node js I get warning 'no such file or directory, open 'C:\Users\username\package.json

npm install getstream --save

答:
--save tells npm to save the installed package version and name to the package.json "dependencies" object. If you don't have a package.json within the directory running npm install using the --save flag you'll end up with this problem.

You'll need to call npm init within your project directory prior to running npm install getstream --save. npm init will ask some questions about your project prior to creating the package.json. If you don't want to answer the init questions, you can use the -f flag to force default answers.

Title: Object expected error on node.js


问:
SSIS Data flow task and "mixed" select
Can't get following to work. Notice it worked just fine using SQL Server 2000 DTS package.

AXDB is external server (SQL Server 2000 Enterprise) and OLAP being the local database, SQL Server 2008 R2 standard (olap is used select statement getting the date to pass on the external SQL Server). Adding server name doesn't help.

Servers are linked if it matters, probably not.

If I just write the date there instead of trying to get it via select statement it works fine as expected.

How to achieve what I want here, notice I have about 100 such packages.

Pics are here:

Error:

答:
Remove the ' ticks from around the sub-select:

```<code>...AND DATEPHYSICAL <= (SELECT lkpv FROM OLAP.dbo.laadimisaeg)
</code>```

Right now your select is being read as a string, and that string is trying to be compared to a date.

Title: SSIS Data flow task and "mixed" select

Body:
Remove the ' ticks from around the sub-select:

...AND DATEPHYSICAL <= (SELECT lkpv FROM OLAP.dbo.laadimisaeg)

Right now your select is being read as a string, and that string is trying to be compared to a date.


问:
Use data binding to set View visibility
Trying to set visibility of View using custom variable, but error occurs: Identifiers must have user defined types from the XML file. visible is missing it. Is it possible to set view visibility using data binding? Thanks.

```<code><data>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? visible : gone}"/>
</code>```

答:
In your layout:

```<code><data>
    <variable
        name="viewModel"
        type="...."/>
</data>

<View
 android:layout_width="10dp"
 android:layout_height="10dp"
 android:visibility="@{viewModel.saleVisibility, default=gone}"/>
</code>```

In your ViewModel java code:

```<code>@Bindable
public int getSaleVisibility(){
 return mSaleIndecator ? VISIBLE : GONE;
}
</code>```

Title: Use data binding to set View visibility

Body:
Trying to set visibility of View using custom variable, but error occurs: Identifiers must have user defined types from the XML file. visible is missing it. Is it possible to set view visibility using data binding? Thanks.

<data>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? visible : gone}"/>

Body:
In your layout:

<data>
    <variable
        name="viewModel"
        type="...."/>
</data>

<View
 android:layout_width="10dp"
 android:layout_height="10dp"
 android:visibility="@{viewModel.saleVisibility, default=gone}"/>

In your ViewModel java code:

@Bindable
public int getSaleVisibility(){
 return mSaleIndecator ? VISIBLE : GONE;
}


问:
How to use *ngFor on a JSON data in Angular?
I am trying to create a dymanic table with rows and columns defined as a array and JSON object. I am able to build the column headers dynamically. But the rows are not getting rendered. I am coming from angularjs 1.x background and new to angular.

Please help we understand the problem. Here is the plunker https://plnkr.co/edit/BG22Z1videTlzU3SrjcT?p=preview

```<code><table class="table">
            <thead>
                <tr>
                    <th *ngFor="let column of columnNames">
                        {{column}}
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let userDate of userDateObj">
                    <td>{{userDate.name}}</td>
                    <td>{{patientData.dob}}</td>
                </tr>
            </tbody>
        </table>
</code>```

答:
I observed that in your plunker userDateObj is not array. You need to correct that as

```<code><tr *ngFor="let userDate of userDateObj.userDate">
</code>```

I have editted the plunker please find the update here

Body:
I am trying to create a dymanic table with rows and columns defined as a array and JSON object. I am able to build the column headers dynamically. But the rows are not getting rendered. I am coming from angularjs 1.x background and new to angular.

Please help we understand the problem. Here is the plunker https://plnkr.co/edit/BG22Z1videTlzU3SrjcT?p=preview

                        {{column}}

                    {{userDate.name}}
                    {{patientData.dob}}

Body:
I observed that in your plunker userDateObj is not array. You need to correct that as

<tr *ngFor="let userDate of userDateObj.userDate">

I have editted the plunker please find the update here


问:
Can I trap the "Cannot truncate table" error and Delete instead?
I know that a valid replacement for TRUNCATE TABLE "MyTable" is:
DELETE FROM MyTable
DBCC CHECKIDENT ('DATABASENAME.dbo.MyTable',RESEED, 0)

However, I'd prefer to use TRUNCATE TABLE whenever possible, but I have a few clients who use database replication.  For those clients, I get the error: Cannot truncate table 'MyTable' because it is published for replication or enabled for Change Data Capture.

Is there a way to either 1) pre-test that TRUNCATE will work, or 2) issue the TRUNCATE command in such a way that it does not fail, but instead leaves a testable value (@@ERROR maybe?) that allows me to execute the DELETE if it fails?

答:
```<code>begin try
    truncata table dbo.YourTableName;
end try
begin catch
    delete from dbo.YourTableName;
end catch
</code>```

Something like this...

Body:
begin try
    truncata table dbo.YourTableName;
end try
begin catch
    delete from dbo.YourTableName;
end catch

Something like this...


问:
Getting days since last occurence in Pandas DataFrame?
Let's say I have a Pandas DataFrame df:

```<code>Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0
</code>```

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

```<code>Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2
</code>```

I could do a loop:

```<code>for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last
</code>```

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

答:
You don't have to update the value to last every step in the for loop. Initiate a variable outside the loop

```<code>last = np.nan
for i in range(len(df)):
    if df.loc[i, 'Value'] == 1:
        last = i
    df.loc[i, 'Last_Occurence'] = i - last
</code>```

and update it only when a 1 occurs in column Value.

Note that no matter what method you select, iterating the whole table once is inevitable.

Body:
Let's say I have a Pandas DataFrame df:

Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2

I could do a loop:

for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

Body:
You don't have to update the value to last every step in the for loop. Initiate a variable outside the loop

last = np.nan
for i in range(len(df)):
    if df.loc[i, 'Value'] == 1:
        last = i
    df.loc[i, 'Last_Occurence'] = i - last

and update it only when a 1 occurs in column Value.

Note that no matter what method you select, iterating the whole table once is inevitable.


问:
Tools, rules or processes for checking internal consistency of XML config files
I've worked on projects that have very complex XML configuration, and one problem that's faced is maintaining the internal consistency of the XML.

In this case I don't mean the strict XML schema consistency, but rather the higher level relation between the nodes used. Most problems were caused by implicit linking between information encoded in the XML, and implicit relation of that information to the codebase. Examples might be:

XML node data implicitly linked to enums in code

Business objects in the same config that are related (in that they share information that needs to be consistent) without any explicit relation between them

Code in XML to be compiled and parsed at runtime

It struck me that a) this might become a practice of increasing frequency and b) that in some cases we're implicitly creating a new coding language that's not compile-time checked -- and in fact has few checks at all until it's run.

Is anyone else out there facing similar scenarios, and are there any tools or approaches that make the problem more tractable? I'd like some general examples that are technology-agnostic -- my own specific experience has been with C# and with config for proprietary systems.

Note: although I have an answer to this below, I've no intent of taking my own as the final answer.

答:
I use automated functional tests to ensure the data integrity of our default config at work. I don't know that the problem you describe is necessarily dependent on the config format being XML.  That being said I would suggest:

You don't use XML as a config format. (Google can give you the reasons)

Tight coupling through the implicit use of enums or any other constructed values are just as bad in a config as they are in code.

Code that get's pulled from a config and executed makes me cringe.  Is it in a config so that it can be overridden?  If so that's a huge vector for bugs, undefined behavior and potential security issues.

the business objects issue also sounds like bad tight coupling.

You may not be able to do anything about XML as the config format, the bad coupling, or the execution of code from config.  You can mitigate the risk by creating a suite of functional tests that ensure:

the enums are valid

the code is compilable, executable, doesn't contain evals, rpc calls, calls no functions, or whatever other analysis checks you want to add.

You can also sometimes help change by providing an alternative (config or config entries).


问:
Get only footer css from materialize
I have a webpage with my own css and bootstrap v4, but I want to use the footer of Materialize, but I don't want to use the entire css code to avoid conflicts with bootstrap, is there any way to get only this part of css?</p>

答:
i dont know if there exist some other code for this . you can try mdbootstrap or similar . but here is a snippet that i have made .

html

```<code><!--Footer-->
<footer class="page-footer blue center-on-small-only">
  <!--Footer Links-->
  <div class="container-fluid">
    <div class="row">
      <!--First column-->
      <div class="col-md-3 offset-md-1">
        <h3 class="title">Footer Content</h3>
        <p>Here you can use rows and columns here to organize your footer content.</p>
      </div>
      <!--/.First column-->
      <hr class="hidden-md-up">
      <!--Second column-->
      <div class="col-md-2 offset-md-1">
        <h5 class="title">Links</h5>
        <ul>
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!--/.Second column-->
      <hr class="hidden-md-up">
      <!--Third column-->
      <div class="col-md-2">
        <h5 class="title">Links</h5>
        <ul>
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!--/.Third column-->
      <hr class="hidden-md-up">
      <!--Fourth column-->
      <div class="col-md-2">
        <h5 class="title">Links</h5>
        <ul>
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!--/.Fourth column-->
    </div>
  </div>
  <!--/.Footer Links-->
  <!--Copyright-->
  <div class="footer-copyright">
    <div class="container-fluid">
      © 2017 Copyright: <a href="https://stackoverflow.com/users/4004879/jayakrishnan">jayakrishnancn.co.nf </a>
    </div>
  </div>
  <!--/.Copyright-->
</footer>
<!--/.Footer-->
</code>```

css

```<code>.blue {
  background: #ee6e73;
}

.page-footer {
  color: #fff;
}
.page-footer .title {
  line-height: 2em;
}
.page-footer .container-fluid {
  padding: 10px;
}
.page-footer li, .page-footer ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
.page-footer a {
  color: #fff;
  text-decoration: none;
}
.page-footer .footer-copyright {
  background: rgba(51, 51, 51, 0.08);
  padding: 10px 0px;
}
</code>```

Title: Get only footer css from materialize

Body:
i dont know if there exist some other code for this . you can try mdbootstrap or similar . but here is a snippet that i have made .

html

<!--Footer-->
<footer class="page-footer blue center-on-small-only">
  <!--Footer Links-->
  <div class="container-fluid">
    <div class="row">
      <!--First column-->
      <div class="col-md-3 offset-md-1">
        <h3 class="title">Footer Content</h3>
        <p>Here you can use rows and columns here to organize your footer content.</p>
      </div>
      <!--/.First column-->
      <hr class="hidden-md-up">
      <!--Second column-->
      <div class="col-md-2 offset-md-1">
        <h5 class="title">Links</h5>
        <ul>
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!--/.Second column-->
      <hr class="hidden-md-up">
      <!--Third column-->
      <div class="col-md-2">
        <h5 class="title">Links</h5>
        <ul>
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!--/.Third column-->
      <hr class="hidden-md-up">
      <!--Fourth column-->
      <div class="col-md-2">
        <h5 class="title">Links</h5>
        <ul>
          <li><a href="#!">Link 1</a></li>
          <li><a href="#!">Link 2</a></li>
          <li><a href="#!">Link 3</a></li>
          <li><a href="#!">Link 4</a></li>
        </ul>
      </div>
      <!--/.Fourth column-->
    </div>
  </div>
  <!--/.Footer Links-->
  <!--Copyright-->
  <div class="footer-copyright">
    <div class="container-fluid">
      © 2017 Copyright: <a href="https://stackoverflow.com/users/4004879/jayakrishnan">jayakrishnancn.co.nf </a>
    </div>
  </div>
  <!--/.Copyright-->
</footer>
<!--/.Footer-->

css

.blue {
  background: #ee6e73;
}

.page-footer {
  color: #fff;
}
.page-footer .title {
  line-height: 2em;
}
.page-footer .container-fluid {
  padding: 10px;
}
.page-footer li, .page-footer ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
.page-footer a {
  color: #fff;
  text-decoration: none;
}
.page-footer .footer-copyright {
  background: rgba(51, 51, 51, 0.08);
  padding: 10px 0px;
}


问:
Proper Edge Recombination Crossover for DNA assembly
I was trying to implement genetic algorithm to assemble DNA fragments into one sequence given only the spectrum. My only operator is Edge Recombination and I was convinced that it's enough to get a pretty good result.

But... i can't beat 80% (% of optimum score) and instances with 500 fragments can take to 2 hours (algorithm stops if there is no improvement in 100 iterations). Am I even implementing it right? I didn't find anywhere that crossover operators should choose elements that are matching better (overlapping of fragments - in most paper it's just random what we pick), but I implemented it that it picks the best matching one, and if there are many - random one. Without picking the best one it doesn't even score 40%.

Should I implement more crossovers? Or it's just not how it works... Or am I missing something? I'm quite desperate at this point, waiting 24hours for 40 instances that simple heuristics (hill climber) can do under 5 seconds...

There's the code (permutation is a shuffled spectrum - list of strings)

```<code>    def crossover(g1, g2, arr, ind):  # edge recombination operator
    neigh_list = {}  # adjacency list
    length = len(g1.permutation)  # expected length of a child
    for i, base in enumerate(g1.permutation):  # create nodes
        neigh_list[base] = {g1.permutation[i - 1], g1.permutation[(i + 1) % length]}
    for i, base in enumerate(g2.permutation):  # add neighbours to each node
        neigh_list[base].add(g2.permutation[i - 1])
        neigh_list[base].add(g2.permutation[(i + 1) % length])

    # a starting point of a child is a starting point of one of the parents
    neigh_chosen = [g1.permutation[0], g2.permutation[0]][random.randint(0, 1)]
    child = [neigh_chosen]

    while len(child) < length:  # run until child has desired length
        min_length = 5  # each list has lower length than 5
        min_neigh_list = []
        for k in neigh_list:  # for every node
            if neigh_chosen in neigh_list[k]:  # remove a chosen fragment from the node
                neigh_list[k].remove(neigh_chosen)
        for k in neigh_list[neigh_chosen]:  # if a node is a neighbour of previously chosen
            if len(neigh_list[k]) < min_length:  # remember nodes with the fewest neighbours
                min_length = len(neigh_list[k])
                min_neigh_list = [k]
            elif len(neigh_list[k]) == min_length:
                min_neigh_list.append(k)
        del neigh_list[neigh_chosen]  # delete list of the chosen node
        if len(min_neigh_list) > 0:  # if the chosen node has any neighbours
            # get the best match out of neighbours as next
            max_overlap = overlap(neigh_chosen, max(min_neigh_list, key=lambda x: overlap(neigh_chosen, x)))
            possibilities = list(filter(lambda x: overlap(neigh_chosen, x) == max_overlap, min_neigh_list))
            neigh_chosen = possibilities[random.randint(0, len(possibilities) - 1)]
        else:
            # get the best match out of every node as next
            max_overlap = overlap(neigh_chosen, max(neigh_list, key=lambda x: overlap(neigh_chosen, x)))
            possibilities = list(filter(lambda x: overlap(neigh_chosen, x) == max_overlap, neigh_list))
            neigh_chosen = possibilities[random.randint(0, len(possibilities) - 1)]
        child.append(neigh_chosen)  # add the node to the solution
    arr[ind] = Gene(child)
</code>```

答:
Ok, I managed to solve this one doing a pretty easy trick. The problem was in understanding what this operator actually does and where to use it. To make it help doing the DNA assembly problem just replace

```<code>    for k in neigh_list[neigh_chosen]:  # if a node is a neighbour of previously chosen
        if len(neigh_list[k]) < min_length:  # remember nodes with the fewest neighbours
            min_length = len(neigh_list[k])
            min_neigh_list = [k]
        elif len(neigh_list[k]) == min_length:
            min_neigh_list.append(k)
    del neigh_list[neigh_chosen]
</code>```

with

```<code>    min_neigh_list = neigh_list[neight_chosen]
    del neigh_list[neigh_chosen]
</code>```

The reason it works is because we are not looking for a fragment with minimum number of neighbours (it might be important in other kind of graph related problem!) but a neighbour with the best match!

It works like a charm after this simple change :)

Body:
I was trying to implement genetic algorithm to assemble DNA fragments into one sequence given only the spectrum. My only operator is Edge Recombination and I was convinced that it's enough to get a pretty good result.

But... i can't beat 80% (% of optimum score) and instances with 500 fragments can take to 2 hours (algorithm stops if there is no improvement in 100 iterations). Am I even implementing it right? I didn't find anywhere that crossover operators should choose elements that are matching better (overlapping of fragments - in most paper it's just random what we pick), but I implemented it that it picks the best matching one, and if there are many - random one. Without picking the best one it doesn't even score 40%.

Should I implement more crossovers? Or it's just not how it works... Or am I missing something? I'm quite desperate at this point, waiting 24hours for 40 instances that simple heuristics (hill climber) can do under 5 seconds...

There's the code (permutation is a shuffled spectrum - list of strings)

    def crossover(g1, g2, arr, ind):  # edge recombination operator
    neigh_list = {}  # adjacency list
    length = len(g1.permutation)  # expected length of a child
    for i, base in enumerate(g1.permutation):  # create nodes
        neigh_list[base] = {g1.permutation[i - 1], g1.permutation[(i + 1) % length]}
    for i, base in enumerate(g2.permutation):  # add neighbours to each node
        neigh_list[base].add(g2.permutation[i - 1])
        neigh_list[base].add(g2.permutation[(i + 1) % length])

    # a starting point of a child is a starting point of one of the parents
    neigh_chosen = [g1.permutation[0], g2.permutation[0]][random.randint(0, 1)]
    child = [neigh_chosen]

    while len(child) < length:  # run until child has desired length
        min_length = 5  # each list has lower length than 5
        min_neigh_list = []
        for k in neigh_list:  # for every node
            if neigh_chosen in neigh_list[k]:  # remove a chosen fragment from the node
                neigh_list[k].remove(neigh_chosen)
        for k in neigh_list[neigh_chosen]:  # if a node is a neighbour of previously chosen
            if len(neigh_list[k]) < min_length:  # remember nodes with the fewest neighbours
                min_length = len(neigh_list[k])
                min_neigh_list = [k]
            elif len(neigh_list[k]) == min_length:
                min_neigh_list.append(k)
        del neigh_list[neigh_chosen]  # delete list of the chosen node
        if len(min_neigh_list) > 0:  # if the chosen node has any neighbours
            # get the best match out of neighbours as next
            max_overlap = overlap(neigh_chosen, max(min_neigh_list, key=lambda x: overlap(neigh_chosen, x)))
            possibilities = list(filter(lambda x: overlap(neigh_chosen, x) == max_overlap, min_neigh_list))
            neigh_chosen = possibilities[random.randint(0, len(possibilities) - 1)]
        else:
            # get the best match out of every node as next
            max_overlap = overlap(neigh_chosen, max(neigh_list, key=lambda x: overlap(neigh_chosen, x)))
            possibilities = list(filter(lambda x: overlap(neigh_chosen, x) == max_overlap, neigh_list))
            neigh_chosen = possibilities[random.randint(0, len(possibilities) - 1)]
        child.append(neigh_chosen)  # add the node to the solution
    arr[ind] = Gene(child)

Body:
Ok, I managed to solve this one doing a pretty easy trick. The problem was in understanding what this operator actually does and where to use it. To make it help doing the DNA assembly problem just replace

    for k in neigh_list[neigh_chosen]:  # if a node is a neighbour of previously chosen
        if len(neigh_list[k]) < min_length:  # remember nodes with the fewest neighbours
            min_length = len(neigh_list[k])
            min_neigh_list = [k]
        elif len(neigh_list[k]) == min_length:
            min_neigh_list.append(k)
    del neigh_list[neigh_chosen]

with

    min_neigh_list = neigh_list[neight_chosen]
    del neigh_list[neigh_chosen]

The reason it works is because we are not looking for a fragment with minimum number of neighbours (it might be important in other kind of graph related problem!) but a neighbour with the best match!

It works like a charm after this simple change :)


问:
NodeJS Express enumerate files in a folder
Sorry, I'm new with NodeJS Express. I want to get all files from a folder. I tried the following but don't work, test is always empty string: </p>

```<code>var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    var test = '';

    const testFolder = './public/images';

    fs.readdir(testFolder, (err, files) => {
      test = files[0];
    })

    res.render('index', { title: 'Express', file: test });
});
</code>```

<p>Basically, I want to get all filenames from public images folder. </p>

答:
Problem here is res.render() will be executed before test is assigned to files[0], because the fs.readdir is asynchronous process. Before your callback is called res.render is excuted. And also, if you are trying to get all files from the folder you should pass files array. Please take a look at this for more info. You might wanna try the below code.

```<code>var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    var test = '';

    const testFolder = './public/images';

    fs.readdir(testFolder, (err, files) => {
       // test = files[0]; this will assign test to the first element of the array of file
       test = files;
       res.render('index', { title: 'Express', file: test });
    })

});
</code>```

Body:
Sorry, I'm new with NodeJS Express. I want to get all files from a folder. I tried the following but don't work, test is always empty string:

var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    var test = '';

    const testFolder = './public/images';

    fs.readdir(testFolder, (err, files) => {
      test = files[0];
    })

    res.render('index', { title: 'Express', file: test });
});

Basically, I want to get all filenames from public images folder.

Body:
Problem here is res.render() will be executed before test is assigned to files[0], because the fs.readdir is asynchronous process. Before your callback is called res.render is excuted. And also, if you are trying to get all files from the folder you should pass files array. Please take a look at this for more info. You might wanna try the below code.

var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    var test = '';

    const testFolder = './public/images';

    fs.readdir(testFolder, (err, files) => {
       // test = files[0]; this will assign test to the first element of the array of file
       test = files;
       res.render('index', { title: 'Express', file: test });
    })

});


问:
Java Bulk Insert with Shared Entity Manager
I am trying to write a method that bulk adds entities to the database. Here's my method:

```<code>@Transactional
protected void bulkInsert(List<?> entities) {
    int batchSize = 25;
    AtomicInteger i = new AtomicInteger(0);
    try {
        em.getTransaction().begin();
        entities.parallelStream().forEach(e -> {
            em.persist(e);
            if ( i.get() > 0 && i.get() % batchSize == 0 ) {
                em.flush();
                em.clear();
            }
            i.incrementAndGet();
        });
        em.getTransaction().commit();
    } catch (RuntimeException e) {
        LOG.error("Error", e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
</code>```

But when I run this I get the following error:

```<code>java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:248) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at com.sun.proxy.$Proxy145.getTransaction(Unknown Source) ~[na:na]
</code>```

I tried removing the @Transactional annotation and still the same error. I tried using Session by doing Session session = em.unwrap(Session.class); but that still resulted in an error (although different error)

How do I bulk insert objects?

答:
in pure hibernate exists managed- and non-managed environments

Non-managed environment

If an JPA persistence layer runs in a non-managed environment, database >connections are usually handled by Hibernate's pooling mechanism behind the >scenes. The common entity manager and transaction handling idiom looks like > this:

// Non-managed environment idiom

EntityManager em = emf.createEntityManager(); EntityTransaction tx =
  null; try {
       tx = em.getTransaction();
       tx.begin();

```<code> // do some work
 ...

 tx.commit(); } catch (RuntimeException e) {
 if ( tx != null && tx.isActive() ) tx.rollback();
 throw e; // or display error message } finally {
 em.close(); }
</code>```

Using JTA
  If you use bean-managed transactions (BMT), the code will
  look like this:

// BMT idiom
  @Resource public UserTransaction utx;
  @Resource public
  EntityManagerFactory factory;

public void doBusiness() {
      EntityManager em = factory.createEntityManager();
      try {

```<code>// do some work
...

utx.commit(); } catch (RuntimeException e) {
if (utx != null) utx.rollback();
throw e; // or display error message
} finally {
em.close();
</code>```

}

With Container Managed Transactions (CMT) in an EJB3 container, transaction >demarcation is done in session bean annotations
  or deployment descriptors, not programatically. The EntityManager will
  automatically be flushed on transaction completion (and if you have
  injected or lookup the EntityManager, it will be also closed
  automatically). If an exception occurs during the EntityManager use,
  transaction rollback occurs automatically if you don't catch the
  exception. Since EntityManager exceptions are RuntimeExceptions they
  will rollback the transaction as per the EJB specification (system
  exception vs. application exception).

you should follow on of two princeple.

annotation @Transactional it's spring annotaniot not hibernate. if you didn;t configued it (or you did configured spring) doen't work.

PC

An EntityManager is an inexpensive, non-threadsafe object that should
  be used once, for a single business process

call  em.flush() ,em.clear() might be dangerous  .

Body:
I am trying to write a method that bulk adds entities to the database. Here's my method:

@Transactional
protected void bulkInsert(List<?> entities) {
    int batchSize = 25;
    AtomicInteger i = new AtomicInteger(0);
    try {
        em.getTransaction().begin();
        entities.parallelStream().forEach(e -> {
            em.persist(e);
            if ( i.get() > 0 && i.get() % batchSize == 0 ) {
                em.flush();
                em.clear();
            }
            i.incrementAndGet();
        });
        em.getTransaction().commit();
    } catch (RuntimeException e) {
        LOG.error("Error", e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

But when I run this I get the following error:

java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:248) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at com.sun.proxy.$Proxy145.getTransaction(Unknown Source) ~[na:na]

I tried removing the @Transactional annotation and still the same error. I tried using Session by doing Session session = em.unwrap(Session.class); but that still resulted in an error (although different error)

How do I bulk insert objects?

Body:
in pure hibernate exists managed- and non-managed environments

Non-managed environment

If an JPA persistence layer runs in a non-managed environment, database >connections are usually handled by Hibernate's pooling mechanism behind the >scenes. The common entity manager and transaction handling idiom looks like > this:

// Non-managed environment idiom

EntityManager em = emf.createEntityManager(); EntityTransaction tx =
  null; try {
       tx = em.getTransaction();
       tx.begin();

 // do some work
 ...

 tx.commit(); } catch (RuntimeException e) {
 if ( tx != null && tx.isActive() ) tx.rollback();
 throw e; // or display error message } finally {
 em.close(); }

Using JTA
  If you use bean-managed transactions (BMT), the code will
  look like this:

// BMT idiom
  @Resource public UserTransaction utx;
  @Resource public
  EntityManagerFactory factory;

public void doBusiness() {
      EntityManager em = factory.createEntityManager();
      try {

// do some work
...

utx.commit(); } catch (RuntimeException e) {
if (utx != null) utx.rollback();
throw e; // or display error message
} finally {
em.close();

}

With Container Managed Transactions (CMT) in an EJB3 container, transaction >demarcation is done in session bean annotations
  or deployment descriptors, not programatically. The EntityManager will
  automatically be flushed on transaction completion (and if you have
  injected or lookup the EntityManager, it will be also closed
  automatically). If an exception occurs during the EntityManager use,
  transaction rollback occurs automatically if you don't catch the
  exception. Since EntityManager exceptions are RuntimeExceptions they
  will rollback the transaction as per the EJB specification (system
  exception vs. application exception).

you should follow on of two princeple.

annotation @Transactional it's spring annotaniot not hibernate. if you didn;t configued it (or you did configured spring) doen't work.

PC

An EntityManager is an inexpensive, non-threadsafe object that should
  be used once, for a single business process

call  em.flush() ,em.clear() might be dangerous  .


问:
changing static variables from another method in java
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

```<code>public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}
</code>```

答:
You declared variables inside of method so you don't have access to them, if you want to change them you either make them global(define them outside of method):

```<code> public class Test
{
int x;
int y;
int z;
void yourMethod(){

  }
}
</code>```

Or change method find to take x, y and z values as parameters.

Body:
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}

Body:
You declared variables inside of method so you don't have access to them, if you want to change them you either make them global(define them outside of method):

 public class Test
{
int x;
int y;
int z;
void yourMethod(){

  }
}

Or change method find to take x, y and z values as parameters.


问:
HTML Button not responding to the CSS in live using dreamweaver
Hello everyone I'm having an issue with my HMTL and the CSS assigned to it not working. The button works, it will link over as it should but the CSS is not effecting it.
I use dreamweaver CC and in design view it seems like the CSS is working but once i live view it on browser it reverts back to its original state I'll provide a few pictures of the code and live view to show you what I mean.

My HTML

```<code><a href="methandrailhome.html" class="returnhome">Return Home</a><!-- end .returnhome -->
</code>```

MY CSS

```<code>#form .returnhome {

    -moz-box-shadow:inset -4px 2px 0px -13px #ffffff;
    -webkit-box-shadow:inset -4px 2px 0px -13px #ffffff;
    box-shadow:inset -4px 2px 0px -13px #ffffff;
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9) );
    background:-moz-linear-gradient( center top, #f9f9f9 5%, #e9e9e9 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9');
    background-color:#f9f9f9;
    -webkit-border-top-left-radius:0px;
    -moz-border-radius-topleft:0px;
    border-top-left-radius:0px;
    -webkit-border-top-right-radius:0px;
    -moz-border-radius-topright:0px;
    border-top-right-radius:0px;
    -webkit-border-bottom-right-radius:0px;
    -moz-border-radius-bottomright:0px;
    border-bottom-right-radius:0px;
    -webkit-border-bottom-left-radius:0px;
    -moz-border-radius-bottomleft:0px;
    border-bottom-left-radius:0px;
    text-indent:-1.9px;
    border:2px solid #dcdcdc;
    display:inline-block;
    color:#666666;
    font-family:Arial;
    font-size:13px;
    font-weight:bold;
    font-style:normal;
    height:40px;
    line-height:40px;
    width:95px;
    text-decoration:none;
    text-align:center;
    text-shadow:0px 0px 0px #ffffff;
}
</code>```

    .returnhome {

     -moz-box-shadow:inset -4px 2px 0px -13px #ffffff;
     -webkit-box-shadow:inset -4px 2px 0px -13px #ffffff;
     box-shadow:inset -4px 2px 0px -13px #ffffff;
     background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9) );
     background:-moz-linear-gradient( center top, #f9f9f9 5%, #e9e9e9 100% );
     filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9');
     background-color:#f9f9f9;
     -webkit-border-top-left-radius:0px;
     -moz-border-radius-topleft:0px;
     border-top-left-radius:0px;
     -webkit-border-top-right-radius:0px;
     -moz-border-radius-topright:0px;
     border-top-right-radius:0px;
     -webkit-border-bottom-right-radius:0px;
     -moz-border-radius-bottomright:0px;
     border-bottom-right-radius:0px;
     -webkit-border-bottom-left-radius:0px;
     -moz-border-radius-bottomleft:0px;
     border-bottom-left-radius:0px;
     text-indent:-1.9px;
     border:2px solid #dcdcdc;
     display:inline-block;
     color:#666666;
     font-family:Arial;
     font-size:13px;
     font-weight:bold;
     font-style:normal;
     height:40px;
     line-height:40px;
     width:95px;
     text-decoration:none;
     text-align:center;
     text-shadow:0px 0px 0px #ffffff;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Return Home</code>```

Here is what live view from Dreamwweaver is showing

答:
Take that #form out.

.returnhome {
  -moz-box-shadow: inset -4px 2px 0px -13px #ffffff;
  -webkit-box-shadow: inset -4px 2px 0px -13px #ffffff;
  box-shadow: inset -4px 2px 0px -13px #ffffff;
  background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9));
  background: -moz-linear-gradient( center top, #f9f9f9 5%, #e9e9e9 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9');
  background-color: #f9f9f9;
  -webkit-border-top-left-radius: 0px;
  -moz-border-radius-topleft: 0px;
  border-top-left-radius: 0px;
  -webkit-border-top-right-radius: 0px;
  -moz-border-radius-topright: 0px;
  border-top-right-radius: 0px;
  -webkit-border-bottom-right-radius: 0px;
  -moz-border-radius-bottomright: 0px;
  border-bottom-right-radius: 0px;
  -webkit-border-bottom-left-radius: 0px;
  -moz-border-radius-bottomleft: 0px;
  border-bottom-left-radius: 0px;
  text-indent: -1.9px;
  border: 2px solid #dcdcdc;
  display: inline-block;
  color: #666666;
  font-family: Arial;
  font-size: 13px;
  font-weight: bold;
  font-style: normal;
  height: 40px;
  line-height: 40px;
  width: 95px;
  text-decoration: none;
  text-align: center;
  text-shadow: 0px 0px 0px #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Return Home</code>```

Body:
Hello everyone I'm having an issue with my HMTL and the CSS assigned to it not working. The button works, it will link over as it should but the CSS is not effecting it.
I use dreamweaver CC and in design view it seems like the CSS is working but once i live view it on browser it reverts back to its original state I'll provide a few pictures of the code and live view to show you what I mean.

My HTML

Return Home

MY CSS

#form .returnhome {

    -moz-box-shadow:inset -4px 2px 0px -13px #ffffff;
    -webkit-box-shadow:inset -4px 2px 0px -13px #ffffff;
    box-shadow:inset -4px 2px 0px -13px #ffffff;
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9) );
    background:-moz-linear-gradient( center top, #f9f9f9 5%, #e9e9e9 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9');
    background-color:#f9f9f9;
    -webkit-border-top-left-radius:0px;
    -moz-border-radius-topleft:0px;
    border-top-left-radius:0px;
    -webkit-border-top-right-radius:0px;
    -moz-border-radius-topright:0px;
    border-top-right-radius:0px;
    -webkit-border-bottom-right-radius:0px;
    -moz-border-radius-bottomright:0px;
    border-bottom-right-radius:0px;
    -webkit-border-bottom-left-radius:0px;
    -moz-border-radius-bottomleft:0px;
    border-bottom-left-radius:0px;
    text-indent:-1.9px;
    border:2px solid #dcdcdc;
    display:inline-block;
    color:#666666;
    font-family:Arial;
    font-size:13px;
    font-weight:bold;
    font-style:normal;
    height:40px;
    line-height:40px;
    width:95px;
    text-decoration:none;
    text-align:center;
    text-shadow:0px 0px 0px #ffffff;
}

    .returnhome {

     -moz-box-shadow:inset -4px 2px 0px -13px #ffffff;
     -webkit-box-shadow:inset -4px 2px 0px -13px #ffffff;
     box-shadow:inset -4px 2px 0px -13px #ffffff;
     background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9) );
     background:-moz-linear-gradient( center top, #f9f9f9 5%, #e9e9e9 100% );
     filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9');
     background-color:#f9f9f9;
     -webkit-border-top-left-radius:0px;
     -moz-border-radius-topleft:0px;
     border-top-left-radius:0px;
     -webkit-border-top-right-radius:0px;
     -moz-border-radius-topright:0px;
     border-top-right-radius:0px;
     -webkit-border-bottom-right-radius:0px;
     -moz-border-radius-bottomright:0px;
     border-bottom-right-radius:0px;
     -webkit-border-bottom-left-radius:0px;
     -moz-border-radius-bottomleft:0px;
     border-bottom-left-radius:0px;
     text-indent:-1.9px;
     border:2px solid #dcdcdc;
     display:inline-block;
     color:#666666;
     font-family:Arial;
     font-size:13px;
     font-weight:bold;
     font-style:normal;
     height:40px;
     line-height:40px;
     width:95px;
     text-decoration:none;
     text-align:center;
     text-shadow:0px 0px 0px #ffffff;
    }

Return Home

Here is what live view from Dreamwweaver is showing

Body:
Take that #form out.

.returnhome {
  -moz-box-shadow: inset -4px 2px 0px -13px #ffffff;
  -webkit-box-shadow: inset -4px 2px 0px -13px #ffffff;
  box-shadow: inset -4px 2px 0px -13px #ffffff;
  background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9));
  background: -moz-linear-gradient( center top, #f9f9f9 5%, #e9e9e9 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9');
  background-color: #f9f9f9;
  -webkit-border-top-left-radius: 0px;
  -moz-border-radius-topleft: 0px;
  border-top-left-radius: 0px;
  -webkit-border-top-right-radius: 0px;
  -moz-border-radius-topright: 0px;
  border-top-right-radius: 0px;
  -webkit-border-bottom-right-radius: 0px;
  -moz-border-radius-bottomright: 0px;
  border-bottom-right-radius: 0px;
  -webkit-border-bottom-left-radius: 0px;
  -moz-border-radius-bottomleft: 0px;
  border-bottom-left-radius: 0px;
  text-indent: -1.9px;
  border: 2px solid #dcdcdc;
  display: inline-block;
  color: #666666;
  font-family: Arial;
  font-size: 13px;
  font-weight: bold;
  font-style: normal;
  height: 40px;
  line-height: 40px;
  width: 95px;
  text-decoration: none;
  text-align: center;
  text-shadow: 0px 0px 0px #ffffff;
}

<a href="methandrailhome.html" class="returnhome">Return Home</a>


问:
Replicate shell environment in python for executing bash commands
I'm trying to execute a bash script from inside python using the subprocess module. The problem is that this bash script relies on many environment variables that are set in my .bashrc file. What I want is for python subprocess to exactly replicate the environment that is setup when I launch a terminal window. So far I tried:

```<code>p = subprocess.Popen(args=['my-script.sh', '--additional_args'], stdout=subprocess.PIPE, env=os.environ.copy(), shell=True)
output_buffer, return_code = p.communicate()
</code>```

But then read somewhere that even after doing shell=True, the .bashrc file is still not loaded, and that i should try something like this:

```<code>p = subprocess.Popen(args=['/bin/bash', '-i', '-c', 'my_script.sh', '--additional_args'], stdout=subprocess.PIPE)
output_buffer, return_code = p.communicate()
</code>```

But with this function call, I get this error:

```<code>tput: No value for $TERM and no -T specified
bash: cannot set terminal process group (2071): Inappropriate ioctl for device
bash: no job control in this shell
</code>```

答:
This worked for me:

Bashrc

```<code>$ cat ~/.bashrc  |grep LOLO
export LOLO="/foo/bar"
</code>```

Bash

```<code>#!/usr/bin/bash

echo $LOLO
</code>```

Python

```<code>#!/usr/bin/python

import subprocess, os
my_env = os.environ.copy()
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
subprocess.Popen('/home/m.ortiz.montealegre/lolo/script.sh', env=my_env)
</code>```

Output:

```<code>$ python script.py
/foo/bar
</code>```

The thing is, if you add new values (aliases / variables) to your bashrc you'll need to restart your terminal in order to bashrc gets executed and make those changes availables in the environment.

I've found the references to do this here and here

Note: From a subshell process you can't set environment variables to the parent shell.

Body:
I'm trying to execute a bash script from inside python using the subprocess module. The problem is that this bash script relies on many environment variables that are set in my .bashrc file. What I want is for python subprocess to exactly replicate the environment that is setup when I launch a terminal window. So far I tried:

p = subprocess.Popen(args=['my-script.sh', '--additional_args'], stdout=subprocess.PIPE, env=os.environ.copy(), shell=True)
output_buffer, return_code = p.communicate()

But then read somewhere that even after doing shell=True, the .bashrc file is still not loaded, and that i should try something like this:

p = subprocess.Popen(args=['/bin/bash', '-i', '-c', 'my_script.sh', '--additional_args'], stdout=subprocess.PIPE)
output_buffer, return_code = p.communicate()

But with this function call, I get this error:

tput: No value for $TERM and no -T specified
bash: cannot set terminal process group (2071): Inappropriate ioctl for device
bash: no job control in this shell

Body:
This worked for me:

Bashrc

$ cat ~/.bashrc  |grep LOLO
export LOLO="/foo/bar"

Bash

#!/usr/bin/bash

echo $LOLO

Python

#!/usr/bin/python

import subprocess, os
my_env = os.environ.copy()
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
subprocess.Popen('/home/m.ortiz.montealegre/lolo/script.sh', env=my_env)

Output:

$ python script.py
/foo/bar

The thing is, if you add new values (aliases / variables) to your bashrc you'll need to restart your terminal in order to bashrc gets executed and make those changes availables in the environment.

I've found the references to do this here and here

Note: From a subshell process you can't set environment variables to the parent shell.


问:
Fatal error: Call to a member function get_cart_contents_count() on a non-object in /functions.php on line 413

on line 413  $product_count =
  $woocommerce->cart->get_cart_contents_count();

```<code>function wc_sell_only_states( $states ) {
        // set our flag to be false until we find a product in that category
    $cat_check = false;
    global $woocommerce;
    ob_start();
    //==========================================AAAAAAAAAAAAAAAAA
    $product_count = $woocommerce->cart->get_cart_contents_count();
    if($product_count > 0){
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) { //foreach

    $product = $cart_item['data'];

    // replace 'membership' with your category's slug
    if ( has_term( 'VIP', 'product_tag', $product->id ) ) {//search product_cat
    $cat_check = true;
    // break because we only need one "true" to matter here
    //////////////////////////////////////////////////////////////////////////////////////
    if (!function_exists('soosti_add_checkout_content')) {
    function soosti_add_checkout_content() { // skyverge function
    echo '<p style="color:#F31114">Attention: In your shopping cart hava Special product that only shipping to <b>California</b>...</p>';
    }//end skyverge function
    }
    add_action( 'woocommerce_before_checkout_form', 'soosti_add_checkout_content', 12 );
    //-------------------------

    //---------------------------
    if (!function_exists('woo_override_checkout_fields')) {
    function woo_override_checkout_fields( $fields ) { // woo_override_checkout_fields Function

    $fields['billing']['billing_country'] = array(
    'type' => 'select',
    'label' => __('Country', 'woocommerce'),
    'options' => array('US' => 'United States(US)')
    );

    $fields['billing']['billing_state'] = array(
    'type' => 'select',
    'label' => __('State', 'woocommerce'),
    'options' => array('CA' => 'California(CA)')

    );

    return $fields;
    } //end woo_override_checkout_fields Function
    }
    add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields' );
</code>```

how to fix this error?

when I run this code I get a fatal error. I think

```<code>$woocommerce->cart->get_cart_contents_count();
</code>```

make empty.

so how  do I resolve this error? please help me

答:
Finally I found answer for

Fatal error: Call to a member function get_cart_contents_count() on a
  non-object

```<code>function a000_remove_bundles_counting(){

global $woocommerce_bundles;
remove_filter( 'woocommerce_cart_contents_count',
array( $woocommerce_bundles->display, 'woo_bundles_cart_contents_count' ) );
}
add_action( 'init', 'a000_remove_bundles_counting' );
</code>```

disable the Bundles filter before simultaneously adding own via
  d000_cart_contents_count

```<code>function d000_cart_contents_count( $count ) {
    global $woocommerce;
 $cat_check = false;
  foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) { //foreach

 $product = $cart_item['data'];

 if ( has_term( 'tv', 'product_tag', $product->id ) ) {//search product_cat
$cat_check = true;
// break because we only need one "true" to matter here
if (!function_exists('woo_override_checkout_fields')) {
function woo_override_checkout_fields( $fields ) { // woo_override_checkout_fields Function

$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array('US' => 'United States(US)')
);

$fields['billing']['billing_state'] = array(
'type' => 'select',
'label' => __('State', 'woocommerce'),
'options' => array('CA' => 'California(CA)')

);

return $fields;
} //end woo_override_checkout_fields Function
}
add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields' );

} // end search product_cat
  }// end foreach

return $count;
}
add_filter( 'woocommerce_cart_contents_count',
'd000_cart_contents_count' );
</code>```

Body:
on line 413  $product_count =
  $woocommerce->cart->get_cart_contents_count();

function wc_sell_only_states( $states ) {
        // set our flag to be false until we find a product in that category
    $cat_check = false;
    global $woocommerce;
    ob_start();
    //==========================================AAAAAAAAAAAAAAAAA
    $product_count = $woocommerce->cart->get_cart_contents_count();
    if($product_count > 0){
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) { //foreach

    $product = $cart_item['data'];

    // replace 'membership' with your category's slug
    if ( has_term( 'VIP', 'product_tag', $product->id ) ) {//search product_cat
    $cat_check = true;
    // break because we only need one "true" to matter here
    //////////////////////////////////////////////////////////////////////////////////////
    if (!function_exists('soosti_add_checkout_content')) {
    function soosti_add_checkout_content() { // skyverge function
    echo '
Attention: In your shopping cart hava Special product that only shipping to California...
';
    }//end skyverge function
    }
    add_action( 'woocommerce_before_checkout_form', 'soosti_add_checkout_content', 12 );
    //-------------------------

    //---------------------------
    if (!function_exists('woo_override_checkout_fields')) {
    function woo_override_checkout_fields( $fields ) { // woo_override_checkout_fields Function

    $fields['billing']['billing_country'] = array(
    'type' => 'select',
    'label' => __('Country', 'woocommerce'),
    'options' => array('US' => 'United States(US)')
    );

    $fields['billing']['billing_state'] = array(
    'type' => 'select',
    'label' => __('State', 'woocommerce'),
    'options' => array('CA' => 'California(CA)')

    );

    return $fields;
    } //end woo_override_checkout_fields Function
    }
    add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields' );

how to fix this error?

when I run this code I get a fatal error. I think

$woocommerce->cart->get_cart_contents_count();

make empty.

so how  do I resolve this error? please help me

Body:
Finally I found answer for

Fatal error: Call to a member function get_cart_contents_count() on a
  non-object

function a000_remove_bundles_counting(){

global $woocommerce_bundles;
remove_filter( 'woocommerce_cart_contents_count',
array( $woocommerce_bundles->display, 'woo_bundles_cart_contents_count' ) );
}
add_action( 'init', 'a000_remove_bundles_counting' );

disable the Bundles filter before simultaneously adding own via
  d000_cart_contents_count

function d000_cart_contents_count( $count ) {
    global $woocommerce;
 $cat_check = false;
  foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) { //foreach

 $product = $cart_item['data'];

 if ( has_term( 'tv', 'product_tag', $product->id ) ) {//search product_cat
$cat_check = true;
// break because we only need one "true" to matter here
if (!function_exists('woo_override_checkout_fields')) {
function woo_override_checkout_fields( $fields ) { // woo_override_checkout_fields Function

$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array('US' => 'United States(US)')
);

$fields['billing']['billing_state'] = array(
'type' => 'select',
'label' => __('State', 'woocommerce'),
'options' => array('CA' => 'California(CA)')

);

return $fields;
} //end woo_override_checkout_fields Function
}
add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields' );

} // end search product_cat
  }// end foreach

return $count;
}
add_filter( 'woocommerce_cart_contents_count',
'd000_cart_contents_count' );