问:
View design not showing in ViewController
I'm trying to create a UIView and set it as a ViewController's view.
I did set it up but it won't show properly. for example, I chose a backgroundColor for the view, which is not showing. I added two buttons and they do show, but not as expected.
This is my UIView code:

```<code>import UIKit

public final class LoginView: UIView {
public override init(frame: CGRect) {
    super.init(frame: frame)
    self.addSubview(stackView)
    self.backgroundColor = UIColor.appColors.white

    NSLayoutConstraint.activate([
        stackView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        stackView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
    ])
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

public let login: UIButton = {
    let button = UIButton(type: .system)
    button.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 17.0)
    button.setTitle("Login", for: .normal)
    button.setTitleColor(UIColor.appColors.white, for: .normal)
    button.backgroundColor = UIColor.appColors.green
    button.contentHorizontalAlignment = .center
    button.layer.cornerRadius = 10
    button.layer.shadowColor = UIColor(white: 0, alpha: 0.25).cgColor
    button.layer.shadowOffset = CGSize(width: 0, height: 2)
    button.layer.shadowOpacity = 1
    button.layer.shadowRadius = 0
    button.layer.masksToBounds = false
    button.clipsToBounds = true

    return button
}()

public let signup: UIButton = {
    let button = UIButton(type: .system)
    button.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 17.0)
    button.setTitle("Signup", for: .normal)
    button.setTitleColor(UIColor.appColors.white, for: .normal)
    button.backgroundColor = UIColor.appColors.red
    button.contentHorizontalAlignment = .center
    button.layer.cornerRadius = 10
    button.layer.shadowColor = UIColor(white: 0, alpha: 0.25).cgColor
    button.layer.shadowOffset = CGSize(width: 0, height: 2)
    button.layer.shadowOpacity = 1
    button.layer.shadowRadius = 0
    button.layer.masksToBounds = false
    button.clipsToBounds = true

    return button
}()

private lazy var stackView: UIStackView = {
    let stackView = UIStackView(arrangedSubviews: [self.login, self.signup])
    stackView.axis = .vertical
    stackView.distribution = .fillEqually
    stackView.alignment = .fill
    stackView.spacing = 10.0
    stackView.translatesAutoresizingMaskIntoConstraints = false

    return stackView
}()
}
</code>```

This is my ViewController:

```<code>import UIKit

class loginVC: UIViewController {
override func loadView() {
    super.loadView()
    self.view = LoginVC()
}
override func viewDidLoad() {
    super.viewDidLoad()
}

}
</code>```

As you can see, I did set up everything, and I did changed the look of the buttons and chose a backgorund color, but it just won't show on the ViewController.
I want to seperate the View and the ViewController because I really need flexability with this app, but it just won't work.
Any ideas?

答:
In loadView(), it must be LoginView() instead of loginVC(), i.e

```<code>class loginVC: UIViewController {
    override func loadView() {
        super.loadView()
        self.view = LoginView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
</code>```

Edit:

Try replacing UIColor.appColors with just UIColor and see if it giving the expected result. This is the only thing I changed in your code to get that working perfectly.

Body:
I'm trying to create a UIView and set it as a ViewController's view.
I did set it up but it won't show properly. for example, I chose a backgroundColor for the view, which is not showing. I added two buttons and they do show, but not as expected.
This is my UIView code:

import UIKit

public final class LoginView: UIView {
public override init(frame: CGRect) {
    super.init(frame: frame)
    self.addSubview(stackView)
    self.backgroundColor = UIColor.appColors.white

    NSLayoutConstraint.activate([
        stackView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        stackView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
    ])
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

public let login: UIButton = {
    let button = UIButton(type: .system)
    button.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 17.0)
    button.setTitle("Login", for: .normal)
    button.setTitleColor(UIColor.appColors.white, for: .normal)
    button.backgroundColor = UIColor.appColors.green
    button.contentHorizontalAlignment = .center
    button.layer.cornerRadius = 10
    button.layer.shadowColor = UIColor(white: 0, alpha: 0.25).cgColor
    button.layer.shadowOffset = CGSize(width: 0, height: 2)
    button.layer.shadowOpacity = 1
    button.layer.shadowRadius = 0
    button.layer.masksToBounds = false
    button.clipsToBounds = true

    return button
}()

public let signup: UIButton = {
    let button = UIButton(type: .system)
    button.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 17.0)
    button.setTitle("Signup", for: .normal)
    button.setTitleColor(UIColor.appColors.white, for: .normal)
    button.backgroundColor = UIColor.appColors.red
    button.contentHorizontalAlignment = .center
    button.layer.cornerRadius = 10
    button.layer.shadowColor = UIColor(white: 0, alpha: 0.25).cgColor
    button.layer.shadowOffset = CGSize(width: 0, height: 2)
    button.layer.shadowOpacity = 1
    button.layer.shadowRadius = 0
    button.layer.masksToBounds = false
    button.clipsToBounds = true

    return button
}()

private lazy var stackView: UIStackView = {
    let stackView = UIStackView(arrangedSubviews: [self.login, self.signup])
    stackView.axis = .vertical
    stackView.distribution = .fillEqually
    stackView.alignment = .fill
    stackView.spacing = 10.0
    stackView.translatesAutoresizingMaskIntoConstraints = false

    return stackView
}()
}

This is my ViewController:

import UIKit

class loginVC: UIViewController {
override func loadView() {
    super.loadView()
    self.view = LoginVC()
}
override func viewDidLoad() {
    super.viewDidLoad()
}

}

As you can see, I did set up everything, and I did changed the look of the buttons and chose a backgorund color, but it just won't show on the ViewController.
I want to seperate the View and the ViewController because I really need flexability with this app, but it just won't work.
Any ideas?

Body:
In loadView(), it must be LoginView() instead of loginVC(), i.e

class loginVC: UIViewController {
    override func loadView() {
        super.loadView()
        self.view = LoginView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Edit:

Try replacing UIColor.appColors with just UIColor and see if it giving the expected result. This is the only thing I changed in your code to get that working perfectly.


来源: stackexchange

问:
Gamekit and iPhone
I have my app set up to send a custom level in a form of a array to another person during a p2p connection. The receiving device saves the array to file for later use. I set up gamekit in my application, it will successfully search and connect to another device without any problems. Though a problem arises when I send data to a device, the receiving device will receive the data (and save the custom level like it should) but it will immediately crash afterwords.

Here are my methods that I use to send and receive data.

```<code>-(void) sendDataToPeers:(NSData *) data
{
    if (currentSession)
    {
        //send the data
        [self.currentSession sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil];

        //Alerting the user that the custom level has been sent.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sent!" message:@"Your custom level has been sent." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

-(void) btnSend
{
    //Data that will be sent
    NSMutableData *theData = [NSMutableData data];

    //Archiver
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];

    //Desired level to send
    int theLevel =[[CTManager sharedInstance]getLevel];

    //Path to the custom levels
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *customLevelsSen = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"customLevels"]];

    //Custom levels array
    NSArray *theLevels = [[NSArray alloc] initWithContentsOfFile: customLevelsSen];

    //Gets the desired level array from array of custom levels
    NSArray *myArray = [[NSArray alloc]initWithArray:[theLevels objectAtIndex:theLevel-51]];

    //prepare data
    [archiver encodeObject:myArray forKey:@"level"];
    [archiver finishEncoding];

    //send the data
    [self sendDataToPeers:theData];

    //cleanup
    [archiver release];
    [theLevels release];
    [myArray release];

}

-(void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context
{
    //Archiver
    NSKeyedUnarchiver *archiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    //Gets the custom level in form of an array from data.
    NSArray *level = [archiver decodeObjectForKey:@"level"];
    [archiver finishDecoding];
    [archiver release];

    //Path to the array of custom levels
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *customLevelsRec = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"customLevels"]];

    //Gets the array of custom levels
    NSMutableArray *customLevelArray = [[NSMutableArray alloc] initWithContentsOfFile:customLevelsRec];

    //Adds a new array to the array of custom levels
    [customLevelArray addObject:level];

    //Saves the array.
    [customLevelArray writeToFile:customLevelsRec atomically:YES];

    //cleanup
    [customLevelArray release];

    //Message saying a custom level has been recieved
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Received!" message:@"A custom level has been saved." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [alert show];
    [alert release];

}
</code>```

Testing this has been a pain since I don't have two devices of my own currently, so I send a beta build to my friend who inturns tests them (he has ipod and iphone). Any help with this is appreciated...

If I can't find the problem I will most likely send the entire xcode project to him and via screen share work with the project on his computer to efficiently build and test the application. And I will be able to use debug mode.

答:
I don't know if you ever found an answer to this question or not, I hope you did. But if you didn't I highly recommend that you try the new features of the new SDK. Instead of going through the whole encode/decode process, they have made it simple by having you do the following (in your send methodology):

data = [NSKeyedArchiver archivedDataWithRootObject:anObject];

where anObject can be pretty much any object, array, dictionary, whatever...

In your receive methodology:

```<code>NSObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
</code>```

where object can also be pretty much any object.

As far as the crash you are experiencing, have you verified on which line the crash occurs? Are you sure it happens in the code you posted? Or is it happening somewhere else?

ContentLicense: CC BY-SA 3.0

Title: Gamekit and iPhone

Body:
I have my app set up to send a custom level in a form of a array to another person during a p2p connection. The receiving device saves the array to file for later use. I set up gamekit in my application, it will successfully search and connect to another device without any problems. Though a problem arises when I send data to a device, the receiving device will receive the data (and save the custom level like it should) but it will immediately crash afterwords.

Here are my methods that I use to send and receive data.

-(void) sendDataToPeers:(NSData *) data
{
    if (currentSession)
    {
        //send the data
        [self.currentSession sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil];

        //Alerting the user that the custom level has been sent.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sent!" message:@"Your custom level has been sent." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

-(void) btnSend
{
    //Data that will be sent
    NSMutableData *theData = [NSMutableData data];

    //Archiver
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];

    //Desired level to send
    int theLevel =[[CTManager sharedInstance]getLevel];

    //Path to the custom levels
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *customLevelsSen = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"customLevels"]];

    //Custom levels array
    NSArray *theLevels = [[NSArray alloc] initWithContentsOfFile: customLevelsSen];

    //Gets the desired level array from array of custom levels
    NSArray *myArray = [[NSArray alloc]initWithArray:[theLevels objectAtIndex:theLevel-51]];

    //prepare data
    [archiver encodeObject:myArray forKey:@"level"];
    [archiver finishEncoding];

    //send the data
    [self sendDataToPeers:theData];

    //cleanup
    [archiver release];
    [theLevels release];
    [myArray release];

}

-(void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context
{
    //Archiver
    NSKeyedUnarchiver *archiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    //Gets the custom level in form of an array from data.
    NSArray *level = [archiver decodeObjectForKey:@"level"];
    [archiver finishDecoding];
    [archiver release];

    //Path to the array of custom levels
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *customLevelsRec = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"customLevels"]];

