问:
How to create a cross dissolve animation when switching between tabs
How can a simple cross dissolve animation be written in the tab controller class that performs when switching between tabs.

Here is an example of the app showing this kind of animation.

I am fairly new to custom transition animations I understand that it has to go within didSelect

```<code>override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

}
</code>```

UPDATE

There seems to be some confusion on my part:

I've created a new Swift File called TabBarClass.swift

Inside of I added the following code:

```<code>    class MyFadeTransition: NSObject, UIViewControllerAnimatedTransitioning {
        func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
            if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
                toVC.view.frame = fromVC.view.frame
                toVC.view.alpha = 0
                fromVC.view.alpha = 1
                transitionContext.containerView.addSubview(fromVC.view)
                transitionContext.containerView.addSubview(toVC.view)

                UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                    toVC.view.alpha = 1
                }) { (finished) in
                    transitionContext.completeTransition(finished)
                }
            }
        }

        func animationEnded(_ transitionCompleted: Bool) {
            // no-op
        }

        func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
            return 0.3
        }
    }

**And in the AppDelegate I added:**

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
            let fade = MyFadeTransition()
            return fade
        }

What is the issue?
</code>```

UPDATE 2

This is how my AppDelegate is written:

```<code>import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var tabBarController: UITabBarController!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let tab = window!.rootViewController as! UITabBarController
        tab.delegate = self

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}
extension AppDelegate: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let fade = MyFadeTransition()

        return fade
    }
}
</code>```

答:
Make use of the UITabBarControllerDelegate method:

```<code>func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
</code>```

The bulk of the work is in the class that conforms to UIViewControllerAnimatedTransitioning.

Here is an implementation that crossfades the two controllers.

MyFadeTransition.swift:

```<code>import UIKit

class MyFadeTransition: NSObject, UIViewControllerAnimatedTransitioning {
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
            toVC.view.frame = fromVC.view.frame
            toVC.view.alpha = 0
            fromVC.view.alpha = 1
            transitionContext.containerView.addSubview(fromVC.view)
            transitionContext.containerView.addSubview(toVC.view)

            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toVC.view.alpha = 1
            }) { (finished) in
                transitionContext.completeTransition(finished)
            }
        }
    }

    func animationEnded(_ transitionCompleted: Bool) {
        // no-op
    }

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
}
</code>```

Something in your code needs to be the tab bar controller's delegate. Set that and then implement the delegate method in that class.

```<code>func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let fade = MyFadeTransition()
    return fade
}
</code>```

Note that this same MyFadeTransition class can be used with a UINavigationController. The UINavigationControllerDelegate has the same basic method so you can reuse the transition class for both tab bar controllers and nav controllers.

Assuming that your tab bar controller is your app's root view controller, you can add the following code to the didFinishLaunchingWithOptions of your AppDelegate:

```<code>let tab = window!.rootViewController as! UITabBarController
tab.delegate = self
</code>```

Then add:

```<code>extension AppDelegate: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let fade = MyFadeTransition()

        return fade
    }
}
</code>```

to AppDelegate.swift.

Body:
How can a simple cross dissolve animation be written in the tab controller class that performs when switching between tabs.

Here is an example of the app showing this kind of animation.

I am fairly new to custom transition animations I understand that it has to go within didSelect

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

}

UPDATE

There seems to be some confusion on my part:

I've created a new Swift File called TabBarClass.swift

Inside of I added the following code:

    class MyFadeTransition: NSObject, UIViewControllerAnimatedTransitioning {
        func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
            if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
                toVC.view.frame = fromVC.view.frame
                toVC.view.alpha = 0
                fromVC.view.alpha = 1
                transitionContext.containerView.addSubview(fromVC.view)
                transitionContext.containerView.addSubview(toVC.view)

                UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                    toVC.view.alpha = 1
                }) { (finished) in
                    transitionContext.completeTransition(finished)
                }
            }
        }

        func animationEnded(_ transitionCompleted: Bool) {
            // no-op
        }

        func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
            return 0.3
        }
    }

**And in the AppDelegate I added:**

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
            let fade = MyFadeTransition()
            return fade
        }

What is the issue?

UPDATE 2

This is how my AppDelegate is written:

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var tabBarController: UITabBarController!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let tab = window!.rootViewController as! UITabBarController
        tab.delegate = self

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}
extension AppDelegate: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let fade = MyFadeTransition()

        return fade
    }
}

Body:
Make use of the UITabBarControllerDelegate method:

func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?

The bulk of the work is in the class that conforms to UIViewControllerAnimatedTransitioning.

Here is an implementation that crossfades the two controllers.

MyFadeTransition.swift:

import UIKit

class MyFadeTransition: NSObject, UIViewControllerAnimatedTransitioning {
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
            toVC.view.frame = fromVC.view.frame
            toVC.view.alpha = 0
            fromVC.view.alpha = 1
            transitionContext.containerView.addSubview(fromVC.view)
            transitionContext.containerView.addSubview(toVC.view)

            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toVC.view.alpha = 1
            }) { (finished) in
                transitionContext.completeTransition(finished)
            }
        }
    }

    func animationEnded(_ transitionCompleted: Bool) {
        // no-op
    }

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
}

Something in your code needs to be the tab bar controller's delegate. Set that and then implement the delegate method in that class.

func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let fade = MyFadeTransition()
    return fade
}

Note that this same MyFadeTransition class can be used with a UINavigationController. The UINavigationControllerDelegate has the same basic method so you can reuse the transition class for both tab bar controllers and nav controllers.

Assuming that your tab bar controller is your app's root view controller, you can add the following code to the didFinishLaunchingWithOptions of your AppDelegate:

let tab = window!.rootViewController as! UITabBarController
tab.delegate = self

Then add:

extension AppDelegate: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let fade = MyFadeTransition()

        return fade
    }
}

to AppDelegate.swift.


来源: stackexchange

问:
Best practice regarding dependencies
Which is the best practice while saving package.json dependencies?

For example, i see that lot's of dependencies are not fixed, like:

```<code>  "tslint": "~5.11.0"
</code>```

I would like to have fixed dependencies, so that will not change in the future when new developers join a team.

I have little knowledge about package-lock.json and shrinkwrap, but I'm not sure about the "best practice" on this.
On this case is an Angular app, but it can be everything. Keeping for example package-lock.json on the repo caused some issues in the past (i know! it is a best practice to push it!)

Any thoughts?

答:
Short answer: Carets (^) and committing your package-lock.json is probably your best approach. This ensures developers always get the same dependencies, and is the least surprising.

Why package-lock.json?

npm specifically recommends you commit your package-lock.json.

It is highly recommended you commit the generated package lock to source control: this will allow anyone else on your team, your deployments, your CI/continuous integration, and anyone else who runs npm install in your package source to get the exact same dependency tree that you were developing on.

(from the npm documentation)

You mentioned pushing package-lock.json to your repository caused some issues in the past. I'm guessing this was due to this issue where the package lock was being ignored and rewritten every time anyone installed anything. This was not the correct behaviour and was fixed in npm@5.4.2, according to this answer.

What you should not do is leave out the package-lock.json and just specify exact versions in your package.json. If you do this, your top level dependencies will look nice and consistent, but their dependencies won't have locked down versions. This way, you're almost as likely to run into bugs, but they'll be harder to find.

Why not npm-shrinkwrap.json?

You also mention shrinkwrap files. Shrinkwrap files are meant for

applications deployed through the publishing process on the registry

(from the npm documentation)

You probably aren't npm publishing your angular webapp, so there's no reason to use npm-shrinkwrap.json.

Why use caret ranges?

I can't find any documentation saying caret (^) ranges are best practice, but I believe they are.

npm makes caret ranges the default option, so it's clear they think this is best practice, though I can't find any of their documentation to justify it.

Using the default is the least surprising approach. If I saw any other kind of version in a package.json, I'd assume it was changed for a good reason, and would be hesitant to update the package without knowing what that reason is, even if it really needed to be updated.

If you ever decide to update all your dependencies at once, caret ranges will serve you well. You're dependencies will normally be locked, but deleting your package-lock.json and rerunning npm install will automatically install the latest versions that are supposedly backwards compatible with the versions you specified (see the npm docs for details on the caret range).

In summary, it's standard to use caret ranges and a package-lock.json. This fulfills your requirement of fixed dependencies, and provides a few other benefits, so it's best to do what's standard, unless you find another reason to change.

ContentLicense: CC BY-SA 4.0

Title: Best practice regarding dependencies

Body:
Which is the best practice while saving package.json dependencies?

For example, i see that lot's of dependencies are not fixed, like:

  "tslint": "~5.11.0"

I would like to have fixed dependencies, so that will not change in the future when new developers join a team.

I have little knowledge about package-lock.json and shrinkwrap, but I'm not sure about the "best practice" on this.
On this case is an Angular app, but it can be everything. Keeping for example package-lock.json on the repo caused some issues in the past (i know! it is a best practice to push it!)

Any thoughts?


问:
Sticky element to top on scroll
I am trying to make my div appear at the top when the user scrolls down the page, and once the user scrolls to the top, the element should not overlap the nav bar.

I am struggling to implement this, so help would be appreciated. This is what I have tried:

```<code> <div id="floating-sidebar-sticky-wrapper" class="floating-sidebar-wrap" style="height: 696px;">
 <div id="floating-sidebar"></div>
</div>

 <script>
    $(window).on('load',function(){
      $("#floating-sidebar").sticky({ topSpacing: 0, wrapperClassName: "floating-sidebar-wrap" });
    });
  </script>
</code>```

