问:
Winforms: Which event to fire? combobox.selectedindexchanged OR bindingsource.currentchanged
Assume we have a Combobox in a winforms application which its items bound to a Bindingsource.

I need to fire an event when the user changes the selected item in the combobox.

Should I handle the combobox.selectedindexchanged event or bindingsource.currentchanged event. Which is better in case of performance or anything else?

I've searched a lot to find an article or something about it, but can't find something straight and clear. I appreciate any suggestion or workaround.

UPDATE

I need to call a function base on the selected object ID after user select an Item from combobox. (ID is accessible from both Combobox1.SelectedValue and bindingSource1.Current.ID).  In this case which event shouldI choose?

答:
If a ComboBox is bound to a BindingSource you usually leave it at that. If you do need to tap into events you're better off creating more properties in the Business Object. For example say you want to disable a button if the combobox is Index Value == 0, simply create a property in the Business Object that the Enabled property of the Button is bound to, eg:

```<code>public virtual bool IsFunctionEnabled
{
  get { return (An_Items_SelectedIndex > 0); }
}
</code>```

If you really need to do stuff in the ComboBox's selected index change event I would lean towards doing it in the Presentation Tier as I don't recommend mucking with binding source controls or their events.

The best solution is handling everything in your Business Objects and binding your controls via BindingSources. Doing any logic in the Presentation Tier makes it hard to test and changing anything in the BindingSources add a lot of testing.

Body:
If a ComboBox is bound to a BindingSource you usually leave it at that. If you do need to tap into events you're better off creating more properties in the Business Object. For example say you want to disable a button if the combobox is Index Value == 0, simply create a property in the Business Object that the Enabled property of the Button is bound to, eg:

public virtual bool IsFunctionEnabled
{
  get { return (An_Items_SelectedIndex > 0); }
}

If you really need to do stuff in the ComboBox's selected index change event I would lean towards doing it in the Presentation Tier as I don't recommend mucking with binding source controls or their events.

The best solution is handling everything in your Business Objects and binding your controls via BindingSources. Doing any logic in the Presentation Tier makes it hard to test and changing anything in the BindingSources add a lot of testing.


来源: stackexchange

问:
How to make ViewChild work in a unit test
I have a test like

```<code>@Component(
  selector: 'my-test',
  template: 'none',
  changeDetection: ChangeDetectionStrategy.OnPush,
)
class MyTestComponent {
  final AngularClientCache clientCache;
  MyTestComponent(this.clientCache) {
    assert(clientCache != null);
  }
}

@Component(
  selector: 'test',
  directives: const <dynamic>[MyTestComponent],
  template: r'<my-test></my-test>',
)
class ComplexTestComponent {
  @ViewChild(MyTestComponent) MyTestComponent testComponent;
}

@AngularEntrypoint()
void main() {
  tearDown(() => disposeAnyRunningTest());

  group('AngularClientCache', () {
    test('should store and return value', () async {

      final testBed =
          new NgTestBed<ComplexTestComponent>().addProviders(<dynamic>[
        provide(AngularClientCache, useValue: new AngularClientCache())
      ]);
      final fixture = await testBed.create();

      // Create an instance of the in-browser page loader that uses our fixture.
      final loader = new HtmlPageLoader(
        fixture.rootElement.parent,
        executeSyncedFn: (c) async {
          await c();
          return fixture.update;
        },
        useShadowDom: false,
      );

      final complex =
          await loader.getInstance<ComplexTestComponent>(ComplexTestComponent);
      print(complex.testComponent); // <<<=== print `null`
    });
  });
}
</code>```

How can I get a reference to the MyTestComponent component.
I expected @ViewChild() to do it, but it doesn't. Any other approach is welcome as well.

答:
Matan Lurey explained in (https://github.com/dart-lang/angular_test/issues/50#issuecomment-291044761 broken)

resolvePageObject is only for getting a package:pageloader object.

What you're trying to do, I think:

```<code>await fixture.update((c) {
  expect(c.testComponent, isNotNull);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a test like

@Component(
  selector: 'my-test',
  template: 'none',
  changeDetection: ChangeDetectionStrategy.OnPush,
)
class MyTestComponent {
  final AngularClientCache clientCache;
  MyTestComponent(this.clientCache) {
    assert(clientCache != null);
  }
}

@Component(
  selector: 'test',
  directives: const <dynamic>[MyTestComponent],
  template: r'<my-test></my-test>',
)
class ComplexTestComponent {
  @ViewChild(MyTestComponent) MyTestComponent testComponent;
}

@AngularEntrypoint()
void main() {
  tearDown(() => disposeAnyRunningTest());

  group('AngularClientCache', () {
    test('should store and return value', () async {

      final testBed =
          new NgTestBed<ComplexTestComponent>().addProviders(<dynamic>[
        provide(AngularClientCache, useValue: new AngularClientCache())
      ]);
      final fixture = await testBed.create();

      // Create an instance of the in-browser page loader that uses our fixture.
      final loader = new HtmlPageLoader(
        fixture.rootElement.parent,
        executeSyncedFn: (c) async {
          await c();
          return fixture.update;
        },
        useShadowDom: false,
      );

      final complex =
          await loader.getInstance<ComplexTestComponent>(ComplexTestComponent);
      print(complex.testComponent); // <<<=== print `null`
    });
  });
}

How can I get a reference to the MyTestComponent component.
I expected @ViewChild() to do it, but it doesn't. Any other approach is welcome as well.

Body:
Matan Lurey explained in (https://github.com/dart-lang/angular_test/issues/50#issuecomment-291044761 broken)

resolvePageObject is only for getting a package:pageloader object.

What you're trying to do, I think:

await fixture.update((c) {
  expect(c.testComponent, isNotNull);
});


问:
How to add and remove active class to anchor tag within li using Jquery/Javascript
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

```<code><ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>
</code>```

My active class is given below.

```<code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}
</code>```

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

答:
Try this:

```<code><ul id="ulCategory">
  <li><a href="javascript:void(0)" class="subcategory">ABC</li>
  <li><a href="javascript:void(0)" class="subcategory">ABF</li>
  <li><a href="javascript:void(0)" class="subcategory">ABK</li>
</ul>
</code>```

Jquery:

```<code>$(".subcategory").click(function() {
  $(this).addClass("active").not(this).removeClass("active");
});
</code>```

Body:
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

ABC

ABF

ABK

My active class is given below.

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

Body:
Try this:

<ul id="ulCategory">
  <li><a href="javascript:void(0)" class="subcategory">ABC</li>
  <li><a href="javascript:void(0)" class="subcategory">ABF</li>
  <li><a href="javascript:void(0)" class="subcategory">ABK</li>
</ul>

Jquery:

$(".subcategory").click(function() {
  $(this).addClass("active").not(this).removeClass("active");
});


答:
$("#ulCategory a").click(function() {

  $(this).addClass("active")
  $("a").not(this).removeClass("active")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  text-align: left;
  color: #fff;
  background-color: #ffbb00;
  text-decoration: none;
}</code>```

ABC

ABF

ABK

