问:
Why can't I use AngularJS to load a JSON file and angular route in the same page?
I'm not a native speaker, sorry for my unclear question.
I'm trying to use AngularJS to read a JSON file. I did it but when I use angular route in the same page, the angular route didn't run. Then I figured out that I can only use one function in 1 page. For more clearly, here is my code:

In home.html:

```<code><!DOCTYPE html>
<html ng-app="UpStore">
<head>

 </head>
 <body ng-controller="ProductController">

 <div ng-view> </div>

 <!--Javascript-->

 <script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-
route.js"></script>

<script src="js/app.js"></script>
<script>

    var app = angular.module("UpStore", [])
    app.controller("ProductController", function ($scope, $http) {
        $http({
            method: "GET",
            url: "productdata.json"
        }).then(function mySucces(respone) {
            $scope.products = respone.data
        }, function myError(respone) {
            $scope.dataError = respone.statusText
        }
            )
    })

 </script>

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

app.js:

```<code>var App = angular.module('UpStore', []);

App.controller('ProductController', function ($scope) {

});

var App = angular.module('UpStore', ['ngRoute']);

App.config(function ($routeProvider) {
$routeProvider

    .when('/men', {
        templateUrl: 'men.html',

    })

    .when('/product', {
        templateUrl: 'product.html',

    }).
    otherwise({
        redirectTo: 'men'
    });
});

App.controller('ProductController', function ($scope) {

});
</code>```

In men.html:

```<code> <div ng-repeat="pd in products">
    <p>{{pd.ID}}</p>
    <p><a href="#product"><img src="image/{{pd.Image}}" /></a></p>
 </div>
</code>```

I also has one more question. In page men.html, I have several products, each product has an ID. I have a page product.html to show the product details. What I want to do is when I click on an image of a product in page men.html. The URL to the product.html would be like product.html/productid. I know that $routeParams can solve my problem, but I don't know how to write the code.

I really need some help because I've been struggling with these 2 problems for hours. Thanks in advance.

答:
You are continuously overwriting the previously defined modules.

As you have already defined the module UpStore in the app.js

```<code>//Define it only once
var App = angular.module('UpStore', ['ngRoute']);
</code>```

You need to get the reference of it in the script block and use.

```<code>//Get the reference to existing module
var app = angular.module("UpStore");

//Use it
app.controller(.......)
</code>```

Additionally: Note always use same version of angular.js and angular-route.js library

Body:
I'm not a native speaker, sorry for my unclear question.
I'm trying to use AngularJS to read a JSON file. I did it but when I use angular route in the same page, the angular route didn't run. Then I figured out that I can only use one function in 1 page. For more clearly, here is my code:

In home.html:

<!DOCTYPE html>

app.js:

var App = angular.module('UpStore', []);

App.controller('ProductController', function ($scope) {

});

var App = angular.module('UpStore', ['ngRoute']);

App.config(function ($routeProvider) {
$routeProvider

    .when('/men', {
        templateUrl: 'men.html',

    })

    .when('/product', {
        templateUrl: 'product.html',

    }).
    otherwise({
        redirectTo: 'men'
    });
});

App.controller('ProductController', function ($scope) {

});

In men.html:

{{pd.ID}}

I also has one more question. In page men.html, I have several products, each product has an ID. I have a page product.html to show the product details. What I want to do is when I click on an image of a product in page men.html. The URL to the product.html would be like product.html/productid. I know that $routeParams can solve my problem, but I don't know how to write the code.

I really need some help because I've been struggling with these 2 problems for hours. Thanks in advance.

Body:
You are continuously overwriting the previously defined modules.

As you have already defined the module UpStore in the app.js

//Define it only once
var App = angular.module('UpStore', ['ngRoute']);

You need to get the reference of it in the script block and use.

//Get the reference to existing module
var app = angular.module("UpStore");

//Use it
app.controller(.......)

Additionally: Note always use same version of angular.js and angular-route.js library


来源: stackexchange

问:
C#: Conversion to TimeSpan is not retaining complete value
I get this issue while converting a string value to TimeSpan.

The values are like : "hrs:mm:ss:ms"
eg: "00:00:10:03"

While converting this value to TimeSpan, the leading part gets truncated.

Code :

```<code>TimeSpan span = new TimeSpan();
TimeSpan.TryParse("00:00:10:03" , out span);
</code>```

Output :
00:10:03

How can i retain the entire value in Timespan only

答: You should use span.Ticks in output</p>

ContentLicense: CC BY-SA 3.0

Body:
I get this issue while converting a string value to TimeSpan.

The values are like : "hrs:mm:ss:ms"
eg: "00:00:10:03"

While converting this value to TimeSpan, the leading part gets truncated.

Code :

TimeSpan span = new TimeSpan();
TimeSpan.TryParse("00:00:10:03" , out span);

Output :
00:10:03

How can i retain the entire value in Timespan only

Body: You should use span.Ticks in output


问:
Docker arguments for Mesos
I am trying to execute a docker container in a Mesos cluster. The effective docker command I want to execute is:

```<code>docker run -it -v /home/me:/home/jovyan/work -p 8888:8888 jupyter/pyspark-notebook
</code>```

I understand the command will be of the form:

```<code>mesos-execute --containerizer=docker --master=127.0.0.1:9090 --name=test --docker_image=jupyter/pyspark-notebook --command="start-notebook.sh" --resources="cpus:8"
</code>```

How do I pass in the equivalents of the -p and the -v arguments to the memos-execute command?

Currently, I am running a vanilla Mesos cluster without any of the added services like Marathon running.

答:
From mesos-execute

The value could be a JSON-formatted string of TaskInfo or a file path containing the JSON-formatted TaskInfo. Path must be of the form file:///path/to/file or /path/to/file.

See the TaskInfo message in mesos.proto for the expected format. NOTE: agent_id need not to be set.

TaskInfo contains filed for container configuration called ContainerInfo where you can configure port mappings.

For any other custom options you can use Parameters

```<code>// Allowing arbitrary parameters to be passed to docker CLI.
// Note that anything passed to this field is not guaranteed
// to be supported moving forward, as we might move away from
// the docker CLI.
repeated Parameter parameters = 5;
</code>```

Title: Docker arguments for Mesos

Body:
I am trying to execute a docker container in a Mesos cluster. The effective docker command I want to execute is:

docker run -it -v /home/me:/home/jovyan/work -p 8888:8888 jupyter/pyspark-notebook

I understand the command will be of the form:

mesos-execute --containerizer=docker --master=127.0.0.1:9090 --name=test --docker_image=jupyter/pyspark-notebook --command="start-notebook.sh" --resources="cpus:8"

How do I pass in the equivalents of the -p and the -v arguments to the memos-execute command?

Currently, I am running a vanilla Mesos cluster without any of the added services like Marathon running.

Body:
From mesos-execute

The value could be a JSON-formatted string of TaskInfo or a file path containing the JSON-formatted TaskInfo. Path must be of the form file:///path/to/file or /path/to/file.

See the TaskInfo message in mesos.proto for the expected format. NOTE: agent_id need not to be set.

TaskInfo contains filed for container configuration called ContainerInfo where you can configure port mappings.

For any other custom options you can use Parameters

// Allowing arbitrary parameters to be passed to docker CLI.
// Note that anything passed to this field is not guaranteed
// to be supported moving forward, as we might move away from
// the docker CLI.
repeated Parameter parameters = 5;


问:
NSNotification addObserver:someOtherClass
I need to pass a message up to a controlling class (which creates an instance of the class which will be sending the message) So, I cannot directly reference the class name in my file, without either making it a Global (which is ridiculous to do if "NSNotification" advertises to be able to pass all kinds of messages, regardless of where / what class they are.

So without further ado...

(calling from Say ClassB)

ClassA creates instance of ClassB

Now in ClassB, I need to pass messages regarding button presses back up to ClassA

```<code>(insdie ClassB)
- (void)viewDidLoad
{
  [[NSNotificationCenter defaultCenter] addObserver:ClassA
                                        selector:@selector(doLoginAction)
                                        name:@"SomeButton"
                                        object:nil];
  [super viewDidLoad];
}
</code>```

This will NOT compile, even when I include, sorry, "#import "ClassA.h"
Now if I do something stupid like,

```<code>ClassA *classa = [[ClassA alloc]init];
</code>```

and then use this Newly created instance of classa in addObserver:classa it will compile, but as I thought, will do absolutely nothing... (I knew that, but surprisingly this kind of code is prevalent in Iphone programming books...) So I tried it anyway.

But if I put this function in ClassA and use addObserver:ClassB
it will get called, but will cause a stack dump unrecognized selector sent to instance
or use addObserver:self.

I am tempted to delete Xcode and go back to vim and use a good old "C" callback...

答:
So, if I get it right, you have a ClassA which creates instances of ClassB. Those instances, in turn, should send notifications directly to ClassA without knowing anything about it.

If that is correct, then NSNotificationCenter is exactly what you need.

In ClassA implementation add an initialialize method like this:

```<code>@implementation ClassA

+ (void)initialize
{
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(YourSelector:)
               name:@"YourNotificationName"
             object:nil];
}

+ (void)YourSelector:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];

    // ...
}

// ...

@end
</code>```

Then, instances of ClassB should post their notifications using only its name:

```<code>@implementation ClassB

- (void)postNotification
{
    NSDictionary *userInfo = ...;    // may be nil
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"YourNotificationName"
                               // the same name is used in the `addObserver` call
                               // in the previous code snippet
                      object:nil
                    userInfo:userInfo];
}

// ...