    //Gets the array of custom levels
    NSMutableArray *customLevelArray = [[NSMutableArray alloc] initWithContentsOfFile:customLevelsRec];

    //Adds a new array to the array of custom levels
    [customLevelArray addObject:level];

    //Saves the array.
    [customLevelArray writeToFile:customLevelsRec atomically:YES];

    //cleanup
    [customLevelArray release];

    //Message saying a custom level has been recieved
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Received!" message:@"A custom level has been saved." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [alert show];
    [alert release];

}

Testing this has been a pain since I don't have two devices of my own currently, so I send a beta build to my friend who inturns tests them (he has ipod and iphone). Any help with this is appreciated...

If I can't find the problem I will most likely send the entire xcode project to him and via screen share work with the project on his computer to efficiently build and test the application. And I will be able to use debug mode.

Body:
I don't know if you ever found an answer to this question or not, I hope you did. But if you didn't I highly recommend that you try the new features of the new SDK. Instead of going through the whole encode/decode process, they have made it simple by having you do the following (in your send methodology):

data = [NSKeyedArchiver archivedDataWithRootObject:anObject];

where anObject can be pretty much any object, array, dictionary, whatever...

In your receive methodology:

NSObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data];

where object can also be pretty much any object.

As far as the crash you are experiencing, have you verified on which line the crash occurs? Are you sure it happens in the code you posted? Or is it happening somewhere else?


问:
Enabling CORS in Firebase Hosting
I have this really annoying issue with CORS and my Google Cloud function...

the error I get is:

Access to XMLHttpRequest at [My function URL] from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Ive already tried to handle it on the function side with the following code:

if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)
```

<p>and then added in the main return with:</p>

<pre class="lang-py prettyprint-override"><code>headers = {
            'Access-Control-Allow-Origin': '*'
        }
....

return(json.dumps(data), 200, headers)
</code>```

this doesnt work....

I also tried with the firebase.json headers approach and also not working...

even tried with the HttpHeaders in angular like so:

```<code>const headers = new HttpHeaders()
      .set("Access-Control-Allow-Origin", "*")
      .set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
      .set('cache-control', 'no-cache')
</code>```

also not working.....

then I tried with a proxy (just to check if that is the actual problem)
added the proxy.config.json and of course in the dev it just works...

but the problem is, I need to be able to upload the Angular app to the firebase hosting so how can I fix the CORS error in the backend?

答:
One of the easiest way to get rid of cors errors is to use callable functions. They also have the user context. Which can be really usefull.

But if you want to create an api. I would recommend using express and cors package. Here is the code that I use:

```<code>import * as express from 'express';
import * as cors from 'cors';

const app = express();
// cors middleware handles all the cors related issues.
app.use(cors({ origin: '*' }));

// you can add your routes in your app.
app.use('/users', usersRoute);

export const api = functions.https.onRequest(app);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Enabling CORS in Firebase Hosting

Body:
I have this really annoying issue with CORS and my Google Cloud function...

the error I get is:

Access to XMLHttpRequest at [My function URL] from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Ive already tried to handle it on the function side with the following code:

if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

and then added in the main return with:

headers = {
            'Access-Control-Allow-Origin': '*'
        }
....

return(json.dumps(data), 200, headers)

this doesnt work....

I also tried with the firebase.json headers approach and also not working...

even tried with the HttpHeaders in angular like so:

const headers = new HttpHeaders()
      .set("Access-Control-Allow-Origin", "*")
      .set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
      .set('cache-control', 'no-cache')

also not working.....

then I tried with a proxy (just to check if that is the actual problem)
added the proxy.config.json and of course in the dev it just works...

but the problem is, I need to be able to upload the Angular app to the firebase hosting so how can I fix the CORS error in the backend?

Body:
One of the easiest way to get rid of cors errors is to use callable functions. They also have the user context. Which can be really usefull.

But if you want to create an api. I would recommend using express and cors package. Here is the code that I use:

import * as express from 'express';
import * as cors from 'cors';

const app = express();
// cors middleware handles all the cors related issues.
app.use(cors({ origin: '*' }));

// you can add your routes in your app.
app.use('/users', usersRoute);

export const api = functions.https.onRequest(app);


问:
How to denormalized data in SQL query
I have a table that has Clinic Names and Doctor Names.  one clinic can have many doctors.  I need to split this data into two tables.  one with clinic info and the other with Doctor info

trying to do this in a SQL query

Table CLINIC_DOC:

```<code>ID  ClinicName  Doctor
------------------------
1   xyz         Dr Joe
2   xyz         Dr Bob
3   abc         Dr Mary
4   abc         Dr John
</code>```

I want to split the data into the following tables like this:

Table ClinicsData:

```<code>ClinicID    ClinicName
----------------------
1           xyz
2           abc
</code>```

Table DoctorData:

```<code>DocId   ClinicID    Doctor
--------------------------
1       1           Dr Joe
2       1           Dr Bob
3       2           Dr Mary
4       2           Dr John
</code>```

答:
First, you'll probably want to create the tables you're going to populate. Here's my best guess at dataypes:

```<code>CREATE TABLE ClinicsData
(
    ClinicID INT IDENTITY(1,1),
    ClinicName varchar(100)
)

CREATE TABLE DoctorData
(
    DocID INT IDENTITY(1,1),
    ClinicID INT,
    Doctor VARCHAR(100)
)
</code>```

Notice that I've made ClinicsData.ClinicID an IDENTITY column. This will help us to populate DoctorData later.

Next, let's populate ClinicsData with all the distinct clinic names.

```<code>INSERT INTO ClinicsData
(
    ClinicName
)
SELECT DISTINCT
    ClinicName
FROM CLINIC_DOC;
</code>```

Now, we can utilize ClinicsData to populate DoctorData, using an INNER JOIN.

```<code>INSERT INTO DoctorData
(
    ClinicID
    ,Doctor
)
SELECT DISTINCT
    cd.ClinicID,
    c_d.Doctor
FROM CLINIC_DOC c_d
INNER JOIN ClinicsData cd ON cd.ClinicName = c_d.ClinicName
</code>```

Title: How to denormalized data in SQL query

Body:
I have a table that has Clinic Names and Doctor Names.  one clinic can have many doctors.  I need to split this data into two tables.  one with clinic info and the other with Doctor info

trying to do this in a SQL query

Table CLINIC_DOC:

ID  ClinicName  Doctor
------------------------
1   xyz         Dr Joe
2   xyz         Dr Bob
3   abc         Dr Mary
4   abc         Dr John

I want to split the data into the following tables like this:

Table ClinicsData:

ClinicID    ClinicName
----------------------
1           xyz
2           abc

Table DoctorData:

DocId   ClinicID    Doctor
--------------------------
1       1           Dr Joe
2       1           Dr Bob
3       2           Dr Mary
4       2           Dr John

Body:
First, you'll probably want to create the tables you're going to populate. Here's my best guess at dataypes:

CREATE TABLE ClinicsData
(
    ClinicID INT IDENTITY(1,1),
    ClinicName varchar(100)
)

CREATE TABLE DoctorData
(
    DocID INT IDENTITY(1,1),
    ClinicID INT,
    Doctor VARCHAR(100)
)

Notice that I've made ClinicsData.ClinicID an IDENTITY column. This will help us to populate DoctorData later.

Next, let's populate ClinicsData with all the distinct clinic names.

INSERT INTO ClinicsData
(
    ClinicName
)
SELECT DISTINCT
    ClinicName
FROM CLINIC_DOC;

Now, we can utilize ClinicsData to populate DoctorData, using an INNER JOIN.

INSERT INTO DoctorData
(
    ClinicID
    ,Doctor
)
SELECT DISTINCT
    cd.ClinicID,
    c_d.Doctor
FROM CLINIC_DOC c_d
INNER JOIN ClinicsData cd ON cd.ClinicName = c_d.ClinicName


问:
Adding page (menu item) in Wordpress admin
I am trying to add a new page to the admin area of Wordpress using the admin_menu action, but it is not working:

```<code>add_action('admin_menu', 'laksh_advert_menu');
function laksh_advert_menu() {
  add_menu_page(
      'Advert',
      'Advert',
      'edit_posts',
      'advert',
      'laksh_advert_page',
      'dashicons-admin-tools'
     );
}

function laksh_advert_page() {
    echo "Hello";
}
</code>```

答:
You trying add position and change capability menu:

```<code>function laksh_advert_menu(){
    add_menu_page(
        __( 'Advert', 'textdomain' ),
        'advert menu',
        'manage_options',
        'advert',
        'laksh_advert_page',
        'dashicons-admin-tools',
       10
    );
}
add_action( 'admin_menu', 'laksh_advert_menu' );

function laksh_advert_page(){
    esc_html_e( 'Admin Page Test', 'textdomain' );
}
</code>```

I think some a plugin external can that write your position or manager your menus, but trying "pin up" your menu position.

You have some plugin for menu?

Body:
I am trying to add a new page to the admin area of Wordpress using the admin_menu action, but it is not working:

add_action('admin_menu', 'laksh_advert_menu');
function laksh_advert_menu() {
  add_menu_page(
      'Advert',
      'Advert',
      'edit_posts',
      'advert',
      'laksh_advert_page',
      'dashicons-admin-tools'
     );
}

function laksh_advert_page() {
    echo "Hello";
}

Body:
You trying add position and change capability menu:

function laksh_advert_menu(){
    add_menu_page(
        __( 'Advert', 'textdomain' ),
        'advert menu',
        'manage_options',
        'advert',
        'laksh_advert_page',
        'dashicons-admin-tools',
       10
    );
}
add_action( 'admin_menu', 'laksh_advert_menu' );

function laksh_advert_page(){
    esc_html_e( 'Admin Page Test', 'textdomain' );
}

I think some a plugin external can that write your position or manager your menus, but trying "pin up" your menu position.

You have some plugin for menu?


问:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
Is it possible to place a WebMethod in an ascx.cs file (for a UserControl)  and then call it from client-side jQuery code?

For some reasons I can't place the WebMethod code in an .asmx or .aspx file.

Example: In ArticleList.ascx.cs I have the following code:

```<code>[WebMethod]
public static string HelloWorld()
{
    return "helloWorld";
}
</code>```

In ArticleList.ascx file there I have the call to the WebMethod as follows:

```<code>$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
            {
                var msg;
                if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            url: "ArticleList.ascx/HelloWorld",
            success: function(msg) {
                alert(msg);
            }
        });