答:
I tried this in Chrome. Provide the top value as your Nav bar height so it will be always below the Nav bar when user will scroll up to the top. </p>

```<code>position: sticky;
top: 100px;---Replace 100 with your Nav bar height
z-index: 99;
</code>```

Title: Sticky element to top on scroll

Body:
I tried this in Chrome. Provide the top value as your Nav bar height so it will be always below the Nav bar when user will scroll up to the top.

position: sticky;
top: 100px;---Replace 100 with your Nav bar height
z-index: 99;


问:
select rows and columns from all tables that have a column whose name begins with "TEST"
I have multiple tables containing varying numbers of columns whose name begins with TEST:

Here is an example of what I would like to see if I were to execute the code:

```<code>TEST2UFLG TEST3UFLG TEST4UFLG TEST5UFLG TEST6UFLG
--------- --------- --------- --------- ---------
0         1         0         1         0
... (rows elided)
0         1         0         1         0
</code>```

This is the query that I have that returns the meta data that I would use to construct a query for each table that contains such columns.

```<code>select
  (
    select
      to_char(wm_concat(column_name))
    from
      dba_tab_columns
    where
      owner = 'XXX'
      and table_name = 'TBLXXXX'
      and column_name like '%TEST%'
  )
from
  XXX.TBLXXXX
</code>```

What I don't know is how to write the code that would use these data to generate the select statement (or statements) that would then be executed to return the rows I want.

答:
One option is to create  a dynamic view

```<code>DECLARE
     v_select   CLOB;
BEGIN
     SELECT
          'SELECT '||LISTAGG(column_name,',')
              WITHIN GROUP (ORDER BY column_id) ||' FROM ' || table_name
         INTO v_select
     FROM all_tab_columns
        where owner = 'XXX'
         and table_name = 'TBLXXXX'
      and column_name like '%TEST%'
      group by table_name;
     IF
          v_select IS NOT NULL
     THEN
          EXECUTE IMMEDIATE 'CREATE OR REPLACE VIEW v_testtbl as ' || v_select;
     END IF;
END;
/
</code>```

DEMO

Body:
I have multiple tables containing varying numbers of columns whose name begins with TEST:

Here is an example of what I would like to see if I were to execute the code:

TEST2UFLG TEST3UFLG TEST4UFLG TEST5UFLG TEST6UFLG
--------- --------- --------- --------- ---------
0         1         0         1         0
... (rows elided)
0         1         0         1         0

This is the query that I have that returns the meta data that I would use to construct a query for each table that contains such columns.

select
  (
    select
      to_char(wm_concat(column_name))
    from
      dba_tab_columns
    where
      owner = 'XXX'
      and table_name = 'TBLXXXX'
      and column_name like '%TEST%'
  )
from
  XXX.TBLXXXX

What I don't know is how to write the code that would use these data to generate the select statement (or statements) that would then be executed to return the rows I want.

Body:
One option is to create  a dynamic view

DECLARE
     v_select   CLOB;
BEGIN
     SELECT
          'SELECT '||LISTAGG(column_name,',')
              WITHIN GROUP (ORDER BY column_id) ||' FROM ' || table_name
         INTO v_select
     FROM all_tab_columns
        where owner = 'XXX'
         and table_name = 'TBLXXXX'
      and column_name like '%TEST%'
      group by table_name;
     IF
          v_select IS NOT NULL
     THEN
          EXECUTE IMMEDIATE 'CREATE OR REPLACE VIEW v_testtbl as ' || v_select;
     END IF;
END;
/

DEMO


问:
Add an empty series on an Excel chart
I'm trying to add many series to a chart using VBA, as in the code below.

```<code>For i = 0 To 9
    Set serNew = chtMap.SeriesCollection.NewSeries
    With serNew
        .XValues = Range("Y4").Cells(1, 1 + 2 * i).Resize(32000, 1)
        .Values = Range("Y4").Cells(1, 2 + 2 * i).Resize(32000, 1)
    End With
Next i
</code>```

The ranges for some of the series have no data in their cells yet; the user will write/load this data later. The idea is to have the chart ready for when they do.

Problem: when the loop hits such a yet empty range, I get an error 1004: Unable to set XValues property of the Series class. Why and is there a way around this?

The weird thing is that doing this manually in Chart menu --> |Source Data... works perfectly fine. Actually, if you record a macro while doing this manually, the result is as follows:

```<code>ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(4).XValues = "=Sheet2!R4C31:R32003C31"
ActiveChart.SeriesCollection(4).Values = "=Sheet2!R4C32:R32003C32"
</code>```

but then Excel gives an error when re-playing this macro!

Doing this manually is not a pleasant prospect. I guess I could stick sham data in the cells, create the series, and then delete the sham data. Do I really have to pull such a bait and switch on Excel?

答:
You could try to copy the range (both columns), and use paste special to add it to the chart:</p>

```<code>TwoColumnRange.Copy
chtMap.SeriesCollection.Paste Rowcol:=xlColumns, SeriesLabels:=False, _
    CategoryLabels:=True, Replace:=False, NewSeries:=True
</code>```

ContentLicense: CC BY-SA 2.5

Title: Add an empty series on an Excel chart

Body:
I'm trying to add many series to a chart using VBA, as in the code below.

For i = 0 To 9
    Set serNew = chtMap.SeriesCollection.NewSeries
    With serNew
        .XValues = Range("Y4").Cells(1, 1 + 2 * i).Resize(32000, 1)
        .Values = Range("Y4").Cells(1, 2 + 2 * i).Resize(32000, 1)
    End With
Next i

The ranges for some of the series have no data in their cells yet; the user will write/load this data later. The idea is to have the chart ready for when they do.

Problem: when the loop hits such a yet empty range, I get an error 1004: Unable to set XValues property of the Series class. Why and is there a way around this?

The weird thing is that doing this manually in Chart menu --> |Source Data... works perfectly fine. Actually, if you record a macro while doing this manually, the result is as follows:

ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(4).XValues = "=Sheet2!R4C31:R32003C31"
ActiveChart.SeriesCollection(4).Values = "=Sheet2!R4C32:R32003C32"

but then Excel gives an error when re-playing this macro!

Doing this manually is not a pleasant prospect. I guess I could stick sham data in the cells, create the series, and then delete the sham data. Do I really have to pull such a bait and switch on Excel?

Body:
You could try to copy the range (both columns), and use paste special to add it to the chart:

TwoColumnRange.Copy
chtMap.SeriesCollection.Paste Rowcol:=xlColumns, SeriesLabels:=False, _
    CategoryLabels:=True, Replace:=False, NewSeries:=True

ContentLicense: CC BY-SA 3.0


问:
The class implementing ApplicationListener interface doesn't fire up when I create the event
I am trying to make account validation via email. I created an event class called OnRegistrationSuccessEvent that represents the event of a success registration.
I created a listener to handle this event called RegistrationEmailListener .
This is the code for the two classes:

OnRegistrationSuccessEvent class.

```<code>public class OnRegistrationSuccessEvent extends ApplicationEvent {

    private String appUrl;

    private User user;

    public OnRegistrationSuccessEvent(User user, String appUrl) {
        super(user);
        this.user = user;
        this.appUrl = appUrl;
    }

    // gettes and setters
}
</code>```

RegistrationEmailListener class.

```<code>@Component
public class RegistrationEmailListener implements ApplicationListener<OnRegistrationSuccessEvent> {

    @Autowired
    private IUserService userService;

    @Autowired
    private MailSender mailSender;

    private static Logger logger = Logger.getLogger(RegistrationEmailListener.class.getName());

    public void onApplicationEvent(OnRegistrationSuccessEvent event) {

        logger.info("The rehistraton success event is fired up.");

        try {

            this.confirmRegistration(event);

        } catch (SendingEmailFailureException e) {

            logger.log(Level.SEVERE, e.getMessage(), e);
        }
    }

    private void confirmRegistration(OnRegistrationSuccessEvent event) throws SendingEmailFailureException {

        User user = event.getUser();

        String token = UUID.randomUUID().toString();

        userService.createVerficationToken(user, token);

        String recipent = user.getEmail();

        String subject = "Registration confirmation";

        String url = event.getAppUrl() + "/confirmRegistration?token=" + token;

        String message = "Thank you for regestring in our Tourists web app. Please click on the link below to complete your registration: ";

        SimpleMailMessage email = new SimpleMailMessage();

        email.setTo(recipent);

        email.setSubject(subject);

        email.setText(message + "http://localhost:8080" + url);

        mailSender.send(email);

        logger.info("Registration >>> Activation email is sent");
        logger.info("Recipient >>> " + recipent);
        logger.info("Text >>> " + email.getText());
    }
}
</code>```

And I have a cntroller so I can test things out. with the following get request:

```<code>@GetMapping("/register")
    public String registerNewUser(WebRequest request) {

        User user = new User("bilal", "basiliusmourk@gmail.com", passwordEncoder.encode("bilal"), new Date());

        try {

            user.addAuthoriry(authorityService.getAuthority(AuthorityType.ROLE_TOURIST));

        } catch (EntityNotFoundException e) {

            logger.info(e.getMessage());
        }

        try {

            userService.registerNewUserAccount(user);

        } catch (UsernameAlreadyExistsException e) {

            logger.info(e.getMessage());

        } catch (EmailAlreadyExistsException e) {

            logger.info(e.getMessage());
        }

        String appUrl = request.getContextPath();

        logger.info("app url >>> " + appUrl);
        logger.info("publishing OnRegistrationSuccessEvent");

        eventPublisher.publishEvent(new OnRegistrationSuccessEvent(user, appUrl));

        //autoAuthentication(context, user.getUsername(), "bilal");

        logger.info("registration process completed for: " + user.getUsername());

        return "registrationSuccess";
    }
</code>```

