问:
UICollectionView inside CustomTableCell
I have some problem when trying to implement UICollectionView with custom cell inside custom cell in tableView.
I have custom table view cell which works fine, showing my label as I want.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    Node *node = [[Node alloc] init];
    if(_nodes != nil){
        node = [_nodes objectAtIndex:indexPath.row];
        if(_tempSensorsDictionary.count > 0){
            NSArray *allSensors = [_tempSensorsDictionary objectForKey:node.number];
            TemperatureSensor *ts = allSensors[0];
            if(node.name != nil && ![node.name  isEqual: @""]){
                cell.unitNameLabel.text = node.name;
            } else {
                cell.unitNameLabel.text = node.number;
            }
            cell.collection = [_tempSensorsDictionary objectForKey:node.number];
        }
    }
    return cell;
}
</code>```

I have set up CollectionView background to gray colour and I can see this "box". So I guess that CollectionView is initialised properly in my TemperatureTaleViewCell class where I putted:

```<code>@implementation TemperatureTableViewCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if (!(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) return nil;

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.collectionView reloadData];
    [self.contentView addSubview:self.collectionView];
    return self;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    cell.tempValTempCollViewCell.text = @"21oC";
    cell.backgroundColor = [UIColor redColor];

    return cell;

}
@end
</code>```

But then my table view looks like this:

What is wrong in my code and where is wrong direction?

答:
As I can see, you designed your TemperatureTaleViewCell via XIB/storyboard, and you create the cell via </p>

```<code>[tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
</code>```

<p>It's ok so far, but you're setting your collectionView's delegate and dataSource inside initWithStyle, which will not be called in this case. So your collection view's delegate and datasource methods will not be called. </p>

Title: UICollectionView inside CustomTableCell

Body:
I have some problem when trying to implement UICollectionView with custom cell inside custom cell in tableView.
I have custom table view cell which works fine, showing my label as I want.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    Node *node = [[Node alloc] init];
    if(_nodes != nil){
        node = [_nodes objectAtIndex:indexPath.row];
        if(_tempSensorsDictionary.count > 0){
            NSArray *allSensors = [_tempSensorsDictionary objectForKey:node.number];
            TemperatureSensor *ts = allSensors[0];
            if(node.name != nil && ![node.name  isEqual: @""]){
                cell.unitNameLabel.text = node.name;
            } else {
                cell.unitNameLabel.text = node.number;
            }
            cell.collection = [_tempSensorsDictionary objectForKey:node.number];
        }
    }
    return cell;
}

I have set up CollectionView background to gray colour and I can see this "box". So I guess that CollectionView is initialised properly in my TemperatureTaleViewCell class where I putted:

@implementation TemperatureTableViewCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if (!(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) return nil;

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.collectionView reloadData];
    [self.contentView addSubview:self.collectionView];
    return self;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    cell.tempValTempCollViewCell.text = @"21oC";
    cell.backgroundColor = [UIColor redColor];

    return cell;

}
@end

But then my table view looks like this:

What is wrong in my code and where is wrong direction?

Body:
As I can see, you designed your TemperatureTaleViewCell via XIB/storyboard, and you create the cell via

[tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];

It's ok so far, but you're setting your collectionView's delegate and dataSource inside initWithStyle, which will not be called in this case. So your collection view's delegate and datasource methods will not be called.


来源: stackexchange

问:
jQuery: simultaneously fadeIn and fadeOut
the following code which is called periodically by setInterval performs the following sequence:

1. fade in an image for 750 msec

2. diplay it for 6 secs

3. fade out the image for 750 msec

4. randomly select another image (function randomPic)

5. fade in for 750 msec and so on:

```<code>$("#_fadee_").fadeIn(750, function() {
    $("#_fadee_").delay(6000).fadeOut(750, randomPic);
});
</code>```

You can see the effect here. How can I get the fadeOut of the old image and the fadeIn of the new one to run simultaneously?

Thanks, Ralf

答:
Basically, you need to load the new image in another div that has a z-index beneath the image fading out.  It's not that it's fading in simultaneously, it's just uncovered as the initial is fading out.  Once the top div is faded out completely, you load the mew image into it and return its opacity to 1 so that it covers the div that you will load the next image into.  In pseudocode it would look something like this:

```<code>var fadeO = function () {
    var $fo = $('#_fadeO_');
    var $fi = $('#_fadeI_');
    var newImg = // load image here;

    $fi.html(newImg);

    $fo.fadeOut(1500, function() {
        // put #_fadeO_ back on top with new image
        $fo.html(newImg);
        $fo.css({'display':'block', 'opacity':1});

        // call function again after 6 seconds
        setTimeout(fadeO, 6000);
    });
};

fadeO();
</code>```

...but I made a fiddle of it so you could see it in action, switching background colors instead of image contents. You should be able to get the idea of how to do the same with loaded images based on the above pseudo-code and how the HTML, CSS, and JS is set up here:

http://jsfiddle.net/UbmS9/

ContentLicense: CC BY-SA 2.5

Body:
the following code which is called periodically by setInterval performs the following sequence:

1. fade in an image for 750 msec

2. diplay it for 6 secs

3. fade out the image for 750 msec

4. randomly select another image (function randomPic)

5. fade in for 750 msec and so on:

$("#_fadee_").fadeIn(750, function() {
    $("#_fadee_").delay(6000).fadeOut(750, randomPic);
});

You can see the effect here. How can I get the fadeOut of the old image and the fadeIn of the new one to run simultaneously?

Thanks, Ralf

Body:
Basically, you need to load the new image in another div that has a z-index beneath the image fading out.  It's not that it's fading in simultaneously, it's just uncovered as the initial is fading out.  Once the top div is faded out completely, you load the mew image into it and return its opacity to 1 so that it covers the div that you will load the next image into.  In pseudocode it would look something like this:

var fadeO = function () {
    var $fo = $('#_fadeO_');
    var $fi = $('#_fadeI_');
    var newImg = // load image here;

    $fi.html(newImg);

    $fo.fadeOut(1500, function() {
        // put #_fadeO_ back on top with new image
        $fo.html(newImg);
        $fo.css({'display':'block', 'opacity':1});

        // call function again after 6 seconds
        setTimeout(fadeO, 6000);
    });
};

fadeO();

...but I made a fiddle of it so you could see it in action, switching background colors instead of image contents. You should be able to get the idea of how to do the same with loaded images based on the above pseudo-code and how the HTML, CSS, and JS is set up here:

http://jsfiddle.net/UbmS9/


问:
What's the equivalent of InStr for an array(2 dimension) in c#
I'm new to c#, if I don't explain what I need very well please tell me.
I'm reading some data from an excel file and then store the data into an array.

```<code>excel.Application x1app = new excel.Application();
        x1app.Visible = true;
        excel.Workbook x1workbook = x1app.Workbooks.Open(@"...");
        x1workbook.Activate();
        excel.Worksheet x1worksheet = x1workbook.Worksheets[1];
        excel.Range x1range = x1worksheet.UsedRange;
        System.Array myvalues;
        myvalues = (System.Array)x1range.Cells.Value;
</code>```

Now I want to use equivalent  for InStr from VBA on the array, but I don't know what's the equivalent.

I have tried Array.IndexOf(myvalue, ""), but this work's only for one dimension array.

答:
If you're going to import a range into a data structure, I think what you want is a 2d array:

```<code>object[,] myvalues = x1range.Cells.Value;
</code>```

Individual values can be extracted as follows:

```<code>object cellValue = myvalues[3, 4];
</code>```

If you want to loop through all cells, a foreach is easiest:

```<code>foreach (object o in myvalues)
{
    string myText = o == null ? null : o.ToString();
}
</code>```

Or, if the x/y position is important, you can loop through the X/Y as follows:

```<code>for (int i = 1; i < myvalues.GetLength(0); i++)
{
    for (int j = 1; j < myvalues.GetLength(1); i++)
    {
        object o = myvalues[i, j];
    }
}
</code>```

Note that C# is 0-based, but in the Excel output you do want to use the 1-based references.

The IndexOf Function does work in C#, but not against an array like this.  If you wanted to use that, you can always cast the array to a list:

```<code>List<object> myList = myvalues.Cast<object>().ToList();
int found = myList.IndexOf("Foo");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to c#, if I don't explain what I need very well please tell me.
I'm reading some data from an excel file and then store the data into an array.

excel.Application x1app = new excel.Application();
        x1app.Visible = true;
        excel.Workbook x1workbook = x1app.Workbooks.Open(@"...");
        x1workbook.Activate();
        excel.Worksheet x1worksheet = x1workbook.Worksheets[1];
        excel.Range x1range = x1worksheet.UsedRange;
        System.Array myvalues;
        myvalues = (System.Array)x1range.Cells.Value;

Now I want to use equivalent  for InStr from VBA on the array, but I don't know what's the equivalent.

I have tried Array.IndexOf(myvalue, ""), but this work's only for one dimension array.

Body:
If you're going to import a range into a data structure, I think what you want is a 2d array:

object[,] myvalues = x1range.Cells.Value;

Individual values can be extracted as follows:

object cellValue = myvalues[3, 4];

If you want to loop through all cells, a foreach is easiest:

foreach (object o in myvalues)
{
    string myText = o == null ? null : o.ToString();
}

Or, if the x/y position is important, you can loop through the X/Y as follows:

for (int i = 1; i < myvalues.GetLength(0); i++)
{
    for (int j = 1; j < myvalues.GetLength(1); i++)
    {
        object o = myvalues[i, j];
    }
}

Note that C# is 0-based, but in the Excel output you do want to use the 1-based references.

The IndexOf Function does work in C#, but not against an array like this.  If you wanted to use that, you can always cast the array to a list:

List<object> myList = myvalues.Cast<object>().ToList();
int found = myList.IndexOf("Foo");


问:
Use resources in unit tests with Swift Package Manager
I'm trying to use a resource file in unit tests and access it with Bundle.path, but it returns nil.

This call in MyProjectTests.swift returns nil:

```<code>Bundle(for: type(of: self)).path(forResource: "TestAudio", ofType: "m4a")
</code>```

Here is my project hierarchy. I also tried moving TestAudio.m4a to a Resources folder:

```<code>├── Package.swift
├── Sources
│   └── MyProject
│       ├── ...
└── Tests
    └── MyProjectTests
        ├── MyProjectTests.swift
        └── TestAudio.m4a
</code>```

Here is my package description:

```<code>// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "MyProject",
    products: [
        .library(
            name: "MyProject",
            targets: ["MyProject"])
    ],
    targets: [
        .target(
            name: "MyProject",
            dependencies: []
        ),
        .testTarget(
            name: "MyProjectTests",
            dependencies: ["MyProject"]
        ),
    ]
)
</code>```

I am using Swift 4 and the Swift Package Manager Description API version 4.

答:
I found another solution looking at this file.

It's possible to create a bundle with a path, for example:

```<code>let currentBundle = Bundle.allBundles.filter() { $0.bundlePath.hasSuffix(".xctest") }.first!
let realBundle = Bundle(path: "\(currentBundle.bundlePath)/../../../../Tests/MyProjectTests/Resources")
</code>```

It's a bit ugly, but if you want to avoid a Makefile, it works.

Body:
I'm trying to use a resource file in unit tests and access it with Bundle.path, but it returns nil.

This call in MyProjectTests.swift returns nil:

Bundle(for: type(of: self)).path(forResource: "TestAudio", ofType: "m4a")

Here is my project hierarchy. I also tried moving TestAudio.m4a to a Resources folder:

├── Package.swift
├── Sources
│   └── MyProject
│       ├── ...
└── Tests
    └── MyProjectTests
        ├── MyProjectTests.swift
        └── TestAudio.m4a

Here is my package description:

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "MyProject",
    products: [
        .library(
            name: "MyProject",
            targets: ["MyProject"])
    ],
    targets: [
        .target(
            name: "MyProject",
            dependencies: []
        ),
        .testTarget(
            name: "MyProjectTests",
            dependencies: ["MyProject"]
        ),
    ]
)