```

Use addClass() and removeClass() with not()

In href use #

Title: How to add and remove active class to anchor tag within li using Jquery/Javascript

Body:
$("#ulCategory a").click(function() {

  $(this).addClass("active")
  $("a").not(this).removeClass("active")
})

.active {
  text-align: left;
  color: #fff;
  background-color: #ffbb00;
  text-decoration: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ulCategory">
  <li><a href='#'>ABC</a></li>
  <li><a href='#'>ABF</a></li>
  <li><a href='#'>ABK</a></li>

</ul>

Use addClass() and removeClass() with not()

In href use #


答: If you wish to handle event when end user selects any item in UI then you should go with combobox.selectedindexchanged because bindingsource.currentchanged can be triggered for number reasons such as mentioned here on MSDN blog, BindingSource.CurrentChanged Event so in case, you need to handle an event for any of the reason mentioned in MSDN then it will unnecessarily go through logic you might have coded for selection change event. Your code should be specific, while handling events.

Title: Winforms: Which event to fire? combobox.selectedindexchanged OR bindingsource.currentchanged

Body:
Assume we have a Combobox in a winforms application which its items bound to a Bindingsource.

I need to fire an event when the user changes the selected item in the combobox.

Should I handle the combobox.selectedindexchanged event or bindingsource.currentchanged event. Which is better in case of performance or anything else?

I've searched a lot to find an article or something about it, but can't find something straight and clear. I appreciate any suggestion or workaround.

UPDATE

I need to call a function base on the selected object ID after user select an Item from combobox. (ID is accessible from both Combobox1.SelectedValue and bindingSource1.Current.ID).  In this case which event shouldI choose?


问:
store username in keychain with different key
I want to store username and password in keychain.  As far I have explored we can store it and retrieve it like this

Store username and password

```<code>[_keychainObject setObject:username forKey:(id)kSecAttrAccount];
[_keychainObject setObject:password forKey:(id)kSecValueData];
</code>```

Retrieve username and password

```<code>NSLog(@"%@", [_keychainObject objectForKey:(id)kSecAttrAccount]);
NSLog(@"%@", [_keychainObject objectForKey:(id)kSecValueData]);
</code>```

Why can't we store it like this

```<code>[_keychainObject setObject:username forKey:@"username"];
</code>```

If I do so its not storing the data.  Is it mandatory to use predefined keys to store an item in keychain?

答: I would recommend checking out SAMKeychain https://github.com/soffes/SAMKeychain.</p>

Body:
I want to store username and password in keychain.  As far I have explored we can store it and retrieve it like this

Store username and password

[_keychainObject setObject:username forKey:(id)kSecAttrAccount];
[_keychainObject setObject:password forKey:(id)kSecValueData];

Retrieve username and password

NSLog(@"%@", [_keychainObject objectForKey:(id)kSecAttrAccount]);
NSLog(@"%@", [_keychainObject objectForKey:(id)kSecValueData]);

Why can't we store it like this

[_keychainObject setObject:username forKey:@"username"];

If I do so its not storing the data.  Is it mandatory to use predefined keys to store an item in keychain?


问:
Getting last modified date of file on FTP server using urlopen not working
```<code>from six.moves.urllib.request import urlopen, urlretrieve, urlrequest

conn = urlopen('ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/surface/lftx.sfc.2017.nc', timeout=20)
last_modified = conn.headers['last-modified']
</code>```

Following How can I get the last-modified time with python3 urllib? I want to get last modification date of a file on a FTP server. However, with the code above, last-modified is None. Any suggestions? I want solution to work on both python 2 and python 3

答:
The documentation of urlopen does not claim that it returns last-modified for FTP URLs.

Note that there are no headers in FTP protocol. The urlopen just fakes few HTTP-like headers for some kind of compatibility of the interface across protocols.

To retrieve timestamp using FTP, use the ftplib. See How to get FTP file's modify time using Python ftplib.

Body:
from six.moves.urllib.request import urlopen, urlretrieve, urlrequest

conn = urlopen('ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/surface/lftx.sfc.2017.nc', timeout=20)
last_modified = conn.headers['last-modified']

Following How can I get the last-modified time with python3 urllib? I want to get last modification date of a file on a FTP server. However, with the code above, last-modified is None. Any suggestions? I want solution to work on both python 2 and python 3


问:
Polymer 2.0 $$() does not work
In Polymer 1.x where this.$$('some selector') was working, what is the equivalent in Polymer 2.0 since this.$$() doesnt work anymore?

Thanks.

答:
$$ is deprecated in Polymer 2.x instead you'll have to use something like

```<code>this.shadowRoot.querySelector
</code>```

If you really want to use $$ you can use it from LegacyMixin which has all the deprecated methods. As LegacyMixin internally extends Polymer.Element you only need to extend LegacyMixin.

```<code>class MyElement extends  Polymer.LegacyElement
</code>```

Title: Polymer 2.0 $$() does not work

Body:
$$ is deprecated in Polymer 2.x instead you'll have to use something like

this.shadowRoot.querySelector

If you really want to use $$ you can use it from LegacyMixin which has all the deprecated methods. As LegacyMixin internally extends Polymer.Element you only need to extend LegacyMixin.

class MyElement extends  Polymer.LegacyElement


问:
how to create website using Django
I have one Django App. I want to get this app on World Wide Web.
Can anyone please help me with steps.
Like Some server addition(e.g. Apache or Nginx),Configuration of server,Integrating with Django,Web Hosting,etc.

Thanks

答:
This at this link you will find a tutorial that helps you to deploy your app with NGINX
http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html

simple and fast

Title: how to create website using Django


问:
Clean code - Where should @Autowired be applied?
I'll start with a simple example. You have a Spring boot application that runs a CommandLineRunner class on initialization.

```<code>// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    @Autowired //IntelliJ Warning
    private DataSource ds;
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner();
    }
}
</code>```

Now, like this, this works, everything is OK. However, IntelliJ reports a warning where @Autowired is located (I marked where in the comment)

Spring team recommends: Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies.

Now if I follow this, I have a constructor based dependency injection

```<code>@Autowired
public MyCommandLineRunner(DataSource ds) { ... }
</code>```

This also means that I have to edit Application.java as well, since the constructor needs an argument. In Application.java if I try to use the setter injection, I'll get the same warning. If I refactor that as well, I'll end up with some, in my opinion, nasty code.

```<code>// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private DataSource ds;
    @Autowired // Note that this line is practically useless now, since we're getting this value as a parameter from Application.java anyway.
    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    private DataSource ds;
    @Autowired
    public Application(DataSource ds) { this.ds = ds; }
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner(ds);
    }
}
</code>```

The above code yields the same result, but doesn't report any warnings in IntelliJ.
I'm confused, how is the 2nd code better than the first one? Am I following an incorrect logic? Should this be wired differently?

In short, what's the correct way to do this?

note DataSource is just a pure example, this question applies to anything being autowired.

note 2 Just to say that MyCommandLineRunner.java can't have another, empty, constructor, since DataSource needs to be autowired/initialized. It will report an error and will not be compiled.

答:
There are several ways to improve it.

You can remove @Autowired from your MyCommandLineRunner as you are letting a @Bean method construct an instance of it. Inject the DataSource directly into the method as an argument.

Or remove @Autowired and remove the @Bean and slap a @Component annotation on your MyCommandLineRunner to have it detected and remove factory method.

Inline your MyCommandLineRunner inside your @Bean method as a lambda.

No Autowiring in the MyCommandLineRunner

```<code>public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private final DataSource ds;

    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }

    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
</code>```

And the application class.

```<code>@SpringBootApplication
public class Application {

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

    @Bean
    public MyCommandLineRunner schedulerRunner(DataSource ds) {
        return new MyCommandLineRunner(ds);
    }
}
</code>```

Usage of @Component

```<code>@Component
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private final DataSource ds;

    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }

    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