I made sure that the OnRegistrationSuccessEvent is really created. The problem is the listener has no idea that the event is launched, and I am not sure why. if anybody ca help i will be thankful.

Edit:
and that what my beans in the configuration class look like:

```<code>@Bean(name = "mailSender")
    public MailSender javaMailService() {

        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

        javaMailSender.setHost("smtp.gmail.com");
        javaMailSender.setPort(587);
        javaMailSender.setProtocol("smtp");
        javaMailSender.setUsername("myEmail");
        javaMailSender.setPassword("myPassword");

        Properties mailProperties = new Properties();

        mailProperties.put("mail.smtp.auth", true);
        mailProperties.put("mail.smtp.starttls.enable", true);
        mailProperties.put("mail.smtp.debug", true);
        javaMailSender.setJavaMailProperties(mailProperties);

        return javaMailSender;
    }

    @Bean
    public MessageSource messageSource() {

        final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();

        messageSource.setBasename("classpath:messages");
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(0);

        return messageSource;
    }
</code>```

logs:

```<code>Hibernate: insert into user_authority (user_id, authority_id) values (?, ?)
2019-05-29 04:03:54 DEBUG AbstractCollectionPersister:384 - Done inserting collection: 1 rows inserted
2019-05-29 04:03:54 DEBUG JdbcCoordinatorImpl:183 - HHH000420: Closing un-released batch
2019-05-29 04:03:54 DEBUG ThreadPoolAsynchronousRunner:236 - com.mchange.v2.async.ThreadPoolAsynchronousRunner@78ae34f7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@1f15b10c
2019-05-29 04:03:54 DEBUG BasicResourcePool:1801 - trace com.mchange.v2.resourcepool.BasicResourcePool@23b62cc3 [managed: 5, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@63544e3b)
2019-05-29 04:03:54 INFO  Class:98 - app url >>> /pfa-web-v2
2019-05-29 04:03:54 INFO  Class:99 - publishing OnRegistrationSuccessEvent
2019-05-29 04:03:54 INFO  Class:105 - registration process completed for: bilal
2019-05-29 04:03:57 DEBUG ThreadPoolAsynchronousRunner:778 - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@692fae76 -- Running DeadlockDetector[Exiting. No pending tasks.]
2019-05-29 04:04:07 DEBUG ThreadPoolAsynchronousRunner:778 - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@692fae76 -- Running DeadlockDetector[Exiting. No pending tasks.]
</code>```

答:
It works for me and couldn't find any problem with event listeners.
Double check your configuration and ensure event is getting triggered.

@SpringBootApplication
@RestController
public class Application {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @GetMapping("/register")
    public String registerNewUser() {

        eventPublisher.publishEvent(new OnRegistrationSuccessEvent(new User(), "http://localhost"));
        return "success";
    }

    @PostConstruct
    public void init() {
        eventPublisher.publishEvent(new OnRegistrationSuccessEvent(new User(), "http://localhost"));
    }

}

class OnRegistrationSuccessEvent extends ApplicationEvent {

    private String appUrl;

    private User user;

    public OnRegistrationSuccessEvent(User user, String appUrl) {
        super(user);
        this.user = user;
        this.appUrl = appUrl;
    }

}

@Component
class RegistrationEmailListener implements ApplicationListener<OnRegistrationSuccessEvent> {

    public void onApplicationEvent(OnRegistrationSuccessEvent event) {
          System.out.println("confirmed");

    }

}

class User{

    private String userName;
}
```

<p>logs:</p>

```2019-05-29 09:01:59.259  INFO 62832 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-29 09:01:59.525  INFO 62832 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-05-29 09:01:59.529  INFO 62832 --- [  restartedMain] com.barath.app.Application               : Started Application in 2.904 seconds (JVM running for 3.815)
2019-05-29 09:02:07.341  INFO 62832 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-05-29 09:02:07.341  INFO 62832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-05-29 09:02:07.349  INFO 62832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
confirmed
```

Body:
I am trying to make account validation via email. I created an event class called OnRegistrationSuccessEvent that represents the event of a success registration.
I created a listener to handle this event called RegistrationEmailListener .
This is the code for the two classes:

OnRegistrationSuccessEvent class.

public class OnRegistrationSuccessEvent extends ApplicationEvent {

    private String appUrl;

    private User user;

    public OnRegistrationSuccessEvent(User user, String appUrl) {
        super(user);
        this.user = user;
        this.appUrl = appUrl;
    }

    // gettes and setters
}

RegistrationEmailListener class.

@Component
public class RegistrationEmailListener implements ApplicationListener<OnRegistrationSuccessEvent> {

    @Autowired
    private IUserService userService;

    @Autowired
    private MailSender mailSender;

    private static Logger logger = Logger.getLogger(RegistrationEmailListener.class.getName());

    public void onApplicationEvent(OnRegistrationSuccessEvent event) {

        logger.info("The rehistraton success event is fired up.");

        try {

            this.confirmRegistration(event);

        } catch (SendingEmailFailureException e) {

            logger.log(Level.SEVERE, e.getMessage(), e);
        }
    }

    private void confirmRegistration(OnRegistrationSuccessEvent event) throws SendingEmailFailureException {

        User user = event.getUser();

        String token = UUID.randomUUID().toString();

        userService.createVerficationToken(user, token);

        String recipent = user.getEmail();

        String subject = "Registration confirmation";

        String url = event.getAppUrl() + "/confirmRegistration?token=" + token;

        String message = "Thank you for regestring in our Tourists web app. Please click on the link below to complete your registration: ";

        SimpleMailMessage email = new SimpleMailMessage();

        email.setTo(recipent);

        email.setSubject(subject);

        email.setText(message + "http://localhost:8080" + url);

        mailSender.send(email);

        logger.info("Registration >>> Activation email is sent");
        logger.info("Recipient >>> " + recipent);
        logger.info("Text >>> " + email.getText());
    }
}

And I have a cntroller so I can test things out. with the following get request:

@GetMapping("/register")
    public String registerNewUser(WebRequest request) {

        User user = new User("bilal", "basiliusmourk@gmail.com", passwordEncoder.encode("bilal"), new Date());

        try {

            user.addAuthoriry(authorityService.getAuthority(AuthorityType.ROLE_TOURIST));

        } catch (EntityNotFoundException e) {

            logger.info(e.getMessage());
        }

        try {

            userService.registerNewUserAccount(user);

        } catch (UsernameAlreadyExistsException e) {

            logger.info(e.getMessage());

        } catch (EmailAlreadyExistsException e) {

            logger.info(e.getMessage());
        }

        String appUrl = request.getContextPath();

        logger.info("app url >>> " + appUrl);
        logger.info("publishing OnRegistrationSuccessEvent");

        eventPublisher.publishEvent(new OnRegistrationSuccessEvent(user, appUrl));

        //autoAuthentication(context, user.getUsername(), "bilal");

        logger.info("registration process completed for: " + user.getUsername());

        return "registrationSuccess";
    }

I made sure that the OnRegistrationSuccessEvent is really created. The problem is the listener has no idea that the event is launched, and I am not sure why. if anybody ca help i will be thankful.

Edit:
and that what my beans in the configuration class look like:

@Bean(name = "mailSender")
    public MailSender javaMailService() {

        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

        javaMailSender.setHost("smtp.gmail.com");
        javaMailSender.setPort(587);
        javaMailSender.setProtocol("smtp");
        javaMailSender.setUsername("myEmail");
        javaMailSender.setPassword("myPassword");

        Properties mailProperties = new Properties();

        mailProperties.put("mail.smtp.auth", true);
        mailProperties.put("mail.smtp.starttls.enable", true);
        mailProperties.put("mail.smtp.debug", true);
        javaMailSender.setJavaMailProperties(mailProperties);

        return javaMailSender;
    }

    @Bean
    public MessageSource messageSource() {

        final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();

        messageSource.setBasename("classpath:messages");
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(0);

        return messageSource;
    }

logs:

Hibernate: insert into user_authority (user_id, authority_id) values (?, ?)
2019-05-29 04:03:54 DEBUG AbstractCollectionPersister:384 - Done inserting collection: 1 rows inserted
2019-05-29 04:03:54 DEBUG JdbcCoordinatorImpl:183 - HHH000420: Closing un-released batch
2019-05-29 04:03:54 DEBUG ThreadPoolAsynchronousRunner:236 - com.mchange.v2.async.ThreadPoolAsynchronousRunner@78ae34f7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@1f15b10c
2019-05-29 04:03:54 DEBUG BasicResourcePool:1801 - trace com.mchange.v2.resourcepool.BasicResourcePool@23b62cc3 [managed: 5, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@63544e3b)
2019-05-29 04:03:54 INFO  Class:98 - app url >>> /pfa-web-v2
2019-05-29 04:03:54 INFO  Class:99 - publishing OnRegistrationSuccessEvent
2019-05-29 04:03:54 INFO  Class:105 - registration process completed for: bilal
2019-05-29 04:03:57 DEBUG ThreadPoolAsynchronousRunner:778 - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@692fae76 -- Running DeadlockDetector[Exiting. No pending tasks.]
2019-05-29 04:04:07 DEBUG ThreadPoolAsynchronousRunner:778 - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@692fae76 -- Running DeadlockDetector[Exiting. No pending tasks.]

Body:
It works for me and couldn't find any problem with event listeners.
Double check your configuration and ensure event is getting triggered.

@SpringBootApplication
@RestController
public class Application {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @GetMapping("/register")
    public String registerNewUser() {

        eventPublisher.publishEvent(new OnRegistrationSuccessEvent(new User(), "http://localhost"));
        return "success";
    }

    @PostConstruct
    public void init() {
        eventPublisher.publishEvent(new OnRegistrationSuccessEvent(new User(), "http://localhost"));
    }

}

class OnRegistrationSuccessEvent extends ApplicationEvent {

    private String appUrl;

    private User user;

    public OnRegistrationSuccessEvent(User user, String appUrl) {
        super(user);
        this.user = user;
        this.appUrl = appUrl;
    }

}

@Component
class RegistrationEmailListener implements ApplicationListener<OnRegistrationSuccessEvent> {

    public void onApplicationEvent(OnRegistrationSuccessEvent event) {
          System.out.println("confirmed");

    }

}

class User{

    private String userName;
}

logs:

2019-05-29 09:01:59.259  INFO 62832 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-29 09:01:59.525  INFO 62832 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-05-29 09:01:59.529  INFO 62832 --- [  restartedMain] com.barath.app.Application               : Started Application in 2.904 seconds (JVM running for 3.815)
2019-05-29 09:02:07.341  INFO 62832 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-05-29 09:02:07.341  INFO 62832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-05-29 09:02:07.349  INFO 62832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
confirmed


问:
How to read first few records of a json file using R?
I have a HUGE json.gz file and the file is already converted to .json file. I would like ask how we can read, say, the first 100 records from the .json file using R. Any help is greatly appreciated. The following is just sample code:

```<code>library(jsonlite)
library(R.utils)
r=stream_in(file("yelp_academic_dataset_business.json"))
</code>```

The file "yelp_academic_dataset_business.json" can be found from the link:
https://www.dropbox.com/s/gd1k41y9gbpfwq3/yelp_academic_dataset_business.json

答:
Using the data from your original link, @Shree's suggestion is spot-on. First, use readLines to download only as many lines as you need:

dat <- readLines("https://uc385e5985dd32823a7dc6ba9b5e.dl.dropboxusercontent.com/cd/0/get/AhyCjVEm8yKnLz4w0-hZaW-titb8fOhQdMcwhTMF1_3i_iJ7DOqOU_KQRTtcvaFBaSTpAznh_6eq-vKAEiDkeVygMnRjThrnz0V5fyC4AURAcg/file?_download_id=9916801659220323334123287637995650900165723151388885263767035946&_notify_domain=www.dropbox.com&dl=1", n =4 )
# dat <- readLines("yelp_academic_dataset_business.json", n = 4)
```