@end
</code>```

To sum it all up, you do not need to know anything about the receiver of notifications if you are using NSNotificationCenter. In fact, you may subscribe as many objects as you like to receive the same notification, and each of them will call its appropriate method (specified in addObserver) upon receiving the notification object.

Please remember that in the case when you add a class instance as an observer, rather than the class object itself, you should call [[NSNotificationCenter defaultCenter] removeObserver:self] in that instance's dealloc method.

Body:
I need to pass a message up to a controlling class (which creates an instance of the class which will be sending the message) So, I cannot directly reference the class name in my file, without either making it a Global (which is ridiculous to do if "NSNotification" advertises to be able to pass all kinds of messages, regardless of where / what class they are.

So without further ado...

(calling from Say ClassB)

ClassA creates instance of ClassB

Now in ClassB, I need to pass messages regarding button presses back up to ClassA

(insdie ClassB)
- (void)viewDidLoad
{
  [[NSNotificationCenter defaultCenter] addObserver:ClassA
                                        selector:@selector(doLoginAction)
                                        name:@"SomeButton"
                                        object:nil];
  [super viewDidLoad];
}

This will NOT compile, even when I include, sorry, "#import "ClassA.h"
Now if I do something stupid like,

ClassA *classa = [[ClassA alloc]init];

and then use this Newly created instance of classa in addObserver:classa it will compile, but as I thought, will do absolutely nothing... (I knew that, but surprisingly this kind of code is prevalent in Iphone programming books...) So I tried it anyway.

But if I put this function in ClassA and use addObserver:ClassB
it will get called, but will cause a stack dump unrecognized selector sent to instance
or use addObserver:self.

I am tempted to delete Xcode and go back to vim and use a good old "C" callback...

Body:
So, if I get it right, you have a ClassA which creates instances of ClassB. Those instances, in turn, should send notifications directly to ClassA without knowing anything about it.

If that is correct, then NSNotificationCenter is exactly what you need.

In ClassA implementation add an initialialize method like this:

@implementation ClassA

+ (void)initialize
{
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(YourSelector:)
               name:@"YourNotificationName"
             object:nil];
}

+ (void)YourSelector:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];

    // ...
}

// ...

@end

Then, instances of ClassB should post their notifications using only its name:

@implementation ClassB

- (void)postNotification
{
    NSDictionary *userInfo = ...;    // may be nil
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"YourNotificationName"
                               // the same name is used in the `addObserver` call
                               // in the previous code snippet
                      object:nil
                    userInfo:userInfo];
}

// ...

@end

To sum it all up, you do not need to know anything about the receiver of notifications if you are using NSNotificationCenter. In fact, you may subscribe as many objects as you like to receive the same notification, and each of them will call its appropriate method (specified in addObserver) upon receiving the notification object.

Please remember that in the case when you add a class instance as an observer, rather than the class object itself, you should call [[NSNotificationCenter defaultCenter] removeObserver:self] in that instance's dealloc method.


问:
FXM - create custom goals
I want to use FXM on the external Non-Sitecore website for tracking the click event which will download documents.

In the external website, User will login so Website is having additional details name, email, phone number etc for the user.So using FXM, can I get Name, email, phone number from the external website to the Sitecore contacts, Once I have this details in Sitecore can I trigger some goals and write some custom code to send this data to Salesforce (an API call)?

Not sure whether this is the right approach but I am just throwing it out. I can directly call the Salesforce API from the external website but I want to take advantage of Sitecore features so that I track the website analytics data.

答:
You can trigger a Sitecore Goal on the txternal site in FXM on the button for the form.

For Salesforce integration have you considered Salesforce connect? https://dev.sitecore.net/Downloads/Salesforce_Connect.aspx

Title: FXM - create custom goals


问:
SQLAlchemy relationship with secondary table joining behaviour changes between lazy and eager loading
I've been playing with SQL Alchemy for a couple of months now and so far been really impressed with it.

There is one issue I've run into now that seems to be a bug, but I'm not sure that I'm doing the right thing. We use MS SQL here, with table reflection to define the table classes, however I can replicate the problem using an in-memory SQLite database, code for which I have included here.

What I am doing is defining a many to many relationship between two tables using a linking table between them. There is one extra piece of information that the linking table contains which I want to use for filtering the links, requiring the use of a primaryjoin statement on the relationship. This works perfectly for lazy loading, however for performance reasons we need eager loading and thats where it all falls over.

If I define the relationship with lazy loading:

```<code>activefunds = relationship('Fund', secondary='fundbenchmarklink',
                           primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                                       'Benchmark.id==FundBenchmarkLink.benchmarkid,'
                                       'Fund.id==FundBenchmarkLink.fundid)')
</code>```

and query the DB normally:

```<code>query = session.query(Benchmark)
</code>```

The behaviour I need is exactly what I want, though performance is really bad, due to the extra SQL queries when iterating through all of the benchmarks and their respective funds.

If I define the relationship with eager loading:

```<code>activefunds = relationship('Fund', secondary='fundbenchmarklink',
                           primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                                       'Benchmark.id==FundBenchmarkLink.benchmarkid,'
                                       'Fund.id==FundBenchmarkLink.fundid)',
                           lazy='joined')
</code>```

and query the DB normally:

```<code>query = session.query(Benchmark)
</code>```

it blows up in my face:

```<code>sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: fund.id
    [SQL: 'SELECT benchmark.id AS benchmark_id,
                   benchmark.name AS benchmark_name,
                   fund_1.id AS fund_1_id,
                   fund_1.name AS fund_1_name,
                   fund_2.id AS fund_2_id,
                   fund_2.name AS fund_2_name
            FROM benchmark
            LEFT OUTER JOIN (fundbenchmarklink AS fundbenchmarklink_1
                             JOIN fund AS fund_1 ON fund_1.id = fundbenchmarklink_1.fundid) ON benchmark.id = fundbenchmarklink_1.benchmarkid
            LEFT OUTER JOIN (fundbenchmarklink AS fundbenchmarklink_2
                             JOIN fund AS fund_2 ON fund_2.id = fundbenchmarklink_2.fundid) ON fundbenchmarklink_2.isactive = 1
            AND benchmark.id = fundbenchmarklink_2.benchmarkid
            AND fund.id = fundbenchmarklink_2.fundid']
</code>```

The SQL above clearly shows the linked table is not being joined before attempting to access columns from it.

If I query the DB, specifically joining the linked table:

```<code>query = session.query(Benchmark).join(FundBenchmarkLink, Fund, isouter=True)
</code>```

It works, however it means I now have to make sure that whenever I query the Benchmark table, I always have to define the join to add both of the extra tables.

Is there something I'm missing, is this a potential bug, or is it simply the way the library works?

Full working sample code to replicate issue:

```<code>import logging

logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine.base').setLevel(logging.INFO)

from sqlalchemy import Column, DateTime, String, Integer, Boolean, ForeignKey, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class FundBenchmarkLink(Base):
    __tablename__ = 'fundbenchmarklink'

    fundid = Column(Integer, ForeignKey('fund.id'), primary_key=True, autoincrement=False)
    benchmarkid = Column(Integer, ForeignKey('benchmark.id'), primary_key=True, autoincrement=False)
    isactive = Column(Boolean, nullable=False, default=True)

    fund = relationship('Fund')
    benchmark = relationship('Benchmark')

    def __repr__(self):
        return "<FundBenchmarkLink(fundid='{}', benchmarkid='{}', isactive='{}')>".format(self.fundid, self.benchmarkid, self.isactive)

class Benchmark(Base):
    __tablename__ = 'benchmark'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    funds = relationship('Fund', secondary='fundbenchmarklink', lazy='joined')

    # activefunds has additional filtering on the secondary table, requiring a primaryjoin statement.
    activefunds = relationship('Fund', secondary='fundbenchmarklink',
                               primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                                           'Benchmark.id==FundBenchmarkLink.benchmarkid,'
                                           'Fund.id==FundBenchmarkLink.fundid)',
                               lazy='joined')

    def __repr__(self):
        return "<Benchmark(id='{}', name='{}')>".format(self.id, self.name)

class Fund(Base):
    __tablename__ = 'fund'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    def __repr__(self):
        return "<Fund(id='{}', name='{}')>".format(self.id, self.name)

if '__main__' == __name__:
    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)
    maker = sessionmaker(bind=engine)

    session = maker()

    # Create some data
    for bmkname in ['foo', 'bar', 'baz']:
        bmk = Benchmark(name=bmkname)
        session.add(bmk)

    for fname in ['fund1', 'fund2', 'fund3']:
        fnd = Fund(name=fname)
        session.add(fnd)

    session.add(FundBenchmarkLink(fundid=1, benchmarkid=1))
    session.add(FundBenchmarkLink(fundid=2, benchmarkid=1))
    session.add(FundBenchmarkLink(fundid=1, benchmarkid=2))
    session.add(FundBenchmarkLink(fundid=2, benchmarkid=2, isactive=False))

    session.commit()

    # This code snippet works when activefunds doesn't exist, or doesn't use eager loading
    # query = session.query(Benchmark)
    # print(query)

    # for bmk in query:
    #     print(bmk)
    #     for fund in bmk.funds:
    #         print('\t{}'.format(fund))

    # This code snippet works for activefunds with eager loading
    query = session.query(Benchmark).join(FundBenchmarkLink, Fund, isouter=True)
    print(query)

    for bmk in query:
        print(bmk)
        for fund in bmk.activefunds:
            print('\t{}'.format(fund))
</code>```

答:
I think you've mixed the primary join and the secondary join a bit. Your primary would seem to contain both at the moment. Remove the predicate for Fund and it should work:

```<code>activefunds = relationship(
    'Fund',
    secondary='fundbenchmarklink',
    primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                'Benchmark.id==FundBenchmarkLink.benchmarkid)',
    lazy='joined')