</code>```

and the error from firebug is:

```<code><html>
<head>
    <title>This type of page is not served.</title>
</code>```

How can I sucessfully call the server-side WebMethod from my client-side jQuery code?

答:
WebMethod should be static. So, You can put it in the user control and add a method in the page to call it.

Edit:

You can not call a web method through a user control because it'll be automatically rendered inside the page.

The web method which you have in the user control:

```<code>public static string HelloWorld()
{
    return "helloWOrld";
}
</code>```

In the Page class add the web method:

```<code>[WebMethod]
public static string HelloWorld()
{
    return ArticleList.HelloWorld(); // call the method which
                                     // exists in the user control
}
</code>```

Body:
Is it possible to place a WebMethod in an ascx.cs file (for a UserControl)  and then call it from client-side jQuery code?

For some reasons I can't place the WebMethod code in an .asmx or .aspx file.

Example: In ArticleList.ascx.cs I have the following code:

[WebMethod]
public static string HelloWorld()
{
    return "helloWorld";
}

In ArticleList.ascx file there I have the call to the WebMethod as follows:

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
            {
                var msg;
                if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            url: "ArticleList.ascx/HelloWorld",
            success: function(msg) {
                alert(msg);
            }
        });

and the error from firebug is:

    <title>This type of page is not served.</title>

How can I sucessfully call the server-side WebMethod from my client-side jQuery code?

Body:
WebMethod should be static. So, You can put it in the user control and add a method in the page to call it.

Edit:

You can not call a web method through a user control because it'll be automatically rendered inside the page.

The web method which you have in the user control:

public static string HelloWorld()
{
    return "helloWOrld";
}

In the Page class add the web method:

[WebMethod]
public static string HelloWorld()
{
    return ArticleList.HelloWorld(); // call the method which
                                     // exists in the user control
}


问:
Calculating width of scrollbar and using result in calc() css
I want to calculate the width of the scrollbar so that I use the result in a CSS calc() declaration.

At the moment, I assume that the width of the scrollbar is always 17px, like this:

body {
    width:calc(100vw - 17px);
}
.container {
    max-width:calc(100vw - 17px);
}
```

<p>The problem with this is when you choose a different browser zoom %, the width of the scrollbar changes. So I want to use the result of the calculation to do something along these lines:</p>

<pre class="lang-css prettyprint-override"><code>body {
    width:calc(100vw - CALCULATED SCROLL-BAR WIDTH);
}
.container {
    max-width:calc(100vw - CALCULATED SCROLL-BAR WIDTH);
}
</code>```

EDIT: I've now solved the problem with the help of this question

The JavaScript used to calculate the scrollbar width (though, I have found you require an interval to get it to autoupdate):

function getScrollbarWidth() {
  var outer = document.createElement("div");
  outer.style.visibility = "hidden";
  outer.style.width = "100px";
  outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps

  document.body.appendChild(outer);

  var widthNoScroll = outer.offsetWidth;
  // force scrollbars
  outer.style.overflow = "scroll";

  // add innerdiv
  var inner = document.createElement("div");
  inner.style.width = "100%";
  outer.appendChild(inner);

  var widthWithScroll = inner.offsetWidth;

  // remove divs
  outer.parentNode.removeChild(outer);

  return widthNoScroll - widthWithScroll;
}```
</div>
</div>
</p>

<p><strong>My code (which is used to embed the result of the function into a CSS <code>calc()</code> declaration).</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('body').css({
  'width':'calc(100vw - ' + getScrollbarWidth() + 'px)'
});

$('.container').css({
  'max-width':'calc(100vw - ' + getScrollbarWidth() + 'px)'
});</code>```

答:
Actually, you can get the scrollbar width just with css and custom properties (and completely without javascript):

```<code>body {
    --scrollbar-width: calc(100vw - 100%);
}
</code>```

Then you can use this variable in a child element like this:

```<code>.container {
    max-width: calc(100vw - var(--scrollbar-width));
}
</code>```

This is because 100vw is always the inner width of the view, but the 100% of the body does not include the scrollbar.

Body:
I want to calculate the width of the scrollbar so that I use the result in a CSS calc() declaration.

At the moment, I assume that the width of the scrollbar is always 17px, like this:

body {
    width:calc(100vw - 17px);
}
.container {
    max-width:calc(100vw - 17px);
}

The problem with this is when you choose a different browser zoom %, the width of the scrollbar changes. So I want to use the result of the calculation to do something along these lines:

body {
    width:calc(100vw - CALCULATED SCROLL-BAR WIDTH);
}
.container {
    max-width:calc(100vw - CALCULATED SCROLL-BAR WIDTH);
}

EDIT: I've now solved the problem with the help of this question

The JavaScript used to calculate the scrollbar width (though, I have found you require an interval to get it to autoupdate):

function getScrollbarWidth() {
  var outer = document.createElement("div");
  outer.style.visibility = "hidden";
  outer.style.width = "100px";
  outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps

  document.body.appendChild(outer);

  var widthNoScroll = outer.offsetWidth;
  // force scrollbars
  outer.style.overflow = "scroll";

  // add innerdiv
  var inner = document.createElement("div");
  inner.style.width = "100%";
  outer.appendChild(inner);

  var widthWithScroll = inner.offsetWidth;

  // remove divs
  outer.parentNode.removeChild(outer);

  return widthNoScroll - widthWithScroll;
}

My code (which is used to embed the result of the function into a CSS calc() declaration).

$('body').css({
  'width':'calc(100vw - ' + getScrollbarWidth() + 'px)'
});

$('.container').css({
  'max-width':'calc(100vw - ' + getScrollbarWidth() + 'px)'
});

Body:
Actually, you can get the scrollbar width just with css and custom properties (and completely without javascript):

body {
    --scrollbar-width: calc(100vw - 100%);
}

Then you can use this variable in a child element like this:

.container {
    max-width: calc(100vw - var(--scrollbar-width));
}

This is because 100vw is always the inner width of the view, but the 100% of the body does not include the scrollbar.


问:
@Async not working for method having return type void
I wanted to make a method writing to DB as async using @Async annotation.

I marked the class with the annotation @EnableAsync:

```<code>@EnableAsync
public class FacialRecognitionAsyncImpl {

    @Async
    public void populateDataInPushQueue(int mediaId, int studentId) {
        //myCode
    }
}
</code>```

while calling the populateDataInPushQueue method, the write operation should be executed in another thread and the flow should continue from the class I am calling this method. But this is not happening and the program execution is waiting for this method to complete.

答:
In my opinion, you are missing @Configuration annotation and your async service is not component scanned. Here is an example code fragment that should do the trick:

```<code>@Configuration
@EnableAsync  //should be placed together.
public class FacialRecognitionAsyncService {

     @Async
     public void populateDataInPushQueue(int mediaId, int studentId) {
         //myCode
     }
}

@Configuration
@EnableAsync
public class FacialServiceConfig {

    // this will make your service to be scanned.
    @Bean
    public FacialRecognitionAsyncService createFacialRecognitionService() {
        return new FacialRecognitionAsyncService();
    }

}
</code>```

Now the service bean that is invoking the async method. Notice that it has been dependency injected. This way spring AOP proxies will be invoked on each invocation fo the facialService. Spring uses AOP in the back scenes in order to implement @Async.

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

@Autowire
FacialRecognitionAsyncService  facialService;

public myBusinessMethod() {
   facialService.populateDataInPushQueue()
}
</code>```

Notice that FacialService is injected in MyService through dependency injection.

Body:
I wanted to make a method writing to DB as async using @Async annotation.

I marked the class with the annotation @EnableAsync:

@EnableAsync
public class FacialRecognitionAsyncImpl {

    @Async
    public void populateDataInPushQueue(int mediaId, int studentId) {
        //myCode
    }
}

while calling the populateDataInPushQueue method, the write operation should be executed in another thread and the flow should continue from the class I am calling this method. But this is not happening and the program execution is waiting for this method to complete.

Body:
In my opinion, you are missing @Configuration annotation and your async service is not component scanned. Here is an example code fragment that should do the trick:

@Configuration
@EnableAsync  //should be placed together.
public class FacialRecognitionAsyncService {

     @Async
     public void populateDataInPushQueue(int mediaId, int studentId) {
         //myCode
     }
}

@Configuration
@EnableAsync
public class FacialServiceConfig {

    // this will make your service to be scanned.
    @Bean
    public FacialRecognitionAsyncService createFacialRecognitionService() {
        return new FacialRecognitionAsyncService();
    }

}

Now the service bean that is invoking the async method. Notice that it has been dependency injected. This way spring AOP proxies will be invoked on each invocation fo the facialService. Spring uses AOP in the back scenes in order to implement @Async.