<p>Now create a "fake text connection" and pass this to the json parser:</p>

<pre class="lang-r prettyprint-override"><code>jsonlite::stream_in(textConnection(dat))
#  Imported 4 records. Simplifying...
#              business_id                                        full_address hours.Tuesday.close hours.Tuesday.open hours.Friday.close hours.Friday.open hours.Monday.close hours.Monday.open
# 1 vcNAWiLM4dR7D2nwwJ7nCA 4840 E Indian School Rd\nSte 101\nPhoenix, AZ 85018               17:00              08:00              17:00             08:00              17:00             08:00
# 2 UsFtqoBl7naz8AVUBZMjQQ                202 McClure St\nDravosburg, PA 15034                <NA>               <NA>               <NA>              <NA>               <NA>              <NA>
# 3 cE27W9VPgO88Qxe4ol6y_g             1530 Hamilton Rd\nBethel Park, PA 15234                <NA>               <NA>               <NA>              <NA>               <NA>              <NA>
# 4 HZdLhv6COCleJMo7nPl-RA               301 S Hills Vlg\nPittsburgh, PA 15241               21:00              10:00              21:00             10:00              21:00             10:00
#   hours.Wednesday.close hours.Wednesday.open hours.Thursday.close hours.Thursday.open hours.Sunday.close hours.Sunday.open hours.Saturday.close hours.Saturday.open  open
# 1                 17:00                08:00                17:00               08:00               <NA>              <NA>                 <NA>                <NA>  TRUE
# 2                  <NA>                 <NA>                 <NA>                <NA>               <NA>              <NA>                 <NA>                <NA>  TRUE
# 3                  <NA>                 <NA>                 <NA>                <NA>               <NA>              <NA>                 <NA>                <NA> FALSE
# 4                 21:00                10:00                21:00               10:00              18:00             11:00                21:00               10:00  TRUE
#                                                                                categories        city review_count                     name neighborhoods  longitude state stars
# 1                                                                              Doctors, Health & Medical     Phoenix            9        Eric Goldberg, MD          NULL -111.98376    AZ   3.5
# 2                                                                                Nightlife  Dravosburg            4             Clancy's Pub          NULL  -79.88693    PA   3.5
# 3                                                                           Active Life, Mini Golf, Golf Bethel Park            5 Cool Springs Golf Center          NULL  -80.01591    PA   2.5
# 4 Shopping, Home Services, Internet Service Providers, Mobile Phones, Professional Services, Electronics  Pittsburgh            3         Verizon Wireless          NULL  -80.05998    PA   3.5
#   latitude attributes.By Appointment Only attributes.Happy Hour attributes.Accepts Credit Cards attributes.Good For Groups attributes.Outdoor Seating attributes.Price Range
# 1 33.49931                           TRUE                    NA                              NA                         NA                         NA                     NA
# 2 40.35052                             NA                  TRUE                            TRUE                       TRUE                      FALSE                      1
# 3 40.35690                             NA                    NA                              NA                         NA                         NA                     NA
# 4 40.35762                             NA                    NA                              NA                         NA                         NA                     NA
#   attributes.Good for Kids     type
# 1                       NA business
# 2                       NA business
# 3                     TRUE business
# 4                       NA business
</code>```

Body:
I have a HUGE json.gz file and the file is already converted to .json file. I would like ask how we can read, say, the first 100 records from the .json file using R. Any help is greatly appreciated. The following is just sample code:

library(jsonlite)
library(R.utils)
r=stream_in(file("yelp_academic_dataset_business.json"))

The file "yelp_academic_dataset_business.json" can be found from the link:
https://www.dropbox.com/s/gd1k41y9gbpfwq3/yelp_academic_dataset_business.json

Body:
Using the data from your original link, @Shree's suggestion is spot-on. First, use readLines to download only as many lines as you need:

dat <- readLines("https://uc385e5985dd32823a7dc6ba9b5e.dl.dropboxusercontent.com/cd/0/get/AhyCjVEm8yKnLz4w0-hZaW-titb8fOhQdMcwhTMF1_3i_iJ7DOqOU_KQRTtcvaFBaSTpAznh_6eq-vKAEiDkeVygMnRjThrnz0V5fyC4AURAcg/file?_download_id=9916801659220323334123287637995650900165723151388885263767035946&_notify_domain=www.dropbox.com&dl=1", n =4 )
# dat <- readLines("yelp_academic_dataset_business.json", n = 4)

Now create a "fake text connection" and pass this to the json parser:

jsonlite::stream_in(textConnection(dat))
#  Imported 4 records. Simplifying...
#              business_id                                        full_address hours.Tuesday.close hours.Tuesday.open hours.Friday.close hours.Friday.open hours.Monday.close hours.Monday.open
# 1 vcNAWiLM4dR7D2nwwJ7nCA 4840 E Indian School Rd\nSte 101\nPhoenix, AZ 85018               17:00              08:00              17:00             08:00              17:00             08:00
# 2 UsFtqoBl7naz8AVUBZMjQQ                202 McClure St\nDravosburg, PA 15034                <NA>               <NA>               <NA>              <NA>               <NA>              <NA>
# 3 cE27W9VPgO88Qxe4ol6y_g             1530 Hamilton Rd\nBethel Park, PA 15234                <NA>               <NA>               <NA>              <NA>               <NA>              <NA>
# 4 HZdLhv6COCleJMo7nPl-RA               301 S Hills Vlg\nPittsburgh, PA 15241               21:00              10:00              21:00             10:00              21:00             10:00
#   hours.Wednesday.close hours.Wednesday.open hours.Thursday.close hours.Thursday.open hours.Sunday.close hours.Sunday.open hours.Saturday.close hours.Saturday.open  open
# 1                 17:00                08:00                17:00               08:00               <NA>              <NA>                 <NA>                <NA>  TRUE
# 2                  <NA>                 <NA>                 <NA>                <NA>               <NA>              <NA>                 <NA>                <NA>  TRUE
# 3                  <NA>                 <NA>                 <NA>                <NA>               <NA>              <NA>                 <NA>                <NA> FALSE
# 4                 21:00                10:00                21:00               10:00              18:00             11:00                21:00               10:00  TRUE
#                                                                                categories        city review_count                     name neighborhoods  longitude state stars
# 1                                                                              Doctors, Health & Medical     Phoenix            9        Eric Goldberg, MD          NULL -111.98376    AZ   3.5
# 2                                                                                Nightlife  Dravosburg            4             Clancy's Pub          NULL  -79.88693    PA   3.5
# 3                                                                           Active Life, Mini Golf, Golf Bethel Park            5 Cool Springs Golf Center          NULL  -80.01591    PA   2.5
# 4 Shopping, Home Services, Internet Service Providers, Mobile Phones, Professional Services, Electronics  Pittsburgh            3         Verizon Wireless          NULL  -80.05998    PA   3.5
#   latitude attributes.By Appointment Only attributes.Happy Hour attributes.Accepts Credit Cards attributes.Good For Groups attributes.Outdoor Seating attributes.Price Range
# 1 33.49931                           TRUE                    NA                              NA                         NA                         NA                     NA
# 2 40.35052                             NA                  TRUE                            TRUE                       TRUE                      FALSE                      1
# 3 40.35690                             NA                    NA                              NA                         NA                         NA                     NA
# 4 40.35762                             NA                    NA                              NA                         NA                         NA                     NA
#   attributes.Good for Kids     type
# 1                       NA business
# 2                       NA business
# 3                     TRUE business
# 4                       NA business


问:
Spring Security URL pattern configuration
This one should be quite simple. But I've been stuck with it for a while.
I'm trying to implement Spring Security in my web application.

By default, all URL's should be publically accessible. Except for following:

/nl/favorieten/

/fr/favorites/

I've tried several things, ending up with the following:

```<code><http auto-config="true" access-denied-page="/login">
    <intercept-url pattern="/*/favori*" access="IS_AUTHENTICATED_FULLY" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <form-login
       always-use-default-target="true"
       login-page="/login"
       default-target-url="/"
       authentication-failure-url="/login?login_error=1" />
    <logout invalidate-session="false" logout-url="/logout" />