I am using Swift 4 and the Swift Package Manager Description API version 4.

Body:
I found another solution looking at this file.

It's possible to create a bundle with a path, for example:

let currentBundle = Bundle.allBundles.filter() { $0.bundlePath.hasSuffix(".xctest") }.first!
let realBundle = Bundle(path: "\(currentBundle.bundlePath)/../../../../Tests/MyProjectTests/Resources")

It's a bit ugly, but if you want to avoid a Makefile, it works.


问:
Why is subscribe handler function behaving different than onValue when preceding by first function?
I have a stream which produces many events. I only want to take the first event to activate certain stuff when that happens.

My first thought was to use stream.first().subscribe(activateStuff) to achieve that. The problem is that the activateStuff handler is getting called twice. But if I use onValue instead of subscribe, it will get called just once (as expected).

Interestingly, if I remove the first() part and I use subscribe with just one event being fired, it will behave like onValue (both of them calling activateStuff just once).

```<code>let stream1 = new Bacon.Bus();
stream1.first().onValue(() => console.log("from stream1"));
stream1.push({});
// it will print from stream1 once

let stream2 = new Bacon.Bus();
stream2.first().subscribe(() => console.log("from stream2"));
stream2.push({});
// it will print from stream2 twice. Why !?

let stream3 = new Bacon.Bus();
stream3.onValue(() => console.log("from stream3"));
stream3.push({});
// it will print from stream3 once

let stream4 = new Bacon.Bus();
stream4.subscribe(() => console.log("from stream4"));
stream4.push({});
// it will print from stream4 once
</code>```

What is wrong here using first() and then subscribe() with the same event stream?

You can play with the code here: https://fiddle.jshell.net/np0r80fn/

答: The subscribe method will call your method with Event (https://github.com/baconjs/bacon.js/#event) objects instead of just new values. You get 2 callbacks: one for the actual value wrapped in a Next event and another for the End event. If you remove the .first() part, the resulting stream will not end; that's why you get just one callback in that case.

Body:
I have a stream which produces many events. I only want to take the first event to activate certain stuff when that happens.

My first thought was to use stream.first().subscribe(activateStuff) to achieve that. The problem is that the activateStuff handler is getting called twice. But if I use onValue instead of subscribe, it will get called just once (as expected).

Interestingly, if I remove the first() part and I use subscribe with just one event being fired, it will behave like onValue (both of them calling activateStuff just once).

let stream1 = new Bacon.Bus();
stream1.first().onValue(() => console.log("from stream1"));
stream1.push({});
// it will print from stream1 once

let stream2 = new Bacon.Bus();
stream2.first().subscribe(() => console.log("from stream2"));
stream2.push({});
// it will print from stream2 twice. Why !?

let stream3 = new Bacon.Bus();
stream3.onValue(() => console.log("from stream3"));
stream3.push({});
// it will print from stream3 once

let stream4 = new Bacon.Bus();
stream4.subscribe(() => console.log("from stream4"));
stream4.push({});
// it will print from stream4 once

What is wrong here using first() and then subscribe() with the same event stream?

You can play with the code here: https://fiddle.jshell.net/np0r80fn/


问:
Docker containerization in Spring Cloud Project
I am trying to create a Spring Cloud microservice using Spring and Spring Boot. I developed a Spring Cloud Eureka server as a separate spring boot project. And also created Spring Boot project for Zuul server for gateway proxy and routing.

Now I have 3 Spring Boot project, as mentioned above. Here I am bringing Docker container into my projects. So I explored pom.xml based containerization like by using fabric tool.

So when I deploying my microservices, need to deploy all projects by containerization? So is cloud platform treating all of the microservices into separate containers?

Is there any problem in cloud by deploying my all microservices in separate containers,since they may communicate/call each other?

答:
So when I deploying my microservices, Need to deploy all projects by
  containerization? So is cloud platform treating all of the
  microservices into separate containers?

You are not forced to dockerize all you microservices. You can dockerize each microservice on its own and keep some non dockerized. However, there is no obvious benefit in doing that. If you are adopting Docker, it is better to Dockerize all
your microservices.

The Docker maven plugin configuration is better done in each project separately. I recommend using the maven plugin only to build the images and optionally push them to a registry. Then you can deploy each image separately. I would recommend
that you use Docker compose or Docker swarm for production, to deploy the different microservice containers.

Is there any problem in cloud by deploying my all microservices in separate containers,since they may communicate/call each other?

No there shouldn't be any problems. But you should be careful about hostnames that need to be used when container commmunicate. If you are using docker compose, containers can talk to each other directly by refering to the service name as a hostname. For instance, other microservices can register with Eureka by using http://eureka:8761. So make sure to set the correct application.properties to reach the other services.

ContentLicense: CC BY-SA 4.0


问:
Spring CrudRepository not working save & delete operation
In Spring, CrudRepository findAll() operation working good for fetching data from the database but with the same configuration in case of saving, update & delete it's not working.

EmployeeService.java

```<code> @Service
    public class EmployeeService {

        @Autowired
        private EmployeeRepo employeeRepoI;

        @Transactional
        public List<Employee> getAllEmployee() {
            return (List<Employee>) employeeRepoI.findAll();
        }

        @Transactional
        public Employee getEmployee(int id) {
            return (Employee) employeeRepoI.findOne(id);
        }

        @Transactional
        public Employee addEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);
        }

        @Transactional
        public Employee updateEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);

        }

        @Transactional
        public void deleteEmployee(int id) {
             employeeRepoI.delete(id);
        }

    }
</code>```

EmployeeRapo.java

```<code>@Repository
public interface EmployeeRepo<T, ID extends Serializable> extends CrudRepository<Employee, Long> {

    List<Employee> findAll();

}
</code>```

答: You have CrudRepository with Long type and deleteEmployee with primitive int. This values should match.</p>

Body:
In Spring, CrudRepository findAll() operation working good for fetching data from the database but with the same configuration in case of saving, update & delete it's not working.

EmployeeService.java

 @Service
    public class EmployeeService {

        @Autowired
        private EmployeeRepo employeeRepoI;

        @Transactional
        public List<Employee> getAllEmployee() {
            return (List<Employee>) employeeRepoI.findAll();
        }

        @Transactional
        public Employee getEmployee(int id) {
            return (Employee) employeeRepoI.findOne(id);
        }

        @Transactional
        public Employee addEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);
        }

        @Transactional
        public Employee updateEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);

        }

        @Transactional
        public void deleteEmployee(int id) {
             employeeRepoI.delete(id);
        }

    }

EmployeeRapo.java

@Repository
public interface EmployeeRepo<T, ID extends Serializable> extends CrudRepository<Employee, Long> {

    List<Employee> findAll();

}


问:
How to initialize git for a new eclipse (neon) java project
I installed a fresh copy of eclipse Neon, and created a new gradle java project in a new and shiny workspace. What is the best practice for adding git to the party?

I read that initializing git in the project directory is really a bad idea.

What is a particularly good idea then?!

Thanks!

答:
The good idea is to git init a parent folder of the project different from the main workspace folder.

This is exactly what happens if you let Egit git init your project (Right click on project -> Team -> Share Project -> Git ->...) and select an external folder as repository, say c:\users\john\my-git-repository.

You will then have two folders:

c:\users\john\my-git-repository containing the \.git folder and \<my-project> folder