@Service
public class MyBusinessService {

@Autowire
FacialRecognitionAsyncService  facialService;

public myBusinessMethod() {
   facialService.populateDataInPushQueue()
}

Notice that FacialService is injected in MyService through dependency injection.


问:
Doing Deep-Nested Parent-Child Relationships using FeathersJS
I am wondering what the best way to do deep nested parent child relationships is using Feathers's recommended Association Method?

If my entries were:

```<code>[
    {"name": "Grandpa", "id": 1, "parent": null},
    {"name": "Mom", "id":2, "parent": 1},
    {"name": "Baby", "id": 3, "parent": 2}
]
</code>```

Then if I wanted to find the top parent of the tree, I would do a recursive get until I reach the top of the tree:

```<code>const family = app.service('/family')
function get_ancestors(childId, parents){
    const child = family.get(childId)
    if(child.parent){
        parents.push(child.parent)
        return get_ancestors(child.parent, parents)
    } else {
        return parents
    }
}
</code>```

But this seems clunky to me and not very extendable. Is there a better way?
This seems like something fastJoin would do, but it is not under the "Recommended" approach to doing associations. I also don't see any examples of more than 3 levels in the guide, except in maybe the batch-loaders,
And that looks to be a little more complex than we need here. What is the "recommended" way of traversing an ancestor tree using Feathers?
Conversely, If I had Grandpa, how would I find Baby?
Should my entries contain a "children" array that populates when a child is added with them as a parent? Or is there a better way of going from the top to the bottom of a parent tree?

答:
What it comes down to is that Feathers is not an ORM, so handling associations depends a lot on the database and ORM you chose much the same as it would with other frameworks like Express or KoaJS. It means more flexibility but also that there isn't really the one true way to do this and the FAQ entry linked tries to cover the different options as good as possible.

fastJoin does support nested associations but may be slower if you are using an SQL database where the ORM could handle optimizing the queries (Sequelize also supports nested includes). But it can be faster than Mongoose $populate. Run some experiments to see which one works best. With parent/child relationships one thing to look out for is circular dependencies so you want to use something that can handle that.

Body:
I am wondering what the best way to do deep nested parent child relationships is using Feathers's recommended Association Method?

If my entries were:

[
    {"name": "Grandpa", "id": 1, "parent": null},
    {"name": "Mom", "id":2, "parent": 1},
    {"name": "Baby", "id": 3, "parent": 2}
]

Then if I wanted to find the top parent of the tree, I would do a recursive get until I reach the top of the tree:

const family = app.service('/family')
function get_ancestors(childId, parents){
    const child = family.get(childId)
    if(child.parent){
        parents.push(child.parent)
        return get_ancestors(child.parent, parents)
    } else {
        return parents
    }
}

But this seems clunky to me and not very extendable. Is there a better way?
This seems like something fastJoin would do, but it is not under the "Recommended" approach to doing associations. I also don't see any examples of more than 3 levels in the guide, except in maybe the batch-loaders,
And that looks to be a little more complex than we need here. What is the "recommended" way of traversing an ancestor tree using Feathers?
Conversely, If I had Grandpa, how would I find Baby?
Should my entries contain a "children" array that populates when a child is added with them as a parent? Or is there a better way of going from the top to the bottom of a parent tree?


问:
List comprehension only returns last iteration
I'm trying to create a population of adjacency matrices with different random weights for which I am using the code underneath. My problem however is that upon running this, all the weights are that of the last iteration of the list comprehension? On printing these adjacencylists during generation, it works fine, however, the output of the getPopulation function is 5 times the same parameter set.

It feels like this would be an easy fix, but something (I think possibly very basic) is missing. Maybe a problem where deep copy is needed or something?

Already tried using normal for-loops, print statements etc.

import networkx as nx
import numpy as np

G = nx.DiGraph()
G.add_nodes_from(["Sadness", "Avoidance", "Guilt"])
G.add_edges_from([("Sadness", "Avoidance")], weight=1)
G.add_edges_from([("Avoidance", "Sadness")], weight=1)
G.add_edges_from([("Avoidance", "Guilt"), ("Guilt", "Sadness")], weight=1)
parameters = nx.to_numpy_matrix(G)

def getRandParamValue(adj):
    for p in np.transpose(adj.nonzero()):
        adj[p[0], p[1]] = adj[p[0], p[1]] * np.random.uniform()
    print(adj)
    return adj

def getPopulation(size, initParam):
    return [getRandParamValue(initParam) for i in range(size)]

getPopulation(5, parameters)
```

<p>Upon printing the output in the getRandParamValue function it works fine:</p>

<pre class="lang-py prettyprint-override"><code>[[0.         0.40218464 0.        ]
 [0.07330473 0.         0.7196376 ]
 [0.53148413 0.         0.        ]]
[[0.         0.34256617 0.        ]
 [0.01773899 0.         0.12460768]
 [0.1401687  0.         0.        ]]
[[0.         0.11086942 0.        ]
 [0.01449088 0.         0.04592752]
 [0.07903259 0.         0.        ]]
[[0.         0.01970867 0.        ]
 [0.00589168 0.         0.00860802]
 [0.06942081 0.         0.        ]]
[[0.         0.01045412 0.        ]
 [0.00084878 0.         0.00713334]
 [0.0024654  0.         0.        ]]
</code>```

However, the output of getPopulation isn't identical to the previous output, while this should be expected:

[matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]])]
```

<p>The parameters matrix is just the following: </p>

<pre class="lang-py prettyprint-override"><code>[[0. 1. 0.]
 [1. 0. 1.]
 [1. 0. 0.]]
</code>```

答:
So the problem is as follows:

```<code>def myfunction(L):
    L[0] += 1
    return L

my_outer_list = [1,2,3]
newlist = myfunction(my_outer_list)

print(newlist)
> [2, 2, 3]
print(my_outer_list)
> [2, 2, 3]

newlist[2]=-1
print(newlist)
> [2, 2, -1]
print(my_outer_list)
> [2, 2, -1]
</code>```

I've passed the object my_outer_list to the function.  Then that object gets modified, and the object is returned.  So now newlist and my_outer_list aren't just equal, they are two different names for the very same thing.  Things I do to that object change the object, and you see those changes no matter which name you use.

This is what's happened to you.  If I had instead had myfunction return L.copy(), it would have returned a copy of L rather than exactly L.

So you should return adj.copy().

Body:
I'm trying to create a population of adjacency matrices with different random weights for which I am using the code underneath. My problem however is that upon running this, all the weights are that of the last iteration of the list comprehension? On printing these adjacencylists during generation, it works fine, however, the output of the getPopulation function is 5 times the same parameter set.

It feels like this would be an easy fix, but something (I think possibly very basic) is missing. Maybe a problem where deep copy is needed or something?

Already tried using normal for-loops, print statements etc.

import networkx as nx
import numpy as np

G = nx.DiGraph()
G.add_nodes_from(["Sadness", "Avoidance", "Guilt"])
G.add_edges_from([("Sadness", "Avoidance")], weight=1)
G.add_edges_from([("Avoidance", "Sadness")], weight=1)
G.add_edges_from([("Avoidance", "Guilt"), ("Guilt", "Sadness")], weight=1)
parameters = nx.to_numpy_matrix(G)

def getRandParamValue(adj):
    for p in np.transpose(adj.nonzero()):
        adj[p[0], p[1]] = adj[p[0], p[1]] * np.random.uniform()
    print(adj)
    return adj

def getPopulation(size, initParam):
    return [getRandParamValue(initParam) for i in range(size)]

getPopulation(5, parameters)

Upon printing the output in the getRandParamValue function it works fine:

[[0.         0.40218464 0.        ]
 [0.07330473 0.         0.7196376 ]
 [0.53148413 0.         0.        ]]
[[0.         0.34256617 0.        ]
 [0.01773899 0.         0.12460768]
 [0.1401687  0.         0.        ]]
[[0.         0.11086942 0.        ]
 [0.01449088 0.         0.04592752]
 [0.07903259 0.         0.        ]]
[[0.         0.01970867 0.        ]
 [0.00589168 0.         0.00860802]
 [0.06942081 0.         0.        ]]
[[0.         0.01045412 0.        ]
 [0.00084878 0.         0.00713334]
 [0.0024654  0.         0.        ]]

However, the output of getPopulation isn't identical to the previous output, while this should be expected:

[matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]]),
 matrix([[0.        , 0.01045412, 0.        ],
         [0.00084878, 0.        , 0.00713334],
         [0.0024654 , 0.        , 0.        ]])]

The parameters matrix is just the following:

[[0. 1. 0.]
 [1. 0. 1.]
 [1. 0. 0.]]

Body:
So the problem is as follows:

def myfunction(L):
    L[0] += 1
    return L

my_outer_list = [1,2,3]
newlist = myfunction(my_outer_list)

print(newlist)
> [2, 2, 3]
print(my_outer_list)
> [2, 2, 3]

newlist[2]=-1
print(newlist)
> [2, 2, -1]
print(my_outer_list)
> [2, 2, -1]

I've passed the object my_outer_list to the function.  Then that object gets modified, and the object is returned.  So now newlist and my_outer_list aren't just equal, they are two different names for the very same thing.  Things I do to that object change the object, and you see those changes no matter which name you use.

This is what's happened to you.  If I had instead had myfunction return L.copy(), it would have returned a copy of L rather than exactly L.

So you should return adj.copy().


问:
Unable to trim whitespaces for the output of xpath
I am creating an xpath but I am having whitespaces in the xpath output. I tried using normalize-space but it didn't work.

```<code>((//a[contains(@class,'product-name')])[3])[normalize-space()='Printed Dress']
</code>```

```<code><div class="product-container" itemscope itemtype="http://schema.org/Product">
    <div class="left-block">
    <div class="product-image-container">
        <a class="product_img_link" href="http://automationpractice.com/index.php?id_product=3&controller=product" title="Printed Dress" itemprop="url">
<img class="replace-2x img-responsive" src="http://automationpractice.com/img/p/8/8-home_default.jpg" alt="Printed Dress" title="Printed Dress"  width="250" height="250" itemprop="image" />
           </a>
                                                    <div class="quick-view-wrapper-mobile">
      <a class="quick-view-mobile" href="http://automationpractice.com/index.php?id_product=3&controller=product" rel="http://automationpractice.com/index.php?id_product=3&controller=product">
        <i class="icon-eye-open"></i>
            </a>
</div>
                        <a class="quick-view" href="http://automationpractice.com/index.php?id_product=3&controller=product" rel="http://automationpractice.com/index.php?id_product=3&controller=product">
                            <span>Quick view</span>
                        </a>
                                                                            <div class="content_price" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
                                                                    <span itemprop="price" class="price product-price">
                                        $26.00                                  </span>
                                    <meta itemprop="priceCurrency" content="USD" />

                                                            </div>
                                                                                </div>

                </div>
</code>```

I wanted the output to be as only "Printed Dress" but i get the output as

```<code>
                            Printed Dress

</code>```

答:
normalize-space is a xpath function all it will do is trim the white spaces while evaluating the xpath but not the output.

You have to trim the output using the language specific method. Eg: if you are using python you can use outPut.strip().

Body:
I am creating an xpath but I am having whitespaces in the xpath output. I tried using normalize-space but it didn't work.