</code>```

And the application class.

```<code>@SpringBootApplication
public class Application {

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

}
</code>```

Inline CommandLineRunner

```<code>@SpringBootApplication
public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class)

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

    @Bean
    public MyCommandLineRunner schedulerRunner(DataSource ds) {
        return (args) -> (logger.info("DataSource: {}", ds);
    }
}
</code>```

All of these are valid ways of constructing your instances. Which one to use, use the one that you feel comfortable with. There are more options (all variations on the ones mentioned here).

ContentLicense: CC BY-SA 4.0

Body:
I'll start with a simple example. You have a Spring boot application that runs a CommandLineRunner class on initialization.

// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    @Autowired //IntelliJ Warning
    private DataSource ds;
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner();
    }
}

Now, like this, this works, everything is OK. However, IntelliJ reports a warning where @Autowired is located (I marked where in the comment)

Spring team recommends: Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies.

Now if I follow this, I have a constructor based dependency injection

@Autowired
public MyCommandLineRunner(DataSource ds) { ... }

This also means that I have to edit Application.java as well, since the constructor needs an argument. In Application.java if I try to use the setter injection, I'll get the same warning. If I refactor that as well, I'll end up with some, in my opinion, nasty code.

// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private DataSource ds;
    @Autowired // Note that this line is practically useless now, since we're getting this value as a parameter from Application.java anyway.
    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    private DataSource ds;
    @Autowired
    public Application(DataSource ds) { this.ds = ds; }
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner(ds);
    }
}

The above code yields the same result, but doesn't report any warnings in IntelliJ.
I'm confused, how is the 2nd code better than the first one? Am I following an incorrect logic? Should this be wired differently?

In short, what's the correct way to do this?

note DataSource is just a pure example, this question applies to anything being autowired.

note 2 Just to say that MyCommandLineRunner.java can't have another, empty, constructor, since DataSource needs to be autowired/initialized. It will report an error and will not be compiled.

Body:
There are several ways to improve it.

You can remove @Autowired from your MyCommandLineRunner as you are letting a @Bean method construct an instance of it. Inject the DataSource directly into the method as an argument.

Or remove @Autowired and remove the @Bean and slap a @Component annotation on your MyCommandLineRunner to have it detected and remove factory method.

Inline your MyCommandLineRunner inside your @Bean method as a lambda.

No Autowiring in the MyCommandLineRunner

public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private final DataSource ds;

    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }

    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}

And the application class.

@SpringBootApplication
public class Application {

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

    @Bean
    public MyCommandLineRunner schedulerRunner(DataSource ds) {
        return new MyCommandLineRunner(ds);
    }
}

Usage of @Component

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private final DataSource ds;

    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }

    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}

And the application class.

@SpringBootApplication
public class Application {

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

}

Inline CommandLineRunner

@SpringBootApplication
public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class)

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

    @Bean
    public MyCommandLineRunner schedulerRunner(DataSource ds) {
        return (args) -> (logger.info("DataSource: {}", ds);
    }
}

All of these are valid ways of constructing your instances. Which one to use, use the one that you feel comfortable with. There are more options (all variations on the ones mentioned here).


问:
secure include files
I'd like to know the BEST solution to secure includes files.
For now my solution is this :

in the index file :

```<code>define('KEY','security');
include('s.php';
</code>```

s.php :

```<code>if(KEY!='security') exit;
</code>```

答:
The best way would be to not put protected files under the document root (public_html, www, htdocs, etc). You can always include PHP files from the outside of the document root:

/home/user/public_html/index.php:

```<code><?php

include('../include.php');
// /home/user/include.php -- not accessible!
</code>```

ContentLicense: CC BY-SA 2.5

Title: secure include files

Body:
I'd like to know the BEST solution to secure includes files.
For now my solution is this :

in the index file :

define('KEY','security');
include('s.php';

s.php :

if(KEY!='security') exit;

Body:
The best way would be to not put protected files under the document root (public_html, www, htdocs, etc). You can always include PHP files from the outside of the document root:

/home/user/public_html/index.php:

<?php

include('../include.php');
// /home/user/include.php -- not accessible!


答:
check below snippet

$(document).ready(function(){
  $("#ulCategory li").on('click', function(){
    $(this).siblings().removeClass('active');
    $(this).addClass('active')
  })
})
function savesubcat(){
  return null
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}</code>```

href='javascript:void(0)' onclick='savesubcat()'>ABC

href='javascript:void(0)' onclick='savesubcat()'>ABF

href='javascript:void(0)' onclick='savesubcat()'>ABK

```

Body:
check below snippet

$(document).ready(function(){
  $("#ulCategory li").on('click', function(){
    $(this).siblings().removeClass('active');
    $(this).addClass('active')
  })
})
function savesubcat(){
  return null
}

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>


问:
How to check if locationManager has updated current location?
I would like to show user's current location on startup, and then keep tracking their location but stop centring on the current location. My idea is to centre on the current location in viewDidLoad(), but I don't know how to wait for locationManager to update the current location before centring. Here are the relevant parts of my code:</p>

```<code>var currentLocation : CLLocation?
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        // wait for currentLocation to be updated
        animateMap(currentLocation!)

    }

    mapView.showsUserLocation = true
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
}

func animateMap(_ location: CLLocation) {
    let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000)
    mapView.setRegion(region, animated: true)
}
</code>```

答:
Call the animateMap function in didUpdateLocations delegate method, instead of in viewDidLoad. And, allow the map to center only the first time. You can you some bool variable for that.</p>

```<code>var isLocationUpdated = false

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
    if (!isLocationUpdated)
     {
        animateMap(currentLocation!)
        isLocationUpdated = true
     }
}
</code>```

Body:
I would like to show user's current location on startup, and then keep tracking their location but stop centring on the current location. My idea is to centre on the current location in viewDidLoad(), but I don't know how to wait for locationManager to update the current location before centring. Here are the relevant parts of my code:

var currentLocation : CLLocation?
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        // wait for currentLocation to be updated
        animateMap(currentLocation!)

    }

    mapView.showsUserLocation = true
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
}

func animateMap(_ location: CLLocation) {
    let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000)
    mapView.setRegion(region, animated: true)
}

Body:
Call the animateMap function in didUpdateLocations delegate method, instead of in viewDidLoad. And, allow the map to center only the first time. You can you some bool variable for that.

var isLocationUpdated = false

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations.last!
    if (!isLocationUpdated)
     {
        animateMap(currentLocation!)
        isLocationUpdated = true
     }
}


问:
Method called after release Exception Camera preview
I have one activity class(CameraActivity) which is using my CameraPreview class. In "OnResume" the camera and preview are initiated. In "OnPause", i am releasing camera resources. When application is started, everything works fine inside the "OnResume" but when i start another activity through intent (E.g. open url in browser) and then come back to my activity then exception is occured inside "OnResume" originating CamerPreview class. Please find below the code:

//CameraActivity class

```<code>public void onResume(){
    super.onResume();
    Log.d("inside onResume, camera==="+mCamera, "inside onResume");
    try {
        if(mCamera==null)
        {

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();
        int rotation = this.getWindowManager().getDefaultDisplay().getRotation();

        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);

        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);

    }

} catch (Exception e) {
    // TODO Auto-generated catch block
    Log.e("onResume",Log.getStackTraceString(e));
}