</code>```

The reason why your explicit join seems to fix the query is that it introduces the table fund before the implicit eager loading joins and so they can refer to it. It's not really a fix, rather than it hides the error. If you really want to use explicit Query.join() with eagerloading, inform the query about it with contains_eager(). Just be careful which relationship you choose as being contained, depending on the query in question; without additional filtering you could fill activefunds with inactive also.

Finally, consider using Query.outerjoin() instead of Query.join(..., isouter=True).

Body:
I've been playing with SQL Alchemy for a couple of months now and so far been really impressed with it.

There is one issue I've run into now that seems to be a bug, but I'm not sure that I'm doing the right thing. We use MS SQL here, with table reflection to define the table classes, however I can replicate the problem using an in-memory SQLite database, code for which I have included here.

What I am doing is defining a many to many relationship between two tables using a linking table between them. There is one extra piece of information that the linking table contains which I want to use for filtering the links, requiring the use of a primaryjoin statement on the relationship. This works perfectly for lazy loading, however for performance reasons we need eager loading and thats where it all falls over.

If I define the relationship with lazy loading:

activefunds = relationship('Fund', secondary='fundbenchmarklink',
                           primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                                       'Benchmark.id==FundBenchmarkLink.benchmarkid,'
                                       'Fund.id==FundBenchmarkLink.fundid)')

and query the DB normally:

query = session.query(Benchmark)

The behaviour I need is exactly what I want, though performance is really bad, due to the extra SQL queries when iterating through all of the benchmarks and their respective funds.

If I define the relationship with eager loading:

activefunds = relationship('Fund', secondary='fundbenchmarklink',
                           primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                                       'Benchmark.id==FundBenchmarkLink.benchmarkid,'
                                       'Fund.id==FundBenchmarkLink.fundid)',
                           lazy='joined')

and query the DB normally:

query = session.query(Benchmark)

it blows up in my face:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: fund.id
    [SQL: 'SELECT benchmark.id AS benchmark_id,
                   benchmark.name AS benchmark_name,
                   fund_1.id AS fund_1_id,
                   fund_1.name AS fund_1_name,
                   fund_2.id AS fund_2_id,
                   fund_2.name AS fund_2_name
            FROM benchmark
            LEFT OUTER JOIN (fundbenchmarklink AS fundbenchmarklink_1
                             JOIN fund AS fund_1 ON fund_1.id = fundbenchmarklink_1.fundid) ON benchmark.id = fundbenchmarklink_1.benchmarkid
            LEFT OUTER JOIN (fundbenchmarklink AS fundbenchmarklink_2
                             JOIN fund AS fund_2 ON fund_2.id = fundbenchmarklink_2.fundid) ON fundbenchmarklink_2.isactive = 1
            AND benchmark.id = fundbenchmarklink_2.benchmarkid
            AND fund.id = fundbenchmarklink_2.fundid']

The SQL above clearly shows the linked table is not being joined before attempting to access columns from it.

If I query the DB, specifically joining the linked table:

query = session.query(Benchmark).join(FundBenchmarkLink, Fund, isouter=True)

It works, however it means I now have to make sure that whenever I query the Benchmark table, I always have to define the join to add both of the extra tables.

Is there something I'm missing, is this a potential bug, or is it simply the way the library works?

Full working sample code to replicate issue:

import logging

logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine.base').setLevel(logging.INFO)

from sqlalchemy import Column, DateTime, String, Integer, Boolean, ForeignKey, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class FundBenchmarkLink(Base):
    __tablename__ = 'fundbenchmarklink'

    fundid = Column(Integer, ForeignKey('fund.id'), primary_key=True, autoincrement=False)
    benchmarkid = Column(Integer, ForeignKey('benchmark.id'), primary_key=True, autoincrement=False)
    isactive = Column(Boolean, nullable=False, default=True)

    fund = relationship('Fund')
    benchmark = relationship('Benchmark')

    def __repr__(self):
        return "<FundBenchmarkLink(fundid='{}', benchmarkid='{}', isactive='{}')>".format(self.fundid, self.benchmarkid, self.isactive)

class Benchmark(Base):
    __tablename__ = 'benchmark'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    funds = relationship('Fund', secondary='fundbenchmarklink', lazy='joined')

    # activefunds has additional filtering on the secondary table, requiring a primaryjoin statement.
    activefunds = relationship('Fund', secondary='fundbenchmarklink',
                               primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                                           'Benchmark.id==FundBenchmarkLink.benchmarkid,'
                                           'Fund.id==FundBenchmarkLink.fundid)',
                               lazy='joined')

    def __repr__(self):
        return "<Benchmark(id='{}', name='{}')>".format(self.id, self.name)

class Fund(Base):
    __tablename__ = 'fund'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    def __repr__(self):
        return "<Fund(id='{}', name='{}')>".format(self.id, self.name)

if '__main__' == __name__:
    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)
    maker = sessionmaker(bind=engine)

    session = maker()

    # Create some data
    for bmkname in ['foo', 'bar', 'baz']:
        bmk = Benchmark(name=bmkname)
        session.add(bmk)

    for fname in ['fund1', 'fund2', 'fund3']:
        fnd = Fund(name=fname)
        session.add(fnd)

    session.add(FundBenchmarkLink(fundid=1, benchmarkid=1))
    session.add(FundBenchmarkLink(fundid=2, benchmarkid=1))
    session.add(FundBenchmarkLink(fundid=1, benchmarkid=2))
    session.add(FundBenchmarkLink(fundid=2, benchmarkid=2, isactive=False))

    session.commit()

    # This code snippet works when activefunds doesn't exist, or doesn't use eager loading
    # query = session.query(Benchmark)
    # print(query)

    # for bmk in query:
    #     print(bmk)
    #     for fund in bmk.funds:
    #         print('\t{}'.format(fund))

    # This code snippet works for activefunds with eager loading
    query = session.query(Benchmark).join(FundBenchmarkLink, Fund, isouter=True)
    print(query)

    for bmk in query:
        print(bmk)
        for fund in bmk.activefunds:
            print('\t{}'.format(fund))

Body:
I think you've mixed the primary join and the secondary join a bit. Your primary would seem to contain both at the moment. Remove the predicate for Fund and it should work:

activefunds = relationship(
    'Fund',
    secondary='fundbenchmarklink',
    primaryjoin='and_(FundBenchmarkLink.isactive==True,'
                'Benchmark.id==FundBenchmarkLink.benchmarkid)',
    lazy='joined')

The reason why your explicit join seems to fix the query is that it introduces the table fund before the implicit eager loading joins and so they can refer to it. It's not really a fix, rather than it hides the error. If you really want to use explicit Query.join() with eagerloading, inform the query about it with contains_eager(). Just be careful which relationship you choose as being contained, depending on the query in question; without additional filtering you could fill activefunds with inactive also.

Finally, consider using Query.outerjoin() instead of Query.join(..., isouter=True).


问:
String form name to form reference
Basically, I am rewriting some code working for years. Over the time I have many (60+) references to forms - there's a menuitem with OnClick event for each form, where a form reference was created:

```<code>Private Sub SomeForm_Click(sender As Object, e As EventArgs) Handles MenuItemForSomeForm.Click
    NewTab("Some Form", New SomeForm, 0)
End Sub
</code>```

...where first parameter is a name to put in a tabPage.Text where the form is opened, second is a new instance of the (particular) form SomeForm and 0 is a default record to display (0 means no default record).

Now, I created a dynamic menu and stored the form names in a database (due to better access control over the access rights, etc). Now, because the menu is generated at runtime, I can't have the OnClick event with separate instance definition of the form and have to create it at runtime, after the MenuItems are created. The side-effect idea was to cut the code short by using only 1 OnClick event or such with MenuItem.Tag paremeter as FormName. Something like:

```<code>Private Sub clickeventhandler(sender As Object, e As EventArgs)
Dim tsmi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim newForm As New >>>FormFrom(tsmi.Tag.ToString)<<<  ' only explanation, this won't work
MainW.OpenModuleInTab(new newForm, tsmi.Tag.ToString, 0)
</code>```

However I am failing to find a way to create form (instances) from this string reference. Reference through collection (i.e. List(of) or Dictionary) would be fine too, I believe.

The structure is obviously:

Object → Form → Form1 (class) → MyForm1 (instance)

I know I can create an object like this:

```<code>' Note that you are getting a NEW instance of MyClassA
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(NameOfMyClass))
</code>```

I can re-type it to a Form type:

```<code>Dim NewForm as Form = CType(MyInstance,Form)
</code>```

... to acccess some of the form properties like Width, TopLevel, etc., but that's about it. I can't do:

```<code>Dim NewForm1 as Form1 = CType(NewForm,Form1)
</code>```

...because obviously, Form1 comes as a string "Form1".

I don't know how to create a Form1 reference from a "Form1" text (then it would be easy to create an instance) or how to create an instance directly (MyForm1).

SOLUTION

As sugested, I used reflection to get the form. The only way working for me I found was this:

```<code>    Dim T As Type = System.Type.GetType(FormName, False)
    If T Is Nothing Then 'if not found prepend default namespace
        Dim Fullname As String = Application.ProductName & "." & FormName
        T = System.Type.GetType(Fullname, True, True)
    End If

    Dim f2 As New Form   ' here I am creating a form and working with it
    f2 = CType(Activator.CreateInstance(T), Form)
    f2.TopLevel = False
    f2.Name = FormName.Replace(" ", "") & Now.ToString("yyyyMMddmmhh")
    f2.FormBorderStyle = FormBorderStyle.None
    f2.Dock = DockStyle.Fill
</code>```

I am using VB.net CallByName to set public variable and same function to run a sub method (every form contains RecordID variable and LoadRecords sub):

```<code>    CallByName(f2, "RecordID", CallType.Set, 111)
    CallByName(f2, "LoadRecords", CallType.Method, Nothing)
</code>```

For testing purposes, I put following into the testing form:

```<code>Public RecordID As Int32
Public Sub LoadRecords()
    MsgBox("Load records!!!!" & vbCrLf & "RecordID = " & RecordID)
End Sub
</code>```

答:
So, let's go with the idea that I have an assembly called "WindowsApp2" and in that assembly I've defined Form1 and Form2. I've also created this module in the same assembly:

```<code>Public Module Module1

    Public Function GetDoStuffWiths() As Dictionary(Of Type, System.Delegate)
        Dim DoStuffWiths As New Dictionary(Of Type, System.Delegate)()
        DoStuffWiths.Add(GetType(WindowsApp2.Form1), CType(Sub(f) WindowsApp2.Module1.DoStuffWithForm1(f), Action(Of WindowsApp2.Form1)))
        DoStuffWiths.Add(GetType(WindowsApp2.Form2), CType(Sub(f) WindowsApp2.Module1.DoStuffWithForm2(f), Action(Of WindowsApp2.Form2)))
        Return DoStuffWiths
    End Function

    Public Sub DoStuffWithForm1(form1 As Form1)
        form1.Text = "This is Form 1"
    End Sub

    Public Sub DoStuffWithForm2(form2 As Form2)
        form2.Text = "This is Form 2"
    End Sub

End Module
</code>```

Now, in another assembly "ConsoleApp1" I write this:

```<code>Sub Main()

    Dim DoStuffWiths As Dictionary(Of Type, System.Delegate) = WindowsApp2.Module1.GetDoStuffWiths()

    Dim formAssembly = System.Reflection.Assembly.Load("WindowsApp2")
    Dim typeOfForm = formAssembly.GetType("WindowsApp2.Form1")

    Dim form As Form = CType(Activator.CreateInstance(typeOfForm), Form)

    DoStuffWiths(typeOfForm).DynamicInvoke(form)

    Application.Run(form)