((//a[contains(@class,'product-name')])[3])[normalize-space()='Printed Dress']

                            Quick view

                                        $26.00
                                    <meta itemprop="priceCurrency" content="USD" />

I wanted the output to be as only "Printed Dress" but i get the output as

                            Printed Dress


问:
how to create knockout text on a background image so that text can animate over the image
I'd like to have a background image that only shows through knockout text and then have that text animate from the top of the page to the bottom of the page, showing the different parts of the background image as the text moves.

I know how to make knockout text:

```<code>#screen1 h1 {
    display:block;
    margin: auto;
    font-family: 'proxima-nova', sans-serif;
    background-image: url('../img/my-image.jpg');
    background-clip: text;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    font-size: 12rem;
    font-weight: 800;
}
</code>```

But what I want is more like a background image on #screen1 that only shows through on the knockout text. So when you animate the knockout text, it shows different parts of the background image.

html:

```<code><div id="screen1" >
<div style="">
<h1>MY TEXT</h1>
</div>
</div>
</code>```

CSS :

```<code>#screen1 {
    background: url(../img/my-image.jpg) no-repeat;
    background-size: cover;
    overflow: hidden;
}
#screen1 h1 {
    display:block;
    margin: auto;
    font-family: 'proxima-nova', sans-serif;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    font-size: 12rem;
    font-weight: 800;
}
</code>```

But this just shows the background image. I sense I'm close.

答:
I'd like to have a background image that only shows through knockout text and then have that text animate from the top of the page to the bottom of the page, showing the different parts of the background image as the text moves.

You can animate the text while revealing the background image:

body {
 margin: 0;
 background-color: lightblue;
 overflow: hidden;
}

h1 {
  display: flex;
  justify-content: center;
  height: 100vh;
  margin: auto;
  font-family: 'proxima-nova', sans-serif;
  background: url('https://placekitten.com/g/200/300') no-repeat;
  background-size: cover;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  font-size: 5rem;
  line-height: 5rem;
  font-weight: 800;
  padding-top: 0;
  animation: animate 5s linear infinite;
}

@keyframes animate {
  to {
    padding-top: calc(100vh - 6rem);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Text</h1></code>```

You can do the same thing with the markup that has the #screen1 and the h1 nested within by inheriting the background to the h1 and then having the clip background effect - see demo below:

body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

#screen1 {
  background: url('https://placekitten.com/g/200/300') no-repeat, lightblue;
  background-size: 0; /* don't show the background yet */
  height: 100vh;
  overflow: hidden;
}

#screen1>div {
  background: inherit;
  /* background size is still zero */
  height: 100%;
}

#screen1 h1 {
  display: flex;
  justify-content: center;
  margin: 0;
  background: inherit;
  /* now show the background */
  background-size: cover;
  font-family: 'proxima-nova', sans-serif;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  font-size: 5rem;
  line-height: 5rem;
  font-weight: 800;
  padding-top: 0;
  animation: animate 5s linear infinite;
  height: 100%;
}

@keyframes animate {
  to {
    padding-top: calc(100vh - 5rem);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="screen1">
  <div>
    <h1>MY TEXT</h1>
  </div>
</div></code>```

Body:
I'd like to have a background image that only shows through knockout text and then have that text animate from the top of the page to the bottom of the page, showing the different parts of the background image as the text moves.

I know how to make knockout text:

#screen1 h1 {
    display:block;
    margin: auto;
    font-family: 'proxima-nova', sans-serif;
    background-image: url('../img/my-image.jpg');
    background-clip: text;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    font-size: 12rem;
    font-weight: 800;
}

But what I want is more like a background image on #screen1 that only shows through on the knockout text. So when you animate the knockout text, it shows different parts of the background image.

html:

MY TEXT

CSS :

#screen1 {
    background: url(../img/my-image.jpg) no-repeat;
    background-size: cover;
    overflow: hidden;
}
#screen1 h1 {
    display:block;
    margin: auto;
    font-family: 'proxima-nova', sans-serif;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    font-size: 12rem;
    font-weight: 800;
}

But this just shows the background image. I sense I'm close.

Body:
I'd like to have a background image that only shows through knockout text and then have that text animate from the top of the page to the bottom of the page, showing the different parts of the background image as the text moves.

You can animate the text while revealing the background image:

body {
 margin: 0;
 background-color: lightblue;
 overflow: hidden;
}

h1 {
  display: flex;
  justify-content: center;
  height: 100vh;
  margin: auto;
  font-family: 'proxima-nova', sans-serif;
  background: url('https://placekitten.com/g/200/300') no-repeat;
  background-size: cover;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  font-size: 5rem;
  line-height: 5rem;
  font-weight: 800;
  padding-top: 0;
  animation: animate 5s linear infinite;
}

@keyframes animate {
  to {
    padding-top: calc(100vh - 6rem);
  }
}

<h1>Text</h1>

You can do the same thing with the markup that has the #screen1 and the h1 nested within by inheriting the background to the h1 and then having the clip background effect - see demo below:

body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

#screen1 {
  background: url('https://placekitten.com/g/200/300') no-repeat, lightblue;
  background-size: 0; /* don't show the background yet */
  height: 100vh;
  overflow: hidden;
}

#screen1>div {
  background: inherit;
  /* background size is still zero */
  height: 100%;
}

#screen1 h1 {
  display: flex;
  justify-content: center;
  margin: 0;
  background: inherit;
  /* now show the background */
  background-size: cover;
  font-family: 'proxima-nova', sans-serif;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  font-size: 5rem;
  line-height: 5rem;
  font-weight: 800;
  padding-top: 0;
  animation: animate 5s linear infinite;
  height: 100%;
}

@keyframes animate {
  to {
    padding-top: calc(100vh - 5rem);
  }
}

<div id="screen1">
  <div>
    <h1>MY TEXT</h1>
  </div>
</div>


问:
Velocity "fadeIn" Issue with Version 2.0.0+ (including 2.0.5)
I am a new programmer of JS. I'm trying to learn some HTML animations on JS and I found an amazing package called "VelocityJS". But when I use the

```<code>$ele.velocity("fadeIn")
</code>```

My chrome keeps throwing an error:

```<code>VelocityJS: First argument (fadeIn) was not a property map, a known action, or a registered redirect. Aborting.
</code>```

Now in the official website,
Chapter "Command" - "fadeIn and fadeOut", there are 2 examples including the usage. But as far as I tested, It only works for the version under 1.5.0.
I wish I can be told if there's any substitution for this after version 2.0.0 (also called Velocity V2)?

And In Chapter "Basics: Performance", it's told that Never use jQuery's $.animate() and $.fade() functions. They slow everything else down, including other animation libraries.

JS FILE

```<code>try {
$(test).velocity("fadeIn", { duration: 1500 }).velocity("fadeOut", { delay: 500, duration: 1500 });
} catch {}
</code>```

HTML FILE

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.js"></script>
<div id='test' style="background-color:black">
    some place holder
</div>
</code>```

copy and past the file above to the example at codepen.io

THIS GIVES THE RIGHT OUTPUT.
but the Velocity version of this page is
https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js
As I want to change the "marginTop" property, I need to use a later version.
But I cannot find any documentation on the latest version.

With version 1.5.0, neither of the "marginTop" or "margin-top" works.
With version 2.0.0 - 2.0.5,
    $(elementID).velocity("fadeIn",{duration:1000})
has no effect.
Fixing either one is fine for me so far.

Thanks in advance.

答:
Velocity V2 is in beta yet. You could always use direct CSS attributes manipulation with:

```<code>element.velocity({
    p: { opacity: 1 },
    o: { duration: 1500 }
}).velocity({
    p: { opacity: 0 },
    o: { delay: 500, duration: 1500 }
});
</code>```

The documentation on for V2 is not maintained on the main site yet. You should instead refer for the docs in the Github wiki

Body:
I am a new programmer of JS. I'm trying to learn some HTML animations on JS and I found an amazing package called "VelocityJS". But when I use the

$ele.velocity("fadeIn")

My chrome keeps throwing an error:

VelocityJS: First argument (fadeIn) was not a property map, a known action, or a registered redirect. Aborting.

Now in the official website,
Chapter "Command" - "fadeIn and fadeOut", there are 2 examples including the usage. But as far as I tested, It only works for the version under 1.5.0.
I wish I can be told if there's any substitution for this after version 2.0.0 (also called Velocity V2)?

And In Chapter "Basics: Performance", it's told that Never use jQuery's $.animate() and $.fade() functions. They slow everything else down, including other animation libraries.

JS FILE

try {
$(test).velocity("fadeIn", { duration: 1500 }).velocity("fadeOut", { delay: 500, duration: 1500 });
} catch {}

HTML FILE

    some place holder

copy and past the file above to the example at codepen.io

THIS GIVES THE RIGHT OUTPUT.
but the Velocity version of this page is
https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js
As I want to change the "marginTop" property, I need to use a later version.
But I cannot find any documentation on the latest version.

With version 1.5.0, neither of the "marginTop" or "margin-top" works.
With version 2.0.0 - 2.0.5,
    $(elementID).velocity("fadeIn",{duration:1000})
has no effect.
Fixing either one is fine for me so far.

Thanks in advance.

Body:
Velocity V2 is in beta yet. You could always use direct CSS attributes manipulation with:

element.velocity({
    p: { opacity: 1 },
    o: { duration: 1500 }
}).velocity({
    p: { opacity: 0 },
    o: { delay: 500, duration: 1500 }
});

The documentation on for V2 is not maintained on the main site yet. You should instead refer for the docs in the Github wiki


问:
NPM: Update all dependencies with scope
Is there a shortcut for updating all package dependencies that are of a particular scope.

For example is there are in the following package.json is there a quick way to update only those packages with an @example scope?:

```<code>…
dependencies: {
  alpha,
  bravo,
  @example/a,
  @example/b,
  @example/c,
  @example/d,
  @example/e,
  @example/f,
}
</code>```

答: I wrote small tool for that. Run npx update-by-scope @example for Yarn project and npx update-by-scope @example npm install for Npm project

Title: NPM: Update all dependencies with scope

Body:
Is there a shortcut for updating all package dependencies that are of a particular scope.

For example is there are in the following package.json is there a quick way to update only those packages with an @example scope?:

…
dependencies: {
  alpha,
  bravo,
  @example/a,
  @example/b,
  @example/c,
  @example/d,
  @example/e,
  @example/f,
}


问:
Is it possible to have an optional output file in Snakemake?
I'm writing a snakemake rule that will handle performing fastq trimming on either single or paired end sequencing data. If the data is paired end there should be two output files, if single end, there should be one.

The rule I have written works so far, however, I don't have it that the second pair of the trimmed is an output file. This means that snakemake is not checking to see if that file exists. It will output, but it's not checking, is it possible to have an optional output?

```<code>    input:
    #get the value in the fast1 column
        fastq_file = lambda wildcards: return_fastq(wildcards.fastq_name,wildcards.unit,first_pair = True)
    output:
        out_fastqc = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_trimmed.fastq.gz",
        fastpjson = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.json",
        fastphtml = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.html"
    params:
        fastp_parameters = return_parsed_extra_params(config['fastp_parameters']),
        fastq_file2 = lambda wildcards: return_fastq(wildcards.fastq_name,wildcards.unit,first_pair = False),
        out_fastqc2 = lambda wildcards: return_fastq2_name(wildcards.fastq_name,wildcards.unit),
        fastpjson = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.json",
        fastphtml = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.html"
    run:
        if config["end_type"] == "se":
            shell("{config[fastp_path]} -i {input.fastq_file} -o {output.out_fastqc} --json {output.fastpjson} --html {output.fastphtml} {params.fastp_parameters}")
        if config["end_type"] == "pe":
            shell("{config[fastp_path]} --in1 {input.fastq_file} --in2 {params.fastq_file2} --out1 {output.out_fastqc} --out2  {params.out_fastqc2} --json {output.fastpjson} --html {output.fastphtml} {params.fastp_parameters}")