public void onPause{
    try {
        super.onPause();
        if (mCamera != null) {
            previewing = false;
            mCamera.stopPreview();
                mCamera.setPreviewCallback(null);
                mCamera.release();
                mCamera = null;
                mPreview=null;

    }
} catch (Exception e) {
    // TODO Auto-generated catch block
    Log.e("releaseCamera",Log.getStackTraceString(e));
}
}

 public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
            Log.e("getCameraInstance",Log.getStackTraceString(e));

    }
    return c;
}
</code>```

// Following is CameraPreview Class:

```<code>public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    Camera mCamera;
    PreviewCallback previewCallback;
    AutoFocusCallback autoFocusCallback;
    private int rotation;
    public int getRotation() {
        return rotation;
    }

    public void setRotation(int rotation) {
        this.rotation = rotation;
    }

    public CameraPreview(Context context, Camera camera,
                         PreviewCallback previewCb,
                         AutoFocusCallback autoFocusCb) {
        super(context);
        mCamera = camera;
        previewCallback = previewCb;
        autoFocusCallback = autoFocusCb;

        /*
         * Set camera to continuous focus if supported, otherwise use
         * software auto-focus. Only works for API level >=9.
         */
        /*
        Camera.Parameters parameters = camera.getParameters();
        for (String f : parameters.getSupportedFocusModes()) {
            if (f == Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
                mCamera.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                autoFocusCallback = null;
                break;
            }
        }
        */

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            if(mCamera==null){
                mCamera=Camera.open();
            }
            mCamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            Log.d("DBG", "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {

        // Camera preview released in activity
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        /*
         * If your preview can change or rotate, take care of those events here.
         * Make sure to stop the preview before resizing or reformatting it.
         */
        if (mHolder.getSurface() == null){
          // preview surface does not exist
          return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
          // ignore: tried to stop a non-existent preview
        }

try{
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e){
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }
    }

}
</code>```

This is from logCat:

```<code>11-05 10:14:34.585: E/AndroidRuntime(7864): FATAL EXCEPTION: main
11-05 10:14:34.585: E/AndroidRuntime(7864): java.lang.RuntimeException: Method called after release()
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.hardware.Camera.setPreviewDisplay(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.hardware.Camera.setPreviewDisplay(Camera.java:393)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceCreated(CameraPreview.java:74)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.SurfaceView.updateWindow(SurfaceView.java:552)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.os.Looper.loop(Looper.java:130)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.app.ActivityThread.main(ActivityThread.java:3687)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at java.lang.reflect.Method.invoke(Method.java:507)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at dalvik.system.NativeStart.main(Native Method)
</code>```

EDIT

I updated "surfaceDestroyed" and put logs as suggested but now i am getting exception in "onPause" --> onSurfaceDestroyed. Initially onPause was executing fine.

1- The camera instance is created in "onResume" of activity class through method "getCameraInstance" and passes mCamera instance to CameraPreview Class. I tried to change it so that camera instance is created only onside "onSurfaceCreated" and assigned back the mCamera instance to the activity class but it did not work. I also noticed through debug that previewCallBack member of "CameraPreview" class is valid the first time but second time the "previewCallBack" member of "CameraPreview" class is null.

Note that first time when "onResume" is called, everything works fine but when it runs second time after onPause then exception is occured originally although code is the same in onResume.

```<code>11-06 01:25:28.375: I/onResume(4332): INITIATED
// Workinf fine till now. Now opening another intent activity
11-06 01:26:23.500: I/onPause(4332): INITIATED
11-06 01:26:23.804: "OnSurfaceDestroyed": "Initiated"
11-06 01:26:23.945: E/AndroidRuntime(4332): FATAL EXCEPTION: main
11-06 01:26:23.945: E/AndroidRuntime(4332): java.lang.RuntimeException: Method called after release()
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.hardware.Camera.stopPreview(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceDestroyed(CameraPreview.java:85)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.reportSurfaceDestroyed(SurfaceView.java:596)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.updateWindow(SurfaceView.java:490)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.os.Looper.loop(Looper.java:130)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.app.ActivityThread.main(ActivityThread.java:3687)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invokeNative(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invoke(Method.java:507)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I was getting same error. Below sequence solves my problem.

Call  getHolder().removeCallback(this); in surfaceDestroyed()

Call

```<code> private void releaseCameraAndPreview() {

        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }

        if(mPreview != null){
            mPreview.destroyDrawingCache();
            mPreview.mCamera = null;
        }

    }
</code>```

in onPause

Call

```<code>  private boolean safeCameraOpenInView(View view) {
        boolean qOpened = false;
        releaseCameraAndPreview();
        mCamera = getCameraInstance();
        mCameraView = view;
        qOpened = (mCamera != null);

        if(qOpened == true){
            mPreview = new CameraPreview(getActivity().getBaseContext(), mCamera,view);
            preview = (FrameLayout) view.findViewById(R.id.camera_preview);
            preview.addView(mPreview);
            mPreview.startCameraPreview();
        }
        return qOpened;
    }
</code>```

in onCreateView().

Body:
I have one activity class(CameraActivity) which is using my CameraPreview class. In "OnResume" the camera and preview are initiated. In "OnPause", i am releasing camera resources. When application is started, everything works fine inside the "OnResume" but when i start another activity through intent (E.g. open url in browser) and then come back to my activity then exception is occured inside "OnResume" originating CamerPreview class. Please find below the code:

//CameraActivity class

public void onResume(){
    super.onResume();
    Log.d("inside onResume, camera==="+mCamera, "inside onResume");
    try {
        if(mCamera==null)
        {

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();
        int rotation = this.getWindowManager().getDefaultDisplay().getRotation();

        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);

        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);

    }

} catch (Exception e) {
    // TODO Auto-generated catch block
    Log.e("onResume",Log.getStackTraceString(e));
}

public void onPause{
    try {
        super.onPause();
        if (mCamera != null) {
            previewing = false;
            mCamera.stopPreview();
                mCamera.setPreviewCallback(null);
                mCamera.release();
                mCamera = null;
                mPreview=null;

    }
} catch (Exception e) {
    // TODO Auto-generated catch block
    Log.e("releaseCamera",Log.getStackTraceString(e));
}
}

 public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
            Log.e("getCameraInstance",Log.getStackTraceString(e));

    }
    return c;
}

// Following is CameraPreview Class:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    Camera mCamera;
    PreviewCallback previewCallback;
    AutoFocusCallback autoFocusCallback;
    private int rotation;
    public int getRotation() {
        return rotation;
    }

    public void setRotation(int rotation) {
        this.rotation = rotation;
    }

    public CameraPreview(Context context, Camera camera,
                         PreviewCallback previewCb,
                         AutoFocusCallback autoFocusCb) {
        super(context);
        mCamera = camera;
        previewCallback = previewCb;
        autoFocusCallback = autoFocusCb;

        /*
         * Set camera to continuous focus if supported, otherwise use
         * software auto-focus. Only works for API level >=9.
         */
        /*
        Camera.Parameters parameters = camera.getParameters();
        for (String f : parameters.getSupportedFocusModes()) {
            if (f == Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
                mCamera.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                autoFocusCallback = null;
                break;
            }
        }
        */

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            if(mCamera==null){
                mCamera=Camera.open();
            }
            mCamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            Log.d("DBG", "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {

        // Camera preview released in activity
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        /*
         * If your preview can change or rotate, take care of those events here.
         * Make sure to stop the preview before resizing or reformatting it.
         */
        if (mHolder.getSurface() == null){
          // preview surface does not exist
          return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
          // ignore: tried to stop a non-existent preview
        }

try{
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e){
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }
    }

}

This is from logCat:

11-05 10:14:34.585: E/AndroidRuntime(7864): FATAL EXCEPTION: main
11-05 10:14:34.585: E/AndroidRuntime(7864): java.lang.RuntimeException: Method called after release()
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.hardware.Camera.setPreviewDisplay(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.hardware.Camera.setPreviewDisplay(Camera.java:393)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceCreated(CameraPreview.java:74)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.SurfaceView.updateWindow(SurfaceView.java:552)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.os.Looper.loop(Looper.java:130)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.app.ActivityThread.main(ActivityThread.java:3687)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at java.lang.reflect.Method.invoke(Method.java:507)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at dalvik.system.NativeStart.main(Native Method)

EDIT

I updated "surfaceDestroyed" and put logs as suggested but now i am getting exception in "onPause" --> onSurfaceDestroyed. Initially onPause was executing fine.

1- The camera instance is created in "onResume" of activity class through method "getCameraInstance" and passes mCamera instance to CameraPreview Class. I tried to change it so that camera instance is created only onside "onSurfaceCreated" and assigned back the mCamera instance to the activity class but it did not work. I also noticed through debug that previewCallBack member of "CameraPreview" class is valid the first time but second time the "previewCallBack" member of "CameraPreview" class is null.

Note that first time when "onResume" is called, everything works fine but when it runs second time after onPause then exception is occured originally although code is the same in onResume.

11-06 01:25:28.375: I/onResume(4332): INITIATED
// Workinf fine till now. Now opening another intent activity
11-06 01:26:23.500: I/onPause(4332): INITIATED
11-06 01:26:23.804: "OnSurfaceDestroyed": "Initiated"
11-06 01:26:23.945: E/AndroidRuntime(4332): FATAL EXCEPTION: main
11-06 01:26:23.945: E/AndroidRuntime(4332): java.lang.RuntimeException: Method called after release()
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.hardware.Camera.stopPreview(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceDestroyed(CameraPreview.java:85)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.reportSurfaceDestroyed(SurfaceView.java:596)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.updateWindow(SurfaceView.java:490)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.os.Looper.loop(Looper.java:130)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.app.ActivityThread.main(ActivityThread.java:3687)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invokeNative(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invoke(Method.java:507)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at dalvik.system.NativeStart.main(Native Method)

Body:
I was getting same error. Below sequence solves my problem.

Call  getHolder().removeCallback(this); in surfaceDestroyed()

Call

 private void releaseCameraAndPreview() {

        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }

        if(mPreview != null){
            mPreview.destroyDrawingCache();
            mPreview.mCamera = null;
        }

    }

in onPause

Call

  private boolean safeCameraOpenInView(View view) {
        boolean qOpened = false;
        releaseCameraAndPreview();
        mCamera = getCameraInstance();
        mCameraView = view;
        qOpened = (mCamera != null);

        if(qOpened == true){
            mPreview = new CameraPreview(getActivity().getBaseContext(), mCamera,view);
            preview = (FrameLayout) view.findViewById(R.id.camera_preview);
            preview.addView(mPreview);
            mPreview.startCameraPreview();
        }
        return qOpened;
    }

in onCreateView().


问:
'fbauth2 is missing from your Info.plist under LSApplicationQueriesSchemes and is required for iOS 9.0'
What does this error mean?

When I run my project at 'ProjectA...eter' I can share to FB.

But when I run it at 'ProjectA...Checkin' the error appeared

Anybody helps me about this error.

Thank you for supporting me

答: You need to add fbauth2 to the LSApplicationQueriesSchemes array in your app's info.plist file. Apple made it so that apps need to whitelist the URL schemes that they'll attempt to call -canOpenURL: on in iOS 9 and above under the LSApplicationQueriesSchemes key, and it sounds like the SDK you're using requires it. For more info see here.


问:
python pandas date convertion to words
I have a particular format of date in my dataframe as
df:
     Date
  12-Jun-16
  22-Jan-12

I want to covert it to this format
df:
     Date
  12-Jan-2015

Any help as to how to do it?

答:
I think you need convert column to_datetime and then if need change format add strftime:

```<code>df.Date = pd.to_datetime(df.Date).dt.strftime('%d-%b-%Y')
print (df)
          Date
0  12-Jun-2016
1  22-Jan-2012
</code>```

Title: python pandas date convertion to words

Body:
I think you need convert column to_datetime and then if need change format add strftime:

df.Date = pd.to_datetime(df.Date).dt.strftime('%d-%b-%Y')
print (df)
          Date
0  12-Jun-2016
1  22-Jan-2012


问:
Speed of different data structures in Python
I have a piece of code I need to run, however, it is taking so long. I estimate it will take a minimum of 2 hours to run and at most 100 hours. As you can see, I would like to speed this up.

My code is as follows:

```<code>#B1
file = open("/home/1015097/Downloads/B1/tour5.txt", "r").readlines()
# This is a very large file. You can find it on http://codemasters.eng.unimelb.edu.au/bit_problems/B1.zip
# It is named tour5.txt, you can also find the question I am trying to solve there.
racers = [int(file[0].split()[0]) / float(x) for x in file[0].split()[1::]]
print("hi")
def av(race):
    race = race.split()
    j = 0
    while j != len([float(race[0]) / float(x) for x in race[1::]]):
        racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
        j += 1
        print(j)
    print("yay...")
for i in range(1, len(file)):
    print("yay")
    av(file[i])
print("yaaay")
a = min(racers)
del(racers[racers.index(min(racers))])
b = min(racers)
c = b-a
h = int(c)
c-=h

m = int(c * 60)
c-=m/60
s = round(c * 60 * 60)
print(str(h) + "h" + str(m) + "m" + str(s) + "s")
</code>```

We are currently coming first in Australia for the Code Bits contest and would not like to drop our perfect score. The random print statements were so that we could tell if the code was actually running, they are essentially checkpoints. the number that is printed out is the racer number, there are at least 3000 racers, we do not know exactly.

答:
Avoid loops like the plague. Vectorize everything. Use numpy, etc. If you have to, even look into Cython. But most importantly, vectorize.

The av() function is probably the part where your code is taking the most time (btw, it would be a good idea to profile the code at various points, figure out the most taxing process and focus on vectorizing it). Also, try to minimize the number of initializations. If you can, create an object only once and for all.

Below is how I would change up the function.

```<code>import numpy as np

racers = np.array(racers)

def av(race, racers):
    race = race.split()
    race_float = np.array(len([float(race[0]) / float(x) for x in race[1::]]))
    racers += race_float
    return racers
</code>```

Also, please refrain from:

Using print for debugging. You have a built-in logging module. Use it.

Using globals. Just pass them into functions as arguments and return the new object instead of directly modifying a global object.

Body:
I have a piece of code I need to run, however, it is taking so long. I estimate it will take a minimum of 2 hours to run and at most 100 hours. As you can see, I would like to speed this up.

My code is as follows:

#B1
file = open("/home/1015097/Downloads/B1/tour5.txt", "r").readlines()
# This is a very large file. You can find it on http://codemasters.eng.unimelb.edu.au/bit_problems/B1.zip
# It is named tour5.txt, you can also find the question I am trying to solve there.
racers = [int(file[0].split()[0]) / float(x) for x in file[0].split()[1::]]
print("hi")
def av(race):
    race = race.split()
    j = 0
    while j != len([float(race[0]) / float(x) for x in race[1::]]):
        racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
        j += 1
        print(j)
    print("yay...")
for i in range(1, len(file)):
    print("yay")
    av(file[i])
print("yaaay")
a = min(racers)
del(racers[racers.index(min(racers))])
b = min(racers)
c = b-a
h = int(c)
c-=h

m = int(c * 60)
c-=m/60
s = round(c * 60 * 60)
print(str(h) + "h" + str(m) + "m" + str(s) + "s")

We are currently coming first in Australia for the Code Bits contest and would not like to drop our perfect score. The random print statements were so that we could tell if the code was actually running, they are essentially checkpoints. the number that is printed out is the racer number, there are at least 3000 racers, we do not know exactly.

Body:
Avoid loops like the plague. Vectorize everything. Use numpy, etc. If you have to, even look into Cython. But most importantly, vectorize.

The av() function is probably the part where your code is taking the most time (btw, it would be a good idea to profile the code at various points, figure out the most taxing process and focus on vectorizing it). Also, try to minimize the number of initializations. If you can, create an object only once and for all.

Below is how I would change up the function.

import numpy as np

racers = np.array(racers)

def av(race, racers):
    race = race.split()
    race_float = np.array(len([float(race[0]) / float(x) for x in race[1::]]))
    racers += race_float
    return racers

Also, please refrain from:

Using print for debugging. You have a built-in logging module. Use it.

Using globals. Just pass them into functions as arguments and return the new object instead of directly modifying a global object.


问:
Getting Result From node.js multipleStatements query?
I have the following node.js code executing the SQL below it via the mysql module, however it is printing null to the console even when the SQL itself executed manually under the same MySQL user account returns the expected value.  Is there something I'm missing in the execution of this to retrieve the appropriate result?

```<code>let wipeSQL = fs.readFileSync('./inc/sql/wipedb.sql', 'utf8').replace('%%DATABASE_NAME%%', conf['databasedatabase']);
conn.query(wipeSQL, (err, results, fields) => {
    if (err) {
        conn.destroy();
        reject (false);
        return;
    }
    console.log(results[results.length - 1][0]['@procedures'], fields[fields.length - 1]);
    resolve();
});
</code>```

```<code>USE `%%DATABASE_NAME%%`;
SET FOREIGN_KEY_CHECKS = 0;

SET @procedures = '';
SELECT
    GROUP_CONCAT(CONCAT('DROP PROCEDURE IF EXISTS `', routine_schema, '`.`', routine_name, '`') SEPARATOR ';')
INTO
    @procedures
FROM
    information_schema.ROUTINES R
WHERE
    R.ROUTINE_TYPE = "PROCEDURE" AND
    R.ROUTINE_SCHEMA = '%%DATABASE_NAME%%';

SET @procedures = CONCAT(@procedures, ';');

SET @functions = '';
SELECT
    GROUP_CONCAT(CONCAT('DROP FUNCTION IF EXISTS `', routine_schema, '`.`', routine_name, '`') SEPARATOR ';')
INTO
    @functions
FROM
    information_schema.ROUTINES R
WHERE
    R.ROUTINE_TYPE = "FUNCTION" AND
    R.ROUTINE_SCHEMA = '%%DATABASE_NAME%%';

SET @functions = CONCAT(@functions, ';');
SET @procedures = CONCAT(@procedures, @functions);

SET @tables = '';
SELECT
    GROUP_CONCAT(CONCAT('`', table_schema, '`.`', table_name, '`'))
INTO
    @tables
FROM
    information_schema.tables
WHERE
    table_schema = '%%DATABASE_NAME%%';

SET @tables = IF(@tables IS NULL, 'SET @tables = NULL;', CONCAT('DROP TABLE ', @tables, ';'));

PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET FOREIGN_KEY_CHECKS = 1;

SELECT @procedures;
</code>```

The purpose is to work around an issue in MySQL which prevents deleting functions and stored procedures from dynamic SQL and from within another stored procedure, requiring that I return the things to be dropped and then execute those as a separate statement.  A solution to drop those functions and stored procedures would work just as well, but I don't expect it to exist (this is a port from PHP, in which the multiple statement return works well.  Console output, if it helps:

```<code>null [ FieldPacket {
    catalog: 'def',
    db: '',
    table: '',
    orgTable: '',
    name: '@procedures',
    orgName: '',
    charsetNr: 33,
    length: 50331645,
    type: 250,
    flags: 0,
    decimals: 31,
    default: undefined,
    zeroFill: false,
    protocol41: true } ]
</code>```

答: do console.log(wipeSQL) before conn.query and check what query is getting build and passing to conn.query.Then fire this query manually on mysql query browser to see results.</p>

Body:
I have the following node.js code executing the SQL below it via the mysql module, however it is printing null to the console even when the SQL itself executed manually under the same MySQL user account returns the expected value.  Is there something I'm missing in the execution of this to retrieve the appropriate result?

let wipeSQL = fs.readFileSync('./inc/sql/wipedb.sql', 'utf8').replace('%%DATABASE_NAME%%', conf['databasedatabase']);
conn.query(wipeSQL, (err, results, fields) => {
    if (err) {
        conn.destroy();
        reject (false);
        return;
    }
    console.log(results[results.length - 1][0]['@procedures'], fields[fields.length - 1]);
    resolve();
});

USE `%%DATABASE_NAME%%`;
SET FOREIGN_KEY_CHECKS = 0;

SET @procedures = '';
SELECT
    GROUP_CONCAT(CONCAT('DROP PROCEDURE IF EXISTS `', routine_schema, '`.`', routine_name, '`') SEPARATOR ';')
INTO
    @procedures
FROM
    information_schema.ROUTINES R
WHERE
    R.ROUTINE_TYPE = "PROCEDURE" AND
    R.ROUTINE_SCHEMA = '%%DATABASE_NAME%%';

SET @procedures = CONCAT(@procedures, ';');

SET @functions = '';
SELECT
    GROUP_CONCAT(CONCAT('DROP FUNCTION IF EXISTS `', routine_schema, '`.`', routine_name, '`') SEPARATOR ';')
INTO
    @functions
FROM
    information_schema.ROUTINES R
WHERE
    R.ROUTINE_TYPE = "FUNCTION" AND
    R.ROUTINE_SCHEMA = '%%DATABASE_NAME%%';

SET @functions = CONCAT(@functions, ';');
SET @procedures = CONCAT(@procedures, @functions);

SET @tables = '';
SELECT
    GROUP_CONCAT(CONCAT('`', table_schema, '`.`', table_name, '`'))
INTO
    @tables
FROM
    information_schema.tables
WHERE
    table_schema = '%%DATABASE_NAME%%';

SET @tables = IF(@tables IS NULL, 'SET @tables = NULL;', CONCAT('DROP TABLE ', @tables, ';'));

PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET FOREIGN_KEY_CHECKS = 1;

SELECT @procedures;

The purpose is to work around an issue in MySQL which prevents deleting functions and stored procedures from dynamic SQL and from within another stored procedure, requiring that I return the things to be dropped and then execute those as a separate statement.  A solution to drop those functions and stored procedures would work just as well, but I don't expect it to exist (this is a port from PHP, in which the multiple statement return works well.  Console output, if it helps:

null [ FieldPacket {
    catalog: 'def',
    db: '',
    table: '',
    orgTable: '',
    name: '@procedures',
    orgName: '',
    charsetNr: 33,
    length: 50331645,
    type: 250,
    flags: 0,
    decimals: 31,
    default: undefined,
    zeroFill: false,
    protocol41: true } ]


问:
Is it possible to combine DevExpress MVC Extensions with DexExtreme components in standard MVC application?
We should make a decision in our company what architecture to use in new web project. We've already successfully used DevExpress' WPF components and thinking of buying their web products, but don't have enough experience with them. So, the next question is for people who have some experience with DevExpress' web components.

Could we start the solution as standard MVC project built in VS 2013 and then add DevExpress' MVC extensions such as data grid etc. and DevExtreme components (jQuery or AngularJS) as well? If we can do that, could you explain, please, what could be possible difficulties?

答:
I think it isn't a good idea to mix up server-side DevExpress Mvc Extensions and client-side DevExtreme Widgets. If you are comfortable with asp.net mvc and want to use client-side javascript technologies, look at DevExtreme Mvc Wrappers.

It supports a convenient razor syntax to configure widgets. And you can use javascript to handle events, implement client-side templates etc.

To see how it works in action, refer DevExtreme demos.


问:
Bitwise NOT of Java BigInteger is Negative
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

```<code>BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));
</code>```

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

```<code>System.out.println(b.not().toString(2));
</code>```

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

```<code>BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}
</code>```

答:
signed byte 64  = 01000000

Invert it

and we get signed byte -65 = 10111111

Sign "minus" is the "not" operator itself:

-1000000 = 0111111

Type this and you see that the values are equal (+1) in absolute

```<code>System.out.println(b.toString());
System.out.println(b.not().toString());
</code>```

Body:
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

System.out.println(b.not().toString(2));

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}

Body:
signed byte 64  = 01000000

Invert it

and we get signed byte -65 = 10111111

Sign "minus" is the "not" operator itself:

-1000000 = 0111111

Type this and you see that the values are equal (+1) in absolute

System.out.println(b.toString());
System.out.println(b.not().toString());


问:
simple recursive merge sort Stack java.lang.StackOverflowError
I have a simple recursive merge sort, I am just try to sort an array list of Integers that implement Comparable. I don't under stand why I am getting an error, when it runs it prints out the ArrayList of random Integers that I created and then it prints

no error yet

no error yet

Exception in thread "main" java.lang.StackOverflowError

and then it repeats

at MergeTemplate.rMerge(MergeTemplate.java:38)

a bunch of times until it finally says

Process complete

```<code>import java.util.*;
public class MergeTemplate{
private ArrayList <Comparable> temp1=new <Comparable> ArrayList();
int num;
Random ar=new Random();
public MergeTemplate(){
    num=25;
}
  public MergeTemplate(int n){
    num=n;
  }
      public ArrayList <Comparable> fillArray(){
          ArrayList <Comparable> ar1=new <Comparable> ArrayList();
          for(int i=0;i<num; i++)
              ar1.add(ar.nextInt(11));
          screenOutput(ar1);
      return ar1;
      }
      public void screenOutput(){
          for(Comparable x: temp1)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void screenOutput(ArrayList <Comparable> temp){
          for(Comparable x: temp)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void rMerge(ArrayList <Comparable> rList){
          rMerge(rList, 0, rList.size()-1);
      }

      public void rMerge(ArrayList <Comparable> rList, int first, int last){
          if (first-last==0){
              System.out.println("no error yet");
          }
          else{
              rMerge(rList, first, last/2);
              rMerge(rList, last/2 + 1, last);
              merge(rList, first, last);
          }
      }
      public void merge(ArrayList <Comparable> a, int first, int last){
          Comparable placeHolder;
          if(a.get(first).compareTo(a.get(last))>1){
              placeHolder=a.get(first);
              a.set(first, a.get(last));
              a.set(last, placeHolder);
          }
      }
}

public class Tester {
    public static void main(String[] args) {
    MergeTemplate one=new MergeTemplate(8);
    one.rMerge(one.fillArray());
    }
}
</code>```

答:
You need one more key to represent the split point to divide the elements appropriately. The merge () method also needs to be re-implemented to iterate over all target elements.
The complete code with an implementation of the rMerge() method adding a single key called mid and an implementation of the merge() method as shown below.</p>

```<code>import java.util.ArrayList;
import java.util.Random;

public class MergeTemplate {

    private Random random = new Random();

    private ArrayList<Comparable> temp1 = new ArrayList<>();
    private int num;

    public MergeTemplate() {
        this.num = 25;
    }

    public MergeTemplate(int num) {
        this.num = num;
    }

    public ArrayList<Comparable> fillArray() {
        ArrayList<Comparable> ar1 = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            ar1.add(random.nextInt(11));
        }
        screenOutput(ar1);
        return ar1;
    }

    public void screeOutput() {
        for (Comparable x : temp1) {
            System.out.println(x + " ");
        }
        System.out.println();
    }

    public void screenOutput(ArrayList<Comparable> temp) {
        for (Comparable x : temp) {
            System.out.println(x + " ");
        }
        System.out.println();
    }

    public void rMerge(ArrayList<Comparable> rList) {
        rMerge(rList, 0, rList.size() - 1);
    }

    public void rMerge(ArrayList<Comparable> rList, int first, int last) {

        int mid = 0;
        if (first >= last) {
            System.out.println("no error yet");
        } else {
            mid = (first + last) / 2;
            rMerge(rList, first, mid);
            rMerge(rList, mid + 1, last);
            merge(rList, first, mid, last);
        }
    }

    public void merge(ArrayList<Comparable> a, int first, int mid, int last) {
        int i, j, k, m;

        i = first;
        j = mid + 1;
        k = first;

        ArrayList<Comparable> tempList = new ArrayList<>();

        // compare two divided parts
        while (i <= mid && j <= last) {
            if (a.get(i).compareTo(a.get(j)) < 1) {
                tempList.add(a.get(i));
                i++;
            } else {
                tempList.add(a.get(j));
                j++;
            }
            k++;
        }

        if (i > mid) {
            for (m = j; m <= last; m++) {
                tempList.add(a.get(m));
                k++;
            }
        } else {
            for (m = i; m <= mid; m++) {
                tempList.add(a.get(m));
                k++;
            }
        }

        for (i = 0, j = first; i < tempList.size(); i++, j++) {
            a.set(j, tempList.get(i));
        }

    }

}
</code>```

Body:
I have a simple recursive merge sort, I am just try to sort an array list of Integers that implement Comparable. I don't under stand why I am getting an error, when it runs it prints out the ArrayList of random Integers that I created and then it prints

no error yet

no error yet

Exception in thread "main" java.lang.StackOverflowError

and then it repeats

at MergeTemplate.rMerge(MergeTemplate.java:38)

a bunch of times until it finally says

Process complete

import java.util.*;
public class MergeTemplate{
private ArrayList <Comparable> temp1=new <Comparable> ArrayList();
int num;
Random ar=new Random();
public MergeTemplate(){
    num=25;
}
  public MergeTemplate(int n){
    num=n;
  }
      public ArrayList <Comparable> fillArray(){
          ArrayList <Comparable> ar1=new <Comparable> ArrayList();
          for(int i=0;i<num; i++)
              ar1.add(ar.nextInt(11));
          screenOutput(ar1);
      return ar1;
      }
      public void screenOutput(){
          for(Comparable x: temp1)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void screenOutput(ArrayList <Comparable> temp){
          for(Comparable x: temp)
              System.out.print(x+ " ");
          System.out.println();
      }
      public void rMerge(ArrayList <Comparable> rList){
          rMerge(rList, 0, rList.size()-1);
      }

      public void rMerge(ArrayList <Comparable> rList, int first, int last){
          if (first-last==0){
              System.out.println("no error yet");
          }
          else{
              rMerge(rList, first, last/2);
              rMerge(rList, last/2 + 1, last);
              merge(rList, first, last);
          }
      }
      public void merge(ArrayList <Comparable> a, int first, int last){
          Comparable placeHolder;
          if(a.get(first).compareTo(a.get(last))>1){
              placeHolder=a.get(first);
              a.set(first, a.get(last));
              a.set(last, placeHolder);
          }
      }
}

public class Tester {
    public static void main(String[] args) {
    MergeTemplate one=new MergeTemplate(8);
    one.rMerge(one.fillArray());
    }
}

Body:
You need one more key to represent the split point to divide the elements appropriately. The merge () method also needs to be re-implemented to iterate over all target elements.
The complete code with an implementation of the rMerge() method adding a single key called mid and an implementation of the merge() method as shown below.

import java.util.ArrayList;
import java.util.Random;

public class MergeTemplate {

    private Random random = new Random();

    private ArrayList<Comparable> temp1 = new ArrayList<>();
    private int num;

    public MergeTemplate() {
        this.num = 25;
    }

    public MergeTemplate(int num) {
        this.num = num;
    }

    public ArrayList<Comparable> fillArray() {
        ArrayList<Comparable> ar1 = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            ar1.add(random.nextInt(11));
        }
        screenOutput(ar1);
        return ar1;
    }

    public void screeOutput() {
        for (Comparable x : temp1) {
            System.out.println(x + " ");
        }
        System.out.println();
    }

    public void screenOutput(ArrayList<Comparable> temp) {
        for (Comparable x : temp) {
            System.out.println(x + " ");
        }
        System.out.println();
    }

    public void rMerge(ArrayList<Comparable> rList) {
        rMerge(rList, 0, rList.size() - 1);
    }

    public void rMerge(ArrayList<Comparable> rList, int first, int last) {

        int mid = 0;
        if (first >= last) {
            System.out.println("no error yet");
        } else {
            mid = (first + last) / 2;
            rMerge(rList, first, mid);
            rMerge(rList, mid + 1, last);
            merge(rList, first, mid, last);
        }
    }

    public void merge(ArrayList<Comparable> a, int first, int mid, int last) {
        int i, j, k, m;

        i = first;
        j = mid + 1;
        k = first;

        ArrayList<Comparable> tempList = new ArrayList<>();

        // compare two divided parts
        while (i <= mid && j <= last) {
            if (a.get(i).compareTo(a.get(j)) < 1) {
                tempList.add(a.get(i));
                i++;
            } else {
                tempList.add(a.get(j));
                j++;
            }
            k++;
        }

        if (i > mid) {
            for (m = j; m <= last; m++) {
                tempList.add(a.get(m));
                k++;
            }
        } else {
            for (m = i; m <= mid; m++) {
                tempList.add(a.get(m));
                k++;
            }
        }

        for (i = 0, j = first; i < tempList.size(); i++, j++) {
            a.set(j, tempList.get(i));
        }

    }

}


问:
latch(used for awaiting async response) freezes the WebView (and the UI)
I have an app that displays a webview on the whole layout. Sometimes I need to call an async method, that async operation is done by a 3-party sdk, and then I wait for it for a while until I get the response to a designated listener. I have solved it with a latch - once the response is received in the listener, I countDown the latch and then the initiating method can continue with this response.
Unfortunately, when I do this, the WebView is stuck. I imagined the native UI would be stuck , but I didn't expect the webview to get frozen as well.
How can that be overcome?

To make it clearer, here is an example. I need the ajaxFunc to wait until MyAsyncListener gets a certain response, and then return this exact response.

part of JS I inject to the webview :

```<code>var response = jsHandler.ajaxFunc(request.data);
</code>```

I have a variable global variable called response.

```<code>public class JavaScriptInterface
{
     @JavascriptInterface
     public String ajaxFunc(String data)
     {
         return MyUtils.handleData( data );
     }
}
</code>```

the handleData method :

```<code> public String handleData( String data )
 {
     SomeClass.startAsyncRequest(); // starts the async request, response is to come at the listener's callbacks .

     latch = new CountDownLatch(1);
     try {
         latch.await(30, TimeUnit.SECONDS);
     }
     catch (InterruptedException e) {
         e.printStackTrace();
     }

     return response;
   }
</code>```

now, once the handleData function calls a function, that does something asynchronously, the async function then returns some answer inside some Listener :

```<code>myAsyncListener = new MyAsyncListener() {
    @Override
        public Response handleEvent(CustomEvent event) {
            //Now I need to return this 'event' back to the handData/ajaxFunc function <--

            response = event.getName();
            latch.countDown();

        }
    });
</code>```

答:
You have put CountDownLatch inside your code which will cause blocking of your main thread. Thats the reason of lag on UI.

For better you should show some ProgressDialog before doing main work of Async task which generally written in doInBackground() method of Async task and hide it after completing your task, Async provide onPostExecute() method for that purpose.

If you need to put some timeout like your CountDownLatch is doing, you can write timer in doInBackground() of Async. That timer will stop your current Async will allotted time is elapsed.

Update, you could use EventBus for your purpose -

EventBus works on Publish/Subscribe pattern. You can subscribe in Activity and publish result from JavaScriptInterface.

Add it in gradle using -

```<code>compile 'org.greenrobot:eventbus:3.0.0'
</code>```

In your Activity start subscribing, generally subscriptions done in onCreate method of Activity -

```<code>EventBus.getDefault().register(this);
</code>```

Also remove subscriptions in onDestroy method of Activity or if your work is done.

```<code>EventBus.getDefault().unregister(this);
</code>```

To listen subscription use below code in your Activity -

```<code>@Subscribe(threadMode = ThreadMode.MAIN)
     public void onMessageEvent(MyMessageEvent event) {
     // Do your work after getting result from ajaxFunc method
 };
</code>```

You just have to post message notification from your method now and remove CountDown latch from your code if it is not needed somewhere else.

```<code>myAsyncListener = new MyAsyncListener() {
    @Override
        public Response handleEvent(CustomEvent event){
        response = event.getName();
        // Create object of message and post it
        final MyMessageEvent msgEvent = new MessageEvent(response);
        EventBus.getDefault().post(msgEvent);
    }
});
</code>```

MyMessageEvent.class

```<code>import android.support.annotation.NonNull;

public class MyMessageEvent {

    private String mMessage;

    public MyMessageEvent(@NonNull final String message) {
        mMessage = message;
    }

    public String getMessage() {
        return mMessage;
    }

}
</code>```

Body:
I have an app that displays a webview on the whole layout. Sometimes I need to call an async method, that async operation is done by a 3-party sdk, and then I wait for it for a while until I get the response to a designated listener. I have solved it with a latch - once the response is received in the listener, I countDown the latch and then the initiating method can continue with this response.
Unfortunately, when I do this, the WebView is stuck. I imagined the native UI would be stuck , but I didn't expect the webview to get frozen as well.
How can that be overcome?

To make it clearer, here is an example. I need the ajaxFunc to wait until MyAsyncListener gets a certain response, and then return this exact response.

part of JS I inject to the webview :

var response = jsHandler.ajaxFunc(request.data);

I have a variable global variable called response.

public class JavaScriptInterface
{
     @JavascriptInterface
     public String ajaxFunc(String data)
     {
         return MyUtils.handleData( data );
     }
}

the handleData method :

 public String handleData( String data )
 {
     SomeClass.startAsyncRequest(); // starts the async request, response is to come at the listener's callbacks .

     latch = new CountDownLatch(1);
     try {
         latch.await(30, TimeUnit.SECONDS);
     }
     catch (InterruptedException e) {
         e.printStackTrace();
     }

     return response;
   }

now, once the handleData function calls a function, that does something asynchronously, the async function then returns some answer inside some Listener :

myAsyncListener = new MyAsyncListener() {
    @Override
        public Response handleEvent(CustomEvent event) {
            //Now I need to return this 'event' back to the handData/ajaxFunc function <--

            response = event.getName();
            latch.countDown();

        }
    });