End Sub
</code>```

When I run my console app I get a form popping up with the message "This is Form 1".

If I change the line formAssembly.GetType("WindowsApp2.Form1") to formAssembly.GetType("WindowsApp2.Form2") then I get the message "Wow this is cool".

That's how you can work with strongly typed objects that you dynamically instantiate.

Title: String form name to form reference

Body:
Basically, I am rewriting some code working for years. Over the time I have many (60+) references to forms - there's a menuitem with OnClick event for each form, where a form reference was created:

Private Sub SomeForm_Click(sender As Object, e As EventArgs) Handles MenuItemForSomeForm.Click
    NewTab("Some Form", New SomeForm, 0)
End Sub

...where first parameter is a name to put in a tabPage.Text where the form is opened, second is a new instance of the (particular) form SomeForm and 0 is a default record to display (0 means no default record).

Now, I created a dynamic menu and stored the form names in a database (due to better access control over the access rights, etc). Now, because the menu is generated at runtime, I can't have the OnClick event with separate instance definition of the form and have to create it at runtime, after the MenuItems are created. The side-effect idea was to cut the code short by using only 1 OnClick event or such with MenuItem.Tag paremeter as FormName. Something like:

Private Sub clickeventhandler(sender As Object, e As EventArgs)
Dim tsmi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim newForm As New >>>FormFrom(tsmi.Tag.ToString)<<<  ' only explanation, this won't work
MainW.OpenModuleInTab(new newForm, tsmi.Tag.ToString, 0)

However I am failing to find a way to create form (instances) from this string reference. Reference through collection (i.e. List(of) or Dictionary) would be fine too, I believe.

The structure is obviously:

Object → Form → Form1 (class) → MyForm1 (instance)

I know I can create an object like this:

' Note that you are getting a NEW instance of MyClassA
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(NameOfMyClass))

I can re-type it to a Form type:

Dim NewForm as Form = CType(MyInstance,Form)

... to acccess some of the form properties like Width, TopLevel, etc., but that's about it. I can't do:

Dim NewForm1 as Form1 = CType(NewForm,Form1)

...because obviously, Form1 comes as a string "Form1".

I don't know how to create a Form1 reference from a "Form1" text (then it would be easy to create an instance) or how to create an instance directly (MyForm1).

SOLUTION

As sugested, I used reflection to get the form. The only way working for me I found was this:

    Dim T As Type = System.Type.GetType(FormName, False)
    If T Is Nothing Then 'if not found prepend default namespace
        Dim Fullname As String = Application.ProductName & "." & FormName
        T = System.Type.GetType(Fullname, True, True)
    End If

    Dim f2 As New Form   ' here I am creating a form and working with it
    f2 = CType(Activator.CreateInstance(T), Form)
    f2.TopLevel = False
    f2.Name = FormName.Replace(" ", "") & Now.ToString("yyyyMMddmmhh")
    f2.FormBorderStyle = FormBorderStyle.None
    f2.Dock = DockStyle.Fill

I am using VB.net CallByName to set public variable and same function to run a sub method (every form contains RecordID variable and LoadRecords sub):

    CallByName(f2, "RecordID", CallType.Set, 111)
    CallByName(f2, "LoadRecords", CallType.Method, Nothing)

For testing purposes, I put following into the testing form:

Public RecordID As Int32
Public Sub LoadRecords()
    MsgBox("Load records!!!!" & vbCrLf & "RecordID = " & RecordID)
End Sub

Body:
So, let's go with the idea that I have an assembly called "WindowsApp2" and in that assembly I've defined Form1 and Form2. I've also created this module in the same assembly:

Public Module Module1

    Public Function GetDoStuffWiths() As Dictionary(Of Type, System.Delegate)
        Dim DoStuffWiths As New Dictionary(Of Type, System.Delegate)()
        DoStuffWiths.Add(GetType(WindowsApp2.Form1), CType(Sub(f) WindowsApp2.Module1.DoStuffWithForm1(f), Action(Of WindowsApp2.Form1)))
        DoStuffWiths.Add(GetType(WindowsApp2.Form2), CType(Sub(f) WindowsApp2.Module1.DoStuffWithForm2(f), Action(Of WindowsApp2.Form2)))
        Return DoStuffWiths
    End Function

    Public Sub DoStuffWithForm1(form1 As Form1)
        form1.Text = "This is Form 1"
    End Sub

    Public Sub DoStuffWithForm2(form2 As Form2)
        form2.Text = "This is Form 2"
    End Sub

End Module

Now, in another assembly "ConsoleApp1" I write this:

Sub Main()

    Dim DoStuffWiths As Dictionary(Of Type, System.Delegate) = WindowsApp2.Module1.GetDoStuffWiths()

    Dim formAssembly = System.Reflection.Assembly.Load("WindowsApp2")
    Dim typeOfForm = formAssembly.GetType("WindowsApp2.Form1")

    Dim form As Form = CType(Activator.CreateInstance(typeOfForm), Form)

    DoStuffWiths(typeOfForm).DynamicInvoke(form)

    Application.Run(form)

End Sub

When I run my console app I get a form popping up with the message "This is Form 1".

If I change the line formAssembly.GetType("WindowsApp2.Form1") to formAssembly.GetType("WindowsApp2.Form2") then I get the message "Wow this is cool".

That's how you can work with strongly typed objects that you dynamically instantiate.


问:
removing uncessary keys in result mongoose
I am currently getting a response in mongoose like this

```<code>    {
        "_id" : "5a0be40836341c8ef9dc6d9d",
        "Username" : "Adkins Daugherty",
        "ContactDetail" : {
            "ApiID" : "5a0be408ed6983954888bdb5",
            "ContactName" : "Pace Roach",
        }
}
</code>```

But i want like this :

```<code>    {
        "_id" : "5a0be40836341c8ef9dc6d9d",
        "Username" : "Adkins Daugherty",
        "ApiID" : "5a0be408ed6983954888bdb5",
        "ContactName" : "Pace Roach",
}
</code>```

How can i do this using  mongoose. My collection name is contacts

Thanks

EDIT-1

```<code>db.contacts.aggregate([{
        $match: { Username: 'year_Adkins Daugherty' } },
        { "$unwind": "$ContactDetail" },
        {
            "$group": { "_id": "$_id",
                        "ApiID": "$ContactDetail.ApiID"
                    }
        }
    ])
</code>```

答:
I think I got an answer in $project

```<code>return Contact.aggregate(
        [
            { $match: { Username: regex } },
            {
            $project:{
                    Username:1,
                    ApiID:"$ContactDetail.ApiID",
                    Name:"$ContactDetail.ContactName",
                    ProfileImageUrl:"$ContactDetail.ProfileImageUrl",
                    OutletName:"$ContactDetail.OutletName"

                }
            }
        ]
    ).exec()
</code>```

The result I got is

```<code>{
        "_id": "5a0be40836341c8ef9dc6d9d",
        "Username": "year_Adkins Daugherty",
        "ApiID": "5a0be408ed6983954888bdb5",
        "Name": "Pace Roach",
        "ProfileImageUrl": "http://placehold.it/256x256",
        "OutletName": "Codehow___kjvolyi3ye"
    }
</code>```

Body:
I am currently getting a response in mongoose like this

    {
        "_id" : "5a0be40836341c8ef9dc6d9d",
        "Username" : "Adkins Daugherty",
        "ContactDetail" : {
            "ApiID" : "5a0be408ed6983954888bdb5",
            "ContactName" : "Pace Roach",
        }
}

But i want like this :

    {
        "_id" : "5a0be40836341c8ef9dc6d9d",
        "Username" : "Adkins Daugherty",
        "ApiID" : "5a0be408ed6983954888bdb5",
        "ContactName" : "Pace Roach",
}

How can i do this using  mongoose. My collection name is contacts

Thanks

EDIT-1

db.contacts.aggregate([{
        $match: { Username: 'year_Adkins Daugherty' } },
        { "$unwind": "$ContactDetail" },
        {
            "$group": { "_id": "$_id",
                        "ApiID": "$ContactDetail.ApiID"
                    }
        }
    ])

Body:
I think I got an answer in $project

return Contact.aggregate(
        [
            { $match: { Username: regex } },
            {
            $project:{
                    Username:1,
                    ApiID:"$ContactDetail.ApiID",
                    Name:"$ContactDetail.ContactName",
                    ProfileImageUrl:"$ContactDetail.ProfileImageUrl",
                    OutletName:"$ContactDetail.OutletName"

                }
            }
        ]
    ).exec()

The result I got is

{
        "_id": "5a0be40836341c8ef9dc6d9d",
        "Username": "year_Adkins Daugherty",
        "ApiID": "5a0be408ed6983954888bdb5",
        "Name": "Pace Roach",
        "ProfileImageUrl": "http://placehold.it/256x256",
        "OutletName": "Codehow___kjvolyi3ye"
    }


问:
email validation using regular expression
i am using this regular expression for email validation but it is not allowing hyphen (-):

```<code>/^\w+([\.-_]?\w+)*@\w+([\.-_]?\w+)*(\.\w{2,4})+$/
</code>```

please any one tell me how can i do this?

答:
try escaping your hyphens:

```<code>/^\w+([.\-_]?\w+)*@\w+([.\-_]?\w+)*(.\w{2,4})+$/
</code>```

the dash is reserved for ranges inside square brackets so if you want to make it a literal, you need to escape it.

ContentLicense: CC BY-SA 2.5

Body:
i am using this regular expression for email validation but it is not allowing hyphen (-):

/^\w+([\.-_]?\w+)*@\w+([\.-_]?\w+)*(\.\w{2,4})+$/

please any one tell me how can i do this?

Body:
try escaping your hyphens:

/^\w+([.\-_]?\w+)*@\w+([.\-_]?\w+)*(.\w{2,4})+$/

the dash is reserved for ranges inside square brackets so if you want to make it a literal, you need to escape it.


问:
BizTalk SQL Server Job always fails after some hours
We have BizTalk 2016 running on SQL Server 2016 AlwaysOn.

The SQL Server Agent Job MessageBox_Message_ManageRefCountLog_BizTalkMsgBoxDb is doing its thing but after some hours it fails. Sometimes 10 hours sometimes 90 hours or anything in between. I know, the job is designed to run forever and in a case of an error restarts itself within a minute. But I would like to know the actual error message for this failed job. The job history is not helpful because the job log entry is truncated.

A failover is not happening. The question is: WHY is this job failing and ultimately: how do I stop it from doing that?

I have set-up the extended monitoring of the failing step and it revealed, that the job failed because of a deadlock and it was chosen as the deadlock victim. So now is the question, why is there a deadlock? Is MessageBox_Message_ManageRefCountLog_BizTalkMsgBoxDbknown for deadlock issues?

答:
Check the documentation at Description of the SQL Server Agent Jobs in BizTalk Server, it says:

Important At first, the MessageBox_Message_ManageRefCountLog_BizTalkMsgBoxDb job status icon displays a status of Success. However, there will be no corresponding success entry in the job history. If one of the jobs in the MessageBox_Message_ManageRefCountLog_BizTalkMsgBoxDb job fails, a failure entry appears in the job history and the status icon displays a status of Failure. The job will always display a status of Failure after the first failure. To verify that the other BizTalk Server SQL Server Agent jobs run correctly, check the status of the other BizTalk Server SQL Server Agent jobs.

Hope this answer your question.


问:
How to use a parameter of the function outside the function?
I have a function which takes in an image from the Camera and processes the image and finally calculates the number of objects detected in the image along with the diameters. I want to check outside the function if the number of objects is 1 or not, and accordingly program to change the value of the signals which are producing the droplet(object).

```<code>def DropletRecognition(image_orig,image_calibration,Mean_section_brightness,line_lowerNozzleEdge):
showImages=1
#To maintain the brightness
mean_brightness=np.mean(np.mean(image_orig[0:line_lowerNozzleEdge][:]))
factor=Mean_section_brightness/mean_brightness
image_orig = misc.imread(image_name)
image=image_orig*factor
image=image_orig
if showImages == 1:
    print('measured image')
    print(image_orig)
    print('image_calibration')
    print(image_calibration)
    fig1 = plt.figure(1)
    fig1.suptitle(image_name)
    plt.imshow(image, cmap='gray')
    plt.draw()
    plt.waitforbuttonpress()