</code>```

The goal is that the out_fastqc2 would be includes as an optional output of the rule so that snakemake will check if it exists and appropiately give me an error if it doesn't.

If Snakemake doesn't allow optional outputs, I could just split into two rules, but that's not quite what I'd like.

答:
Look at how does the expand function work. It is being called at the phase when Snakemake constructs the DAG of dependencies, and it uses the result of this function to construct the list of files for the output section.

I would suggest you to try the same: construct the list that would be either empty or not - depends on the condition.

This solution would work only if you know if you need the out_fastqc2 in advance (however defining 2 rules with priorities does the same). If you get the information about the need of out_fastqc2 only while running the rule, that is completely different case where you need checkpoints.

Below is the code that illustrates my approach: out_fastqc2 becomes a string that describes the file (if the end_type is configured to "pe"), otherwise is becomes an empty list that doesn't change the list of outputs.

```<code>output:
    out_fastqc = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_trimmed.fastq.gz",
    out_fastqc2 = lambda wildcards: return_fastq2_name(wildcards.fastq_name,wildcards.unit) if config["end_type"] == "pe" else []
</code>```

Body:
I'm writing a snakemake rule that will handle performing fastq trimming on either single or paired end sequencing data. If the data is paired end there should be two output files, if single end, there should be one.

The rule I have written works so far, however, I don't have it that the second pair of the trimmed is an output file. This means that snakemake is not checking to see if that file exists. It will output, but it's not checking, is it possible to have an optional output?

    input:
    #get the value in the fast1 column
        fastq_file = lambda wildcards: return_fastq(wildcards.fastq_name,wildcards.unit,first_pair = True)
    output:
        out_fastqc = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_trimmed.fastq.gz",
        fastpjson = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.json",
        fastphtml = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.html"
    params:
        fastp_parameters = return_parsed_extra_params(config['fastp_parameters']),
        fastq_file2 = lambda wildcards: return_fastq(wildcards.fastq_name,wildcards.unit,first_pair = False),
        out_fastqc2 = lambda wildcards: return_fastq2_name(wildcards.fastq_name,wildcards.unit),
        fastpjson = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.json",
        fastphtml = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_fastp.html"
    run:
        if config["end_type"] == "se":
            shell("{config[fastp_path]} -i {input.fastq_file} -o {output.out_fastqc} --json {output.fastpjson} --html {output.fastphtml} {params.fastp_parameters}")
        if config["end_type"] == "pe":
            shell("{config[fastp_path]} --in1 {input.fastq_file} --in2 {params.fastq_file2} --out1 {output.out_fastqc} --out2  {params.out_fastqc2} --json {output.fastpjson} --html {output.fastphtml} {params.fastp_parameters}")

The goal is that the out_fastqc2 would be includes as an optional output of the rule so that snakemake will check if it exists and appropiately give me an error if it doesn't.

If Snakemake doesn't allow optional outputs, I could just split into two rules, but that's not quite what I'd like.

Body:
Look at how does the expand function work. It is being called at the phase when Snakemake constructs the DAG of dependencies, and it uses the result of this function to construct the list of files for the output section.

I would suggest you to try the same: construct the list that would be either empty or not - depends on the condition.

This solution would work only if you know if you need the out_fastqc2 in advance (however defining 2 rules with priorities does the same). If you get the information about the need of out_fastqc2 only while running the rule, that is completely different case where you need checkpoints.

Below is the code that illustrates my approach: out_fastqc2 becomes a string that describes the file (if the end_type is configured to "pe"), otherwise is becomes an empty list that doesn't change the list of outputs.

output:
    out_fastqc = config["fastp_trimmed_output_folder"] + "{unit}/{fastq_name}_trimmed.fastq.gz",
    out_fastqc2 = lambda wildcards: return_fastq2_name(wildcards.fastq_name,wildcards.unit) if config["end_type"] == "pe" else []


答:
The @Async annotation has few limitations - check whether those are respected:

it must be applied to public methods only

it cannot be called from the same class as defined

the return type must be either void or Future

The following can be found at the documentation of @EnableAsync:

Please note that proxy mode allows for the interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.

Another fact is that the class annotated with @EnableAsync must be a @Configuration as well. Therefore start with an empty class:

```<code>@EnableAsync
@Configuration
public class AsyncConfiguration { }
</code>```

Title: @Async not working for method having return type void

Body:
The @Async annotation has few limitations - check whether those are respected:

it must be applied to public methods only

it cannot be called from the same class as defined

the return type must be either void or Future

The following can be found at the documentation of @EnableAsync:

Please note that proxy mode allows for the interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.

Another fact is that the class annotated with @EnableAsync must be a @Configuration as well. Therefore start with an empty class:

@EnableAsync
@Configuration
public class AsyncConfiguration { }


问:
How to get CircleCI status badge for particular branch
I have a CircleCI badge in my readme file, which is just retrieved via:

```<code><img src="https://circleci.com/gh/ORESoftware/live-mutex.png?circle-token=8ee836581">
</code>```

is there a way to retrieve the badge for just a certain branch? Is there a way to keep it updated? Sometimes it lags - probably because of http caching.

答:
Have you tried using the Status Badges page in your CircleCI project's notifications setting section?

You should be able to build a badge for your specific branch via the Branch dropdown:

By default, the badge displays the status of your project’s default branch. If you want to show the status of a different branch, use the Branch dropdown menu to select it.

Body:
I have a CircleCI badge in my readme file, which is just retrieved via:

is there a way to retrieve the badge for just a certain branch? Is there a way to keep it updated? Sometimes it lags - probably because of http caching.


问:
Is possible to show a dialog before show Recents, Press Back or Home Button?
I'm trying to detect when the user click on BackPressed (this I can override the onBackPressed()) also the home button and the recent button.

My goal is, don't quit the app until the user Accepts a dialog, I mean, for instance I'm using an app, that doesn't let go to another app to see something, so I want to do something like a "Security thingy".

Scenario would be :

User is watching a video (that's an example)

User tries to press the square button to show recent apps

Then user sees a dialog saying if you leave you are gonna loose the video (whatever...) if he press yes do the normal stuff like see the recents if he presses no, don't show recents...

The same with the home button

I've already tried onPause() but the thing is that I see the dialog after the action is done and if I do an if condition it crashes because it needs the super.onPause().

Any clue how to achieve this?

答:
I think you only can handle the back button. For back button, you can override the onBackPressed() method of your Activity and show the user a dialog and then call  android.os.Process.killProcess(android.os.Process.myPid()) when the user clicks on Yes button of your dialog

```<code>@Override
public void onBackPressed() {
     //show dialog
}