Body:
You have put CountDownLatch inside your code which will cause blocking of your main thread. Thats the reason of lag on UI.

For better you should show some ProgressDialog before doing main work of Async task which generally written in doInBackground() method of Async task and hide it after completing your task, Async provide onPostExecute() method for that purpose.

If you need to put some timeout like your CountDownLatch is doing, you can write timer in doInBackground() of Async. That timer will stop your current Async will allotted time is elapsed.

Update, you could use EventBus for your purpose -

EventBus works on Publish/Subscribe pattern. You can subscribe in Activity and publish result from JavaScriptInterface.

Add it in gradle using -

compile 'org.greenrobot:eventbus:3.0.0'

In your Activity start subscribing, generally subscriptions done in onCreate method of Activity -

EventBus.getDefault().register(this);

Also remove subscriptions in onDestroy method of Activity or if your work is done.

EventBus.getDefault().unregister(this);

To listen subscription use below code in your Activity -

@Subscribe(threadMode = ThreadMode.MAIN)
     public void onMessageEvent(MyMessageEvent event) {
     // Do your work after getting result from ajaxFunc method
 };

You just have to post message notification from your method now and remove CountDown latch from your code if it is not needed somewhere else.

myAsyncListener = new MyAsyncListener() {
    @Override
        public Response handleEvent(CustomEvent event){
        response = event.getName();
        // Create object of message and post it
        final MyMessageEvent msgEvent = new MessageEvent(response);
        EventBus.getDefault().post(msgEvent);
    }
});