#To subtract the calibration image from the measured image
image_subtracted = image-image_calibration

#Calculating the lower nozzle edge and doing further resizing
image_subtracted[0:line_lowerNozzleEdge][:]=0

#To delete the nozzle lines
image_subtracted=image_subtracted[line_lowerNozzleEdge+10:][:]
image_subtracted=image_subtracted.astype('uint32')

#Erosion and Dilation to condition the image
image_tmp=image_subtracted
kernel = np.ones((5,5),np.uint8)

image_tmp = ndimage.grey_erosion(image_tmp, size=(6,6))
image_tmp = ndimage.grey_dilation(image_tmp, size=(6,6))
image_subtracted=image_tmp

#To convert the image to Binary
thresh_rc = mh.thresholding.rc(image_subtracted)
thresh=thresh_rc
image_binary = image_subtracted > thresh
image_bin_int=image_binary.astype('uint8')

#To extract the features from the Binary Image
image_tmp=image_bin_int
im_floodfill = image_tmp.copy()
h, w = image_tmp.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(im_floodfill, mask, (0,0), 255);
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
im_out = image_tmp | im_floodfill_inv
image_extracted=im_out

#To count the number of objects found in the image
T = mh.thresholding.otsu(image_extracted.astype('uint8'))
labeled,nr_objects = mh.label(image_extracted.astype('uint8') > T)
print(nr_objects)
print('number of detected objects = '+str(nr_objects))
label_array=np.array(labeled).ravel()
label_array=np.sort(label_array)
pixel_sum=np.zeros(nr_objects+1)
for ii in range(1,nr_objects+1,1):
    n_tmp=np.where(label_array==ii)[0]
    pixel_sum[ii]=len(n_tmp)

#To calculate the Object Diameter using pixel sum and area
ObjectArea=pixel_sum*pixelArea

#Assuming that the object is a circle
Radius=np.sqrt(ObjectArea/np.pi)
Diameter=2*Radius
print(' ')
print('object diameters in um =',Diameter/1e-8)
print(' ')
print(' ')
if showImages == 1:
    fig2 = plt.figure(2)
    plt.clf()
    plt.imshow(labeled)
    plt.draw()
    plt.waitforbuttonpress()
return nr_objects
</code>```

This is the function and I have to check outside the function like

```<code>if nr_objects == 1:
    break
elif nr_objects > 1:
    voltage +=80
else:
    voltage-=80
</code>```

But this is not working. The program is not checking these if loops at all. I also checked normally like
    if nr_objects == 1:
       print('Yes')
Even this is not working. So i can see that the parameter is not being accessed. Could anyone guide me how to do this??

Thanks in Advance!

答:
The variable you need to test for is not necesarily nr_objects. It's whatever appears to the left of the call to the function. i.e.

```<code>test_me = DropletRecognition(... your arguments here)

if test_me == 1:
    break
elif test_me > 1:
    voltage +=80
else:
    voltage-=80
</code>```

Body:
I have a function which takes in an image from the Camera and processes the image and finally calculates the number of objects detected in the image along with the diameters. I want to check outside the function if the number of objects is 1 or not, and accordingly program to change the value of the signals which are producing the droplet(object).

def DropletRecognition(image_orig,image_calibration,Mean_section_brightness,line_lowerNozzleEdge):
showImages=1
#To maintain the brightness
mean_brightness=np.mean(np.mean(image_orig[0:line_lowerNozzleEdge][:]))
factor=Mean_section_brightness/mean_brightness
image_orig = misc.imread(image_name)
image=image_orig*factor
image=image_orig
if showImages == 1:
    print('measured image')
    print(image_orig)
    print('image_calibration')
    print(image_calibration)
    fig1 = plt.figure(1)
    fig1.suptitle(image_name)
    plt.imshow(image, cmap='gray')
    plt.draw()
    plt.waitforbuttonpress()

#To subtract the calibration image from the measured image
image_subtracted = image-image_calibration

#Calculating the lower nozzle edge and doing further resizing
image_subtracted[0:line_lowerNozzleEdge][:]=0

#To delete the nozzle lines
image_subtracted=image_subtracted[line_lowerNozzleEdge+10:][:]
image_subtracted=image_subtracted.astype('uint32')

#Erosion and Dilation to condition the image
image_tmp=image_subtracted
kernel = np.ones((5,5),np.uint8)

image_tmp = ndimage.grey_erosion(image_tmp, size=(6,6))
image_tmp = ndimage.grey_dilation(image_tmp, size=(6,6))
image_subtracted=image_tmp

#To convert the image to Binary
thresh_rc = mh.thresholding.rc(image_subtracted)
thresh=thresh_rc
image_binary = image_subtracted > thresh
image_bin_int=image_binary.astype('uint8')

#To extract the features from the Binary Image
image_tmp=image_bin_int
im_floodfill = image_tmp.copy()
h, w = image_tmp.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(im_floodfill, mask, (0,0), 255);
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
im_out = image_tmp | im_floodfill_inv
image_extracted=im_out

#To count the number of objects found in the image
T = mh.thresholding.otsu(image_extracted.astype('uint8'))
labeled,nr_objects = mh.label(image_extracted.astype('uint8') > T)
print(nr_objects)
print('number of detected objects = '+str(nr_objects))
label_array=np.array(labeled).ravel()
label_array=np.sort(label_array)
pixel_sum=np.zeros(nr_objects+1)
for ii in range(1,nr_objects+1,1):
    n_tmp=np.where(label_array==ii)[0]
    pixel_sum[ii]=len(n_tmp)

#To calculate the Object Diameter using pixel sum and area
ObjectArea=pixel_sum*pixelArea

#Assuming that the object is a circle
Radius=np.sqrt(ObjectArea/np.pi)
Diameter=2*Radius
print(' ')
print('object diameters in um =',Diameter/1e-8)
print(' ')
print(' ')
if showImages == 1:
    fig2 = plt.figure(2)
    plt.clf()
    plt.imshow(labeled)
    plt.draw()
    plt.waitforbuttonpress()
return nr_objects

This is the function and I have to check outside the function like

if nr_objects == 1:
    break
elif nr_objects > 1:
    voltage +=80
else:
    voltage-=80

But this is not working. The program is not checking these if loops at all. I also checked normally like
    if nr_objects == 1:
       print('Yes')
Even this is not working. So i can see that the parameter is not being accessed. Could anyone guide me how to do this??

Thanks in Advance!

Body:
The variable you need to test for is not necesarily nr_objects. It's whatever appears to the left of the call to the function. i.e.

test_me = DropletRecognition(... your arguments here)

if test_me == 1:
    break
elif test_me > 1:
    voltage +=80
else:
    voltage-=80


问:
How to add an additional button to a column header (extjs 6.2)
i need to add a button to the column header besides the filters menu (like the blue mark on the photo)

答:
A little hack like this could work. Just get the layout aligned to show content in left and right most parts of Container.

```<code>Ext.create('Ext.container.Viewport', {
layout: 'fit',

items: [{
    xtype: 'container',
    items: [{
        xtype: 'grid',
        sortable: true,
        columns: [{
            flex: 1
        }, {
            text: "Age",
            flex: 1
        }],
        listeners: {
            afterrender: function (grid) {
                var columns = grid.columnManager.getColumns();
                var nameCol = columns[0];
                var targetDom = nameCol.textInnerEl.dom;
                var newPanel = Ext.create('Ext.container.Container', {
                    items: [{
                        xtype: 'label',
                        text: "Name"
                    }, {
                        xtype: 'button',
                        text: "DO IT"
                    }],
                    renderTo: targetDom
                   });
               }
           }
        }]
   }]
});
</code>```

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/29o8

Body:
A little hack like this could work. Just get the layout aligned to show content in left and right most parts of Container.

Ext.create('Ext.container.Viewport', {
layout: 'fit',

items: [{
    xtype: 'container',
    items: [{
        xtype: 'grid',
        sortable: true,
        columns: [{
            flex: 1
        }, {
            text: "Age",
            flex: 1
        }],
        listeners: {
            afterrender: function (grid) {
                var columns = grid.columnManager.getColumns();
                var nameCol = columns[0];
                var targetDom = nameCol.textInnerEl.dom;
                var newPanel = Ext.create('Ext.container.Container', {
                    items: [{
                        xtype: 'label',
                        text: "Name"
                    }, {
                        xtype: 'button',
                        text: "DO IT"
                    }],
                    renderTo: targetDom
                   });
               }
           }
        }]
   }]
});

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/29o8


答:
From MSDN:

```<code>private static void ParseTimeSpan(string intervalStr)
{
  // Write the first part of the output line.
  Console.Write( "{0,20}   ", intervalStr );

  // Parse the parameter, and then convert it back to a string.
  TimeSpan intervalVal;
  if (TimeSpan.TryParse(intervalStr, out intervalVal))
  {
     string intervalToStr = intervalVal.ToString();

     // Pad the end of the TimeSpan string with spaces if it
     // does not contain milliseconds.
     int pIndex = intervalToStr.IndexOf(':');
     pIndex = intervalToStr.IndexOf('.', pIndex);
     if (pIndex < 0)
        intervalToStr += "        ";

     Console.WriteLine("{0,21}", intervalToStr);
     // Handle failure of TryParse method.
  }
  else
  {
     Console.WriteLine("Parse operation failed.");
  }
}
</code>```

Call them like:

```<code>ParseTimeSpan("0");
    ParseTimeSpan("14");
    ParseTimeSpan("1:2:3");
    ParseTimeSpan("0:0:0.250");
    ParseTimeSpan("10.20:30:40.50");
    ParseTimeSpan("99.23:59:59.9999999");
    ParseTimeSpan("0023:0059:0059.0099");
    ParseTimeSpan("23:0:0");
    ParseTimeSpan("24:0:0");
    ParseTimeSpan("0:59:0");
    ParseTimeSpan("0:60:0");
    ParseTimeSpan("0:0:59");
    ParseTimeSpan("0:0:60");
    ParseTimeSpan("10:");
    ParseTimeSpan("10:0");
    ParseTimeSpan(":10");
    ParseTimeSpan("0:10");
    ParseTimeSpan("10:20:");
    ParseTimeSpan("10:20:0");
    ParseTimeSpan(".123");
    ParseTimeSpan("0.12:00");
    ParseTimeSpan("10.");
    ParseTimeSpan("10.12");
    ParseTimeSpan("10.12:00");