c:\users\john\<eclipse-workspace> the eclipse workspace folder, which will NOT contain your project folder (remember that eclipse workspace is just a logical container for projects, they don't need to be physically there).

Another option is to create a folder inside the workspace, create the project as a subfolder of that folder and then git init that folder. This way:

c:\users\john\<eclipse-workspace>\shared-projects\<my-project>

You will create the repository in the \shared-projects folder (either by command line with git init or from whithin Eclipse with the wizard), which will contain the \.git folder, \<my-project> folder and any other project you want to share.

Remember why Eclipse suggests to keep repositories outside the workspace (https://wiki.eclipse.org/EGit/User_Guide#Creating_Repositories):

It is a good idea to keep your Repository outside of your Eclipse Workspace.

  There are several reasons for this:

  The new Repository will consider the complete folder structure of the Eclipse workspace as (potential) content. This can result in performance issues, for example when calculating the changes before committing (which will scan the complete .metadata folder, for example)

If your git repo is in the \shared-projects folder the repository will NOT consider the complete folder structure of the Eclipse workspace as (potential) content and will NOT scan the .metadata folder since it's outside the repo. The only contents of the repo will be your shared projects!


问:
What are the advantages gain by defining a template function with static and inline in a source file(cpp)?
Assume that we have define a template function in a X.cpp source file as below:

```<code>/............. X.cpp .........................../
template<class Container>
static inline void foo(const Container& container,std::string& content)
{
     /.../
}
</code>```

Do we gain any compiler/linker optimization using static and inline here?

If we have considerable amount of template functions definitions in a cpp file,will this affect to reduce build time for each translation unit?

答:
Do we gain any compiler/linker optimization using static and inline here?

Not likely. The static qualifier makes the template function have internal linkage. Meaning that the name foo will refer to it only inside the translation unit of X.cpp. If that very same definition appears in Y.cpp, it's a different template function for all intents and purposes.

The inline specifier is probably a misguided attempt to encourage the compiler into inlining the call. Since compilers do it even without the specifier, and can even ignore it if they choose to, it's pointless. The most one can say is that it clarifies intent. But YMMV on how good an idea it is.

If we have considerable amount of template functions definitions in a cpp file,will this affect to reduce build time for each translation unit?

Don't try to do the compiler/linker's work for them. Specify the linkage that makes sense. Put the definition in a header/cpp file based on the same rationale, and let your build system work.

If you artificially start making templates static and including them in different translation units, your compiler/linker is very likely going to err on the side of caution and blow up your executable size.

Body:
Assume that we have define a template function in a X.cpp source file as below:

/............. X.cpp .........................../
template<class Container>
static inline void foo(const Container& container,std::string& content)
{
     /.../
}

Do we gain any compiler/linker optimization using static and inline here?

If we have considerable amount of template functions definitions in a cpp file,will this affect to reduce build time for each translation unit?


问:
Rails: call another controller action from a controller
I need to call the create action in controller A, from controller B.

The reason is that I need to redirect differently when I'm calling from controller B.

Can it be done in Rails?

答:
Composition to the rescue!

Given the reason, rather than invoking actions across controllers one should design controllers to seperate shared and custom parts of the code. This will help to avoid both - code duplication and breaking MVC pattern.

Although that can be done in a number of ways, using concerns (composition) is a good practice.

```<code># controllers/a_controller.rb
class AController < ApplicationController
  include Createable

  private def redirect_url
    'one/url'
  end
end

# controllers/b_controller.rb
class BController < ApplicationController
  include Createable

  private def redirect_url
    'another/url'
  end
end

# controllers/concerns/createable.rb
module Createable
  def create
    do_usefull_things
    redirect_to redirect_url
  end
end
</code>```

Hope that helps.

Body:
Composition to the rescue!

Given the reason, rather than invoking actions across controllers one should design controllers to seperate shared and custom parts of the code. This will help to avoid both - code duplication and breaking MVC pattern.

Although that can be done in a number of ways, using concerns (composition) is a good practice.

# controllers/a_controller.rb
class AController < ApplicationController
  include Createable

  private def redirect_url
    'one/url'
  end
end

# controllers/b_controller.rb
class BController < ApplicationController
  include Createable

  private def redirect_url
    'another/url'
  end
end

# controllers/concerns/createable.rb
module Createable
  def create
    do_usefull_things
    redirect_to redirect_url
  end
end

Hope that helps.


问:
Grid layout align-items doesn't respect grid row dimensions
Look at this codepen:

https://codepen.io/rachelandrew/pen/WQNqKy

body {
  margin: 40px;
  font: 80% Arial, Helvetica, sans-serif;
}

.wrapper {
  display: grid;
  align-items: center;
  background: no-repeat url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/12005/grid.png);
  grid-gap: 10px;
  grid-template-columns: repeat(6, 150px);
  grid-template-rows: repeat( 4, 150px);
  background-color: #fff;
  color: #444;
}

.box {
  border: 1px solid #444;
  padding: 20px;
  font-size: 150%;
}

.a {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

.b {
  grid-column: 3 / 5;
  grid-row: 1 / 3;
}

.c {
  grid-column: 1 / 3;
  grid-row: 3 / 6;
}

.d {
  grid-column: 3 / 5;
  grid-row: 3 / 6;
}

.e {
  grid-column: 5 / 7;
  grid-row: 1 / 6;
  align-self: stretch;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="box a">
    <p>This is box A. </p>

  </div>
  <div class="box b">
    <p>This is box B.</p>

  </div>
  <div class="box c">
    <p>This is box C.</p>

  </div>
  <div class="box d">
    <p>This is box D.</p>

  </div>
  <div class="box e">
    <p>Each of the boxes on the left has a grid area of 3 columns and 3 rows (we're counting the gutter col/row). </p>
    <p>The align-items property is used to align the content inside each grid-area.</p>
    <p>Other values of align-items are:</p>
    <ul>
      <li>stretch</li>
      <li>start</li>
      <li>end</li>
      <li>center</li>
    </ul>
  </div>
</div></code>```

from

https://gridbyexample.com/examples/example24/

Element a has these rules:

```<code>.a {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}
</code>```

without align-items: center;

it takes the first two square (x,y)

as the rule states, but if I apply the rule

align-items: center to the parent

the size becomes smaller.

Can anyone explain why, please ?

答:
The HTML structure of a grid container consists of three levels:

the container

the item

the content

Each of these levels represents a separate element.

When you apply align-items: center to the container, it applies to the grid item. That is exactly what is happening in your code sample.

If you want the content of the grid item centered, then you don't target it from the primary container (2 levels up). You target it from the grid item (the parent).

You can center the text using a nested grid or even flex container.

```<code>.wrapper {
  display: grid;
  /* align-items: center; */
  grid-gap: 10px;
  grid-template-columns:  repeat(6, 150px);
  grid-template-rows: repeat( 4, 150px);
}

.box {
  display: flex;           /* new */
  align-items: center;     /* new; vertical alignment */
  justify-content: center; /* new (and optional); horizontal alignment */
}
</code>```

revised codepen

body {
  margin: 40px;
  font: 80% Arial, Helvetica, sans-serif;
}

.wrapper {
  display: grid;
  /* align-items: center; */
  background: no-repeat url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/12005/grid.png);
  grid-gap: 10px;
  grid-template-columns: repeat(6, 150px);
  grid-template-rows: repeat( 4, 150px);
  background-color: #fff;
  color: #444;
}

.box {
  border: 1px solid #444;
  padding: 20px;
  font-size: 150%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* optional */
}

.a {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

.b {
  grid-column: 3 / 5;
  grid-row: 1 / 3;
}

.c {
  grid-column: 1 / 3;
  grid-row: 3 / 6;
}

.d {
  grid-column: 3 / 5;
  grid-row: 3 / 6;
}

.e {
  grid-column: 5 / 7;
  grid-row: 1 / 6;
  align-self: stretch;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="box a">
    <p>This is box A. </p>

  </div>
  <div class="box b">
    <p>This is box B.</p>

  </div>
  <div class="box c">
    <p>This is box C.</p>

  </div>
  <div class="box d">
    <p>This is box D.</p>

  </div>
</div></code>```

More details here: Centering in CSS Grid

Body:
Look at this codepen:

https://codepen.io/rachelandrew/pen/WQNqKy

body {
  margin: 40px;
  font: 80% Arial, Helvetica, sans-serif;
}

.wrapper {
  display: grid;
  align-items: center;
  background: no-repeat url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/12005/grid.png);
  grid-gap: 10px;
  grid-template-columns: repeat(6, 150px);
  grid-template-rows: repeat( 4, 150px);
  background-color: #fff;
  color: #444;
}

.box {
  border: 1px solid #444;
  padding: 20px;
  font-size: 150%;
}

.a {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

.b {
  grid-column: 3 / 5;
  grid-row: 1 / 3;
}

.c {
  grid-column: 1 / 3;
  grid-row: 3 / 6;
}

.d {
  grid-column: 3 / 5;
  grid-row: 3 / 6;
}

.e {
  grid-column: 5 / 7;
  grid-row: 1 / 6;
  align-self: stretch;
}

This is box A.

This is box B.

This is box C.

This is box D.

Each of the boxes on the left has a grid area of 3 columns and 3 rows (we're counting the gutter col/row).

The align-items property is used to align the content inside each grid-area.

Other values of align-items are:

stretch

start

end

center

from

https://gridbyexample.com/examples/example24/

Element a has these rules:

.a {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

without align-items: center;

it takes the first two square (x,y)

as the rule states, but if I apply the rule

align-items: center to the parent

the size becomes smaller.

Can anyone explain why, please ?

Body:
The HTML structure of a grid container consists of three levels:

the container

the item

the content

Each of these levels represents a separate element.

When you apply align-items: center to the container, it applies to the grid item. That is exactly what is happening in your code sample.

If you want the content of the grid item centered, then you don't target it from the primary container (2 levels up). You target it from the grid item (the parent).

You can center the text using a nested grid or even flex container.

.wrapper {
  display: grid;
  /* align-items: center; */
  grid-gap: 10px;
  grid-template-columns:  repeat(6, 150px);
  grid-template-rows: repeat( 4, 150px);
}

.box {
  display: flex;           /* new */
  align-items: center;     /* new; vertical alignment */
  justify-content: center; /* new (and optional); horizontal alignment */
}

revised codepen

body {
  margin: 40px;
  font: 80% Arial, Helvetica, sans-serif;
}

.wrapper {
  display: grid;
  /* align-items: center; */
  background: no-repeat url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/12005/grid.png);
  grid-gap: 10px;
  grid-template-columns: repeat(6, 150px);
  grid-template-rows: repeat( 4, 150px);
  background-color: #fff;
  color: #444;
}

.box {
  border: 1px solid #444;
  padding: 20px;
  font-size: 150%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* optional */
}

.a {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

.b {
  grid-column: 3 / 5;
  grid-row: 1 / 3;
}

.c {
  grid-column: 1 / 3;
  grid-row: 3 / 6;
}

.d {
  grid-column: 3 / 5;
  grid-row: 3 / 6;
}

.e {
  grid-column: 5 / 7;
  grid-row: 1 / 6;
  align-self: stretch;
}

<div class="wrapper">
  <div class="box a">
    <p>This is box A. </p>

  </div>
  <div class="box b">
    <p>This is box B.</p>

  </div>
  <div class="box c">
    <p>This is box C.</p>

  </div>
  <div class="box d">
    <p>This is box D.</p>

  </div>
</div>

More details here: Centering in CSS Grid


问:
How connect client to server with feathers js authentication?
this is my server.js:

```<code>app.use('/users', {
    find(params) {
      return Promise.resolve(Users);
    }
  });
  app.service('authentication').hooks({
  before: {
    create: [
      auth.hooks.authenticate(['local', 'jwt'])
    ]
  }
});
app.service('users').hooks({
  before: {
    create: [
      local.hooks.hashPassword()
    ]
  }
});
/////////////////
app.post('/login', auth.express.authenticate('local', { successRedirect: '/app', failureRedirect: '/login' }));

app.get('/app', (req, res, next) => {
  res.json({ success: true });
});

app.get('/login', (req, res, next) => {
  res.json({ success: false });
});
//////////////
</code>```

please who can help me if i have an error in my code ? and what i should do in my file in frontend ? I work with reactjs.

答:
In feathersjs having default authentication(login) api something like this.

Url:    http://localhost:8080/authentication

method: Post

Body:  {"strategy": "local","email":"admin@xyz.com","password":"admin123"}

Than you will get Token which you expected.

response:

```<code>{
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyIsInR5cGUiOiJhY2Nlc3MifQ.eyJ1c2VySWQiOjEsImFjY291bnRJZCI6MSwiaWF0IjoxNTE",
    "code": 200,
    "authentication": "user login successful"
}
</code>```

After that add this token to all other api calls in Headers Authorization equal to token.

Body:
this is my server.js:

app.use('/users', {
    find(params) {
      return Promise.resolve(Users);
    }
  });
  app.service('authentication').hooks({
  before: {
    create: [
      auth.hooks.authenticate(['local', 'jwt'])
    ]
  }
});
app.service('users').hooks({
  before: {
    create: [
      local.hooks.hashPassword()
    ]
  }
});
/////////////////
app.post('/login', auth.express.authenticate('local', { successRedirect: '/app', failureRedirect: '/login' }));

app.get('/app', (req, res, next) => {
  res.json({ success: true });
});

app.get('/login', (req, res, next) => {
  res.json({ success: false });
});
//////////////

please who can help me if i have an error in my code ? and what i should do in my file in frontend ? I work with reactjs.

Body:
In feathersjs having default authentication(login) api something like this.

Url:    http://localhost:8080/authentication

method: Post

Body:  {"strategy": "local","email":"admin@xyz.com","password":"admin123"}

Than you will get Token which you expected.

response:

{
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyIsInR5cGUiOiJhY2Nlc3MifQ.eyJ1c2VySWQiOjEsImFjY291bnRJZCI6MSwiaWF0IjoxNTE",
    "code": 200,
    "authentication": "user login successful"
}

After that add this token to all other api calls in Headers Authorization equal to token.


问:
Would like to write bytes to multiple binary files
I need to write the same bytes to all files with extension TIFF in a particular folder. I am completely new to PowerShell (or any other coding for that matter). I have worked out how to change the bytes in a single file like this (simplified for this post):

```<code>$bytes  = [System.IO.File]::ReadAllBytes("C:\test.tiff")
$bytes[5] = 0x51
$bytes[8] = 0x4A
[System.IO.File]::WriteAllBytes("C:\test.tiff", $bytes)
</code>```

However, rather than specifying the file I need to loop through the files in a particular folder to check if they have the extension TIFF before writing the bytes and I am not sure how to do that. Any help would be appreciated.

答:
use a ForEach loop with Get-ChildItem

```<code>foreach ($File in (Get-ChildItem 'C:\Folder' -Filter '*.tiff')){
    $bytes  = [System.IO.File]::ReadAllBytes($File.FullName)
    $bytes[5] = 0x51 ; $bytes[8] = 0x4A
    [System.IO.File]::WriteAllBytes($File.FullName, $bytes)
}
</code>```

change C:\Folder to your folder, this will modify only .tiff files.

Body:
I need to write the same bytes to all files with extension TIFF in a particular folder. I am completely new to PowerShell (or any other coding for that matter). I have worked out how to change the bytes in a single file like this (simplified for this post):

$bytes  = [System.IO.File]::ReadAllBytes("C:\test.tiff")
$bytes[5] = 0x51
$bytes[8] = 0x4A
[System.IO.File]::WriteAllBytes("C:\test.tiff", $bytes)

However, rather than specifying the file I need to loop through the files in a particular folder to check if they have the extension TIFF before writing the bytes and I am not sure how to do that. Any help would be appreciated.

Body:
use a ForEach loop with Get-ChildItem

foreach ($File in (Get-ChildItem 'C:\Folder' -Filter '*.tiff')){
    $bytes  = [System.IO.File]::ReadAllBytes($File.FullName)
    $bytes[5] = 0x51 ; $bytes[8] = 0x4A
    [System.IO.File]::WriteAllBytes($File.FullName, $bytes)
}

change C:\Folder to your folder, this will modify only .tiff files.


问:
Access roles in oauth.getToken response vert.x keycloak
I am using the code below to 1) Login the user on keycloak, 2) Verify if the user has the specific role to access some resource.

```<code>JsonObject keycloakJson = new JsonObject()
        .put("realm", "OQM") // (1)
        .put("realm-public-key", "MIIBIwercerewrcewrc7BAij3P+Nz76opTVlhWijnIGefnBygViDrUdxS/nZSDTkXrFnKy2lpNZyecWrNVD6Zs6w65pBa60zDWODkuIqE6LbbfwHBs5RyvuzAFRtRFbieZub8x4suzN5pJOUPWdtgWqQasdawercwerewvrewrvewrcwxewrvbewvrxw9k+TPKGdf3e9QXL9FGG/9084+6Z8RSZ4JL4v5YqVtpDyohf9MPJwn/i46KcAYzgleJFFCqwuPry8CEzafqXVlzIEkSqwIDAQAB") // (2)
        .put("auth-server-url", "http://152.18.17.63:8080/auth")
        .put("ssl-required", "external")
        .put("resource", "oqm") // (3)
        .put("credentials", new JsonObject().put("secret", "2343253252-c8f1-42b2-866c-87a2a7ff95f6")); // (4)

OAuth2Auth oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.PASSWORD, keycloakJson);

JsonObject tokenConfig = new JsonObject().put("username", "dummyUser").put("password", "password").put("scope", "modify-account view-account");

oauth2.getToken(tokenConfig, res -> {
    if (res.failed()) {
        rc.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
    } else {
        AccessToken token = (AccessToken)res.result();
        token.isAuthorised("ReleaseOrders", handler -> {
            if(handler.result()) {
                HttpServerResponse response = VerticleUtils.buildOKHeaders(rc);
                response.end(Json.encodePrettily(token.principal()));
            }
            else {
                VerticleUtils.notAuthorized(rc);
            }
        });
    }
});
</code>```

However, I need to get a list of roles user is authorized for. I can see the roles in a property of the
AccessToken object returned, but since its access is private I cant access them.

答: Currently you can only get the full token from the principal() method call. For 3.5.1 we're are working on exposing the token from the AcessToken object.

Body:
I am using the code below to 1) Login the user on keycloak, 2) Verify if the user has the specific role to access some resource.

JsonObject keycloakJson = new JsonObject()
        .put("realm", "OQM") // (1)
        .put("realm-public-key", "MIIBIwercerewrcewrc7BAij3P+Nz76opTVlhWijnIGefnBygViDrUdxS/nZSDTkXrFnKy2lpNZyecWrNVD6Zs6w65pBa60zDWODkuIqE6LbbfwHBs5RyvuzAFRtRFbieZub8x4suzN5pJOUPWdtgWqQasdawercwerewvrewrvewrcwxewrvbewvrxw9k+TPKGdf3e9QXL9FGG/9084+6Z8RSZ4JL4v5YqVtpDyohf9MPJwn/i46KcAYzgleJFFCqwuPry8CEzafqXVlzIEkSqwIDAQAB") // (2)
        .put("auth-server-url", "http://152.18.17.63:8080/auth")
        .put("ssl-required", "external")
        .put("resource", "oqm") // (3)
        .put("credentials", new JsonObject().put("secret", "2343253252-c8f1-42b2-866c-87a2a7ff95f6")); // (4)

OAuth2Auth oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.PASSWORD, keycloakJson);

JsonObject tokenConfig = new JsonObject().put("username", "dummyUser").put("password", "password").put("scope", "modify-account view-account");

oauth2.getToken(tokenConfig, res -> {
    if (res.failed()) {
        rc.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
    } else {
        AccessToken token = (AccessToken)res.result();
        token.isAuthorised("ReleaseOrders", handler -> {
            if(handler.result()) {
                HttpServerResponse response = VerticleUtils.buildOKHeaders(rc);
                response.end(Json.encodePrettily(token.principal()));
            }
            else {
                VerticleUtils.notAuthorized(rc);
            }
        });
    }
});

However, I need to get a list of roles user is authorized for. I can see the roles in a property of the
AccessToken object returned, but since its access is private I cant access them.


问:
UPI Deep Link - Unable to complete the transaction

Trying to connect the UPI payment using deeplink for my Android application, but every-time it fails at the last step.

The code fragment for the UPI payment call is below:

```<code> button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            URI_URL = getUPIString("xxx@upi", "xxx xxx", "test_101", "Test Transaction", "10", "INR");

            //Creating an intent for the UPI APP
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(URI_URL));
            Intent chooser = Intent.createChooser(intent, "Pay the MSME by");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                startActivityForResult(chooser, 1, null);
            }
        }
    });
</code>```

To frame the UPI String using this function:

```<code>       private String getUPIString(String payeeAddress, String payeeName, String trxnRefId,
                            String trxnNote, String payeeAmount, String currencyCode) {
    String UPI = "upi://pay?pa=" + payeeAddress + "&pn=" + payeeName
            + "&tr=" + trxnRefId
            + "&tn=" + trxnNote + "&am=" + payeeAmount + "&cu=" + currencyCode;
    return UPI.replace(" ", "+");
}
</code>```

What could be the possible reasons of failure? Any suggestion or help is welcome.

答: The error is T04 meaning the refId should be alphanumeric with minlength 1 and maxlength 35. instead of test_101 use test101.

Body:
Trying to connect the UPI payment using deeplink for my Android application, but every-time it fails at the last step.

The code fragment for the UPI payment call is below:

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            URI_URL = getUPIString("xxx@upi", "xxx xxx", "test_101", "Test Transaction", "10", "INR");

            //Creating an intent for the UPI APP
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(URI_URL));
            Intent chooser = Intent.createChooser(intent, "Pay the MSME by");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                startActivityForResult(chooser, 1, null);
            }
        }
    });