MyMessageEvent.class

import android.support.annotation.NonNull;

public class MyMessageEvent {

    private String mMessage;

    public MyMessageEvent(@NonNull final String message) {
        mMessage = message;
    }

    public String getMessage() {
        return mMessage;
    }

}


问:
How to add and remove active class to anchor tag within li using Jquery/Javascript
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

```<code><ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>
</code>```

My active class is given below.

```<code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}
</code>```

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

答:
You can use addClass() and removeClass() as below

HTML:

```<code><ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>
</code>```

JQuery:

```<code> $("#ulCategory>li").click(function(){
   $("#ulCategory>li").removeClass("active");
   $(this).addClass("active");
})
</code>```

DEMO HERE

Body:
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

ABC

ABF

ABK

My active class is given below.

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

Body:
You can use addClass() and removeClass() as below

HTML:

<ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>

JQuery:

 $("#ulCategory>li").click(function(){
   $("#ulCategory>li").removeClass("active");
   $(this).addClass("active");
})

DEMO HERE


答:
use with this element in the function call

function savesubcat(that){
$('#ulCategory li a').removeClass('active')
$(that).addClass('active')

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  text-align: left;
  color: #fff;
  background-color: #ffbb00;
  text-decoration: none;
}</code>```

href='javascript:void(0)' onclick='savesubcat(this)'>ABC

href='javascript:void(0)' onclick='savesubcat(this)'>ABF

href='javascript:void(0)' onclick='savesubcat(this)'>ABK

```

Body:
use with this element in the function call

function savesubcat(that){
$('#ulCategory li a').removeClass('active')
$(that).addClass('active')

}

.active {
  text-align: left;
  color: #fff;
  background-color: #ffbb00;
  text-decoration: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ulCategory">
  <li><a href='javascript:void(0)' onclick='savesubcat(this)'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat(this)'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat(this)'>ABK</li>

</ul>


答:
Just add div to your "ul" tag and write onclick event on it.Try below code</p>

```<code>//HTML
 <div id="list_div">
      <ul id="ulCategory">
       <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
       <li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
      <li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>
     </ul>
    </div>

//JS
     $(document).on("click","#list_div a",function() {
           $(this).parent().addClass('active').siblings().removeClass('active');
        });
</code>```

Body:
Just add div to your "ul" tag and write onclick event on it.Try below code

//HTML
 <div id="list_div">
      <ul id="ulCategory">
       <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
       <li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
      <li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>
     </ul>
    </div>

//JS
     $(document).on("click","#list_div a",function() {
           $(this).parent().addClass('active').siblings().removeClass('active');
        });