</code>```

Title: C#: Conversion to TimeSpan is not retaining complete value

Body:
From MSDN:

private static void ParseTimeSpan(string intervalStr)
{
  // Write the first part of the output line.
  Console.Write( "{0,20}   ", intervalStr );

  // Parse the parameter, and then convert it back to a string.
  TimeSpan intervalVal;
  if (TimeSpan.TryParse(intervalStr, out intervalVal))
  {
     string intervalToStr = intervalVal.ToString();

     // Pad the end of the TimeSpan string with spaces if it
     // does not contain milliseconds.
     int pIndex = intervalToStr.IndexOf(':');
     pIndex = intervalToStr.IndexOf('.', pIndex);
     if (pIndex < 0)
        intervalToStr += "        ";

     Console.WriteLine("{0,21}", intervalToStr);
     // Handle failure of TryParse method.
  }
  else
  {
     Console.WriteLine("Parse operation failed.");
  }
}

Call them like:

ParseTimeSpan("0");
    ParseTimeSpan("14");
    ParseTimeSpan("1:2:3");
    ParseTimeSpan("0:0:0.250");
    ParseTimeSpan("10.20:30:40.50");
    ParseTimeSpan("99.23:59:59.9999999");
    ParseTimeSpan("0023:0059:0059.0099");
    ParseTimeSpan("23:0:0");
    ParseTimeSpan("24:0:0");
    ParseTimeSpan("0:59:0");
    ParseTimeSpan("0:60:0");
    ParseTimeSpan("0:0:59");
    ParseTimeSpan("0:0:60");
    ParseTimeSpan("10:");
    ParseTimeSpan("10:0");
    ParseTimeSpan(":10");
    ParseTimeSpan("0:10");
    ParseTimeSpan("10:20:");
    ParseTimeSpan("10:20:0");
    ParseTimeSpan(".123");
    ParseTimeSpan("0.12:00");
    ParseTimeSpan("10.");
    ParseTimeSpan("10.12");
    ParseTimeSpan("10.12:00");


问:
Is there a way to get the source code from an APK file?
The hard drive on my laptop just crashed and I lost all the source code for an app that I have been working on for the past two months.
All I have is the APK file that is stored in my email from when I sent it to a friend.

Is there any way to extract my source code from this APK file?

答:
You can try DexPatcher. It even integrates with Android Studio. It uses Apktool and Dex2Jar internally.<br>
You can use those tools independently as well.
Apktool decompiles apk, and extracts .dex files, which can further be converted to jar using Dex2Jar. Jar can be decompiled by using JD-GUI. You can see the Java code with the help of that tool. Although the similarity of decompiled code to the actual code cannot be guaranteed. There are some advanced code obfuscation tools available in the market, which mess up the code to make it difficult to decompile /  understand. eg. Proguard </p>

Body:
You can try DexPatcher. It even integrates with Android Studio. It uses Apktool and Dex2Jar internally.

You can use those tools independently as well.
Apktool decompiles apk, and extracts .dex files, which can further be converted to jar using Dex2Jar. Jar can be decompiled by using JD-GUI. You can see the Java code with the help of that tool. Although the similarity of decompiled code to the actual code cannot be guaranteed. There are some advanced code obfuscation tools available in the market, which mess up the code to make it difficult to decompile /  understand. eg. Proguard


问:
White line under UINavigationBar in IOS 7
I have a UITableViewController with a UISearchDisplayController and UISearchBar.  I'm seeing a white line under the navbar when I present the view in a UITabBarController.  When I present the view modally in a UINavigationController, the line is either gray or black (I can't tell) and it looks perfectly normal.  Any ideas?

答:
Swift version of Divya's answers</p>

```<code>    let hideLineView = UIView(frame: CGRect(x: 0, y: navigationController!.navigationBar.frame.size.height, width: view.frame.size.width, height: 1))
    hideLineView.backgroundColor = UIColor.white
    navigationController!.navigationBar.addSubview(hideLineView)
</code>```

Body:
Swift version of Divya's answers

    let hideLineView = UIView(frame: CGRect(x: 0, y: navigationController!.navigationBar.frame.size.height, width: view.frame.size.width, height: 1))
    hideLineView.backgroundColor = UIColor.white
    navigationController!.navigationBar.addSubview(hideLineView)


问:
Type mismatch, expected ListBuffer[Any], actual ListBuffer[CustomClass]
I don't understand the title error knowing that for this function :

```<code>def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}
</code>```

called with these parameters :

```<code>myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)
</code>```

Am i obliged to call function like this :

```<code>myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)
</code>```

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

答: Thats because ListBuffer is invariant so you can't assign ListBuffer[A] to ListBuffer[SuperTypeOfA], the reason for that is ListBuffer is mutable which is unsafe to make Covaraint. https://docs.scala-lang.org/tour/variances.html

Body:
I don't understand the title error knowing that for this function :

def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}

called with these parameters :

myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)

Am i obliged to call function like this :

myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)

Produces mismatch type error only for ListBuffer parameter.
So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you


问:
how to hide child elements child elements in jQuery
I have a menu populating from MySQL table and PHP up to some nested sub levels.
my menu like this:

A

B

C

If click on A first time it is showing all the child elements and again I click child elements of A it displaying child elements also fine.

But the problem is when I click on the B after open all the levels items of A it shows B sub elements fine. But again if I click A it showing all the elements except child child elements also.

I used jQuery for this.

So I want to bring back to the original state? ( only expand the top child elements, not the sub child elements ),

how to do that?

//this is my jquery code for elements clickable in menu.
$(document).ready(function() {
  $(".lichild").parent().hide();

  $(".limain").click(function() {
    $(this).children('ul').show();
    $(this).siblings(".limain").children('ul').hide();
  });
  $(".lichild").click(function() {
    $(this).children('ul').show();
    $(this).siblings().children('ul').hide()
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- This is the html I am generating using a PHP function -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="limain">A
    <ul>
      <li class="lichild">A1
        <ul>
          <li class="lichild">a2</li>
          <li class="lichild">a1
            <ul>
              <li class="lichild">aaaaaa</li>
              <li class="lichild">abbbbbb</li>
            </ul>
          </li>
        </ul>
      </li>
      <li class="lichild">A2</li>
      <li class="lichild">A3</li>
      <li class="lichild">A4</li>
      <li class="lichild">A5</li>
    </ul>
    <li class="limain">B
      <ul>
        <li class="lichild">B1</li>
        <li class="lichild">B2</li>
      </ul>
    </li>
    <li class="limain">C
      <ul>
        <li class="lichild">C1</li>
        <li class="lichild">C2</li>
        <li class="lichild">C3</li>
        <li class="lichild">A6
          <ul>
            <li class="lichild">A8
              <ul>
                <li class="lichild">A10
                  <ul>
                    <li class="lichild">A13
                    </li>
                    <li class="lichild">A14
                    </li>
                  </ul>
                </li>
                <li class="lichild">A11
                </li>
              </ul>
            </li>
            <li class="lichild">A9
            </li>
          </ul>
        </li>
        <li class="lichild">A7
        </li>
      </ul>
    </li>
    <li class="limain">D
      <ul>
        <li class="lichild">D1</li>
        <li class="lichild">D2
        </li>
      </ul>
    </li>
</ul></code>```

答:
```<code>       $(document).ready(function () {
        $(".lichild").parent().hide();
        $(".limain").click(function () {
            $(this).children('ul').show();
            $(this).siblings().find('ul').hide();
        });
        $(".lichild").click(function () {
            $(this).children('ul').show();
            $(this).siblings('li').find('ul').hide()

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

Body:
I have a menu populating from MySQL table and PHP up to some nested sub levels.
my menu like this:

A

B

C

If click on A first time it is showing all the child elements and again I click child elements of A it displaying child elements also fine.

But the problem is when I click on the B after open all the levels items of A it shows B sub elements fine. But again if I click A it showing all the elements except child child elements also.

I used jQuery for this.

So I want to bring back to the original state? ( only expand the top child elements, not the sub child elements ),

how to do that?

//this is my jquery code for elements clickable in menu.
$(document).ready(function() {
  $(".lichild").parent().hide();

  $(".limain").click(function() {
    $(this).children('ul').show();
    $(this).siblings(".limain").children('ul').hide();
  });
  $(".lichild").click(function() {
    $(this).children('ul').show();
    $(this).siblings().children('ul').hide()
  });
});

A

A1

a2

a1

aaaaaa

abbbbbb

A2

A3

A4

A5

B

B1

B2

C

C1

C2

C3

A6

A8

A10

A13

A14

A11

A9

A7

D

D1

D2


问:
iOS @IBDesignable autorefresh UILabel params as title, font, color
I'm working on a feature, that I can set my custom style on UILabel (by taping name of style). I have a simple code for this:

```<code>struct Style {
    var fontName: String!
    var fontSize: CGFloat!
    var color: UIColor!
    var styleName: String!
    var font: UIFont {
        return UIFont(name: self.fontName, size: self.fontSize)!
    }

    init(styleName: String, fontName: String!, fontSize: CGFloat!, color: UIColor!) {
        self.fontName = fontName
        self.fontSize = fontSize
        self.color = color
    }

    var desc: String {
        return "Style: \(styleName)"
    }
}

let dictStyle: [String: Style] = [
                "normal": Style(styleName: "normal", fontName: "HelveticaNeue-Light", fontSize: 20, color: UIColor.red),
                "bold": Style(styleName: "bold", fontName: "HelveticaNeue-Bold", fontSize: 30, color: UIColor.black)
            ]

@IBDesignable class Label: UILabel {