To frame the UPI String using this function:

       private String getUPIString(String payeeAddress, String payeeName, String trxnRefId,
                            String trxnNote, String payeeAmount, String currencyCode) {
    String UPI = "upi://pay?pa=" + payeeAddress + "&pn=" + payeeName
            + "&tr=" + trxnRefId
            + "&tn=" + trxnNote + "&am=" + payeeAmount + "&cu=" + currencyCode;
    return UPI.replace(" ", "+");
}

What could be the possible reasons of failure? Any suggestion or help is welcome.


问:
JPA/Hibernate Multiple representations of the same entity
My Entities:

```<code>@Entity
public class Document  {

   @Id
   protected String id; //It string in purpose

   @OneToOne(cascade = ALL)
   @JoinColumn(name = "DOCUMENT_DETAILS")
   private DocumentDetails details;

}

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "documentDiscr")
@EqualsAndHashCode
public abstract class DocumentDetails {

   @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
   private Long id;

   private Money total;

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "SELLER_ID")
   private Company seller;

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "BUYER_ID")
   private Company buyer;
}

@Entity
public class Company {

   @Id
   protected String id;

   private String name;
   private String phoneNumber;
   private String email;

   @OneToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "address_id")
   private Address address;
}

@Entity
@EqualsAndHashCode
public class Address {

   @Id
   @GeneratedValue(strategy= GenerationType.SEQUENCE)
   private Long id;
   private String country;
   private String city;
   private String postalCode;
   private String streetName;
   private String streetNumber;
   private String apartmentNumber;
}

@Path("path")
@Transactional
public class MyResource {

   @Inject
   MyRepo myRepo;

   @PUT
   public Document updateDoc(Document document){
       myRepo.update(document);
   }

}

public class Repo<T extends MyClass> implements MyRepo<T> {

    @PersistenceContext
    protected EntityManager entityManager;

    public T create(T t) {
       t.generateId();
       this.entityManager.persist(t);
       return t;
    }

    public T update(T entity) {
       return entityManager.merge(entity);
    }

}
</code>```