</http>
</code>```

obviously without success.
I've tried just about any combination of regex, ordering the rules, changing roles. But nothing seems to redirect my request to /login.

Except ofcourse if I say /** should be IS_AUTHENTICATED_FULLY

答:
Simply put:</p>

```<code><intercept-url pattern="/nl/favorieten/*" access="IS_AUTHENTICATED_FULLY" />
<intercept-url pattern="/fr/favorites/*" access="IS_AUTHENTICATED_FULLY" />
</code>```

Body:
This one should be quite simple. But I've been stuck with it for a while.
I'm trying to implement Spring Security in my web application.

By default, all URL's should be publically accessible. Except for following:

/nl/favorieten/

/fr/favorites/

I've tried several things, ending up with the following:

<http auto-config="true" access-denied-page="/login">
    <intercept-url pattern="/*/favori*" access="IS_AUTHENTICATED_FULLY" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <form-login
       always-use-default-target="true"
       login-page="/login"
       default-target-url="/"
       authentication-failure-url="/login?login_error=1" />
    <logout invalidate-session="false" logout-url="/logout" />
</http>

obviously without success.
I've tried just about any combination of regex, ordering the rules, changing roles. But nothing seems to redirect my request to /login.

Except ofcourse if I say /** should be IS_AUTHENTICATED_FULLY

Body:
Simply put:

<intercept-url pattern="/nl/favorieten/*" access="IS_AUTHENTICATED_FULLY" />
<intercept-url pattern="/fr/favorites/*" access="IS_AUTHENTICATED_FULLY" />


问:
US Census Data using MatPlotLib
I am working with some info from the US CENSUS website. I am able to plot every state and the population, but I want to isolate just one state (UTAH) and I am having trouble with the code.

The code below is the data I want to chart and the configuration:
    content.loc[45:45, ['1910_POPULATION', '1920_POPULATION',
    '1930_POPULATION', '1940_POPULATION', '1950_POPULATION',
    '1960_POPULATION', '1970_POPULATION', '1980_POPULATION','1990_POPULATION',
    '2000_POPULATION']]

```<code>fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
plt.plot(content.[45:45], content.['1910_POPULATION', '1920_POPULATION',
'1930_POPULATION', '1940_POPULATION', '1950_POPULATION',
'1960_POPULATION', '1970_POPULATION', '1980_POPULATION','1990_POPULATION',
'2000_POPULATION'])
plt.xlabel([45:45])
plt.ylabel('POPULATION')
plt.show()
</code>```

ANy idea how I can fix this to plot a simple chart if the population growth using MATPLOTLIB?

答:
Try this:</p>

```<code>fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
plt.plot(content.loc[45, ['1910_POPULATION', '1920_POPULATION',
'1930_POPULATION', '1940_POPULATION', '1950_POPULATION',
'1960_POPULATION', '1970_POPULATION', '1980_POPULATION','1990_POPULATION',
'2000_POPULATION']])
plt.xlabel([45:45])
plt.ylabel('POPULATION')
plt.show()
</code>```

Title: US Census Data using MatPlotLib

Body:
I am working with some info from the US CENSUS website. I am able to plot every state and the population, but I want to isolate just one state (UTAH) and I am having trouble with the code.

The code below is the data I want to chart and the configuration:
    content.loc[45:45, ['1910_POPULATION', '1920_POPULATION',
    '1930_POPULATION', '1940_POPULATION', '1950_POPULATION',
    '1960_POPULATION', '1970_POPULATION', '1980_POPULATION','1990_POPULATION',
    '2000_POPULATION']]

fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
plt.plot(content.[45:45], content.['1910_POPULATION', '1920_POPULATION',
'1930_POPULATION', '1940_POPULATION', '1950_POPULATION',
'1960_POPULATION', '1970_POPULATION', '1980_POPULATION','1990_POPULATION',
'2000_POPULATION'])
plt.xlabel([45:45])
plt.ylabel('POPULATION')
plt.show()

ANy idea how I can fix this to plot a simple chart if the population growth using MATPLOTLIB?

Body:
Try this:

fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
plt.plot(content.loc[45, ['1910_POPULATION', '1920_POPULATION',
'1930_POPULATION', '1940_POPULATION', '1950_POPULATION',
'1960_POPULATION', '1970_POPULATION', '1980_POPULATION','1990_POPULATION',
'2000_POPULATION']])
plt.xlabel([45:45])
plt.ylabel('POPULATION')
plt.show()


问:
How can I using this variable?
I want to using this variable (ntime[]) in main class
I think I must using 'extends', but I don't know how I using that.
What Can I using variable, and How can I use it?
I want to know It is using extends, or another variable it can.
Thank you

I was using extends
~~ void main(String args[]) extends * throws IOException
&
~~ void main extends * (String args[]) *** throws IOException

but it is not work

import java.util.Calendar;

```<code>class *****
 {
 public void ***** throws IOException
 {
 int [] ntime = new int [6];
 BufferedReader inbr = new BufferedReader (new
 InputStreamReader(System.in));
 Calendar now= Calendar.getInstance();
 ntime[0] = now.get(Calendar.YEAR);
 ntime[1] = now.get(Calendar.MONTH);
....
 ntime[5] = now.get(Calendar.SECOND);
 }
 }

 class *****  {
 public static void main(String args[]) throws IOException
 {

***** objecta = new ***();
   objecta.test01();
  System.out.println("Time is  " + ntime[0] + ... + ntime[5]);
 }
 }