    @IBInspectable var style: String = "normal" {
        didSet {
            setNeedsDisplay()
        }
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        self.text = "\(style)" // there is normal or bold

        if let color = dictStyle[self.style]?.color {
            self.textColor =  color
        }
        if let font = dictStyle[self.style]?.font {
            self.font = font
        }
        if let name = dictStyle[self.style]?.styleName {
            self.text =  name
        }
    }
}
</code>```

and it's work ok, but I would like to automatic change title, font, color in Interface Builder(in red rect below).

I've seen in .storyboard file

```<code><label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="9lO-cw-I2Z" customClass="Label" customModule="AutoRefresh" customModuleProvider="target">
                            <rect key="frame" x="24" y="44" width="327" height="24"/>
                            <fontDescription key="fontDescription" name="HelveticaNeue" family="Helvetica Neue" pointSize="32"/>
                            <color key="textColor" red="0.25098040700000002" green="0.50196081400000003" blue="0.0" alpha="0.76206656679999996" colorSpace="calibratedRGB"/>
                            <nil key="highlightedColor"/>
                            <userDefinedRuntimeAttributes>
                                <userDefinedRuntimeAttribute type="string" keyPath="style" value="normal"/>
                            </userDefinedRuntimeAttributes>
                        </label>
</code>```

so there fields as "text" or "textColor" don't change.

答:
Here's what you're looking for in Swift 4:</p>

```<code>@IBDesignable
class Label: UILabel {

    override func awakeFromNib() {
        super.awakeFromNib()
        config()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        config()
    }

    func config() {
        // Setup how you please, e.g. color = UIColor.black
    }

}
</code>```

Body:
I'm working on a feature, that I can set my custom style on UILabel (by taping name of style). I have a simple code for this:

struct Style {
    var fontName: String!
    var fontSize: CGFloat!
    var color: UIColor!
    var styleName: String!
    var font: UIFont {
        return UIFont(name: self.fontName, size: self.fontSize)!
    }

    init(styleName: String, fontName: String!, fontSize: CGFloat!, color: UIColor!) {
        self.fontName = fontName
        self.fontSize = fontSize
        self.color = color
    }

    var desc: String {
        return "Style: \(styleName)"
    }
}

let dictStyle: [String: Style] = [
                "normal": Style(styleName: "normal", fontName: "HelveticaNeue-Light", fontSize: 20, color: UIColor.red),
                "bold": Style(styleName: "bold", fontName: "HelveticaNeue-Bold", fontSize: 30, color: UIColor.black)
            ]

@IBDesignable class Label: UILabel {

    @IBInspectable var style: String = "normal" {
        didSet {
            setNeedsDisplay()
        }
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        self.text = "\(style)" // there is normal or bold

        if let color = dictStyle[self.style]?.color {
            self.textColor =  color
        }
        if let font = dictStyle[self.style]?.font {
            self.font = font
        }
        if let name = dictStyle[self.style]?.styleName {
            self.text =  name
        }
    }
}

and it's work ok, but I would like to automatic change title, font, color in Interface Builder(in red rect below).

I've seen in .storyboard file

                            <rect key="frame" x="24" y="44" width="327" height="24"/>
                            <fontDescription key="fontDescription" name="HelveticaNeue" family="Helvetica Neue" pointSize="32"/>
                            <color key="textColor" red="0.25098040700000002" green="0.50196081400000003" blue="0.0" alpha="0.76206656679999996" colorSpace="calibratedRGB"/>
                            <nil key="highlightedColor"/>
                            <userDefinedRuntimeAttributes>
                                <userDefinedRuntimeAttribute type="string" keyPath="style" value="normal"/>
                            </userDefinedRuntimeAttributes>

so there fields as "text" or "textColor" don't change.

Body:
Here's what you're looking for in Swift 4:

@IBDesignable
class Label: UILabel {

    override func awakeFromNib() {
        super.awakeFromNib()
        config()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        config()
    }

    func config() {
        // Setup how you please, e.g. color = UIColor.black
    }

}


问:
Click button on page load with div content changed
I have links which change content on click. I want one of the links to be cliked on page load and stay as active. Looks like it works in the below fiddle but when I add it on website this one is loaded :

http://jsfiddle.net/0e91svrr/

I think I have some mistake in JS:

```<code>   <script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">//<![CDATA[
    $(document).ready(function() {
        $('a[class^=question]').click(function(e){
      e.preventDefault();
        var id = $(this).attr("class").replace("question","")
            $('.new_member_box_display').html($('#answer' + id).html());
        })
      document.getElementById("modal").click();

    });//end of ready
    </script>
</code>```

答:
The code you have written is perfectly fine. I would just suggest try JQuery's trigger click.</p>

```<code>$('#modal').trigger('click');
</code>```

Body:
The code you have written is perfectly fine. I would just suggest try JQuery's trigger click.

$('#modal').trigger('click');


问:
Ionic virtual scroll list elements always blink when data set being changed
I'm using Ionic virtual scroll and infinite scroll to display my items list, it works fine but I notice that whenever it fetches data from server, the list element will blink a moment, I guess it's because virtual scroll is re-rendering the html elements. If I just used ngFor to display the item list, there would not be any blink but it cannot display too much items properly like more than 200. This is kind of annoying and I want to remove that blink on virtual scroll, how can I do that?

<ion-list [virtualScroll]="list | pesStatus: statusFilter" [approxItemHeight]="'108px'" [virtualTrackBy]="trackBy">

  <ion-item *virtualItem="let item">
    <ion-row class="pes-info-title">
      <ion-col class="pull-side">

{{item.TrackingNumber}}

{{item.BusinessPartnerName}}

      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col class="pull-side">

          <svg-icon width="16px" height="16px" [id]="'svg-icon-status' + item.PesStatusId"></svg-icon>

{{item.StatusName}}

{{item.PesCode}}

      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col class="pull-side">

          <svg-icon width="16px" height="16px" [id]="'svg-icon-status' + item.PesStatusId"></svg-icon>

{{item.DateDelivered}}

{{item.ProjectName}}

      </ion-col>
    </ion-row>

  </ion-item>

</ion-list>
 <ion-infinite-scroll #infiniteScroll
    (ionInfinite)="$event.waitFor(doInfinite($event))">
   <ion-infinite-scroll-content loadingText="Loading..."></ion-infinite-scroll-content>
 </ion-infinite-scroll>

```

答:
This is a known issue with the virtual scroll in ionic.
see https://github.com/ionic-team/ionic/issues/11788

You should have shared how you append data from the server, and further details about the filter.

Mainly this issue is related to the way you push new data into your array.

DO NOT use concatenate(or spread operator) because it will replace the current array and cause a full refresh of the virtual scroll. I solved this issue by iterating over the rows, and pushing them one by one to the array.

```<code>// WRONG WAY will CAUSE BLINKS AND JUMPS
gotData(_data:any[]){
   this.list = this.list.concat(_data); // will cause the issue.
}

// CORRECT WAY TO SOLVE THE BLINKING ISSUE
gotData(_data:any[]){

 let len:number = _data.length;

for(let i:number = 0; i< len; i++)
 this.list.push(_data[i]); // this will work without blinks or jumps
}
</code>```

I have solved the issue with infinite scroller and virtual list by applying this fix.

Body:
This is a known issue with the virtual scroll in ionic.
see https://github.com/ionic-team/ionic/issues/11788

You should have shared how you append data from the server, and further details about the filter.

Mainly this issue is related to the way you push new data into your array.

DO NOT use concatenate(or spread operator) because it will replace the current array and cause a full refresh of the virtual scroll. I solved this issue by iterating over the rows, and pushing them one by one to the array.

// WRONG WAY will CAUSE BLINKS AND JUMPS
gotData(_data:any[]){
   this.list = this.list.concat(_data); // will cause the issue.
}

// CORRECT WAY TO SOLVE THE BLINKING ISSUE
gotData(_data:any[]){

 let len:number = _data.length;

for(let i:number = 0; i< len; i++)
 this.list.push(_data[i]); // this will work without blinks or jumps
}

I have solved the issue with infinite scroller and virtual list by applying this fix.


问:
php file_get_contents() converts html entities like ö to ö
I try to display the contents of a php file in a textarea with

```<code><textarea ...>
<?php echo file_get_contents("file.php"); ?>
</textarea>
</code>```

but it converts the html entities like ö to ö. As it is php code I can not use a conversion like htmlspecialchars because it would brick the <> and quotes etc.

EDIT:

I checked the sourcecode with the browser and there is really an ö.

Please help, thank you!

答:
htmlspecialchars will change:

```<code>< ö
</code>```

to:

```<code>< &ouml;
</code>```

and it's ok.

It will display in textarea:

```<code>< ö
</code>```

After you submit form, it will send to server text

```<code>< ö
</code>```

not:

```<code>< &ouml;
</code>```

Tested in Chrome with jQuery:

```<code>$('#layout').html('<form method="POST"><textarea name="x"><&ouml;</textarea><input type="submit" /></form>')
</code>```

Body:
I try to display the contents of a php file in a textarea with

<textarea ...>
<?php echo file_get_contents("file.php"); ?>
</textarea>

but it converts the html entities like ö to ö. As it is php code I can not use a conversion like htmlspecialchars because it would brick the <> and quotes etc.

EDIT:

I checked the sourcecode with the browser and there is really an ö.

Please help, thank you!

Body:
htmlspecialchars will change:

< &ouml;

to:

&lt; &amp;ouml;

and it's ok.

It will display in textarea:

< &ouml;

After you submit form, it will send to server text

< &ouml;

not:

&lt; &amp;ouml;

Tested in Chrome with jQuery:

$('#layout').html('<form method="POST"><textarea name="x">&lt;&amp;ouml;</textarea><input type="submit" /></form>')


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答:
You must do it by using an extra boolean.

To implement using an extra boolean, you could try logic like the following template:

```<code>template<typename T>
struct Defined
{
 bool defined;
 T value;
 Defined() : defined(false) {}
 Defined(const T& value_) : defined(true), value(value_) {}
 ... and perhaps other operators here ...
 ... to make this behave even more like a T ...
};
</code>```

OwnerDisplayName: Tunnuz

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

Body:
You must do it by using an extra boolean.

To implement using an extra boolean, you could try logic like the following template:

template<typename T>
struct Defined
{
 bool defined;
 T value;
 Defined() : defined(false) {}
 Defined(const T& value_) : defined(true), value(value_) {}
 ... and perhaps other operators here ...
 ... to make this behave even more like a T ...
};

OwnerDisplayName: ChrisW


问:
Composing a Controller class with Dependency Injection in PHP
How to solve the problem of composing a Controller class in PHP, which should be:

easily testable by employing Dependency Injection,

provide shared objects for end programmer

provide a way to load new user libraries

Look down, for controller instantiation with a Dependency injection framework

The problem is, that derived Controllers may use whatever resources the programmer wants to (eg. the framework provides). How to create a unified access to shared resources (DB, User, Storage, Cache, Helpers), user defined Classes or another libraries?

Elegant solution?

There are several possible solutions to my problem, but neither one looks to be a elegant

Try to pass all shared objects by constructor? (may create constructor even with 10 placeholders)

Create getters, settters? (bloated code) $controller->setApplication($app)

Apply singletons on shared resources? User::getInstance() or Database::getInstance()

Use Dependency Injection container as a singleton for object sharing inside the controller?

provide one global application singleton as a factory? (this one looks very used in php frameworks, hovewer it goes strongly against DI principles and Demeter's law)

I understand, that creating strongly coupled classes is discouraged and banished for :), however I don't know how this paradigm applies to a starting point for other programmers (a Controller class), in which they should be able to access shared resources provided to the MVC architecture. I believe, that breaking up the controller class into smaller classes would somehow destroy the practical meaning of MVC.

Dependency Injection Framework

DI Framework looks like a viable choice. However the problem still persists. A class like Controller does not reside in the Application layer, but in the RequestHandler/Response layer.

How should this layer instantiate the controller?

pass the DI injector into this layer?

DI Framework as a singleton?

put isolated DI framework config only for this layer and create separate DI injector instance?

答:
As far as I understand, the Application class of yours should be the dispatcher. If so, I would rather use the controller constructor to pass an instance of the Application, so the controller would know who's invoking it. At later point if you want to have a different Application instance depending on whether the code is invoked from within CLI, you can have an ApplicationInterface which the Application\Http and Application\Cli would implement and everything would be easy to maintain.

You could also implement some factory pattern to get a nice implementation of the DI. For example, check the createThroughReflection method here: https://github.com/troelskn/bucket/blob/master/lib/bucket.inc.php

I hope this makes sense.

Regards,
Nick


问:
Android - center text in OpenSansBTextView
I'm designing my constraint layout using XML.

I have an OpenSansBTextView and I need my text to be centered in it. It's centered horizontally, and not centered vertically. I don't know why. Here is my xml file. Can you see my mistake?

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:id="@+id/dashboard">

    <com.doyousonder.android.utils.RochesterTextView
        android:id="@+id/YourActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginStart="25dp"
        app:layout_constraintVertical_bias="0.34"
        android:text="@string/YourActivity"
        android:textColor="@color/colorPrimaryMoreDark"
        android:textSize="23sp" />

    <com.doyousonder.android.utils.OpenSansRTextView
        android:id="@+id/YouVoted"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/YourActivity"
        android:layout_marginTop="15dp"
        android:layout_marginStart="20dp"
        android:text="@string/YouVoted"
        android:textColor="@color/colorPrimaryMoreDark"
        android:textSize="15sp" />

    <com.doyousonder.android.utils.OpenSansSBTextView
        android:id="@+id/VoteCount"
        android:layout_width="29dp"
        android:layout_height="35dp"
        app:layout_constraintStart_toEndOf="@+id/YouVoted"
        app:layout_constraintTop_toTopOf="@+id/YouVoted"
        app:layout_constraintBottom_toBottomOf="@+id/YouVoted"
        android:layout_marginStart="5dp"
        android:background="@drawable/more_curved_edge_button_button_primarycolor_background"
        android:gravity="center"
        android:text="1"
        android:textAlignment="center"
        android:textSize="25sp" />
</code>```

答:
You haven't provided much code to work with, i.e what is the youVoted variable. I'm assuming youvoted is your parent layout

I think you're issue comes with how you set up your constraints. Try these instead

```<code>...other layout info
    app:layout_constraintBottom_toBottomOf="@+id/YouVoted"
    app:layout_constraintStart_toStartOf="@+id/YouVoted"
    app:layout_constraintTop_toTopOf="@+id/YouVoted"
    app:layout_constraintEnd_toEndOf="@+id/YouVoted"/>
</code>```

Explanation
I believe the mistake is you made is stating your textview should start at the end of your youvoted layout instead of saying it should start at the start of the youvoted layout.

change app:layout_constraintStart_toEndOf="@+id/YouVoted" to app:layout_constraintStart_toStartOf="@+id/YouVoted"

also add an end constraint.

```<code>app:layout_constraintEnd_toEndOf="@+id/YouVoted"
</code>```

Body:
I'm designing my constraint layout using XML.

I have an OpenSansBTextView and I need my text to be centered in it. It's centered horizontally, and not centered vertically. I don't know why. Here is my xml file. Can you see my mistake?

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:id="@+id/dashboard">

    <com.doyousonder.android.utils.RochesterTextView
        android:id="@+id/YourActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginStart="25dp"
        app:layout_constraintVertical_bias="0.34"
        android:text="@string/YourActivity"
        android:textColor="@color/colorPrimaryMoreDark"
        android:textSize="23sp" />

    <com.doyousonder.android.utils.OpenSansRTextView
        android:id="@+id/YouVoted"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/YourActivity"
        android:layout_marginTop="15dp"
        android:layout_marginStart="20dp"
        android:text="@string/YouVoted"
        android:textColor="@color/colorPrimaryMoreDark"
        android:textSize="15sp" />

    <com.doyousonder.android.utils.OpenSansSBTextView
        android:id="@+id/VoteCount"
        android:layout_width="29dp"
        android:layout_height="35dp"
        app:layout_constraintStart_toEndOf="@+id/YouVoted"
        app:layout_constraintTop_toTopOf="@+id/YouVoted"
        app:layout_constraintBottom_toBottomOf="@+id/YouVoted"
        android:layout_marginStart="5dp"
        android:background="@drawable/more_curved_edge_button_button_primarycolor_background"
        android:gravity="center"
        android:text="1"
        android:textAlignment="center"
        android:textSize="25sp" />

Body:
You haven't provided much code to work with, i.e what is the youVoted variable. I'm assuming youvoted is your parent layout

I think you're issue comes with how you set up your constraints. Try these instead

...other layout info
    app:layout_constraintBottom_toBottomOf="@+id/YouVoted"
    app:layout_constraintStart_toStartOf="@+id/YouVoted"
    app:layout_constraintTop_toTopOf="@+id/YouVoted"
    app:layout_constraintEnd_toEndOf="@+id/YouVoted"/>

Explanation
I believe the mistake is you made is stating your textview should start at the end of your youvoted layout instead of saying it should start at the start of the youvoted layout.

change app:layout_constraintStart_toEndOf="@+id/YouVoted" to app:layout_constraintStart_toStartOf="@+id/YouVoted"

also add an end constraint.

app:layout_constraintEnd_toEndOf="@+id/YouVoted"


答:
Use find inside siblings and hide it.

$(".lichild").parent().hide();

$(".limain").click(function() {
  $(this).children('ul').show();
  $(this).siblings(".limain").find('ul').hide(); // Change in this line
});
$(".lichild").click(function() {
  $(this).children('ul').show();
  $(this).siblings().children('ul').hide()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
  <li class="limain">
    A
    <ul>
      <li class="lichild">
        A1
        <ul>
          <li class="lichild">a2</li>
          <li class="lichild">
            a1
            <ul>
              <li class="lichild">aaaaaa</li <li class="lichild">abbbbbb</li>
          </ul>
      </li>
      </ul>
  </li>
  <li class="lichild">A2</li>
  <li class="lichild">A3</li>
  <li class="lichild">A4</li>
  <li class="lichild">A5</li>
  </ul>
  <li class="limain">
    B
    <ul>
      <li class="lichild">B1</li>
      <li class="lichild">B2</li>
    </ul>
  </li>
  <li class="limain">
    C
    <ul>
      <li class="lichild">C1</li>
      <li class="lichild">C2</li>
      <li class="lichild">C3</li>
      <li class="lichild">
        A6
        <ul>
          <li class="lichild">
            A8
            <ul>
              <li class="lichild">
                A10
                <ul>
                  <li class="lichild">A13
                  </li>
                  <li class="lichild">A14
                  </li>
                </ul>
              </li>
              <li class="lichild">A11
              </li>
            </ul>
          </li>
          <li class="lichild">A9
          </li>
        </ul>
      </li>
      <li class="lichild">A7
      </li>
    </ul>
  </li>
  <li class="limain">
    D
    <ul>
      <li class="lichild">D1</li>
      <li class="lichild">D2
      </li>
    </ul>
  </li>
</ul></code>```

Title: how to hide child elements child elements in jQuery

Body:
Use find inside siblings and hide it.

$(".lichild").parent().hide();

$(".limain").click(function() {
  $(this).children('ul').show();
  $(this).siblings(".limain").find('ul').hide(); // Change in this line
});
$(".lichild").click(function() {
  $(this).children('ul').show();
  $(this).siblings().children('ul').hide()
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
  <li class="limain">
    A
    <ul>
      <li class="lichild">
        A1
        <ul>
          <li class="lichild">a2</li>
          <li class="lichild">
            a1
            <ul>
              <li class="lichild"><a href="vuv">aaaaaa</a></li <li class="lichild"><a href="xyz">abbbbbb</a></li>
          </ul>
      </li>
      </ul>
  </li>
  <li class="lichild">A2</li>
  <li class="lichild">A3</li>
  <li class="lichild">A4</li>
  <li class="lichild"><a href="home">A5</a></li>
  </ul>
  <li class="limain">
    B
    <ul>
      <li class="lichild">B1</li>
      <li class="lichild"><a href="about">B2</a></li>
    </ul>
  </li>
  <li class="limain">
    C
    <ul>
      <li class="lichild">C1</li>
      <li class="lichild">C2</li>
      <li class="lichild">C3</li>
      <li class="lichild">
        A6
        <ul>
          <li class="lichild">
            A8
            <ul>
              <li class="lichild">
                A10
                <ul>
                  <li class="lichild"><a href="abc">A13</a>
                  </li>
                  <li class="lichild"><a href="fgh">A14</a>
                  </li>
                </ul>
              </li>
              <li class="lichild"><a href="cde">A11</a>
              </li>
            </ul>
          </li>
          <li class="lichild"><a href="abcd">A9</a>
          </li>
        </ul>
      </li>
      <li class="lichild"><a href="nop">A7</a>
      </li>
    </ul>
  </li>
  <li class="limain">
    D
    <ul>
      <li class="lichild">D1</li>
      <li class="lichild"><a href="klm">D2</a>
      </li>
    </ul>
  </li>
</ul>