When I call entityManage.update(documentEntity) and same Company is added as supplier and buyer I see
'Multiple representations of the same entity'.

I read this but nothing helps. When I removed CascadeType.All I am getting

'detached entity passed to persist: my.pckg.Address'

I also tried to remove CascadeType.Merge but error is the same.
What I can do? Where is my mistake?

UPDATE

First I changed @ManyToOne(Cascade.All) to @ManyToOne() in DocumentDetails

Second I changed @ManyToOne(Cascade.All) to @ManyToOne(Cascade.Merge) in DocumentDetails.

Third I I changed @ManyToOne(Cascade.All) to @ManyToOne(all types except all and merge) in DocumentDetails.

I also tried same with Address class

答:
This happens when you overwrite the object with same value but with
  different hashcode, If i am having employee class and employee is
  having the address
      class and if I will save the same employee with same address value but with different hashcode then I will get this issue, If I will
  clone address and set in employee then Hibernate will get confused and
  not able to save data

```<code>@Entity
@Getter
@Setter
class Person implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", unique = true, nullable = false)
    private Long id;

    @OneToMany(cascade= CascadeType.ALL)
    private Set<Address> Addresses = new HashSet<>();

    protected Person(){}
}

@Entity
@Getter
@Setter
class Address implements Serializable {
    @EmbeddedId
    private AddressId addressId;
    private State state;
    protected Address(){}
}

@Embeddable
@Getter
@Setter
public class AddressId implements Serializable {
    @Column(name = "person_id")
    private Long personId;
    @Column(name = "postcode")
    private String postcode;
}
</code>```

Solution For this

```<code>AddressId addressId = new AddressId();
addressId.setPersonId(personId);
addressId.setPostcode("4000"); //person already has an address with this postcode
Address address = null;
for (Address a : person.getAddresses()) {
    if (a.getAddressId().equals(addressId)) {
        address = a;
        break;
    }
}
if (address == null) {
    address = new Address();
    address.setAddressId(addressId);
    address.setState(State.ABC); //but I want to change the state from QLD to TAS
    person.getAddresses().add(address);
}
else {
    address.setState(State.TAS);
}
person = personRepo.save(person);
</code>```

Body:
My Entities:

@Entity
public class Document  {

   @Id
   protected String id; //It string in purpose

   @OneToOne(cascade = ALL)
   @JoinColumn(name = "DOCUMENT_DETAILS")
   private DocumentDetails details;

}

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "documentDiscr")
@EqualsAndHashCode
public abstract class DocumentDetails {

   @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
   private Long id;

   private Money total;

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "SELLER_ID")
   private Company seller;

   @ManyToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "BUYER_ID")
   private Company buyer;
}

@Entity
public class Company {

   @Id
   protected String id;

   private String name;
   private String phoneNumber;
   private String email;

   @OneToOne(cascade = CascadeType.ALL)
   @JoinColumn(name = "address_id")
   private Address address;
}

@Entity
@EqualsAndHashCode
public class Address {

   @Id
   @GeneratedValue(strategy= GenerationType.SEQUENCE)
   private Long id;
   private String country;
   private String city;
   private String postalCode;
   private String streetName;
   private String streetNumber;
   private String apartmentNumber;
}

@Path("path")
@Transactional
public class MyResource {

   @Inject
   MyRepo myRepo;

   @PUT
   public Document updateDoc(Document document){
       myRepo.update(document);
   }

}

public class Repo<T extends MyClass> implements MyRepo<T> {

    @PersistenceContext
    protected EntityManager entityManager;

    public T create(T t) {
       t.generateId();
       this.entityManager.persist(t);
       return t;
    }

    public T update(T entity) {
       return entityManager.merge(entity);
    }

}

When I call entityManage.update(documentEntity) and same Company is added as supplier and buyer I see
'Multiple representations of the same entity'.

I read this but nothing helps. When I removed CascadeType.All I am getting

'detached entity passed to persist: my.pckg.Address'

I also tried to remove CascadeType.Merge but error is the same.
What I can do? Where is my mistake?

UPDATE

First I changed @ManyToOne(Cascade.All) to @ManyToOne() in DocumentDetails

Second I changed @ManyToOne(Cascade.All) to @ManyToOne(Cascade.Merge) in DocumentDetails.

Third I I changed @ManyToOne(Cascade.All) to @ManyToOne(all types except all and merge) in DocumentDetails.

I also tried same with Address class

Body:
This happens when you overwrite the object with same value but with
  different hashcode, If i am having employee class and employee is
  having the address
      class and if I will save the same employee with same address value but with different hashcode then I will get this issue, If I will
  clone address and set in employee then Hibernate will get confused and
  not able to save data

@Entity
@Getter
@Setter
class Person implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", unique = true, nullable = false)
    private Long id;

    @OneToMany(cascade= CascadeType.ALL)
    private Set<Address> Addresses = new HashSet<>();

    protected Person(){}
}

@Entity
@Getter
@Setter
class Address implements Serializable {
    @EmbeddedId
    private AddressId addressId;
    private State state;
    protected Address(){}
}

@Embeddable
@Getter
@Setter
public class AddressId implements Serializable {
    @Column(name = "person_id")
    private Long personId;
    @Column(name = "postcode")
    private String postcode;
}

Solution For this

AddressId addressId = new AddressId();
addressId.setPersonId(personId);
addressId.setPostcode("4000"); //person already has an address with this postcode
Address address = null;
for (Address a : person.getAddresses()) {
    if (a.getAddressId().equals(addressId)) {
        address = a;
        break;
    }
}
if (address == null) {
    address = new Address();
    address.setAddressId(addressId);
    address.setState(State.ABC); //but I want to change the state from QLD to TAS
    person.getAddresses().add(address);
}
else {
    address.setState(State.TAS);
}
person = personRepo.save(person);


问:
Display a number from array in PHP
Hello I would like to have a code that displays randomly from an array a number and displays it.
For example this code

```<code><?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
</code>```

will return

```<code>Array
(
    [1] => January
    [2] => February
    [3] => March
)
</code>```

Instead of this, I would like to display on

答:
A simple function called array_rand

example:

```<code>$selection = array_rand($my_array);
</code>```

Documentation

Title: Display a number from array in PHP

Body:
Hello I would like to have a code that displays randomly from an array a number and displays it.
For example this code

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

will return

Array
(
    [1] => January
    [2] => February
    [3] => March
)

Instead of this, I would like to display on

Body:
A simple function called array_rand

example:

$selection = array_rand($my_array);

Documentation


问:
Fade the end of a label text
I have one UILabel, and i want to fade the end of the string, that is going to be out of bounds. What is the better solution for this?
Should i calculate the width of the label, compare it with the string width, and if string width is bigger than label's, i should fade last two letters? How exactly should i do that?
I hope it will be easy. Please write your solutions. Thanks!
I prefer to use this method for calculating the width:

```<code>CGRect labelRect = [text
                    boundingRectWithSize:labelSize
                    options:NSStringDrawingUsesLineFragmentOrigin
                    attributes:@{
                     NSFontAttributeName : [UIFont systemFontOfSize:14]
                    }
                    context:nil];
</code>```

答:
Swift 4.0 example:

    let gradient = CAGradientLayer()

    gradient.frame      = titleLabel.bounds
    gradient.colors     = [UIColor.white.cgColor, UIColor.clear.cgColor]
    gradient.startPoint = CGPoint(x: 0.1, y: 0.0)
    gradient.endPoint   = CGPoint(x: 0.95, y: 0.0)

    label.lineBreakMode = .byClipping
    label.layer.mask = gradient
```

result:

Title: Fade the end of a label text

Body:
I have one UILabel, and i want to fade the end of the string, that is going to be out of bounds. What is the better solution for this?
Should i calculate the width of the label, compare it with the string width, and if string width is bigger than label's, i should fade last two letters? How exactly should i do that?
I hope it will be easy. Please write your solutions. Thanks!
I prefer to use this method for calculating the width:

CGRect labelRect = [text
                    boundingRectWithSize:labelSize
                    options:NSStringDrawingUsesLineFragmentOrigin
                    attributes:@{
                     NSFontAttributeName : [UIFont systemFontOfSize:14]
                    }
                    context:nil];

Body:
Swift 4.0 example:

    let gradient = CAGradientLayer()

    gradient.frame      = titleLabel.bounds
    gradient.colors     = [UIColor.white.cgColor, UIColor.clear.cgColor]
    gradient.startPoint = CGPoint(x: 0.1, y: 0.0)
    gradient.endPoint   = CGPoint(x: 0.95, y: 0.0)

    label.lineBreakMode = .byClipping
    label.layer.mask = gradient

result:


问:
Modal jQuery doesn't work (bootstrap 4)
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

```<code><a href="#" data-href="stackoverflow.com" data-toggle="modal" data-target="#openModal">Link</a>
</code>```

Modal

```<code><div class="modal fade" id="openModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>
                    </div>
                </div>
            </div>
        </div>
</code>```

JQuery

```<code>    <script>
        $('#openModal').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
            $('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-ok').attr('href') + '</strong>');
        });
    </script>
</code>```

jQuery/Popper/JS

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.2/umd/popper.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</code>```

Error

```<code>Uncaught ReferenceError: $ is not defined
</code>```

答:
Try using shown instead of show