</code>```

symbol:   variable ntime
  location: class ***

答:
The problem is that main does not have access to the int array.

You can solve this by returning the int[] from your function

```<code>class Thing {
    public int[] fun() {
        Calendar now = Calendar.getInstance();
        return new int[]{
                now.get(Calendar.YEAR),
                now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH)
        };
    }
}
</code>```

then in main, you can have

```<code>class Scratch {
    public static void main(String[] args) {
        Thing thing = new Thing();
        int[] ntime = thing.fun();

        System.out.println("time is " + ntime[0]);
    }
}
</code>```

This should solve your problem.

Title: How can I using this variable?

Body:
I want to using this variable (ntime[]) in main class
I think I must using 'extends', but I don't know how I using that.
What Can I using variable, and How can I use it?
I want to know It is using extends, or another variable it can.
Thank you

I was using extends
~~ void main(String args[]) extends * throws IOException
&
~~ void main extends * (String args[]) *** throws IOException

but it is not work

import java.util.Calendar;

class *****
 {
 public void ***** throws IOException
 {
 int [] ntime = new int [6];
 BufferedReader inbr = new BufferedReader (new
 InputStreamReader(System.in));
 Calendar now= Calendar.getInstance();
 ntime[0] = now.get(Calendar.YEAR);
 ntime[1] = now.get(Calendar.MONTH);
....
 ntime[5] = now.get(Calendar.SECOND);
 }
 }

 class *****  {
 public static void main(String args[]) throws IOException
 {

***** objecta = new ***();
   objecta.test01();
  System.out.println("Time is  " + ntime[0] + ... + ntime[5]);
 }
 }

symbol:   variable ntime
  location: class ***

Body:
The problem is that main does not have access to the int array.

You can solve this by returning the int[] from your function

class Thing {
    public int[] fun() {
        Calendar now = Calendar.getInstance();
        return new int[]{
                now.get(Calendar.YEAR),
                now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH)
        };
    }
}

then in main, you can have

class Scratch {
    public static void main(String[] args) {
        Thing thing = new Thing();
        int[] ntime = thing.fun();

        System.out.println("time is " + ntime[0]);
    }
}

This should solve your problem.


问:
How to add Firebase custom events for analytics?
I've seen some questions and answers about custom events for firebase analytics, but i just wanted to ask you a straight question so you can give me a straight answer :)

So, this is my method for logging:

```<code>@Override
public void logFeatureSelectedEvent(String categoryName, String actionName, String labelName) {
    Bundle bundle = new Bundle();
    bundle.putString(EventTrackingKeys.EventTypes.CATEGORY, categoryName);
    bundle.putString(EventTrackingKeys.EventTypes.ACTION, actionName);
    bundle.putString(EventTrackingKeys.EventTypes.LABEL, labelName);
    mFirebaseAnalytics.logEvent(EventTrackingKeys.EventAnalyticTypes.FEATURE_SELECTED_EVENT, bundle);
}
</code>```

with custom event/key names:

```<code>String CATEGORY = "category";
String ACTION = "action";
String LABEL = "label";
String FEATURE_SELECTED_EVENT = "feature_selected_event";
</code>```

So, in my firebase console I only get event name "feature_selected_event", without custom parameter names..
I've seen some answers that i should call setUserProperty() method and register that user property in the User Properties tab of Firebase Analytics.
Is this the right way to implement that method? :

```<code>   @Override
public void logFeatureSelectedEvent(String categoryName, String actionName, long value) {
    Bundle bundle = new Bundle();
    bundle.putString(EventTrackingKeys.EventTypes.CATEGORY, categoryName);
    bundle.putString(EventTrackingKeys.EventTypes.ACTION, actionName);
    bundle.putLong(EventTrackingKeys.EventTypes.VALUE, value);
    mFirebaseAnalytics.setUserProperty(EventTrackingKeys.EventTypes.CATEGORY, categoryName);
    mFirebaseAnalytics.setUserProperty(EventTrackingKeys.EventTypes.ACTION, actionName);
    mFirebaseAnalytics.setUserProperty(EventTrackingKeys.EventTypes.VALUE, value);
    mFirebaseAnalytics.logEvent(EventTrackingKeys.EventAnalyticTypes.FEATURE_SELECTED_EVENT, bundle);
}
</code>```

答:
Similar to @Josef Vancura answer, but in Kotlin:

```<code>val params = Bundle()
params.putString("invalid_url", urlPart)
mFirebaseAnalytics.logEvent("eventInvalidUrl", params)
</code>```

Body:
I've seen some questions and answers about custom events for firebase analytics, but i just wanted to ask you a straight question so you can give me a straight answer :)

So, this is my method for logging:

@Override
public void logFeatureSelectedEvent(String categoryName, String actionName, String labelName) {
    Bundle bundle = new Bundle();
    bundle.putString(EventTrackingKeys.EventTypes.CATEGORY, categoryName);
    bundle.putString(EventTrackingKeys.EventTypes.ACTION, actionName);
    bundle.putString(EventTrackingKeys.EventTypes.LABEL, labelName);
    mFirebaseAnalytics.logEvent(EventTrackingKeys.EventAnalyticTypes.FEATURE_SELECTED_EVENT, bundle);
}

with custom event/key names:

String CATEGORY = "category";
String ACTION = "action";
String LABEL = "label";
String FEATURE_SELECTED_EVENT = "feature_selected_event";

So, in my firebase console I only get event name "feature_selected_event", without custom parameter names..
I've seen some answers that i should call setUserProperty() method and register that user property in the User Properties tab of Firebase Analytics.
Is this the right way to implement that method? :

   @Override
public void logFeatureSelectedEvent(String categoryName, String actionName, long value) {
    Bundle bundle = new Bundle();
    bundle.putString(EventTrackingKeys.EventTypes.CATEGORY, categoryName);
    bundle.putString(EventTrackingKeys.EventTypes.ACTION, actionName);
    bundle.putLong(EventTrackingKeys.EventTypes.VALUE, value);
    mFirebaseAnalytics.setUserProperty(EventTrackingKeys.EventTypes.CATEGORY, categoryName);
    mFirebaseAnalytics.setUserProperty(EventTrackingKeys.EventTypes.ACTION, actionName);
    mFirebaseAnalytics.setUserProperty(EventTrackingKeys.EventTypes.VALUE, value);
    mFirebaseAnalytics.logEvent(EventTrackingKeys.EventAnalyticTypes.FEATURE_SELECTED_EVENT, bundle);
}

Body:
Similar to @Josef Vancura answer, but in Kotlin:

val params = Bundle()
params.putString("invalid_url", urlPart)
mFirebaseAnalytics.logEvent("eventInvalidUrl", params)


问:
RollingFile Appender Log4j2 not printing Line number
I am using log4j2 with following dependency ::

```<code>   <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.0-rc1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.0-rc1</version>
    </dependency>
</code>```

I am using following configuration ::

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

    <Properties>
        <Property name="LOGGER_HOME">/logs</Property>
    </Properties>

    <Appenders>

        <RollingFile name="application" fileName="${LOGGER_HOME}/application.log"
            filePattern="${LOGGER_HOME}/application.%d{yyyy-MM-dd}_%i.log">

            <PatternLayout pattern="%d{ISO8601}{GMT} %-5p %C{2} (%F:%L) - %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="1 GB" />
            </Policies>

        </RollingFile>

        <RollingFile name="framework" fileName="${LOGGER_HOME}/em-logs/framework.log"
            filePattern="${LOGGER_HOME}/framework.%d{yyyy-MM-dd}_%i.log">

            <PatternLayout pattern="%d{ISO8601}{GMT} %-5p %C{2} (%F:%L) - %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="1 GB" />
            </Policies>
        </RollingFile>

        <Console name="out" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{ISO8601}{GMT} %-5p %C{2} (%F:%L) - %m%n" />
        </Console>

        <Async name="asyncApplication">
            <AppenderRef ref="application" />
        </Async>

        <Async name="asyncFramework">
            <AppenderRef ref="framework" />
        </Async>

    </Appenders>

    <Loggers>

        <Logger name="com.memorynotfound.logging" level="debug"
            includeLocation="true">
            <AppenderRef ref="asyncApplication" />
        </Logger>

    <Root level="debug" includeLocation="true">
            <AppenderRef ref="asyncApplication"></AppenderRef>
        </Root>

        <Logger name="org.axonframework" level="info" additivity="false"
            includeLocation="true">
            <AppenderRef ref="asyncFramework" />
        </Logger>

        <Root level="error" includeLocation="true">
            <AppenderRef ref="out" />
        </Root>

    </Loggers>

</Configuration>
</code>```

However i am getting logs on the console in the following format

```<code>2015-08-20 14:29:41,613 DEBUG logging.LoggerExample (LoggerExample.java:11) - This will be printed on debug
</code>```

And in the Rolling file i get following pattern where the line number is missing ::

```<code>2015-08-20 14:29:41,613 DEBUG ? () - This will be printed on debug
</code>```

I have gone nuts as nothing seem to work for printing the line numbers i also followed the official log4j2 link
Log4j2 Migration
but still the result is same as above. If any one has any solution please let me know .

答:
The document describe the reason that not printing line number .
It say you can override the default behaviour in your logger or asynchronous appender configuration by specifying includeLocation="true".
But i did not solve the problem that not printing line number after i did it.
Maybe because i didn`t understand what it meant, i made the wrong place.

My solution is add %L in Log4j2 PatternLayout pattern.
My Log4j2.xml is following:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN" monitorInterval="30">
        <Properties>
            <Property name="LOG_HOME">./logs</Property>
        </Properties>

        <Console name="Console" target="SYSTEM_OUT">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%L - %msg%n" />
        </Console>

        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/pinche_quartz.log"
                     filePattern="${LOG_HOME}/test.log-%d{yyyy-MM-dd}.log">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%L - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${LOG_HOME}/error/pinche_quartz-error.log"
                     filePattern="${LOG_HOME}/error/pinche_quartz-error.log-%d{yyyy-MM-dd}.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%L - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>

    <Loggers>
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </Loggers>

</Configuration>
</code>```

I hope to help you.

Log4j2 document https://logging.apache.org/log4j/2.x/manual/layouts.html#LocationInformation

Body:
I am using log4j2 with following dependency ::

   <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.0-rc1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.0-rc1</version>
    </dependency>

I am using following configuration ::

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

    <Properties>
        <Property name="LOGGER_HOME">/logs</Property>
    </Properties>

    <Appenders>

        <RollingFile name="application" fileName="${LOGGER_HOME}/application.log"
            filePattern="${LOGGER_HOME}/application.%d{yyyy-MM-dd}_%i.log">

            <PatternLayout pattern="%d{ISO8601}{GMT} %-5p %C{2} (%F:%L) - %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="1 GB" />
            </Policies>

        </RollingFile>

        <RollingFile name="framework" fileName="${LOGGER_HOME}/em-logs/framework.log"
            filePattern="${LOGGER_HOME}/framework.%d{yyyy-MM-dd}_%i.log">

            <PatternLayout pattern="%d{ISO8601}{GMT} %-5p %C{2} (%F:%L) - %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="1 GB" />
            </Policies>
        </RollingFile>

        <Console name="out" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{ISO8601}{GMT} %-5p %C{2} (%F:%L) - %m%n" />
        </Console>

        <Async name="asyncApplication">
            <AppenderRef ref="application" />
        </Async>

        <Async name="asyncFramework">
            <AppenderRef ref="framework" />
        </Async>

    </Appenders>

    <Loggers>

        <Logger name="com.memorynotfound.logging" level="debug"
            includeLocation="true">
            <AppenderRef ref="asyncApplication" />
        </Logger>

    <Root level="debug" includeLocation="true">
            <AppenderRef ref="asyncApplication"></AppenderRef>
        </Root>

        <Logger name="org.axonframework" level="info" additivity="false"
            includeLocation="true">
            <AppenderRef ref="asyncFramework" />
        </Logger>

        <Root level="error" includeLocation="true">
            <AppenderRef ref="out" />
        </Root>

    </Loggers>

</Configuration>

However i am getting logs on the console in the following format

2015-08-20 14:29:41,613 DEBUG logging.LoggerExample (LoggerExample.java:11) - This will be printed on debug

And in the Rolling file i get following pattern where the line number is missing ::

2015-08-20 14:29:41,613 DEBUG ? () - This will be printed on debug