private void onDialogYesButtonClick() {
    android.os.Process.killProcess(android.os.Process.myPid())
}
</code>```

Body:
I think you only can handle the back button. For back button, you can override the onBackPressed() method of your Activity and show the user a dialog and then call  android.os.Process.killProcess(android.os.Process.myPid()) when the user clicks on Yes button of your dialog

@Override
public void onBackPressed() {
     //show dialog
}

private void onDialogYesButtonClick() {
    android.os.Process.killProcess(android.os.Process.myPid())
}


问:
How to write complex constraints in cvxpy?
I am trying to write a portfolio optimization problem using cvxpy.

```<code>initial_weights = [0.045, 0.035, 0.024, 0.028...]
rets = (np.log(data/data.shift(1))
w = cvx.Variable(38)
ret = np.sum(rets.mean()*w)*252
prob = cvx.Problem(cvx.Maximize(ret), [cvx.sum_entries(w)==1, w>0.02, w<0.06])
result = prob.solve()
</code>```

After solving, w.value is of the form [[0.02], [0.02], [0.04]...]

I want to add a constraint that works something like this:

```<code>for i in range(len(initial_weights)):
    abs(initial_weights[i]-w[1][i])>0.005
</code>```

Does anyone have any suggestions on how to include this in the constraints?

答:
If you want to add constraints in a for loop, this answer seems to provide the solution.

I am also surprised that the value being returned is an array of arrays, instead of an array of values. If you ensure that the dimension of rets.mean() is correct, then w should be a simple array with 38 values. In that case, your constraint simplifies to
abs(initial_weights-w)>0.005

Body:
I am trying to write a portfolio optimization problem using cvxpy.

initial_weights = [0.045, 0.035, 0.024, 0.028...]
rets = (np.log(data/data.shift(1))
w = cvx.Variable(38)
ret = np.sum(rets.mean()*w)*252
prob = cvx.Problem(cvx.Maximize(ret), [cvx.sum_entries(w)==1, w>0.02, w<0.06])
result = prob.solve()

After solving, w.value is of the form [[0.02], [0.02], [0.04]...]

I want to add a constraint that works something like this:

for i in range(len(initial_weights)):
    abs(initial_weights[i]-w[1][i])>0.005

Does anyone have any suggestions on how to include this in the constraints?


问:
MVC: Where to put business logic?
First of all, I have seen many questions of this, but not enough reasoning behind that. If my question is not good enough and should be removed I'll understand.

I have taken a look at, for example, this and a 45+ voted up answer says he advises you to put the business logic in the model, which sounds pretty logical.

However, my first large project I have done with all my BL fully in the controllers, because I didn't question these things and looked how it is done in the AccountController which is the automatically added if you choose MVC with form authentication. All the methods look pretty stuffed with BL. Or maybe it is the least amount of code that was possible to be added and I am overlooking things?

A person on youtube asked me whether he is right by putting all the logic into his models and at first I was no! Then I started thinking that maybe he was right!?

So, after all, where do I put my business logic? If it is in models classes, then, how much code should be considered a healthy amount in a method which is in controller? One line to call some method from the model in a controller at most and then a return to the view?

答:
The general answer I have is that business logic normally fits into two categories:

Object Oriented Business Logic: Gets modeled as objects (in the model), usually injected as repositories.

Procedural Business Logic: Goes in a service with an interface that can be injected into a controller.

Controller Logic: Logic that controls how commands are received and passed to the models/services, then how those results are passed to the view.

Controllers should have no business logic, it's a very specific part of a design pattern for controlling how a user interface passes input off to the models that handle business logic (or services if your problems are more procedural in nature).

Title: MVC: Where to put business logic?


问:
Get a listing of the parts of a gmail with PHP and IMAP
I am trying to get past an attachment and get the text in the body of a gmail.

I have tried:

```<code>$message = imap_qprint(imap_fetchbody($inbox,$email_number,""));
</code>```

And have attempted using several different part #s, but if there is an attachment, even if there is a message in the body, all I get is text that looks like this:

gu1OyQR8H/cpWM3Vnmv2R9O+ymSvBRIImhqaK7EqPaH8GUtxwyfxHhc6JjiM6nmEyMzIJ/jcameckzqQL

I have tried to get all the part #s of the gmail, but I am not sure what the code is for that.

If I knew what the part # is for the body of the email I might be able to retrieve the text of the body

EDIT

Here is the code to access the gmail email:

```<code><?php
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'user';
$password = 'pass';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

$emails = imap_search($inbox,"UNSEEN");

if($emails) {
$output = '';

rsort($emails);

foreach($emails as $email_number) {

$headerInfo = imap_headerinfo($inbox,$email_number);
$structure = imap_fetchstructure($inbox, $email_number);

$overview = imap_fetch_overview($inbox,$email_number,0);

$message = imap_qprint(imap_fetchbody($inbox,$email_number,"1.2"));

$output .= 'Subject: '.$overview[0]->subject.'<br />';
$output .= 'Body: '.$message.'<br />';
$output .= 'From: '.$overview[0]->from.'<br />';
$output .= 'Date: '.$overview[0]->date.'<br />';
$output .= 'CC: '.$headerInfo->ccaddress.'<br />';

$status = imap_setflag_full($inbox, $overview[0]->msgno, "\\Seen \\Flagged");
}

echo $output;
}

imap_close($inbox);
?>
</code>```

And here is the output:

```<code>Subject: Test
Body:
From: Test Acct
Date: Thu, 30 May 2019 11:59:22 -0400
CC:
</code>```

Notice that the Body above is empty, but in the email there is displayed text:

```<code>Dear Valued Partner,

Loan No.23322 has been successfully locked with a Final Price of -.821%. Please see the attached Lock Confirmation for details. You may also pick the document up on EASE. ...
</code>```

However, in the source I see this instead:

```<code>RGVhciBWYWx1ZWQgUGFydG5lciwgPGJyLz4NCg0KPGJyLz4NCkxvYW4gTm8uMTIxOTE4NjIyMSBo
YXMgYmVlbiBzdWNjZXNzZnVsbHkgbG9ja2VkIHdpdGggYSBGaW5hbCBQcmljZSBvZiAtLjgyMSUu
IFBsZWFzZSBzZWUgdGhlIGF0dGFjaGVkIExvY2sgQ29uZmlybWF0aW9uIGZvciBkZXRhaWxzLiBZ
b3UgbW
</code>```

So it appears as if the text in the body of the email is encrypted and has nothing to do with the IMAP code.

If I forward the email to the same email address, when I check that message, this line of code works:

```<code>$message = imap_qprint(imap_fetchbody($inbox,$email_number,"1.2"));
</code>```

because in the source of the forwarded email the text in the body of the email displays normally, without the original encryption

EDIT 2

Adding this line of code did the trick:

```<code> $message1 = imap_base64($message);
</code>```

答:
For anybody who has the same issue, here is the code that works:</p>

```<code><?php
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'user';
$password = 'pass';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

$emails = imap_search($inbox,"UNSEEN");

if($emails) {
$output = '';

rsort($emails);

foreach($emails as $email_number) {

$headerInfo = imap_headerinfo($inbox,$email_number);
$structure = imap_fetchstructure($inbox, $email_number);

    $overview = imap_fetch_overview($inbox,$email_number,0);

    $message = imap_qprint(imap_fetchbody($inbox,$email_number,"1"));

//since the incoming email was encrypted with base64, I insert this line below to decode it, and the above part number, "1", will work. This was the key
$message1 = imap_base64($message);

$output .= 'Subject: '.$overview[0]->subject.'<br />';
$output .= 'Body: '.$message1.'<br />';
$output .= 'From: '.$overview[0]->from.'<br />';
$output .= 'Date: '.$overview[0]->date.'<br />';
$output .= 'CC: '.$headerInfo->ccaddress.'<br />';

$status = imap_setflag_full($inbox, $overview[0]->msgno, "\\Seen \\Flagged");
}

echo $output;
}

/* close the connection */
imap_close($inbox);
?>
</code>```

Body:
I am trying to get past an attachment and get the text in the body of a gmail.

I have tried:

$message = imap_qprint(imap_fetchbody($inbox,$email_number,""));

And have attempted using several different part #s, but if there is an attachment, even if there is a message in the body, all I get is text that looks like this:

gu1OyQR8H/cpWM3Vnmv2R9O+ymSvBRIImhqaK7EqPaH8GUtxwyfxHhc6JjiM6nmEyMzIJ/jcameckzqQL

I have tried to get all the part #s of the gmail, but I am not sure what the code is for that.

If I knew what the part # is for the body of the email I might be able to retrieve the text of the body

EDIT

Here is the code to access the gmail email:

<?php
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'user';
$password = 'pass';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

$emails = imap_search($inbox,"UNSEEN");

if($emails) {
$output = '';

rsort($emails);

foreach($emails as $email_number) {

$headerInfo = imap_headerinfo($inbox,$email_number);
$structure = imap_fetchstructure($inbox, $email_number);

$overview = imap_fetch_overview($inbox,$email_number,0);

$message = imap_qprint(imap_fetchbody($inbox,$email_number,"1.2"));

$output .= 'Subject: '.$overview[0]->subject.'
';
$output .= 'Body: '.$message.'
';
$output .= 'From: '.$overview[0]->from.'
';
$output .= 'Date: '.$overview[0]->date.'
';
$output .= 'CC: '.$headerInfo->ccaddress.'
';

$status = imap_setflag_full($inbox, $overview[0]->msgno, "\\Seen \\Flagged");
}

echo $output;
}

imap_close($inbox);
?>

And here is the output:

Subject: Test
Body:
From: Test Acct
Date: Thu, 30 May 2019 11:59:22 -0400
CC:

Notice that the Body above is empty, but in the email there is displayed text:

Dear Valued Partner,

Loan No.23322 has been successfully locked with a Final Price of -.821%. Please see the attached Lock Confirmation for details. You may also pick the document up on EASE. ...

However, in the source I see this instead:

RGVhciBWYWx1ZWQgUGFydG5lciwgPGJyLz4NCg0KPGJyLz4NCkxvYW4gTm8uMTIxOTE4NjIyMSBo
YXMgYmVlbiBzdWNjZXNzZnVsbHkgbG9ja2VkIHdpdGggYSBGaW5hbCBQcmljZSBvZiAtLjgyMSUu
IFBsZWFzZSBzZWUgdGhlIGF0dGFjaGVkIExvY2sgQ29uZmlybWF0aW9uIGZvciBkZXRhaWxzLiBZ
b3UgbW

So it appears as if the text in the body of the email is encrypted and has nothing to do with the IMAP code.

If I forward the email to the same email address, when I check that message, this line of code works:

$message = imap_qprint(imap_fetchbody($inbox,$email_number,"1.2"));

because in the source of the forwarded email the text in the body of the email displays normally, without the original encryption

EDIT 2

Adding this line of code did the trick:

 $message1 = imap_base64($message);

Body:
For anybody who has the same issue, here is the code that works:

<?php
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'user';
$password = 'pass';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

$emails = imap_search($inbox,"UNSEEN");

if($emails) {
$output = '';

rsort($emails);

foreach($emails as $email_number) {

$headerInfo = imap_headerinfo($inbox,$email_number);
$structure = imap_fetchstructure($inbox, $email_number);

    $overview = imap_fetch_overview($inbox,$email_number,0);

    $message = imap_qprint(imap_fetchbody($inbox,$email_number,"1"));

//since the incoming email was encrypted with base64, I insert this line below to decode it, and the above part number, "1", will work. This was the key
$message1 = imap_base64($message);

$output .= 'Subject: '.$overview[0]->subject.'<br />';
$output .= 'Body: '.$message1.'<br />';
$output .= 'From: '.$overview[0]->from.'<br />';
$output .= 'Date: '.$overview[0]->date.'<br />';
$output .= 'CC: '.$headerInfo->ccaddress.'<br />';

$status = imap_setflag_full($inbox, $overview[0]->msgno, "\\Seen \\Flagged");
}

echo $output;
}

/* close the connection */
imap_close($inbox);
?>


问:
Sample project throwing NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper
I have implemented the project as per https://spring.io/guides/gs/batch-processing/

But i am getting :

Error creating bean with name 'batchConfigurer': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper

I am new to spring-batch
Can anyone please help

答:
2 jars were corrupted , jackson-data bind and log4 .

While mvn clean install error was (invalid LOC header bad signature) in the logs but build was getting successfull hence i missed the logs.

i had to  delete the folder from .m2 and then run mvn clean install this resolved the issue


问:
SSRS using vbcrlf in TextBox to Concatenate field need exclude blank return line
I've created an SSRS report to print per address.

I am using vbcrlf to concatenate multiple fields in one text box.

On some occurrences, one of the fields with in the concatenate might be null.  If this is the case, the line returned creates a blank line within my textbox.

Is there a way to remove the blank line break?

```<code>=Fields!SOP10200_ADDRESS1.Value & vbcrlf & Fields!SOP10200_ADDRESS2.Value & vbcrlf & TRIM(Fields!SOP10200_CITY.Value) & "," & TRIM(Fields!SOP10200_STATE.Value) & " " & TRIM(Fields!SOP10200_ZIPCODE.Value)
</code>```

Expected Results:

4349 Green Ash Dr.
 Earth City,MO 63045

Actual Results:

4349 Green Ash Dr.

                                                                                Earth City,MO 63045

答:
I would add in an IIF statement to check the Address 2 field to make sure it's not NULL or blank. If it is blank or null then have a blank otherwise out in the VBCRLF.

```<code>IIF(ISNOTHING(Fields!SOP10200_ADDRESS2.Value) OR Fields!SOP10200_ADDRESS2.Value = "", "", VBCRLF)
</code>```

So your expression would be

```<code>=Fields!SOP10200_ADDRESS1.Value & vbcrlf &
 Fields!SOP10200_ADDRESS2.Value &
 IIF(ISNOTHING(Fields!SOP10200_ADDRESS2.Value)
      OR Fields!SOP10200_ADDRESS2.Value = "", "", VBCRLF) &
 TRIM(Fields!SOP10200_CITY.Value) & "," &
 TRIM(Fields!SOP10200_STATE.Value) & " " &
 TRIM(Fields!SOP10200_ZIPCODE.Value)
</code>```

Body:
I've created an SSRS report to print per address.

I am using vbcrlf to concatenate multiple fields in one text box.

On some occurrences, one of the fields with in the concatenate might be null.  If this is the case, the line returned creates a blank line within my textbox.

Is there a way to remove the blank line break?

=Fields!SOP10200_ADDRESS1.Value & vbcrlf & Fields!SOP10200_ADDRESS2.Value & vbcrlf & TRIM(Fields!SOP10200_CITY.Value) & "," & TRIM(Fields!SOP10200_STATE.Value) & " " & TRIM(Fields!SOP10200_ZIPCODE.Value)

Expected Results:

4349 Green Ash Dr.
 Earth City,MO 63045

Actual Results:

4349 Green Ash Dr.

                                                                                Earth City,MO 63045

Body:
I would add in an IIF statement to check the Address 2 field to make sure it's not NULL or blank. If it is blank or null then have a blank otherwise out in the VBCRLF.

IIF(ISNOTHING(Fields!SOP10200_ADDRESS2.Value) OR Fields!SOP10200_ADDRESS2.Value = "", "", VBCRLF)

So your expression would be

=Fields!SOP10200_ADDRESS1.Value & vbcrlf &
 Fields!SOP10200_ADDRESS2.Value &
 IIF(ISNOTHING(Fields!SOP10200_ADDRESS2.Value)
      OR Fields!SOP10200_ADDRESS2.Value = "", "", VBCRLF) &
 TRIM(Fields!SOP10200_CITY.Value) & "," &
 TRIM(Fields!SOP10200_STATE.Value) & " " &
 TRIM(Fields!SOP10200_ZIPCODE.Value)


问:
C - scanf value directly from terminal
I have a c process that waits for a scanf() input.

I want to save its results to a *.txt file.
To terminal (linux)

```<code>./process > out.txt
</code>```

What's the way to write in terminal the scanf prehand?

Thanks.

答:
```<code>#include <stdio.h>
int main ()
{
    int i = 0;
    printf("Enter value of i:");
    scanf("%d", &i);
    printf("Value of i = %d\n", i);
    return 0;
}
</code>```

if I want to give dynamic input value of i. how to give it?

in the following code static value is given by echo.

```<code>$ gcc -o exe file.c
$ echo 2 | ./exe
Value of i = 2
</code>```

it should display printf statement in file and from that file I should be able to give input instead of terminal.

Title: C - scanf value directly from terminal

Body:
I have a c process that waits for a scanf() input.

I want to save its results to a *.txt file.
To terminal (linux)

./process > out.txt

What's the way to write in terminal the scanf prehand?

Thanks.

Body:
#include <stdio.h>
int main ()
{
    int i = 0;
    printf("Enter value of i:");
    scanf("%d", &i);
    printf("Value of i = %d\n", i);
    return 0;
}

if I want to give dynamic input value of i. how to give it?

in the following code static value is given by echo.

$ gcc -o exe file.c
$ echo 2 | ./exe
Value of i = 2

it should display printf statement in file and from that file I should be able to give input instead of terminal.


问:
How to select from a database using getter and setter methods in PHP
I need to select/insert data from/to database using getter and setter methods. What I'm trying to achieve for now is to select everything from the db and echo it out in html, to see if I'm receiving anything at all.

This the code so far:

class Products extends DbConnect {

    protected $id;
    protected $sku;
    protected $name;
    protected $price;
    protected $type;
    protected $attributes;

    public function select() {
        $query = "SELECT * FROM products";
        $result = $this->connect()->query($query);

        $row = $result->fetch(PDO::FETCH_ASSOC);
        $this->id = $row['Id'];
        $this->sku = $row['SKU'];
        $this->name = $row['Name'];
        $this->price = $row['Price'];
        $this->type = $row['Type'];
        $this->attributes = $row['Attributes'];
    }

    public function getId() {
        return $this->id;
    }

    public function getSKU() {
        return $this->sku;
    }

    public function getName() {
        return $this->name;
    }

    public function getPrice() {
        return $this->price;
    }

    public function getType() {
        return $this->type;
    }

    public function getAttributes() {
        return $this->attributes;
    }

}
```

<p>I'm not sure what I have to do next. I tried to see if I get any data like this:</p>

<pre class="lang-php prettyprint-override"><code>public function __construct($name) {
        $this->name = $name;
    }

$product = new Products();
echo $product->name;
</code>```

It tells me I'm not passing any arguments. Do I have to do something else with the selected data before I print it out? I'm completely new to this approach and I'm not really sure what to do.

答:
Your constructor needs to be in the class

```<code>class Products extends DbConnect {

    protected $id;
    protected $sku;
    protected $name;
    protected $price;
    protected $type;
    protected $attributes;

    public function __construct($name) {
        $this->name = $name;
    }

    public function select() {
        $query = "SELECT * FROM products";
        $result = $this->connect()->query($query);

        $row = $result->fetch(PDO::FETCH_ASSOC);
        $this->id = $row['Id'];
        $this->sku = $row['SKU'];
        $this->name = $row['Name'];
        $this->price = $row['Price'];
        $this->type = $row['Type'];
        $this->attributes = $row['Attributes'];
    }

    public function getId() {
        return $this->id;
    }

    public function getSKU() {
        return $this->sku;
    }

    public function getName() {
        return $this->name;
    }

    public function getPrice() {
        return $this->price;
    }

    public function getType() {
        return $this->type;
    }

    public function getAttributes() {
        return $this->attributes;
    }

}
</code>```

Then you pass the parameters when you define the new class

```<code>$product = new Products("Product Name");
echo $product->name;
</code>```

One thing I would suggest would be to change the constructor to accept an array that way you can pass any number of parameters across and order doesn't matter.

```<code>public function __construct(array $config = []) {
  $this->name = $config["name"];
  $this->id = $config["id"];
}
</code>```

And then you can send any number of arguments through like this

```<code>$options = [
  "name" => "ProductName",
  "id" => "ProductID"
];

$product = new Products($options);
echo "Name: ".$product->name;
echo "ID: ".$product->id;
</code>```

Body:
I need to select/insert data from/to database using getter and setter methods. What I'm trying to achieve for now is to select everything from the db and echo it out in html, to see if I'm receiving anything at all.

This the code so far:

class Products extends DbConnect {

    protected $id;
    protected $sku;
    protected $name;
    protected $price;
    protected $type;
    protected $attributes;

    public function select() {
        $query = "SELECT * FROM products";
        $result = $this->connect()->query($query);

        $row = $result->fetch(PDO::FETCH_ASSOC);
        $this->id = $row['Id'];
        $this->sku = $row['SKU'];
        $this->name = $row['Name'];
        $this->price = $row['Price'];
        $this->type = $row['Type'];
        $this->attributes = $row['Attributes'];
    }

    public function getId() {
        return $this->id;
    }

    public function getSKU() {
        return $this->sku;
    }

    public function getName() {
        return $this->name;
    }

    public function getPrice() {
        return $this->price;
    }

    public function getType() {
        return $this->type;
    }

    public function getAttributes() {
        return $this->attributes;
    }

}

I'm not sure what I have to do next. I tried to see if I get any data like this:

public function __construct($name) {
        $this->name = $name;
    }

$product = new Products();
echo $product->name;

It tells me I'm not passing any arguments. Do I have to do something else with the selected data before I print it out? I'm completely new to this approach and I'm not really sure what to do.

Body:
Your constructor needs to be in the class

class Products extends DbConnect {

    protected $id;
    protected $sku;
    protected $name;
    protected $price;
    protected $type;
    protected $attributes;

    public function __construct($name) {
        $this->name = $name;
    }

    public function select() {
        $query = "SELECT * FROM products";
        $result = $this->connect()->query($query);

        $row = $result->fetch(PDO::FETCH_ASSOC);
        $this->id = $row['Id'];
        $this->sku = $row['SKU'];
        $this->name = $row['Name'];
        $this->price = $row['Price'];
        $this->type = $row['Type'];
        $this->attributes = $row['Attributes'];
    }

    public function getId() {
        return $this->id;
    }

    public function getSKU() {
        return $this->sku;
    }

    public function getName() {
        return $this->name;
    }

    public function getPrice() {
        return $this->price;
    }

    public function getType() {
        return $this->type;
    }

    public function getAttributes() {
        return $this->attributes;
    }

}

Then you pass the parameters when you define the new class

$product = new Products("Product Name");
echo $product->name;

One thing I would suggest would be to change the constructor to accept an array that way you can pass any number of parameters across and order doesn't matter.

public function __construct(array $config = []) {
  $this->name = $config["name"];
  $this->id = $config["id"];
}

And then you can send any number of arguments through like this

$options = [
  "name" => "ProductName",
  "id" => "ProductID"
];

$product = new Products($options);
echo "Name: ".$product->name;
echo "ID: ".$product->id;