$('#openModal').on('shown.bs.modal', function(e) {

Title: Modal jQuery doesn't work (bootstrap 4)

Body:
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

Link

Modal

                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>

JQuery

jQuery/Popper/JS

Error

Uncaught ReferenceError: $ is not defined


问:
The "main" div around the options html element does not allow to insert them into parent component

I have 2 dropdowns as below:

```<code> <div class="row">
      <div class="col-4 offset-3 text-center">
          <select v-model="animation1">
            <option selected hidden>In Animation</option>
            <app-dropdown-options></app-dropdown-options>
          </select>
      </div>
    </div>

    <br>

    <div class="row">
      <div class="col-4 offset-3 text-center">
        <select v-model="animation2">
          <option selected hidden>Out Animation</option>
          <app-dropdown-options></app-dropdown-options>
        </select>
      </div>
    </div>
</code>```

Because i dont want to repeat myself i have create a component which has these options as below :

```<code><template>

        <div>
          <option value="animated bounce">bounce</option>
          <option value="animated wobble">wobble</option>
          <option value="animated bounceInLeft">bounceInLeft</option>
          <option value="animated bounceOutDown">bounceOutDown</option>
          <option value="animated fadeIn">fadeIn</option>
          <option value="animated fadeInLeftBig">fadeInLeftBig</option>
          <option value="animated fadeInUpBig">fadeInUpBig</option>
          <option value="animated fadeOutLeft">fadeOutLeft</option>
        </div>
    </template>
</code>```

After that,i use the child component on selects.The only problem is on child component in which the main div,around the options cause problem.
  I have try a lot to find a solution but i can't so i decided to publish my problem

答:
What you are really reusing here is the data, so rather than creating a component with options you should use a mixin and loop through the data using v-for:

```<code>// SelectData Mixin
const SelectData = {
  data() {
    return {
      options: [{
        value: 'animated bounce', text: 'bounce'
      }, {
        value: 'animated wobble', text: 'wobble'
      }, {
        value: 'animated bounceInLeft', text: 'bounceInLeft'
      }, {
        value: 'animated bounceOutDown', text: 'bounceOutDown'
      }]
    }
  }
}
</code>```

Then to use it you simply do:

```<code>new Vue({
  el: '#app',
  mixins: [SelectData],
  data: {
    selected: 'animated bounce'
  }
})
</code>```

Because a mixin is merged into your Vue instance, options is now available in your template:

```<code><select v-model="selected">
  <option v-for="option in options" :value="option.value">{{option.text}}</option>
</select>
</code>```

Here's the JSFiddle: https://jsfiddle.net/dL7zxjc8/

Of course, if you only need this data in one component, then you could simply declare the options in that Vue instance and forget about the mixin.

Body:
I have 2 dropdowns as below:

          <select v-model="animation1">
            <option selected hidden>In Animation</option>
            <app-dropdown-options></app-dropdown-options>
          </select>

        <select v-model="animation2">
          <option selected hidden>Out Animation</option>
          <app-dropdown-options></app-dropdown-options>
        </select>

Because i dont want to repeat myself i have create a component which has these options as below :

<template>

          <option value="animated bounce">bounce</option>
          <option value="animated wobble">wobble</option>
          <option value="animated bounceInLeft">bounceInLeft</option>
          <option value="animated bounceOutDown">bounceOutDown</option>
          <option value="animated fadeIn">fadeIn</option>
          <option value="animated fadeInLeftBig">fadeInLeftBig</option>
          <option value="animated fadeInUpBig">fadeInUpBig</option>
          <option value="animated fadeOutLeft">fadeOutLeft</option>

    </template>

After that,i use the child component on selects.The only problem is on child component in which the main div,around the options cause problem.
  I have try a lot to find a solution but i can't so i decided to publish my problem

Body:
What you are really reusing here is the data, so rather than creating a component with options you should use a mixin and loop through the data using v-for:

// SelectData Mixin
const SelectData = {
  data() {
    return {
      options: [{
        value: 'animated bounce', text: 'bounce'
      }, {
        value: 'animated wobble', text: 'wobble'
      }, {
        value: 'animated bounceInLeft', text: 'bounceInLeft'
      }, {
        value: 'animated bounceOutDown', text: 'bounceOutDown'
      }]
    }
  }
}

Then to use it you simply do:

new Vue({
  el: '#app',
  mixins: [SelectData],
  data: {
    selected: 'animated bounce'
  }
})

Because a mixin is merged into your Vue instance, options is now available in your template:

<select v-model="selected">
  <option v-for="option in options" :value="option.value">{{option.text}}</option>
</select>

Here's the JSFiddle: https://jsfiddle.net/dL7zxjc8/

Of course, if you only need this data in one component, then you could simply declare the options in that Vue instance and forget about the mixin.


问:
Why does adding an array to number return a string?
```<code>var array = [1,2,4];

array+1  //gives '1,2,41'.
</code>```

<p>Can anyone explain this behaviour? </p>

答:
Can anyone explain this behaviour?

This answer attempts to explain this behavior from the point of view of spec.

As per spec, during the run-time evaluation of +, both expressions (left and right) are converted to their primitive values.

Let lprim be ToPrimitive(lval).

Let rprim be ToPrimitive(rval).

toPrimitive tries to pass hint:number (since invoked during arithmetic evaluation) to OrdinaryToPrimitive

If hint is "string", then

  a. Let methodNames be «"toString", "valueOf"».

Else,

  b. Let methodNames be «"valueOf", "toString"». //this gets invoked

Since one of the values were casted to string via 4a) above, string concatenation takes place.

Hence

[1,2,4] + 1 => [1,2,4].toString() + "1" => "1,2,4" + "1" => (finally) "1,2,41"

Body:
var array = [1,2,4];

array+1  //gives '1,2,41'.

Can anyone explain this behaviour?


问:
Update a nested state array based on selected value
I am trying to update which menu item was clicked and therefore change the class accordingly. I have tried different way suggested to do it but couldn't make it work.

Heres my code:

```<code>constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            menuState: [
                {
                    menuName: 'homeMenuStatus',
                    homeMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },
                {
                    menuName: 'accountMenuStatus',
                    accountMenuStatus: 'active',
                    ulSidenavClass: "nav child_menu block-display"
                },
                {
                    menuName: 'contactMenuStatus',
                    peopleMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },

            ]
        }
    }

handleClick(menuClicked) {
        this.state.menuState.map((name, index) => {
            let thisMenu = name.menuName;

            if(name.menuName == menuClicked) {
                if(this.state.menuClicked === 'active') {
                    this.setState({
                        ...this.state,
                        menuClicked: 'inactive',
                        ulSidenavClass: 'block-display height-adjust'
                    });
                } else {
                    this.setState({
                        ...this.state,
                        menuClicked: 'active',
                        ulSidenavClass: 'block-display'
                    });
                }
            } else {
                this.setState({
                    ...this.state,
                    thisMenu: 'inactive',
                    ulSidenavClass: 'block-display height-adjust'
                });
            }
        });
    }
</code>```

HTML:

```<code>    <div>
        <ul>
            <li className={this.state.menuState[0].homeMenuStatus}>
                <a onClick={() => this.handleClick('homeMenuStatus')}>Home </a>
                <ul className={this.state.menuState[0].ulSidenavClass}>
                    <li>
                        <a href="#">Dashboard</a>
                    </li>
                    <li>
                        <a href="#">Activities</a>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</code>```

My state object is not getting changed. Must be doing something wrong in setState(). Can anyone please guide me.

答:
You must handle this in another way. The following handleClick function should solve your issue:

```<code>handleClick(menuClicked) {
  let menuStateDup = this.state.menuState.slice();
  let itemToUpdate = menuStateDup.find((element) => (
    element.menuName === menuClicked
  ));
  if ( itemToUpdate.menuClicked === 'active' ) {
    itemToUpdate.menuClicked = 'inactive';
    itemToUpdate.ulSidenavClass = 'block-display height-adjust';
  } else {
    // do vice-versa
  }
  this.setState({
    menuState: menuStateDup
  });
}
</code>```

Body:
I am trying to update which menu item was clicked and therefore change the class accordingly. I have tried different way suggested to do it but couldn't make it work.

Heres my code:

constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            menuState: [
                {
                    menuName: 'homeMenuStatus',
                    homeMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },
                {
                    menuName: 'accountMenuStatus',
                    accountMenuStatus: 'active',
                    ulSidenavClass: "nav child_menu block-display"
                },
                {
                    menuName: 'contactMenuStatus',
                    peopleMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },

            ]
        }
    }

handleClick(menuClicked) {
        this.state.menuState.map((name, index) => {
            let thisMenu = name.menuName;

            if(name.menuName == menuClicked) {
                if(this.state.menuClicked === 'active') {
                    this.setState({
                        ...this.state,
                        menuClicked: 'inactive',
                        ulSidenavClass: 'block-display height-adjust'
                    });
                } else {
                    this.setState({
                        ...this.state,
                        menuClicked: 'active',
                        ulSidenavClass: 'block-display'
                    });
                }
            } else {
                this.setState({
                    ...this.state,
                    thisMenu: 'inactive',
                    ulSidenavClass: 'block-display height-adjust'
                });
            }
        });
    }

HTML:

                 this.handleClick('homeMenuStatus')}>Home

                        Dashboard

                        Activities

My state object is not getting changed. Must be doing something wrong in setState(). Can anyone please guide me.

Body:
You must handle this in another way. The following handleClick function should solve your issue:

handleClick(menuClicked) {
  let menuStateDup = this.state.menuState.slice();
  let itemToUpdate = menuStateDup.find((element) => (
    element.menuName === menuClicked
  ));
  if ( itemToUpdate.menuClicked === 'active' ) {
    itemToUpdate.menuClicked = 'inactive';
    itemToUpdate.ulSidenavClass = 'block-display height-adjust';
  } else {
    // do vice-versa
  }
  this.setState({
    menuState: menuStateDup
  });
}


问:
How to make 0 in all column in a specific table where value is null using MSSQL
Let the table name is "MyTable"

My current data looks like:

Following, I need after a query on above table:

Actually I need to update all column where value is "NULL", in a single query.

答:
UPDATE Table SET ColumnName1=0 WHERE ColumnName1 IS NULL

...


问:
How could you retrieve a method's POD from inside a REPL or debugger?
I would like to be able to see the documentation of a method/function when using it inside REPL or debuger.

Is there any module that allow you to see the documentation of a function when using REPL or  a debuger?.

Obviously if that module exist it would ask you to have your POD and code with a parseable structure in order to extract the docs. That is not a problem because I have all my code documented and I can adapt to whatever is needed. Currently I have all my methods with a preceding POD with a =head2 method_name and the typical lines for name, usage, example, args, return, exeptions etc

The typical example is when you are in the debuger (or REPL) and you want to use a function and you don't remember the order of arguments or their types, or the type of the return element or you want a hint for the usage.

I would like to have something like get_pod($moudle_bar, $method_foo), or even better being able to put a get_pod in a base module and being able to say $bar->get_pod('foo'). I know that this is not trivial and has a lot of corner cases. This is the reason that I am asking about a method-POD extractor module.

I want to show the output inside the REPL or debuger so any pointer to an anchored html-pod in a browser is not convenient for me.

It could be that there is something much more simple and I am obfuscated.

My first brute force and expensive approach:

```<code>> $self = new MyModule
> m $self # to see the available methods for double check the spelling
> # method wanted '_connect_db'
> $cmd = 'perldoc -t ' . ref($self)
> x qx{$cmd}=~/(_connect_db.*?)\n\n/msg
</code>```

```
0  '_connect_db
     Title   : _connect_db
     Usage   :
     Function: create a database conection and return the handler
     Example : $dbh = $self->_connect_db($user, $pass, $db_name) # host is FPrefect by default
     Returns : [0] DBI $dbh object
     Args    :
                [0] $user,
                [1] $pass,
                [2] $db_name,
                [3] $host,
                [4] $db_brand # mysql, sqlite
                [5] $mode = (ro, rw) # not used now. in the future it would use this for read the user and password'
```

Obviously this works because I know that I don't have any empty lines in my method description PODs so I use .*?)\n\n in the regex to capture the rest of the method POD.

Do someone have any good suggestion or advice for this task?

UPDATE:

Following snoopy suggestions I have taken a look at Pod::Coverage source code and I found that Pod::Coverage::Extractor (a package inside the file for Pod::Coverage) has the method command that look for Pods  Item or head elements and extract them. I will take a look how to retrieve this items.

```<code># package Pod::Coverage::Extractor
#extract subnames from a pod stream
sub command {
    my $self = shift;
    my ( $command, $text, $line_num ) = @_;
    if ( $command eq 'item' || $command =~ /^head(?:2|3|4)/ ) {

        # take a closer look
        my @pods = ( $text =~ /\s*([^\s\|,\/]+)/g );
        $self->{recent} = [];

        foreach my $pod (@pods) {
            print "Considering: '$pod'\n" if debug;

            # it's dressed up like a method cal
            $pod =~ /-E<\s*gt\s*>(.*)/ and $pod = $1;
            $pod =~ /->(.*)/           and $pod = $1;

            # it's used as a (bare) fully qualified name
            $pod =~ /\w+(?:::\w+)*::(\w+)/ and $pod = $1;

            # it's wrapped in a pod style B<>
            $pod =~ s/[A-Z]<//g;
            $pod =~ s/>//g;

            # has arguments, or a semicolon
            $pod =~ /(\w+)\s*[;\(]/ and $pod = $1;

            print "Adding: '$pod'\n" if debug;
            push @{ $self->{ $self->{nonwhitespace}
                    ? "recent"
                    : "identifiers" } }, $pod;
        }
    }
</code>```

UPDATE 2

Another place from where to take info is pdoc. This script generates html for browsing APIs and I use it in Ensembl and BioPerl. I am sure I will learn something reading the source code.

答:
I also could find any single CPAN module that does exactly want you want.

I wonder if you could somehow combine Pod::Coverage and Pod::Select.

Pod::Coverage lets you get at the symbols as below:

```<code>snoopy@deb6:~$ perl -de0
DB<1> use Pod::Coverage
DB<2> our $pc = Pod::Coverage->new(package => 'Mouse');
DB<3> $pc->coverage;
DB<4> use Data::Dumper
DB<5> p Dumper $pc->{symbols}
$VAR1 = {
  'around' => 1,
  'init_meta' => 0,
  'super' => 0,
  'has' => 1,
  'after' => 1,
  'augment' => 0,
  'inner' => 0,
  'override' => 0,
  'with' => 0,
  'extends' => 1,
  'before' => 1
};
</code>```

Maybe Pod::Select (or Similar) could then be used to extract the relevant sections?

EDIT or maybe subclass/modify Pod::Coverage to gather body text along with the symbols.

Body:
I would like to be able to see the documentation of a method/function when using it inside REPL or debuger.

Is there any module that allow you to see the documentation of a function when using REPL or  a debuger?.

Obviously if that module exist it would ask you to have your POD and code with a parseable structure in order to extract the docs. That is not a problem because I have all my code documented and I can adapt to whatever is needed. Currently I have all my methods with a preceding POD with a =head2 method_name and the typical lines for name, usage, example, args, return, exeptions etc

The typical example is when you are in the debuger (or REPL) and you want to use a function and you don't remember the order of arguments or their types, or the type of the return element or you want a hint for the usage.

I would like to have something like get_pod($moudle_bar, $method_foo), or even better being able to put a get_pod in a base module and being able to say $bar->get_pod('foo'). I know that this is not trivial and has a lot of corner cases. This is the reason that I am asking about a method-POD extractor module.

I want to show the output inside the REPL or debuger so any pointer to an anchored html-pod in a browser is not convenient for me.

It could be that there is something much more simple and I am obfuscated.

My first brute force and expensive approach:

> $self = new MyModule
> m $self # to see the available methods for double check the spelling
> # method wanted '_connect_db'
> $cmd = 'perldoc -t ' . ref($self)
> x qx{$cmd}=~/(_connect_db.*?)\n\n/msg

0  '_connect_db
     Title   : _connect_db
     Usage   :
     Function: create a database conection and return the handler
     Example : $dbh = $self->_connect_db($user, $pass, $db_name) # host is FPrefect by default
     Returns : [0] DBI $dbh object
     Args    :
                [0] $user,
                [1] $pass,
                [2] $db_name,
                [3] $host,
                [4] $db_brand # mysql, sqlite
                [5] $mode = (ro, rw) # not used now. in the future it would use this for read the user and password'

Obviously this works because I know that I don't have any empty lines in my method description PODs so I use .*?)\n\n in the regex to capture the rest of the method POD.

Do someone have any good suggestion or advice for this task?

UPDATE:

Following snoopy suggestions I have taken a look at Pod::Coverage source code and I found that Pod::Coverage::Extractor (a package inside the file for Pod::Coverage) has the method command that look for Pods  Item or head elements and extract them. I will take a look how to retrieve this items.