I have gone nuts as nothing seem to work for printing the line numbers i also followed the official log4j2 link
Log4j2 Migration
but still the result is same as above. If any one has any solution please let me know .

Body:
The document describe the reason that not printing line number .
It say you can override the default behaviour in your logger or asynchronous appender configuration by specifying includeLocation="true".
But i did not solve the problem that not printing line number after i did it.
Maybe because i didn`t understand what it meant, i made the wrong place.

My solution is add %L in Log4j2 PatternLayout pattern.
My Log4j2.xml is following:

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN" monitorInterval="30">
        <Properties>
            <Property name="LOG_HOME">./logs</Property>
        </Properties>

        <Console name="Console" target="SYSTEM_OUT">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%L - %msg%n" />
        </Console>

        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/pinche_quartz.log"
                     filePattern="${LOG_HOME}/test.log-%d{yyyy-MM-dd}.log">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%L - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${LOG_HOME}/error/pinche_quartz-error.log"
                     filePattern="${LOG_HOME}/error/pinche_quartz-error.log-%d{yyyy-MM-dd}.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%L - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>

    <Loggers>
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </Loggers>

</Configuration>

I hope to help you.

Log4j2 document https://logging.apache.org/log4j/2.x/manual/layouts.html#LocationInformation


问:
Bootstrap div- align to center of page
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

```<code><div class="panel-group col-sm-6" style="float: none;">
<div class="panel panel-default">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div>
</code>```

答:
You can use display: flex for this to handle alignment in a easier way. I have done a sample code below. Hope it helps you

HTML

```<code><div class="panel-group col-sm-6">
<div class="panel panel-default d-flex h-100">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div>
</code>```

CSS

```<code>.d-flex {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center
}

.h-100 {
  height: 100vh !important;
}
</code>```

JS Fiddle Link: https://jsfiddle.net/SJ_KIllshot/bhgx3yzv/

Title: Bootstrap div- align to center of page

Body:
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

test

test

Body:
You can use display: flex for this to handle alignment in a easier way. I have done a sample code below. Hope it helps you

HTML

<div class="panel-group col-sm-6">
<div class="panel panel-default d-flex h-100">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div>

CSS

.d-flex {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center
}

.h-100 {
  height: 100vh !important;
}

JS Fiddle Link: https://jsfiddle.net/SJ_KIllshot/bhgx3yzv/


问:
AdWords API get costs
I am looking for a simple solution to extract daily costs from Google AdWords via the API. I've looked at Apility and the official AdWords API, but the first is not maintained any more while the second is an overkill - I mean 76MB of uncompressed code to only get the daily costs?

Does anybody know of a simple solution to get the costs from Google AdWords?

答:
Use

```<code>composer require googleads/googleads-php-lib
</code>```

Script for Laravel 5.8

Google Ads v201809

```<code><?php namespace App\Console\Commands\Google;

use App\Model\AdvExpense;
use App\Model\Campaign;
use App\Model\Source;
use App\Service\Xml;
use Carbon\Carbon;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201809\DownloadFormat;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDefinition;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDefinitionDateRangeType;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDownloader;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\AdWords\v201809\cm\DateRange;
use Google\AdsApi\AdWords\v201809\cm\OrderBy;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\cm\ReportDefinitionReportType;
use Google\AdsApi\AdWords\v201809\cm\Selector;
use Google\AdsApi\AdWords\v201809\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Illuminate\Console\Command;

class Expenses extends Command
{
    /**
     * The name and signature of the console command
     *
     * @var string
     */
    protected $signature = 'google:expenses';
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'Import Google Ads Expenses';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Import Google Ads Expenses";

    public function handle()
    {
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile(storage_path('adsapi_php.ini'))->build();
        $session = (new AdWordsSessionBuilder())->fromFile(storage_path('adsapi_php.ini'))->withOAuth2Credential($oAuth2Credential)->build();

        $date = Carbon::yesterday();

        $this->saveExpenses($session, $date);
    }

    public function saveExpenses($session, $date)
    {
// Create selector.
        $selector = new Selector();
        $selector->setFields(['CampaignId', 'CampaignName', 'Clicks', 'Cost']);
        $selector->setDateRange(new DateRange(
            $date->format('Ymd'),
            $date->format('Ymd')
        ));

// Create report definition.
        $reportDefinition = new ReportDefinition();
        $reportDefinition->setSelector($selector);
        $reportDefinition->setReportName('Expenses report ' . uniqid());
        $reportDefinition->setDateRangeType(ReportDefinitionDateRangeType::CUSTOM_DATE);
        $reportDefinition->setReportType(ReportDefinitionReportType::CAMPAIGN_PERFORMANCE_REPORT);
        $reportDefinition->setDownloadFormat(DownloadFormat::XML);

// Download report.
        $reportDownloader = new ReportDownloader($session);
        $reportDownloadResult = $reportDownloader->downloadReport($reportDefinition);
        $result = $reportDownloadResult->getAsString();

        $report = Xml::namespacedXMLToArray($result);
        foreach ($report['table']['row'] as $item) {
            $campaign_id = $item['@attributes']['campaignID'];
            $campaign_name = $item['@attributes']['campaign'];
            $cost = $item['@attributes']['cost'];

            if ($cost > 0) {
                $dbCampaign = Campaign::where('code', $campaign_id)->get()->first();

                if ($dbCampaign) {
                    $price = round($cost / 1000000);
                    if ($price) {
                        $dbCost = AdvExpense::updateOrCreate(
                            [
                                'campaign_id' => $dbCampaign->id,
                                'date' => $date,
                            ],
                            [
                                'price' => $price,
                            ]
                        );

                        if ($dbCost->exists) {
                            $this->info($dbCampaign->name . ' - ' . $date->format('Y-m-d') . ' - ' . $price . ' OK');
                        } else {
                            $this->error($dbCampaign->name . ' - ' . $date->format('Y-m-d') . ' - ' . $price . ' ERROR');
                        }
                    }
                } else {
                    $this->error('Campaign ' . $campaign_name . ' not found!');
                }
            }
        }
    }
}
</code>```

Title: AdWords API get costs

Body:
Use

composer require googleads/googleads-php-lib

Script for Laravel 5.8

Google Ads v201809

<?php namespace App\Console\Commands\Google;

use App\Model\AdvExpense;
use App\Model\Campaign;
use App\Model\Source;
use App\Service\Xml;
use Carbon\Carbon;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201809\DownloadFormat;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDefinition;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDefinitionDateRangeType;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDownloader;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\AdWords\v201809\cm\DateRange;
use Google\AdsApi\AdWords\v201809\cm\OrderBy;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\cm\ReportDefinitionReportType;
use Google\AdsApi\AdWords\v201809\cm\Selector;
use Google\AdsApi\AdWords\v201809\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Illuminate\Console\Command;

class Expenses extends Command
{
    /**
     * The name and signature of the console command
     *
     * @var string
     */
    protected $signature = 'google:expenses';
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'Import Google Ads Expenses';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Import Google Ads Expenses";

    public function handle()
    {
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile(storage_path('adsapi_php.ini'))->build();
        $session = (new AdWordsSessionBuilder())->fromFile(storage_path('adsapi_php.ini'))->withOAuth2Credential($oAuth2Credential)->build();

        $date = Carbon::yesterday();

        $this->saveExpenses($session, $date);
    }

    public function saveExpenses($session, $date)
    {
// Create selector.
        $selector = new Selector();
        $selector->setFields(['CampaignId', 'CampaignName', 'Clicks', 'Cost']);
        $selector->setDateRange(new DateRange(
            $date->format('Ymd'),
            $date->format('Ymd')
        ));

// Create report definition.
        $reportDefinition = new ReportDefinition();
        $reportDefinition->setSelector($selector);
        $reportDefinition->setReportName('Expenses report ' . uniqid());
        $reportDefinition->setDateRangeType(ReportDefinitionDateRangeType::CUSTOM_DATE);
        $reportDefinition->setReportType(ReportDefinitionReportType::CAMPAIGN_PERFORMANCE_REPORT);
        $reportDefinition->setDownloadFormat(DownloadFormat::XML);

// Download report.
        $reportDownloader = new ReportDownloader($session);
        $reportDownloadResult = $reportDownloader->downloadReport($reportDefinition);
        $result = $reportDownloadResult->getAsString();

        $report = Xml::namespacedXMLToArray($result);
        foreach ($report['table']['row'] as $item) {
            $campaign_id = $item['@attributes']['campaignID'];
            $campaign_name = $item['@attributes']['campaign'];
            $cost = $item['@attributes']['cost'];

            if ($cost > 0) {
                $dbCampaign = Campaign::where('code', $campaign_id)->get()->first();

                if ($dbCampaign) {
                    $price = round($cost / 1000000);
                    if ($price) {
                        $dbCost = AdvExpense::updateOrCreate(
                            [
                                'campaign_id' => $dbCampaign->id,
                                'date' => $date,
                            ],
                            [
                                'price' => $price,
                            ]
                        );

                        if ($dbCost->exists) {
                            $this->info($dbCampaign->name . ' - ' . $date->format('Y-m-d') . ' - ' . $price . ' OK');
                        } else {
                            $this->error($dbCampaign->name . ' - ' . $date->format('Y-m-d') . ' - ' . $price . ' ERROR');
                        }
                    }
                } else {
                    $this->error('Campaign ' . $campaign_name . ' not found!');
                }
            }
        }
    }
}


问:
How do I create a loop, or a way to use the results of previous SELECT statements into the next SELECT statement?
I have a database with a nested hierarchy structure.  At the high levels of the hierarchy, there aren't any actual typeIDs (individual items) associated with a given marketGroupID.

Instead, I start at the top using a string search to find the categories I want. I need to keep going down in the hierarchy by using the marketGroupIDs I've selected as the parentGroupIDs for the next search so that I find all IDs within that subcategory. This keeps dividing into more subcategories until the column hasTypes = 1 (there are typeIDs associated with this subcategory).

While I'm currently pursuing a very manual option: keep making another search until I get to the level I want, is there a way to construct a loop that keeps SELECTING based upon WHERE marketGroupID X = parentGroupID Y, and hasTypes = 0 ?

MANUAL METHOD I'M TRYING TO REPLACE

The columns I am mainly working with are marketGroupID and parentID. What I've tried so far is using c.fetchall() to get the previous result and put it in a variable next_input. Then I use the parameter '?' using sqlite3 in Python. The issue with this is that the number of inputs can change, as the previous SELECT statement will give me a list of tuples that could be anywhere from sixty to several hundred long.

c.execute("""SELECT marketGroupID FROM invMarketGroups WHERE parentGroupID IN (SELECT marketGroupID FROM invMarketGroups WHERE marketGroupName='Ships'
OR marketGroupName = 'Ship Equipment' OR marketGroupName = 'Implants & Boosters')""");
```

<h2>Next search step.</h2>

<p><code>python
next_input = c.fetchall()</code></p>

<p>So, taking the time to make the number of these equal to list length, I've managed to make it work by turning the result into a single list:</p>

```next_input = [i[0] for i in next_input]

c.execute("SELECT marketGroupID FROM invMarketGroups WHERE parentGroupID IN ({idlist_formatted})".format(idlist_formatted= ','.join(['?']*len(next_input))), next_input)
```

How do I make a loop so that it keeps running recursively that ends until hasTypes != 0, grabbing marketGroupIDs where hasTypes = 1?

答:
Sqllite supports recursive queries which can be used for hierarchical queries (which is what you are trying to do). Take a look at the documentation here
It even has a section about hierarchical queries. This way you can completely replace your loop with one call to the DB and let it do the work.</p>

Body:
I have a database with a nested hierarchy structure.  At the high levels of the hierarchy, there aren't any actual typeIDs (individual items) associated with a given marketGroupID.

Instead, I start at the top using a string search to find the categories I want. I need to keep going down in the hierarchy by using the marketGroupIDs I've selected as the parentGroupIDs for the next search so that I find all IDs within that subcategory. This keeps dividing into more subcategories until the column hasTypes = 1 (there are typeIDs associated with this subcategory).

While I'm currently pursuing a very manual option: keep making another search until I get to the level I want, is there a way to construct a loop that keeps SELECTING based upon WHERE marketGroupID X = parentGroupID Y, and hasTypes = 0 ?

MANUAL METHOD I'M TRYING TO REPLACE

The columns I am mainly working with are marketGroupID and parentID. What I've tried so far is using c.fetchall() to get the previous result and put it in a variable next_input. Then I use the parameter '?' using sqlite3 in Python. The issue with this is that the number of inputs can change, as the previous SELECT statement will give me a list of tuples that could be anywhere from sixty to several hundred long.

c.execute("""SELECT marketGroupID FROM invMarketGroups WHERE parentGroupID IN (SELECT marketGroupID FROM invMarketGroups WHERE marketGroupName='Ships'
OR marketGroupName = 'Ship Equipment' OR marketGroupName = 'Implants & Boosters')""");

Next search step.

python
next_input = c.fetchall()

So, taking the time to make the number of these equal to list length, I've managed to make it work by turning the result into a single list:

next_input = [i[0] for i in next_input]

c.execute("SELECT marketGroupID FROM invMarketGroups WHERE parentGroupID IN ({idlist_formatted})".format(idlist_formatted= ','.join(['?']*len(next_input))), next_input)

How do I make a loop so that it keeps running recursively that ends until hasTypes != 0, grabbing marketGroupIDs where hasTypes = 1?


问:
Return the heading of the maximum value for more than one Max
I have five columns in Excel and I want to return the maximum value's column heading name. However, there are cases where the max values are repeated more than once for the same row. So, I am trying to return both column names.

The green values are the min and red are the max. In row 4, it is clearly there is more than one Max with same value, I would like to return B and E in the stream cell.

I tried this formula in Excel using the index:

```<code>=IF(ISNUMBER(A6),INDEX($B$5:$F$5,1,MATCH(L6,B6:F6,0)),"")
</code>```

答:
MATCH returns the first match, so I think you need something gross like the following (I started with the first column and row, but you can shift the column numbers -- the rows are designed to be draggable)</p>

```<code>=IF(ISNUMBER(F2),IF(F2=A2,$A$1,"")&IF(F2=B2,$B$1,"")&IF(F2=C2,$C$1,"")&IF(F2=D2,$D$1,"")&IF(F2=E2,$E$1,""))
</code>```

Body:
I have five columns in Excel and I want to return the maximum value's column heading name. However, there are cases where the max values are repeated more than once for the same row. So, I am trying to return both column names.

The green values are the min and red are the max. In row 4, it is clearly there is more than one Max with same value, I would like to return B and E in the stream cell.

I tried this formula in Excel using the index:

=IF(ISNUMBER(A6),INDEX($B$5:$F$5,1,MATCH(L6,B6:F6,0)),"")

Body:
MATCH returns the first match, so I think you need something gross like the following (I started with the first column and row, but you can shift the column numbers -- the rows are designed to be draggable)

=IF(ISNUMBER(F2),IF(F2=A2,$A$1,"")&IF(F2=B2,$B$1,"")&IF(F2=C2,$C$1,"")&IF(F2=D2,$D$1,"")&IF(F2=E2,$E$1,""))


问:
End time validation in jquery time picker
I need to restrict user to select end time greater than start time in a timepicker with 12 hrs format. - http://jsfiddle.net/jonthornton/28uvg/</p>

```<code>      <script>
          $(function(){
          $('#start').timepicker();
          });
          $(function(){
          $('#end').timepicker();
          });
       </script>

        <div class="col-sm-8">
        <label> Start :</label>
        <input type="text" name="start" id="start" style=" width: 107px !important;padding: 12px 20px !important;margin: 12px 0 !important;border: 1px solid #ccc !important;border-radius: 5px !important;" required/>

        <label>End : </label>
        <input type="text" name="end" id="end" style=" width: 107px !important;padding: 12px 20px !important;margin: 12px 0 !important;border: 1px solid #ccc !important;border-radius: 5px !important;" required/>
    </div>
</code>```

答:
JQuery bootstrap time picker for rails app:
And this code i provided validation for business hours starting and ending time.

Gemfile:

```<code>gem 'bootstrap-timepicker-rails-addon'
</code>```

application.js:

```<code>//= require bootstrap-timepicker
</code>```

application.css.scss:

```<code>*= require bootstrap-timepicker
</code>```

application.js:

```<code>$(window).on('click', function() {
  $('#timepicker_start').timepicker();
  $('#timepicker_end').timepicker();
})

$(function() {
  jQuery.validator.addMethod("lessThanZero", function(value, element) {
    //alert($('#timepicker_end').val());
     st = minFromMidnight($('#timepicker_start').val());
 et = minFromMidnight($('#timepicker_end').val());
console.log(st)
console.log(et)

    return st < et

}, "* Starting time must be greater than endingtime");
  $.validator.setDefaults({ ignore: ":hidden:not(select)" })
  $.validator.setDefaults({
    ignore: []
});

function minFromMidnight(tm){
 var ampm= tm.substr(-2)
 var clk = tm.substr(0, 5);
 var m  = parseInt(clk.match(/\d+/g)[1])
 var h  = parseInt(clk.match(/\d+/g)[0])
 h += (ampm.match(/pm/i))? 12: 0;
 return h*60+m;
}
</code>```

Body:
I need to restrict user to select end time greater than start time in a timepicker with 12 hrs format. - http://jsfiddle.net/jonthornton/28uvg/

         Start :
        <input type="text" name="start" id="start" style=" width: 107px !important;padding: 12px 20px !important;margin: 12px 0 !important;border: 1px solid #ccc !important;border-radius: 5px !important;" required/>

        End :
        <input type="text" name="end" id="end" style=" width: 107px !important;padding: 12px 20px !important;margin: 12px 0 !important;border: 1px solid #ccc !important;border-radius: 5px !important;" required/>

Body:
JQuery bootstrap time picker for rails app:
And this code i provided validation for business hours starting and ending time.

Gemfile:

gem 'bootstrap-timepicker-rails-addon'

application.js:

//= require bootstrap-timepicker

application.css.scss:

*= require bootstrap-timepicker

application.js:

$(window).on('click', function() {
  $('#timepicker_start').timepicker();
  $('#timepicker_end').timepicker();
})

$(function() {
  jQuery.validator.addMethod("lessThanZero", function(value, element) {
    //alert($('#timepicker_end').val());
     st = minFromMidnight($('#timepicker_start').val());
 et = minFromMidnight($('#timepicker_end').val());
console.log(st)
console.log(et)

    return st < et

}, "* Starting time must be greater than endingtime");
  $.validator.setDefaults({ ignore: ":hidden:not(select)" })
  $.validator.setDefaults({
    ignore: []
});

function minFromMidnight(tm){
 var ampm= tm.substr(-2)
 var clk = tm.substr(0, 5);
 var m  = parseInt(clk.match(/\d+/g)[1])
 var h  = parseInt(clk.match(/\d+/g)[0])
 h += (ampm.match(/pm/i))? 12: 0;
 return h*60+m;
}