# package Pod::Coverage::Extractor
#extract subnames from a pod stream
sub command {
    my $self = shift;
    my ( $command, $text, $line_num ) = @_;
    if ( $command eq 'item' || $command =~ /^head(?:2|3|4)/ ) {

        # take a closer look
        my @pods = ( $text =~ /\s*([^\s\|,\/]+)/g );
        $self->{recent} = [];

        foreach my $pod (@pods) {
            print "Considering: '$pod'\n" if debug;

            # it's dressed up like a method cal
            $pod =~ /-E<\s*gt\s*>(.*)/ and $pod = $1;
            $pod =~ /->(.*)/           and $pod = $1;

            # it's used as a (bare) fully qualified name
            $pod =~ /\w+(?:::\w+)*::(\w+)/ and $pod = $1;

            # it's wrapped in a pod style B<>
            $pod =~ s/[A-Z]<//g;
            $pod =~ s/>//g;

            # has arguments, or a semicolon
            $pod =~ /(\w+)\s*[;\(]/ and $pod = $1;

            print "Adding: '$pod'\n" if debug;
            push @{ $self->{ $self->{nonwhitespace}
                    ? "recent"
                    : "identifiers" } }, $pod;
        }
    }

UPDATE 2

Another place from where to take info is pdoc. This script generates html for browsing APIs and I use it in Ensembl and BioPerl. I am sure I will learn something reading the source code.

Body:
I also could find any single CPAN module that does exactly want you want.

I wonder if you could somehow combine Pod::Coverage and Pod::Select.

Pod::Coverage lets you get at the symbols as below:

snoopy@deb6:~$ perl -de0
DB<1> use Pod::Coverage
DB<2> our $pc = Pod::Coverage->new(package => 'Mouse');
DB<3> $pc->coverage;
DB<4> use Data::Dumper
DB<5> p Dumper $pc->{symbols}
$VAR1 = {
  'around' => 1,
  'init_meta' => 0,
  'super' => 0,
  'has' => 1,
  'after' => 1,
  'augment' => 0,
  'inner' => 0,
  'override' => 0,
  'with' => 0,
  'extends' => 1,
  'before' => 1
};

Maybe Pod::Select (or Similar) could then be used to extract the relevant sections?

EDIT or maybe subclass/modify Pod::Coverage to gather body text along with the symbols.


问:
Real-time display of variable changes
Now,i used code :

```<code>UINT postThread(LPVOID pParam)
{
    CGA_SpikeDlg*p = (CGA_SpikeDlg*)pParam;
    p->RunTimer();
    return 0;
}
void CGA_SpikeDlg::threadNew()
{
    AfxBeginThread(postThread, this);
}

void CGA_SpikeDlg::RunTimer()
{
    SetTimer(1, 6000, NULL);
}

void task1(M_args Parameter_, double Mtime, double tempVB, double TimeStep, double m_I, int FlagParameter[], M_args_Bound Parameter_Bound[], int MaxGeneration, float gL, float C, const int POPULATION_SIZE, float crossver, float mutations, stringstream &strResult)
{
    solveGPU_cpp(Parameter_, Mtime, tempVB, TimeStep, m_I, FlagParameter, Parameter_Bound, MaxGeneration, gL, C, POPULATION_SIZE, crossver, mutations, strResult);
    //cout << "task1 says: " << endl;
}
void CGA_SpikeDlg::OnTimer(UINT_PTR nIDEvent)
{
    // TODO:  在此添加消息处理程序代码和/或调用默认值
    switch (nIDEvent)
    {
        case 1:   //定时器1处理函数，定时发送数据进行更新
        {

            CString cstr((strResult.str()).c_str());
            //str.Format("%f", duration);
            m_result.SetWindowText(cstr);
            UpdateData(false);
            break;
        }
    }
    CDialogEx::OnTimer(nIDEvent);
}
void CGA_SpikeDlg::OnBnClickedButtonRun()
{
    // TODO:  在此添加控件通知处理程序代码
    UpdateData(true);
    threadNew();
    thread t1(task1, Parameter_, Mtime, tempVB, TimeStep, m_I, FlagParameter, Parameter_Bound, MaxGeneration, gL, C, POPULATION_SIZE, crossver, mutations, std::ref(strResult));
    t1.join();
}
</code>```

I want to show the value of strResult on my EDIT. I want to see how it change when i run.But when i run,The window displays no response,After a period of time, it shows the final result,That's not what I want.

答:
The thread is local variable and joining it cause the main thread to block and wait the helper thread t1 to finish.

Make the thread a pointer or shared_ptr, make it member if your dialog class make sure you join it in the destructor at least.

Like:

```<code>mThread = std::make_shared<std::thread>(task1, Parameter_, Mtime, tempVB, TimeStep, m_I, FlagParameter, Parameter_Bound, MaxGeneration, gL, C, POPULATION_SIZE, crossver, mutations, std::ref(strResult));
</code>```

And ... you don't need a thread for the window timers.

UPDATE:
Make the tread a member of the dialog:

```<code>std::stared_ptr<std::thread> mThread;
</code>```

Pack all parameters in a struct or class:

```<code>struct Args
{
   M_args Parameter_;
   double Mtime;
   double tempVB;
   double TimeStep;
   double m_I;
   std::vector<int> FlagParameter;
   std::vector<M_args_Bound> Parameter_Bound;
   int MaxGeneration;
   float gL;
   float C;
   int POPULATION_SIZE;
   float crossver;
   float mutations;
};
</code>```

Copy all data in the struct and pass it to the thread together with a reference to the strResult:

```<code>mThread = std::make_shared<std::thread>(Args, std::ref(strResult));
</code>```

join in the destructor. Make sure you do no start the thread twice etc..

Title: Real-time display of variable changes

Body:
Now,i used code :

UINT postThread(LPVOID pParam)
{
    CGA_SpikeDlg*p = (CGA_SpikeDlg*)pParam;
    p->RunTimer();
    return 0;
}
void CGA_SpikeDlg::threadNew()
{
    AfxBeginThread(postThread, this);
}

void CGA_SpikeDlg::RunTimer()
{
    SetTimer(1, 6000, NULL);
}

void task1(M_args Parameter_, double Mtime, double tempVB, double TimeStep, double m_I, int FlagParameter[], M_args_Bound Parameter_Bound[], int MaxGeneration, float gL, float C, const int POPULATION_SIZE, float crossver, float mutations, stringstream &strResult)
{
    solveGPU_cpp(Parameter_, Mtime, tempVB, TimeStep, m_I, FlagParameter, Parameter_Bound, MaxGeneration, gL, C, POPULATION_SIZE, crossver, mutations, strResult);
    //cout << "task1 says: " << endl;
}
void CGA_SpikeDlg::OnTimer(UINT_PTR nIDEvent)
{
    // TODO:  在此添加消息处理程序代码和/或调用默认值
    switch (nIDEvent)
    {
        case 1:   //定时器1处理函数，定时发送数据进行更新
        {

            CString cstr((strResult.str()).c_str());
            //str.Format("%f", duration);
            m_result.SetWindowText(cstr);
            UpdateData(false);
            break;
        }
    }
    CDialogEx::OnTimer(nIDEvent);
}
void CGA_SpikeDlg::OnBnClickedButtonRun()
{
    // TODO:  在此添加控件通知处理程序代码
    UpdateData(true);
    threadNew();
    thread t1(task1, Parameter_, Mtime, tempVB, TimeStep, m_I, FlagParameter, Parameter_Bound, MaxGeneration, gL, C, POPULATION_SIZE, crossver, mutations, std::ref(strResult));
    t1.join();
}

I want to show the value of strResult on my EDIT. I want to see how it change when i run.But when i run,The window displays no response,After a period of time, it shows the final result,That's not what I want.

Body:
The thread is local variable and joining it cause the main thread to block and wait the helper thread t1 to finish.

Make the thread a pointer or shared_ptr, make it member if your dialog class make sure you join it in the destructor at least.

Like:

mThread = std::make_shared<std::thread>(task1, Parameter_, Mtime, tempVB, TimeStep, m_I, FlagParameter, Parameter_Bound, MaxGeneration, gL, C, POPULATION_SIZE, crossver, mutations, std::ref(strResult));

And ... you don't need a thread for the window timers.

UPDATE:
Make the tread a member of the dialog:

std::stared_ptr<std::thread> mThread;

Pack all parameters in a struct or class:

struct Args
{
   M_args Parameter_;
   double Mtime;
   double tempVB;
   double TimeStep;
   double m_I;
   std::vector<int> FlagParameter;
   std::vector<M_args_Bound> Parameter_Bound;
   int MaxGeneration;
   float gL;
   float C;
   int POPULATION_SIZE;
   float crossver;
   float mutations;
};

Copy all data in the struct and pass it to the thread together with a reference to the strResult:

mThread = std::make_shared<std::thread>(Args, std::ref(strResult));

join in the destructor. Make sure you do no start the thread twice etc..


问:
Are there security risks to whitelisting all the column names in a model with strong params?
I'm in the process of extracting some parts of a project into an engine and I wanted to whitelist user params in such a way that the user doesn't have to configure anything.

This is what I ultimately came up with:

```<code>def user_params
  params.permit(::User.columns.map(&:name), :current_password, :password, :password_confirmation)
end
</code>```

It works so far (it allows all attributes in the user model and seems to reject anything else), however, I can't find another implementation of this in my searching that does it the same way and I'm wondering if that's because there's something I'm not seeing.

Is there a security vulnerability with setting strong params up like this?

答:
Is there a security vulnerability with setting strong params up like this?

Yes, there is. This defeats the purpose of whitelisting, which is to allow some fields, but not the others. Malicious clients will be able to write any of your fields, including, say, roles or is_admin.

If you don't have any restricted fields, you may skip strong params entirely and just use params[:user] (or params if your attributes are at the top level as shown in the question). The end result will be the same, but at least you won't have any illusions of security.

Body:
I'm in the process of extracting some parts of a project into an engine and I wanted to whitelist user params in such a way that the user doesn't have to configure anything.

This is what I ultimately came up with:

def user_params
  params.permit(::User.columns.map(&:name), :current_password, :password, :password_confirmation)
end

It works so far (it allows all attributes in the user model and seems to reject anything else), however, I can't find another implementation of this in my searching that does it the same way and I'm wondering if that's because there's something I'm not seeing.

Is there a security vulnerability with setting strong params up like this?


问:
Angular cli mathjax
Angular 4.0 npm install mathjax for node_module, add "scripts": ["./node_modules/mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"],  to angular-cli.json and addtypes": ["mathjax"],` to tsconfig.app.json

but error say "MathZoom.js and MathMenu.js not found".
How to deal with this problem......
thanks!!!!!!

答:
To add MathJax into Angular 4 application, simply add the below lines in index.html and do the following steps.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>
<!-- MathJax Implementation -->
  <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
         showProcessingMessages: false,
         tex2jax: { inlineMath: [['$','$'],['\\(','\\)']] }
        });
    </script>
</code>```

HTML code where you want to render the formula

```<code><div class="mathjax" >{{Formula}}</div>
</code>```

TS file where you want to apply mathjax

```<code>let mathjax=document.getElementsByClassName('mathjax');
       eval('MathJax.Hub.Queue(["Typeset",MathJax.Hub, mathjax])');
      eval('MathJax.Hub.Queue(["Typeset",MathJax.Hub, mathjax])');
</code>```

Title: Angular cli mathjax

Body:
To add MathJax into Angular 4 application, simply add the below lines in index.html and do the following steps.

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>
<!-- MathJax Implementation -->
  <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
         showProcessingMessages: false,
         tex2jax: { inlineMath: [['$','$'],['\\(','\\)']] }
        });
    </script>

HTML code where you want to render the formula

<div class="mathjax" >{{Formula}}</div>

TS file where you want to apply mathjax

let mathjax=document.getElementsByClassName('mathjax');
       eval('MathJax.Hub.Queue(["Typeset",MathJax.Hub, mathjax])');
      eval('MathJax.Hub.Queue(["Typeset",MathJax.Hub, mathjax])');


问:
How to get the value of the href attribute?
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

```<code><a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
</code>```

That is, to get the value of the href attribute if the link has a particular text.

答:
I'd use an opensource class like simple_html_dom.php</p>

```<code>$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
    echo $oElement->href
}
</code>```

Body:
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

a wrong one
the right one
a wrong one

That is, to get the value of the href attribute if the link has a particular text.

Body:
I'd use an opensource class like simple_html_dom.php

$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
    echo $oElement->href
}


问:
How can I wrap each 3 columns with a row using bootstrap/wordpress?
I would like to wrap each 3 column with a row using this loop.
I know that I have to use a counter but I don't know where I have to open/close the rows.

Here is my code:

```<code><div id="blog" class="sezione">
<section id="content" class="container">
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
     if (!is_paged() && $wp_query->current_post === 0 ) { ?>
        <div class="col-md-7 col-sm-12">
            ...
        </div>
    <?php
    } elseif (!is_paged() &&  $wp_query->current_post >= 1 && $wp_query->current_post <= 2 ) { ?>
        <div class="col-md-5 col-sm-6">
            ...
        </div>
    <?php
    } elseif (!is_paged() &&  $wp_query->current_post >= 3 ) { ?>
        <div class="col-md-4 col-sm-6">
            ...
        </div>
    <?php
    } elseif ( is_paged() ) { ?>
        <div class="col-md-4 col-sm-6">
            ...
        </div>
    <?php }
    endwhile;
        // Restore original post data.
        wp_reset_postdata();
    endif; ?>
    <div>
        <?php posts_nav_link('|', '...'); ?>
    </div>
</section>
</div><!-- /sezione -->
</code>```

答:
```<code><?php
//set up counter
$count = 1;
?>

<div id="blog" class="sezione">
<section id="content" class="container">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();

// if count is equal to 1 start a row
if ($count === 1){
    echo '<div class="row">';
}

if (!is_paged() && $wp_query->current_post === 0 ) { ?>
    <div class="col-md-7 col-sm-12">
        ...
    </div>
<?php
} elseif (!is_paged() &&  $wp_query->current_post >= 1 && $wp_query->current_post <= 2 ) { ?>
    <div class="col-md-5 col-sm-6">
        ...
    </div>
<?php
} elseif (!is_paged() &&  $wp_query->current_post >= 3 ) { ?>
    <div class="col-md-4 col-sm-6">
        ...
    </div>
<?php
} elseif ( is_paged() ) { ?>
    <div class="col-md-4 col-sm-6">
        ...
    </div>
<?php }

    // if count is equal 3 close row and reset $count
    // or else increment
    if ($count === 3){
        echo '</div>';
        $count = 1;
    }else{
        //increment counter
        $count++;
    }

endwhile;
    // Restore original post data.
    wp_reset_postdata();

endif; ?>
<div>
    <?php posts_nav_link('|', '...'); ?>
</div>
</code>```

<p>
</p>

Body:
I would like to wrap each 3 column with a row using this loop.
I know that I have to use a counter but I don't know where I have to open/close the rows.

Here is my code:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
     if (!is_paged() && $wp_query->current_post === 0 ) { ?>

            ...

    <?php
    } elseif (!is_paged() &&  $wp_query->current_post >= 1 && $wp_query->current_post <= 2 ) { ?>

            ...

    <?php
    } elseif (!is_paged() &&  $wp_query->current_post >= 3 ) { ?>

            ...

    <?php
    } elseif ( is_paged() ) { ?>

            ...

    <?php }
    endwhile;
        // Restore original post data.
        wp_reset_postdata();
    endif; ?>

        <?php posts_nav_link('|', '...'); ?>