问:
Symfony 3.3 ContextErrorException
I have two entities as follows:

```<code>    <?php
// src/coreBundle/Entity/model.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\brand;

/**
*@ORM\Entity
*@ORM\Table(name="model")
*/
class model
{
    /**
    * @ORM\ManyToOne(targetEntity="brand", inversedBy="models")
    * @ORM\JoinColumn(name="brand_id", referencedColumnName="id")
    */
    private $brands;
</code>```

And Second one is as follows:

```<code>    <?php
// src/coreBundle/Entity/brand.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\model;
use Doctrine\Common\Collections\ArrayCollection;

/**
*@ORM\Entity
*@ORM\Table(name="brand")
*/
class brand
{
    /**
     * ORM\OneToMany(targetEntity="model", mappedBy="brands")
     */
    private $models;
    public function __construct()
    {
        $this->models = new ArrayCollection();
    }
</code>```

Now In my controller, I have following code

```<code>public function createBrandFormAction()
    {
        $brand = new brand();
        $form = $this->createFormBuilder($brand)
        ->add('name',TextType::class,array('label'=>'Brand Name'))
        ->add('save',SubmitType::class, array('label'=>'Add Brand'))
        ->getForm();

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
        // perform some action, such as saving the task to the database

            $em = $this->getDoctrine()->getManager();
            $brand = $form->getData();
            $em->persist($brand);
            $em->flush();
            return $this->render('coreBundle:layouts:newBrand.html.twig',
                array('form'=>$form->createView(),));
        }

        return $this->render('coreBundle:layouts:newBrand.html.twig',
            array('form'=>$form->createView(),));
    }
</code>```

While executing the controller, I am getting following Exception

Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag::initialize() must be of the type array, object given, called in C:\ledger\var\cache\dev\classes.php on line 248 and defined

"model" has a ManyToOne relationship with "brand"

Can you tell what am I doing wrong, Thanks in advance.

Stack Trace is given below:

```<code>ContextErrorException
Symfony\Component\Debug\Exception\ContextErrorException:
Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag::initialize() must be of the type array, object given, called in C:\ledger\var\cache\dev\classes.php on line 248 and defined

  at vendor\symfony\symfony\src\Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag.php:57
  at Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag->initialize(object(Stub))
     (var\cache\dev\classes.php:248)
  at Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->loadSession()
     (var\cache\dev\classes.php:116)
  at Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start()
     (var\cache\dev\classes.php:192)
  at Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->getBag('attributes')
     (var\cache\dev\classes.php:540)
  at Symfony\Component\HttpFoundation\Session\Session->getAttributeBag()
     (var\cache\dev\classes.php:459)
  at Symfony\Component\HttpFoundation\Session\Session->get('_security_main')
     (vendor\symfony\symfony\src\Symfony\Component\Security\Http\Firewall\ContextListener.php:83)
  at Symfony\Component\Security\Http\Firewall\ContextListener->handle(object(GetResponseEvent))
     (var\cache\dev\classes.php:4700)
  at Symfony\Component\Security\Http\Firewall->onKernelRequest(object(GetResponseEvent))
     (vendor\symfony\symfony\src\Symfony\Bundle\SecurityBundle\EventListener\FirewallListener.php:48)
  at Symfony\Bundle\SecurityBundle\EventListener\FirewallListener->onKernelRequest(object(GetResponseEvent))
     (var\cache\dev\appDevDebugProjectContainer.php:783)
  at appDevDebugProjectContainer->{closure}(object(GetResponseEvent), 'kernel.request', object(TraceableEventDispatcher))
  at call_user_func(object(Closure), object(GetResponseEvent), 'kernel.request', object(TraceableEventDispatcher))
     (vendor\symfony\symfony\src\Symfony\Component\EventDispatcher\Debug\WrappedListener.php:112)
  at Symfony\Component\EventDispatcher\Debug\WrappedListener->__invoke(object(GetResponseEvent), 'kernel.request', object(ContainerAwareEventDispatcher))
  at call_user_func(object(WrappedListener), object(GetResponseEvent), 'kernel.request', object(ContainerAwareEventDispatcher))
     (var\cache\dev\classes.php:3429)
  at Symfony\Component\EventDispatcher\EventDispatcher->doDispatch(array(object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener)), 'kernel.request', object(GetResponseEvent))
     (var\cache\dev\classes.php:3344)
  at Symfony\Component\EventDispatcher\EventDispatcher->dispatch('kernel.request', object(GetResponseEvent))
     (vendor\symfony\symfony\src\Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher.php:146)
  at Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher->dispatch('kernel.request', object(GetResponseEvent))
     (var\cache\dev\classes.php:4380)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (var\cache\dev\classes.php:4350)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php:171)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (web\app_dev.php:30)
  at require('C:\\ledger\\web\\app_dev.php')
     (vendor\symfony\symfony\src\Symfony\Bundle\WebServerBundle\Resources\router.php:42)
</code>```

答: Possible that another reason causes the Catchable Fatal Error: I have the same problem, and find out, that a controller was not utf8-encoded. I changed the encoding to utf8, clear the cache - and the error doesn't occur again.</p>

Title: Symfony 3.3 ContextErrorException

Body:
I have two entities as follows:

    <?php
// src/coreBundle/Entity/model.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\brand;

/**
*@ORM\Entity
*@ORM\Table(name="model")
*/
class model
{
    /**
    * @ORM\ManyToOne(targetEntity="brand", inversedBy="models")
    * @ORM\JoinColumn(name="brand_id", referencedColumnName="id")
    */
    private $brands;

And Second one is as follows:

    <?php
// src/coreBundle/Entity/brand.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\model;
use Doctrine\Common\Collections\ArrayCollection;

/**
*@ORM\Entity
*@ORM\Table(name="brand")
*/
class brand
{
    /**
     * ORM\OneToMany(targetEntity="model", mappedBy="brands")
     */
    private $models;
    public function __construct()
    {
        $this->models = new ArrayCollection();
    }

Now In my controller, I have following code

public function createBrandFormAction()
    {
        $brand = new brand();
        $form = $this->createFormBuilder($brand)
        ->add('name',TextType::class,array('label'=>'Brand Name'))
        ->add('save',SubmitType::class, array('label'=>'Add Brand'))
        ->getForm();

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
        // perform some action, such as saving the task to the database

            $em = $this->getDoctrine()->getManager();
            $brand = $form->getData();
            $em->persist($brand);
            $em->flush();
            return $this->render('coreBundle:layouts:newBrand.html.twig',
                array('form'=>$form->createView(),));
        }

        return $this->render('coreBundle:layouts:newBrand.html.twig',
            array('form'=>$form->createView(),));
    }

While executing the controller, I am getting following Exception

Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag::initialize() must be of the type array, object given, called in C:\ledger\var\cache\dev\classes.php on line 248 and defined

"model" has a ManyToOne relationship with "brand"

Can you tell what am I doing wrong, Thanks in advance.

Stack Trace is given below:

ContextErrorException
Symfony\Component\Debug\Exception\ContextErrorException:
Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag::initialize() must be of the type array, object given, called in C:\ledger\var\cache\dev\classes.php on line 248 and defined

  at vendor\symfony\symfony\src\Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag.php:57
  at Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag->initialize(object(Stub))
     (var\cache\dev\classes.php:248)
  at Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->loadSession()
     (var\cache\dev\classes.php:116)
  at Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start()
     (var\cache\dev\classes.php:192)
  at Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->getBag('attributes')
     (var\cache\dev\classes.php:540)
  at Symfony\Component\HttpFoundation\Session\Session->getAttributeBag()
     (var\cache\dev\classes.php:459)
  at Symfony\Component\HttpFoundation\Session\Session->get('_security_main')
     (vendor\symfony\symfony\src\Symfony\Component\Security\Http\Firewall\ContextListener.php:83)
  at Symfony\Component\Security\Http\Firewall\ContextListener->handle(object(GetResponseEvent))
     (var\cache\dev\classes.php:4700)
  at Symfony\Component\Security\Http\Firewall->onKernelRequest(object(GetResponseEvent))
     (vendor\symfony\symfony\src\Symfony\Bundle\SecurityBundle\EventListener\FirewallListener.php:48)
  at Symfony\Bundle\SecurityBundle\EventListener\FirewallListener->onKernelRequest(object(GetResponseEvent))
     (var\cache\dev\appDevDebugProjectContainer.php:783)
  at appDevDebugProjectContainer->{closure}(object(GetResponseEvent), 'kernel.request', object(TraceableEventDispatcher))
  at call_user_func(object(Closure), object(GetResponseEvent), 'kernel.request', object(TraceableEventDispatcher))
     (vendor\symfony\symfony\src\Symfony\Component\EventDispatcher\Debug\WrappedListener.php:112)
  at Symfony\Component\EventDispatcher\Debug\WrappedListener->__invoke(object(GetResponseEvent), 'kernel.request', object(ContainerAwareEventDispatcher))
  at call_user_func(object(WrappedListener), object(GetResponseEvent), 'kernel.request', object(ContainerAwareEventDispatcher))
     (var\cache\dev\classes.php:3429)
  at Symfony\Component\EventDispatcher\EventDispatcher->doDispatch(array(object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener)), 'kernel.request', object(GetResponseEvent))
     (var\cache\dev\classes.php:3344)
  at Symfony\Component\EventDispatcher\EventDispatcher->dispatch('kernel.request', object(GetResponseEvent))
     (vendor\symfony\symfony\src\Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher.php:146)
  at Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher->dispatch('kernel.request', object(GetResponseEvent))
     (var\cache\dev\classes.php:4380)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (var\cache\dev\classes.php:4350)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php:171)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (web\app_dev.php:30)
  at require('C:\\ledger\\web\\app_dev.php')
     (vendor\symfony\symfony\src\Symfony\Bundle\WebServerBundle\Resources\router.php:42)


来源: stackexchange

问:
Hold off React Render until after request
I have a component that's being loaded with the initial state:

```<code>  getInitialState: function() {
    return {
      panel: "deals",
      showExtension: false,
      person: {}

    };
  },
</code>```

And I have this to find a person:

```<code>  componentDidMount: function() {
    this.findPersonFromBackground();
  },
  findPersonFromBackground: function() {
    chrome.runtime.sendMessage({ action: "findPerson", email: this.props.currentEmail.from_email }, function(person) {
      this.setState({person: person});
    }.bind(this));
  },
</code>```

So all works fine. If the person is found, I render one thing, and if not, something else.

When the first is found, the view goes from non-found state to found state real fast, since the API calls are pretty quick.

What's the best way to wait to render until that first call comes back?

答:
maybe you need this project: https://github.com/toplan/react-hold

You can use the placeholder to keep the shape of your component.

ContentLicense: CC BY-SA 3.0

Body:
I have a component that's being loaded with the initial state:

  getInitialState: function() {
    return {
      panel: "deals",
      showExtension: false,
      person: {}

    };
  },

And I have this to find a person:

  componentDidMount: function() {
    this.findPersonFromBackground();
  },
  findPersonFromBackground: function() {
    chrome.runtime.sendMessage({ action: "findPerson", email: this.props.currentEmail.from_email }, function(person) {
      this.setState({person: person});
    }.bind(this));
  },

So all works fine. If the person is found, I render one thing, and if not, something else.

When the first is found, the view goes from non-found state to found state real fast, since the API calls are pretty quick.

What's the best way to wait to render until that first call comes back?


问:
UINavigationController setViewControllers makes application crash
I'm having a strange issue and I don't know if it is my bug (most probably) or a bug in UINavigationController.

I use UINavigationController in my application. In some cases I need complicated navigations like "pop 2 screens and push new one". Currently I do it by getting current navigationController.viewControllers, modifying the collection, and calling [navigationController setViewControllers:newStack animated:YES].

It occurs that this makes my application crash very often. Usually crashes are SIGBUS or SIGSEGV. Steps to reproduce looks like following:

Do one of those complicated navigations

Navigate back one or two times depending on navigation kind

Crash!

Interesting things are that:

If navigation was simply "several screens back" then next back would crash. If navigation was "several screens back and push new screen" then second back would crash. Moreover, in such case navigations like back, forward, back, back usually doesn't crash application

The most strange: if I do [navigationController popToRootViewControllerAnimated:NO] before updating stack, application doesn't crash or at least crashes much rarer (I wasn't able to reproduce crash).

Example of crash stack trace caught by my signal handler:

0x0027a9 mysighandler()

0x3293d82b _sigtramp()

0x31c59065 -[UIApplication sendAction:to:from:forEvent:]

0x31c59005 -[UIApplication sendAction:toTarget:fromSender:forEvent:]

0x31c58fd7 -[UIControl sendAction:to:forEvent:]

0x31c58d31 -[UIControl _sendActionsForEvents:withEvent:]

0x31c59645 -[UIControl touchesEnded:withEvent:]

0x31c5865d -[UIWindow _sendTouchesForEvent:]

0x31c58039 -[UIWindow sendEvent:]

0x31c5492f -[UIApplication sendEvent:]

0x31c543a7 _UIApplicationHandleEvent()

0x3352c9ed PurpleEventCallback()

0x3358ac2d CFRunLoopRunSpecific()

0x3358a35d CFRunLoopRunInMode()

0x3352bb33 GSEventRunModal()

0x3352bbdf GSEventRun()

0x31c1976f -[UIApplication _run]

0x31c18473 UIApplicationMain()

0x00214d main()

0x0020c4 start()

Another one:

0x002945 mysighandler()

0x3293d82b _sigtramp()

0x31c5ead3 -[UIScrollView _updatePanWithStartDelta:event:gesture:ignoringDirectionalScroll:]

0x31c5e435 -[UIScrollView handlePan:]

0x31d14651 -[UITableView handlePan:]

0x33590da7 -[Protocol performSelector:withObject:]

0x31c428b5 -[UIGestureRecognizer _updateGestureWithEvent:]

0x31c427a9 -[UIGestureRecognizer _updateGestureStateWithEvent:afterDelay:]

0x31c583d5 -[UIWindow _sendGesturesForEvent:]

0x31c5802b -[UIWindow sendEvent:]

0x31c5492f -[UIApplication sendEvent:]

0x31c543a7 _UIApplicationHandleEvent()

0x3352c9ed PurpleEventCallback()

0x3358ac2d CFRunLoopRunSpecific()

0x3358a35d CFRunLoopRunInMode()

0x3352bb33 GSEventRunModal()

0x3352bbdf GSEventRun()

0x31c1976f -[UIApplication _run]

0x31c18473 UIApplicationMain()

0x0022e9 main()

0x002260 start()

Example of "complicated" navigation implementation:

```<code>@implementation UINavigationController(MyCategory)
- (void)popViewControllers:(NSInteger)count {
    NSArray* oldList = self.viewControllers;
    NSMutableArray* newList = [NSMutableArray arrayWithArray:oldList];
    if(count > [oldList count]) {
        CLogError(@"Poping %d screens when there is only %d", count, [oldList count]);
        count = [oldList count] - 1;
    }
    for(int i = 0; i<count; i++) {
        [newList removeLastObject];
    }
    [self setViewControllers:newList animated:YES];
}
@end
</code>```

Does anybody now, what I might be doing wrong? I just run out of ideas.

Addition:

I did run my application using NSZombieEnabled and MallocStackLogging to find out what object fails. However it didn't give my reasonable results. For stack trace #1 it fails at step 3 (-[UIApplication sendAction:to:from:forEvent:]) and zombie object is
-[UIBarButtonItem performSelector:withObject:withObject:]: message sent to deallocated instance 0xa5f5f90. This is right navigation bar button of the screen that application navigates 2 screens back from (and remember, this 2-screens-back navigation works, only next "usual" back navigation fails). But I don't do anything with that button. Corresponding code in ViewControler's initWithSomething:(Something*)something is:

```<code>UIBarButtonItem* doneItem = [[UIBarButtonItem alloc] initWithTitle:@"Complete"
                                                             style:UIBarButtonItemStyleDone
                                                             target:self action:@selector(onDone)];
self.navigationItem.rightBarButtonItem = doneItem;
[doneItem release];
</code>```

The only special thing about this button is that onDone selector does that 2-screens-back navigation, but I don't think that this really matters. So I believe there is something wrong at higher level object (probably View Controller or UINavigationController?). But what is wrong?

Addition October, 4 2011:

As people are still sometimes search for this question, here is some code. My current approach to this issue is to use custom subclass of UINavigationController instead of it with following hack (no guarantees that this works or is still necessary):

```<code>@interface CustomUINavigationController : UINavigationController {
}

@end

@implementation CustomUINavigationController
- (void)setViewControllers:(NSArray*)newStack animated:(BOOL)animated {
    // HACK HACK
    // Somehow everything fails if I don't clean stack before putting new
    // But on iOS4 popToRootViewControllerAnimated might call setViewControllers:animated
    // let's avoid call stack overflow
    static int stackCount = 0;
    if(!stackCount++) {
        if([self.viewControllers count] != 1) {
            [self popToRootViewControllerAnimated:NO];
        }
        else {
            UIViewController* tmpVc = [[[UIViewController alloc] init] autorelease];
            NSArray* tmpStack = [NSArray arrayWithObject:tmpVc];
            [super setViewControllers:tmpStack animated:NO];
        }
    }
    [super setViewControllers:newStack animated:animated];
    stackCount--;
}
@end
</code>```

Another important thing: you'd better don't start animated navigation while previous animated navigation is still in progress (i.e. at least till viewWillAppear: is called).

答:
For the second stack trace, I had the same problem.
I was releasing the view controller which contained the scrollview.

```<code>[mainScrollView addSubview:rubriqueController.view];
[rubriqueController release]; // Comment this line
</code>```

Something like this.

Hope it helps even 9 months after.

Body:
I'm having a strange issue and I don't know if it is my bug (most probably) or a bug in UINavigationController.

I use UINavigationController in my application. In some cases I need complicated navigations like "pop 2 screens and push new one". Currently I do it by getting current navigationController.viewControllers, modifying the collection, and calling [navigationController setViewControllers:newStack animated:YES].

It occurs that this makes my application crash very often. Usually crashes are SIGBUS or SIGSEGV. Steps to reproduce looks like following:

Do one of those complicated navigations

Navigate back one or two times depending on navigation kind

Crash!

Interesting things are that:

If navigation was simply "several screens back" then next back would crash. If navigation was "several screens back and push new screen" then second back would crash. Moreover, in such case navigations like back, forward, back, back usually doesn't crash application

The most strange: if I do [navigationController popToRootViewControllerAnimated:NO] before updating stack, application doesn't crash or at least crashes much rarer (I wasn't able to reproduce crash).

Example of crash stack trace caught by my signal handler:

0x0027a9 mysighandler()

0x3293d82b _sigtramp()

0x31c59065 -[UIApplication sendAction:to:from:forEvent:]

0x31c59005 -[UIApplication sendAction:toTarget:fromSender:forEvent:]

0x31c58fd7 -[UIControl sendAction:to:forEvent:]

0x31c58d31 -[UIControl _sendActionsForEvents:withEvent:]

0x31c59645 -[UIControl touchesEnded:withEvent:]

0x31c5865d -[UIWindow _sendTouchesForEvent:]

0x31c58039 -[UIWindow sendEvent:]

0x31c5492f -[UIApplication sendEvent:]

0x31c543a7 _UIApplicationHandleEvent()

0x3352c9ed PurpleEventCallback()

0x3358ac2d CFRunLoopRunSpecific()

0x3358a35d CFRunLoopRunInMode()

0x3352bb33 GSEventRunModal()

0x3352bbdf GSEventRun()

0x31c1976f -[UIApplication _run]

0x31c18473 UIApplicationMain()

0x00214d main()

0x0020c4 start()

Another one:

0x002945 mysighandler()

0x3293d82b _sigtramp()

0x31c5ead3 -[UIScrollView _updatePanWithStartDelta:event:gesture:ignoringDirectionalScroll:]

0x31c5e435 -[UIScrollView handlePan:]

0x31d14651 -[UITableView handlePan:]

0x33590da7 -[Protocol performSelector:withObject:]

0x31c428b5 -[UIGestureRecognizer _updateGestureWithEvent:]

0x31c427a9 -[UIGestureRecognizer _updateGestureStateWithEvent:afterDelay:]

0x31c583d5 -[UIWindow _sendGesturesForEvent:]

0x31c5802b -[UIWindow sendEvent:]

0x31c5492f -[UIApplication sendEvent:]

0x31c543a7 _UIApplicationHandleEvent()

0x3352c9ed PurpleEventCallback()

0x3358ac2d CFRunLoopRunSpecific()

0x3358a35d CFRunLoopRunInMode()

0x3352bb33 GSEventRunModal()

0x3352bbdf GSEventRun()

0x31c1976f -[UIApplication _run]

0x31c18473 UIApplicationMain()

0x0022e9 main()

0x002260 start()

Example of "complicated" navigation implementation:

@implementation UINavigationController(MyCategory)
- (void)popViewControllers:(NSInteger)count {
    NSArray* oldList = self.viewControllers;
    NSMutableArray* newList = [NSMutableArray arrayWithArray:oldList];
    if(count > [oldList count]) {
        CLogError(@"Poping %d screens when there is only %d", count, [oldList count]);
        count = [oldList count] - 1;
    }
    for(int i = 0; i<count; i++) {
        [newList removeLastObject];
    }
    [self setViewControllers:newList animated:YES];
}
@end

Does anybody now, what I might be doing wrong? I just run out of ideas.

Addition:

I did run my application using NSZombieEnabled and MallocStackLogging to find out what object fails. However it didn't give my reasonable results. For stack trace #1 it fails at step 3 (-[UIApplication sendAction:to:from:forEvent:]) and zombie object is
-[UIBarButtonItem performSelector:withObject:withObject:]: message sent to deallocated instance 0xa5f5f90. This is right navigation bar button of the screen that application navigates 2 screens back from (and remember, this 2-screens-back navigation works, only next "usual" back navigation fails). But I don't do anything with that button. Corresponding code in ViewControler's initWithSomething:(Something*)something is:

UIBarButtonItem* doneItem = [[UIBarButtonItem alloc] initWithTitle:@"Complete"
                                                             style:UIBarButtonItemStyleDone
                                                             target:self action:@selector(onDone)];
self.navigationItem.rightBarButtonItem = doneItem;
[doneItem release];

The only special thing about this button is that onDone selector does that 2-screens-back navigation, but I don't think that this really matters. So I believe there is something wrong at higher level object (probably View Controller or UINavigationController?). But what is wrong?

Addition October, 4 2011:

As people are still sometimes search for this question, here is some code. My current approach to this issue is to use custom subclass of UINavigationController instead of it with following hack (no guarantees that this works or is still necessary):

@interface CustomUINavigationController : UINavigationController {
}

@end

@implementation CustomUINavigationController
- (void)setViewControllers:(NSArray*)newStack animated:(BOOL)animated {
    // HACK HACK
    // Somehow everything fails if I don't clean stack before putting new
    // But on iOS4 popToRootViewControllerAnimated might call setViewControllers:animated
    // let's avoid call stack overflow
    static int stackCount = 0;
    if(!stackCount++) {
        if([self.viewControllers count] != 1) {
            [self popToRootViewControllerAnimated:NO];
        }
        else {
            UIViewController* tmpVc = [[[UIViewController alloc] init] autorelease];
            NSArray* tmpStack = [NSArray arrayWithObject:tmpVc];
            [super setViewControllers:tmpStack animated:NO];
        }
    }
    [super setViewControllers:newStack animated:animated];
    stackCount--;
}
@end

Another important thing: you'd better don't start animated navigation while previous animated navigation is still in progress (i.e. at least till viewWillAppear: is called).

Body:
For the second stack trace, I had the same problem.
I was releasing the view controller which contained the scrollview.

[mainScrollView addSubview:rubriqueController.view];
[rubriqueController release]; // Comment this line

Something like this.

Hope it helps even 9 months after.

ContentLicense: CC BY-SA 2.5


问:
Reading network directory with java using scheduled task
I have spent two days trying to get this to work. J: is a mapped network drive.

```<code>import java.io.File;

File file = new File("J:\\data\\newpasload\\savedir\\");
File[] attachedFiles=file.listFiles();
if (attachedFiles==null) {
    System.out.println("Failed to read j: drive");
} else {
    System.out.println("Number of files = "+attachedFiles.length);
}
</code>```

The executable jar file works fine when run directly, showing me the number of files in the directory. However I want the executable jar file to run as a scheduled task. When I run it as such the attachedFiles becomes null.

答:
According documentation listFiles() returns:

An array of abstract pathnames denoting the files and directories in
  the directory denoted by this abstract pathname. The array will be
  empty if the directory is empty. Returns null if this abstract
  pathname does not denote a directory, or if an I/O error occurs

So you should check path or task permissions. As a variant you can run your java application as a daemon.

Body:
I have spent two days trying to get this to work. J: is a mapped network drive.

import java.io.File;

File file = new File("J:\\data\\newpasload\\savedir\\");
File[] attachedFiles=file.listFiles();
if (attachedFiles==null) {
    System.out.println("Failed to read j: drive");
} else {
    System.out.println("Number of files = "+attachedFiles.length);
}

The executable jar file works fine when run directly, showing me the number of files in the directory. However I want the executable jar file to run as a scheduled task. When I run it as such the attachedFiles becomes null.


问:
C# file passed to exe event
I want to create a program that can open a CSV file. I want to be able to right click on the file name in windows and say open with my.exe.

What event in the .exe do I need to cover to handle the file being passed in?

答:
This would be the arguments..</p>

```<code>class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Console.WriteLine(args[0]);  // <-- args[0] contains filename
            }
            Console.ReadLine();
        }
    }
</code>```

Title: C# file passed to exe event

Body:
This would be the arguments..

class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Console.WriteLine(args[0]);  // <-- args[0] contains filename
            }
            Console.ReadLine();
        }
    }


问:
How to not return null value in sql server?
I have this data set like shown below;

Company | Address | Business            | Telephone Number | Contact Person

```<code>A&B     | Perak   | Khmer Restaurants   | 012541           | Mr. Yu Lee
A&B     | Perak   | F&B                 | 012541           | Mr. Yu Lee
King Co.| Ipoh    | Paper Distributors  | 021453           | Mrs. Cheng
King Co.| Ipoh    | Paper Distributors  | Null             | Mrs. Cheng
DinoX   | Sunway  | Guesthouses         | 0124587          | Mr. Hong
Dinox   | Sunway  | Guesthouses         | 0124587          | Mr. Q
</code>```

After making some query like shown below, i get a new dataset :

```<code>IF OBJECT_ID('tempdb..#tCat') IS NOT NULL DROP TABLE #tcat
GO
DECLARE @portal varchar(100) = 'A4E7890F-A188-4663-89EB-176D94DF6774'
SELECT * INTO #tcat
FROM (
SELECT DISTINCT  list.[name]
                ,lc.listing_uuid
                ,dCat.[name]  as Category
                ,catg.[name]  as Sub_Category
                ,comm.[value] as Telephone_Number
                ,pp.title + ' ' + pp.first_name + ' ' + pp.last_name as Contact_Person
FROM panpages.listings as list
LEFT JOIN panpages.listing_categories as lc on lc.listing_uuid=list.uuid AND lc.portal_uuid=@portal
LEFT JOIN panpages.categories as catg on catg.uuid=lc.category_uuid AND catg.portal_uuid=@portal
left join panpages.listing_people as lp on lp.listing_uuid = list.uuid
left join panpages.people as pp on pp.id = lp.person_id
left join panpages.person_communications as comm on comm.person_id = lp.person_id and (comm.communication_type = 'Mobile Phone' or comm.communication_type = 'Tel')
LEFT JOIN ( SELECT DISTINCT uuid,[name] FROM panpages.categories WHERE parent_uuid IS NULL ) as dCat on dCat.uuid=catg.parent_uuid
WHERE list.portal_uuid=@portal and list.is_active=1
)as tCat

select
     list.[name] as [Company]
    ,list.[address] as [Address]
    ,replace(cats.Sub_Category,'&','&')     as [Nature of Business]
    ,replace(cats.Telephone_Number,'&','&') as [Telephone Number]
    ,replace(cats.Contact_Person,'&','&')   as [Contact Person]

from [panpages].[listings] as list
left join (

            SELECT DISTINCT tc1.listing_uuid,tc1.[name],
            Sub_Category = STUFF(( SELECT   ',   ' + tc2.Sub_Category
            FROM
                (
                SELECT Sub_Category, MIN(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Sub_Category
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Sub_Category
                FOR XML PATH('')), 1, 1, ''),
            Telephone_Number = STUFF(( SELECT   ',  ' + tc2.Telephone_Number
            FROM
                (
                SELECT Telephone_Number, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Telephone_Number
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Telephone_Number
                FOR XML PATH('')), 1, 1, ''),
            Contact_Person = STUFF(( SELECT   ',  ' + tc2.Contact_Person
            FROM
                (
                SELECT Contact_Person, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Contact_Person
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Contact_Person
                FOR XML PATH('')), 1, 1, '')
            FROM #tCat as tc1 where tc1.listing_uuid is not null
        ) cats on cats.listing_uuid=list.uuid
where
    list.[portal_uuid]=@portal and
    list.[is_active]=1
</code>```

And below is the new dataset :

```<code>Company |Address| Business              | Telephone Number | Contact Person

A&B     | Perak | Khmer Restaurants, F&B| 012541           | Mr. Yu Lee
King Co.| Ipoh  | Paper Distributors    | 021453, Null     | Mrs. Cheng
DinoX   | Sunway| Guesthouses           | 0124587          | Mr. Hong, Mr Q
</code>```

How to not return the null value? I dont want to return the "Null" value.

答:
Use STUFF inside a replace to replace the null values.</p>

```<code>        Telephone_Number = Replace(STUFF( SELECT   ',  ' + tc2.Telephone_Number
        FROM
            (
            SELECT Telephone_Number, MAX(listing_uuid) AS listing_uuid
            FROM #tCat
            GROUP BY Telephone_Number
            ) AS tc2
            WHERE tc1.listing_uuid = tc2.listing_uuid
            ORDER BY tc2.Telephone_Number
            FOR XML PATH('')), 1, 1, ''), ' null', ''),
</code>```

Body:
I have this data set like shown below;

Company | Address | Business            | Telephone Number | Contact Person

A&B     | Perak   | Khmer Restaurants   | 012541           | Mr. Yu Lee
A&B     | Perak   | F&B                 | 012541           | Mr. Yu Lee
King Co.| Ipoh    | Paper Distributors  | 021453           | Mrs. Cheng
King Co.| Ipoh    | Paper Distributors  | Null             | Mrs. Cheng
DinoX   | Sunway  | Guesthouses         | 0124587          | Mr. Hong
Dinox   | Sunway  | Guesthouses         | 0124587          | Mr. Q

After making some query like shown below, i get a new dataset :

IF OBJECT_ID('tempdb..#tCat') IS NOT NULL DROP TABLE #tcat
GO
DECLARE @portal varchar(100) = 'A4E7890F-A188-4663-89EB-176D94DF6774'
SELECT * INTO #tcat
FROM (
SELECT DISTINCT  list.[name]
                ,lc.listing_uuid
                ,dCat.[name]  as Category
                ,catg.[name]  as Sub_Category
                ,comm.[value] as Telephone_Number
                ,pp.title + ' ' + pp.first_name + ' ' + pp.last_name as Contact_Person
FROM panpages.listings as list
LEFT JOIN panpages.listing_categories as lc on lc.listing_uuid=list.uuid AND lc.portal_uuid=@portal
LEFT JOIN panpages.categories as catg on catg.uuid=lc.category_uuid AND catg.portal_uuid=@portal
left join panpages.listing_people as lp on lp.listing_uuid = list.uuid
left join panpages.people as pp on pp.id = lp.person_id
left join panpages.person_communications as comm on comm.person_id = lp.person_id and (comm.communication_type = 'Mobile Phone' or comm.communication_type = 'Tel')
LEFT JOIN ( SELECT DISTINCT uuid,[name] FROM panpages.categories WHERE parent_uuid IS NULL ) as dCat on dCat.uuid=catg.parent_uuid
WHERE list.portal_uuid=@portal and list.is_active=1
)as tCat

select
     list.[name] as [Company]
    ,list.[address] as [Address]
    ,replace(cats.Sub_Category,'&','&')     as [Nature of Business]
    ,replace(cats.Telephone_Number,'&','&') as [Telephone Number]
    ,replace(cats.Contact_Person,'&','&')   as [Contact Person]

from [panpages].[listings] as list
left join (

            SELECT DISTINCT tc1.listing_uuid,tc1.[name],
            Sub_Category = STUFF(( SELECT   ',   ' + tc2.Sub_Category
            FROM
                (
                SELECT Sub_Category, MIN(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Sub_Category
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Sub_Category
                FOR XML PATH('')), 1, 1, ''),
            Telephone_Number = STUFF(( SELECT   ',  ' + tc2.Telephone_Number
            FROM
                (
                SELECT Telephone_Number, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Telephone_Number
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Telephone_Number
                FOR XML PATH('')), 1, 1, ''),
            Contact_Person = STUFF(( SELECT   ',  ' + tc2.Contact_Person
            FROM
                (
                SELECT Contact_Person, MAX(listing_uuid) AS listing_uuid
                FROM #tCat
                GROUP BY Contact_Person
                ) AS tc2
                WHERE tc1.listing_uuid = tc2.listing_uuid
                ORDER BY tc2.Contact_Person
                FOR XML PATH('')), 1, 1, '')
            FROM #tCat as tc1 where tc1.listing_uuid is not null
        ) cats on cats.listing_uuid=list.uuid
where
    list.[portal_uuid]=@portal and
    list.[is_active]=1

And below is the new dataset :

Company |Address| Business              | Telephone Number | Contact Person

A&B     | Perak | Khmer Restaurants, F&B| 012541           | Mr. Yu Lee
King Co.| Ipoh  | Paper Distributors    | 021453, Null     | Mrs. Cheng
DinoX   | Sunway| Guesthouses           | 0124587          | Mr. Hong, Mr Q

How to not return the null value? I dont want to return the "Null" value.

Body:
Use STUFF inside a replace to replace the null values.

        Telephone_Number = Replace(STUFF( SELECT   ',  ' + tc2.Telephone_Number
        FROM
            (
            SELECT Telephone_Number, MAX(listing_uuid) AS listing_uuid
            FROM #tCat
            GROUP BY Telephone_Number
            ) AS tc2
            WHERE tc1.listing_uuid = tc2.listing_uuid
            ORDER BY tc2.Telephone_Number
            FOR XML PATH('')), 1, 1, ''), ' null', ''),


问:
Copy constructor usage with pointer
I have a question about the usage of copy constructors. I know that there are many other answered questions and a huge variety of tutorials but I could not completely solve my problem.

I have a class A which implements a copy constructor:

```<code>A::A(const A& a) { ....... }
</code>```

Now in another class B, I have a private attribute:

```<code>A myA;
</code>```

During execution, a method of B gets called with a pointer to an A object, lets call it anAPointer. I now want to copy the element pointed by anAPointer into B::myA. If the element behind the pointer later changes, I don't want these changes to affect the myA attribute.

I used this->myA = A(*anAPointer); yet. Does this have the effect I want it to have?

And do I have to call delete myA in B's destructor?

答:
Your code:

```<code>A(*anAPointer)
</code>```

is calling A's copy constructor so this->myA will be an instance of A unrelated to the value pointed by anAPointer. Changes to the first won't be propagated to the other and vice versa (unless your class A handles shared resources, but that's not pointed in your question).

myA is not a pointer, so you don't have to call delete in B's destructor.

Note that if you're implementing copy constructor in A, you should consider rule of 3/5/0 and maybe copy and swap idiom.

Title: Copy constructor usage with pointer

Body:
I have a question about the usage of copy constructors. I know that there are many other answered questions and a huge variety of tutorials but I could not completely solve my problem.

I have a class A which implements a copy constructor:

A::A(const A& a) { ....... }

Now in another class B, I have a private attribute:

A myA;

During execution, a method of B gets called with a pointer to an A object, lets call it anAPointer. I now want to copy the element pointed by anAPointer into B::myA. If the element behind the pointer later changes, I don't want these changes to affect the myA attribute.

I used this->myA = A(*anAPointer); yet. Does this have the effect I want it to have?

And do I have to call delete myA in B's destructor?

Body:
Your code:

A(*anAPointer)

is calling A's copy constructor so this->myA will be an instance of A unrelated to the value pointed by anAPointer. Changes to the first won't be propagated to the other and vice versa (unless your class A handles shared resources, but that's not pointed in your question).

myA is not a pointer, so you don't have to call delete in B's destructor.

Note that if you're implementing copy constructor in A, you should consider rule of 3/5/0 and maybe copy and swap idiom.


问:
Android studio : Can not choose signature version
I want to build my app with V1 & V2 signature version. But both of them are greyed out. Can anyone please tell me how to make it avaiable to choose?
[generate signature]</p>

答:
As described in the official document,

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.

So be sure that the android studio and the gradle plugin of module(build.gradle->com.android.tools.build:gradle) are updated to 2.3 and above.


问:
RStudio does not see packages after update to R 3.4
I have Ubuntu 16.04 and after update of R to 3.4.1 version it does not see my packages even though they have also been updated:

```<code>> library(dplyr)
Error in library(dplyr) : there is no package called ‘dplyr’
</code>```

Packages are there:

```<code>$ ls ~/R/x86_64-pc-linux-gnu-library/3.4/ | grep plyr
dplyr
plyr
</code>```

My .libPaths:

```<code>> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"       "/usr/lib/R/library"
</code>```

Setting .libPaths to desired path does the thing just for one session. I'd like it to be permanent.

I also tried to set the variables R_LIBS, R_LIBS_SITE and R_LIBS_USER to desired path as indicated here but it worked only in the console (didn't work in RStudio).

答:
I had the same problem on Windows, maybe my solution works for you aswell. The default for R-Studio seems to be, that it looks for the packages in a folder that has the same name as the most recent R version you have installed.

So check in the Library Settings for R-Studio, (e. g. Tools -> Install packages -> Path beneath the search bar) it should say some path ending in ~/3.4.1 [Default], whereas the packages currently lie in ~/3.4.

What I did:

Copy/move the content from ~/3.4 to ~/3.4.1.

This is obviously not the nicest way, since that means moving the packages with every R update, but it worked for me.

Edit: formatting.

Body:
I have Ubuntu 16.04 and after update of R to 3.4.1 version it does not see my packages even though they have also been updated:

> library(dplyr)
Error in library(dplyr) : there is no package called ‘dplyr’

Packages are there:

$ ls ~/R/x86_64-pc-linux-gnu-library/3.4/ | grep plyr
dplyr
plyr

My .libPaths:

> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"       "/usr/lib/R/library"

Setting .libPaths to desired path does the thing just for one session. I'd like it to be permanent.

I also tried to set the variables R_LIBS, R_LIBS_SITE and R_LIBS_USER to desired path as indicated here but it worked only in the console (didn't work in RStudio).


问:
how can I get the String from hashCode
I am working on a project where I had got my password field value's hashCode and stored that hashCode in DB for security purposes.Now I want to recover the password from the hashCode.How can I do it? Is it possible to get the String value back from the hashCode?If it is not, can anyone suggest me a better way to store my password in anyother format?

答:
You know that several objects can have same hash(), as it mentioned in java doc for Object.hashCode()

It is not required that if two objects are unequal
       *     according to the {@link java.lang.Object#equals(java.lang.Object)}
       *     method, then calling the {@code hashCode} method on each of the
       *     two objects must produce distinct integer results.

It's obvious you can't restore different objects from same hash code, so it's impossible at all, simple logic.

ContentLicense: CC BY-SA 4.0

Title: how can I get the String from hashCode


问:
Change tmp for ImageMagick
My tmp folder is getting spammed by imagemagick files. I want to change the path where the temporary files are saved so i can delete them with a script. For that I have tried changing the path in the policy.xml but it is still using the /tmp/ folder. The method setRegistry(), suggested in this post, does not seem to exist in the class Imagick and I don't know where find the enviornment variables like MAGICK_TEMPORARY_PATH. Can someone help me with that?

答:
It can also be used directly in your convert commands with -define registry:temporary-path. Example:

```<code>convert -define registry:temporary-path='/home/www/tmp_imagemagick' file1.jpg file2.png
</code>```

Title: Change tmp for ImageMagick

Body:
It can also be used directly in your convert commands with -define registry:temporary-path. Example:

convert -define registry:temporary-path='/home/www/tmp_imagemagick' file1.jpg file2.png


答:
File name will be passed as a parameter in your static void Main(string[] args)

```<code>static void Main(string[] args)
{
    if (args != null && args.Length > 0)
        Console.WriteLine("File: {0}", args[0]); // Your file
}
</code>```

Title: C# file passed to exe event

Body:
I want to create a program that can open a CSV file. I want to be able to right click on the file name in windows and say open with my.exe.

What event in the .exe do I need to cover to handle the file being passed in?

Body:
File name will be passed as a parameter in your static void Main(string[] args)

static void Main(string[] args)
{
    if (args != null && args.Length > 0)
        Console.WriteLine("File: {0}", args[0]); // Your file
}


问:
Trouble with my While Loop
Beginner in Java here and I'm creating a program that will calculate the area and volume of a sphere after a value for the radius has been given. If the radius is <= 0, then it should display an error message in the form of a JOptionPane and then return to asking for the radius, however, I am struggling with the while loop.

Here is my code:

```<code>public static void main(String[] args) {
    String volume = "V = (4(pi)r^3)/3";
    String area = "V = 4(pi)r^2";
    JOptionPane.showMessageDialog(null, "Formulas for a Sphere:"+"\n"+"V = (4(pi)r^3)/3"+"\n"+"A = 4(pi)r^2");
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)"));
    while(radius <= 0) {
        JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
    }
    JOptionPane.showMessageDialog(null, volume + " = " + Math.round((4*3.1415*Math.pow(radius,3)/3)) + "cm" +
            "\n" + area + " = " + Math.round(4*3.1415*Math.pow(radius,2)));
</code>```

答:
The value of radius never changes in this loop

```<code> while(radius <= 0) {
    JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
}
</code>```

add this into the loop

```<code> radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)"));
</code>```

Title: Trouble with my While Loop

Body:
Beginner in Java here and I'm creating a program that will calculate the area and volume of a sphere after a value for the radius has been given. If the radius is <= 0, then it should display an error message in the form of a JOptionPane and then return to asking for the radius, however, I am struggling with the while loop.

Here is my code:

public static void main(String[] args) {
    String volume = "V = (4(pi)r^3)/3";
    String area = "V = 4(pi)r^2";
    JOptionPane.showMessageDialog(null, "Formulas for a Sphere:"+"\n"+"V = (4(pi)r^3)/3"+"\n"+"A = 4(pi)r^2");
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)"));
    while(radius <= 0) {
        JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
    }
    JOptionPane.showMessageDialog(null, volume + " = " + Math.round((4*3.1415*Math.pow(radius,3)/3)) + "cm" +
            "\n" + area + " = " + Math.round(4*3.1415*Math.pow(radius,2)));

Body:
The value of radius never changes in this loop

 while(radius <= 0) {
    JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
}

add this into the loop

 radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)"));


问:
Can I cancel the method "applicationDidEnterBackground?
I wanted to cancel the method, to request a confirmation from the user when he presses the button "HOME" where on iPhone would go into the execution in background.

If the user accepts, enters into the execution in background, if not accept, I do not do anything.

I looked in the FORUM, in the documentation from Apple and I found nothing.

Could anyone help me?

Thanks in advance!

答:
No you can't override this. The event will always fire but it does give you time to clean up before you move to the background.

Your delegate’s applicationDidEnterBackground: method has approximately five seconds to finish
  any tasks and return. In practice, this method should return as quickly as possible. If the method does not
  return before time runs out, your application is terminated and purged from memory. If you still need more
  time to perform tasks, call the beginBackgroundTaskWithExpirationHandler: method to request
  background execution time and then start any long-running tasks in a secondary thread. Regardless of
  whether you start any background tasks, the applicationDidEnterBackground: method must still exit
  within five seconds

iOS Application Programming Guide


问:
ERROR: Failed to deploy to device, no devices found -cordova using visual studio
I am developing an Apache Cordova mobile app using Visual Studio 2013. When I run my app in device mode I get the following error:

ERROR: Failed to deploy to device, no devices found

I have already enabled USB debugging in the developer options.

答:
I have had problem that I have got "device not found" after first working connection an next reconnection. I have found solution by closing chrome://inspect/#devices tab in chrome dev tools. Hope this help someone. Happy coding!

Credit: https://stackoverflow.com/a/36662403/861615


问:
What is the floating-point (__m256d) version of the non-temporal streaming load intrinsic (_mm256_stream_load_si256)?
In AVX/AVX2 I could only find _mm256_stream_load_si256() , which is for __m256i. Is there no way to stream-load __m256d and why? (I would like to load it without polluting CPU cache)

Is there any obstacle for doing the following (aggressive casting)?

```<code>__m256d *pDest = /* ... */;
__m256d *pSrc = /* ... */;

/* ... */

const __m256i iWeight = _mm256_stream_load_si256(reinterpret_cast<const __m256i*>(pSrc));
const __m256d prior = _mm256_div_pd(*reinterpret_cast<const __m256d*>(&iWeight), divisor);
_mm256_stream_pd(reinterpret_cast<double*>(pDest), prior);
</code>```

答:
The _mm256_stream_load_si256() intrinsic corresponds to the (V)MOVNTDQA instruction. This is the only non-temporal load instruction, so this is the one you have to use, even when you are loading floating-point data.

(The other three non-temporal instructions only do stores: (V)MOVNTDQ (_mm256_stream_si256) is for double quadword integers, (V)MOVNTPS (_mm256_stream_ps) is for packed single-precision floating-point values, and (V)MOVNTPD (_mm256_stream_pd) is for packed double-precision floating-point values.)

The cast from __m256i* to __m256d*, and vice versa, is safe. These are just bits, and they're all stored in YMM registers. I've never seen a compiler that had trouble with these types of casts. Probably should check the resulting assembly code to be sure that it's not doing something funky, though!

The only time it would matter is on certain processors, where there is a domain-crossing penalty when you mix floating-point SIMD instructions with integer SIMD instructions. But since the only NT load is in the integer domain, you really have no choice here.

Note that all non-temporal instructions (loads and stores) require aligned addresses!

Body:
In AVX/AVX2 I could only find _mm256_stream_load_si256() , which is for __m256i. Is there no way to stream-load __m256d and why? (I would like to load it without polluting CPU cache)

Is there any obstacle for doing the following (aggressive casting)?

__m256d *pDest = /* ... */;
__m256d *pSrc = /* ... */;

/* ... */

const __m256i iWeight = _mm256_stream_load_si256(reinterpret_cast<const __m256i*>(pSrc));
const __m256d prior = _mm256_div_pd(*reinterpret_cast<const __m256d*>(&iWeight), divisor);
_mm256_stream_pd(reinterpret_cast<double*>(pDest), prior);


问:
How to replace back button in Material in Swift
I want to change behavior of back button and I replace back button of Material with new bar button like bellow:

```<code>let backButton: UIButton = {
    let btn = UIButton()
    btn.setImage(UIImage(named: "prev"), for: .normal)
    btn.frame = CGRect(x: 0, y: 0, width: 33/2, height: 27/2)

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

In viewDidLoad function:

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

    backButton.action = { [weak self] in self?.showAlert() }
    let barButton = UIBarButtonItem(customView: backButton)
    navigationItem.backButton.isHidden = true
    navigationItem.leftBarButtonItems = [barButton]
}
</code>```

But I can not click to new back button because it was coverred by UINavigationBarBackIndicatorView.

How can I replace back button with Material. I want to keep Material library because in other features of project I need Material.

Thanks in advance for help.

答:
Do this in your viewDidLoad() method :

```<code>    self.navigationItem.backBarButtonItem.hidden = YES
    let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(YourViewController.back(sender:)))
    self.navigationItem.leftBarButtonItem = newBackButton
    self.navigationItem.leftBarButtonItem?.image = UIImage(named : "prev")
    self.navigationItem.leftBarButtonItem?.accessibilityFrame = CGRect(x: 0, y: 0, width: 33/2, height: 27/2)
</code>```

Then define a function named back in your view controller,this function will perform the desired action for your new back button

```<code>func back(sender: UIBarButtonItem) {
        // Perform your custom action
    }
</code>```

Note No need to define a separate button variable

**If self.navigationItem.backBarButtonItem.hidden = YES doesnt works then replace it with self.navigationItem.backBarButtonItem = nil; **

Body:
I want to change behavior of back button and I replace back button of Material with new bar button like bellow:

let backButton: UIButton = {
    let btn = UIButton()
    btn.setImage(UIImage(named: "prev"), for: .normal)
    btn.frame = CGRect(x: 0, y: 0, width: 33/2, height: 27/2)

    return btn
}()

In viewDidLoad function:

override func viewDidLoad() {
    super.viewDidLoad()

    backButton.action = { [weak self] in self?.showAlert() }
    let barButton = UIBarButtonItem(customView: backButton)
    navigationItem.backButton.isHidden = true
    navigationItem.leftBarButtonItems = [barButton]
}

But I can not click to new back button because it was coverred by UINavigationBarBackIndicatorView.

How can I replace back button with Material. I want to keep Material library because in other features of project I need Material.

Thanks in advance for help.

Body:
Do this in your viewDidLoad() method :

    self.navigationItem.backBarButtonItem.hidden = YES
    let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(YourViewController.back(sender:)))
    self.navigationItem.leftBarButtonItem = newBackButton
    self.navigationItem.leftBarButtonItem?.image = UIImage(named : "prev")
    self.navigationItem.leftBarButtonItem?.accessibilityFrame = CGRect(x: 0, y: 0, width: 33/2, height: 27/2)

Then define a function named back in your view controller,this function will perform the desired action for your new back button

func back(sender: UIBarButtonItem) {
        // Perform your custom action
    }

Note No need to define a separate button variable

**If self.navigationItem.backBarButtonItem.hidden = YES doesnt works then replace it with self.navigationItem.backBarButtonItem = nil; **


问:
Get List<Guid> from object C#
I have function GetChildren, which returns all the child nodes, in a structure as they need to be in treeview.

```<code> public static object GetChildrenNodes(IEnumerable<NodeDto> aNodes, Guid aNodeGuid)
    {
        var childrens = from childrenNode in aNodes
                        where (childrenNode.NodeParentGuid == aNodeGuid)
                        select new
                        {
                            id = childrenNode.NodeGuid,
                            text = childrenNode.Label,
                            nodes = (aNodes.Count(x => x.NodeParentGuid == childrenNode.NodeGuid) > 0) ? GetChildrenNodes(aNodes, childrenNode.NodeGuid) : null
                        };

        return childrens;
    }
</code>```

This function must remain as is, because TreeView requires that kind of object to build itself.

I would like to use the same function to get the guids of nodes to delete, so i have:

```<code> object nodesList = GetChildrenNodes(nodeList, aNodeGuid);
</code>```

The thing is i want to get List<Guid> guids from  "id"s of object nodesList, so i please for your help.

答:
I would avoid using the same method. You've got two different requirements:

Build a collection of anonymous types for use in the UI

Build a list of GUIDs for children of the given node ID

(I'm assuming you only want direct children, rather than all descendants? It's not clear.)

They may have the same filter, but that's about all. I'd suggest factoring out the common part (the filtering) and then having two different methods that call it:

```<code>private static IEnumerable<NodeDto> FindChildren(
    IEnumerable<NodeDto> allNodes, Guid parentId) =>
    allNodes.Where(node => node.NodeParentGuid == parentId);

public static object GetChildrenNodes(IEnumerable<NodeDto> allNodes, Guid parentId) =>
    FindChildren(allNodes, parentId).Select(node =>
    {
        id = childrenNode.NodeGuid,
        text = childrenNode.Label,
        nodes = allNodes.Any(x => x.NodeParentGuid == node.NodeGuid)
            ? GetChildrenNodes(allNodes, node.NodeGuid) : null
    });

public static List<Guid> FindChildIds(IEnumerable<NodeDto> allNodes, Guid parentId) =>
    FindChildren(allNodes, parentId).Select(node => node.NodeGuid).ToList();
</code>```

Title: Get List<Guid> from object C#

Body:
I have function GetChildren, which returns all the child nodes, in a structure as they need to be in treeview.

 public static object GetChildrenNodes(IEnumerable<NodeDto> aNodes, Guid aNodeGuid)
    {
        var childrens = from childrenNode in aNodes
                        where (childrenNode.NodeParentGuid == aNodeGuid)
                        select new
                        {
                            id = childrenNode.NodeGuid,
                            text = childrenNode.Label,
                            nodes = (aNodes.Count(x => x.NodeParentGuid == childrenNode.NodeGuid) > 0) ? GetChildrenNodes(aNodes, childrenNode.NodeGuid) : null
                        };

        return childrens;
    }

This function must remain as is, because TreeView requires that kind of object to build itself.

I would like to use the same function to get the guids of nodes to delete, so i have:

 object nodesList = GetChildrenNodes(nodeList, aNodeGuid);

The thing is i want to get List<Guid> guids from  "id"s of object nodesList, so i please for your help.

Body:
I would avoid using the same method. You've got two different requirements:

Build a collection of anonymous types for use in the UI

Build a list of GUIDs for children of the given node ID

(I'm assuming you only want direct children, rather than all descendants? It's not clear.)

They may have the same filter, but that's about all. I'd suggest factoring out the common part (the filtering) and then having two different methods that call it:

private static IEnumerable<NodeDto> FindChildren(
    IEnumerable<NodeDto> allNodes, Guid parentId) =>
    allNodes.Where(node => node.NodeParentGuid == parentId);

public static object GetChildrenNodes(IEnumerable<NodeDto> allNodes, Guid parentId) =>
    FindChildren(allNodes, parentId).Select(node =>
    {
        id = childrenNode.NodeGuid,
        text = childrenNode.Label,
        nodes = allNodes.Any(x => x.NodeParentGuid == node.NodeGuid)
            ? GetChildrenNodes(allNodes, node.NodeGuid) : null
    });

public static List<Guid> FindChildIds(IEnumerable<NodeDto> allNodes, Guid parentId) =>
    FindChildren(allNodes, parentId).Select(node => node.NodeGuid).ToList();


问:
What is the cost/overhead of defining a type?
Is there any runtime cost or overhead for having defined too many types in C++? For example, is there any difference at all between these two piece of code:

```<code>int main()
{
    int x, y;
    double fx, fy;

    return 0;
}
</code>```

And:

```<code>template<typename T>
struct Point
{
    T x, y;
};

int main()
{
    Point<int> p;
    Point<double> fp;

    return 0;
}
</code>```

Imagine a code which has many templated types, so that at compile time it generates even more concrete types: is it going to have any impact at runtime? My main concern is about static memory consumption.

答:
There is no such thing as types in the machine code (apart from the special case of RTTI). Therefore declaring types does not create any overhead.

Your examples are identical since both of them will result in a program that does exactly nothing, with no memory allocated. The variables aren't used by the program so they will get optimized away.

Body:
Is there any runtime cost or overhead for having defined too many types in C++? For example, is there any difference at all between these two piece of code:

int main()
{
    int x, y;
    double fx, fy;

    return 0;
}

And:

template<typename T>
struct Point
{
    T x, y;
};

int main()
{
    Point<int> p;
    Point<double> fp;

    return 0;
}

Imagine a code which has many templated types, so that at compile time it generates even more concrete types: is it going to have any impact at runtime? My main concern is about static memory consumption.


问:
pip install - Connection reset by peer
When I try to install lxml using pip I had the exception "Connection reset by peer":

```<code>Downloading/unpacking lxml
  Downloading lxml-3.0.1.tar.gz (3.2Mb): 643Kb downloaded
Exception:
Traceback (most recent call last):
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main
    status = self.run(options, args)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 245, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 985, in prepare_files
    self.unpack_url(url, location, self.is_download)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1109, in unpack_url
    retval = unpack_http_url(link, location, self.download_cache, self.download_dir)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/download.py", line 451, in unpack_http_url
    download_hash = _download_url(resp, link, temp_location)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/download.py", line 368, in _download_url
    chunk = resp.read(4096)
  File "/usr/lib/python2.7/socket.py", line 380, in read
    data = self._sock.recv(left)
  File "/usr/lib/python2.7/httplib.py", line 561, in read
    s = self.fp.read(amt)
  File "/usr/lib/python2.7/socket.py", line 380, in read
    data = self._sock.recv(left)
error: [Errno 104] Connection reset by peer
</code>```

This only happened when installing lxml, other modules got installed with pip no problems. Anybody had the same problem?

答:
In my case, was an ipv6 issue. Some mirrors still don't have full ipv6 access.

Disable ipv6 and try again.

Title: pip install - Connection reset by peer

Body:
When I try to install lxml using pip I had the exception "Connection reset by peer":

Downloading/unpacking lxml
  Downloading lxml-3.0.1.tar.gz (3.2Mb): 643Kb downloaded
Exception:
Traceback (most recent call last):
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main
    status = self.run(options, args)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 245, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 985, in prepare_files
    self.unpack_url(url, location, self.is_download)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1109, in unpack_url
    retval = unpack_http_url(link, location, self.download_cache, self.download_dir)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/download.py", line 451, in unpack_http_url
    download_hash = _download_url(resp, link, temp_location)
  File "/home/dummyuser/work/virt-dev-env/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/download.py", line 368, in _download_url
    chunk = resp.read(4096)
  File "/usr/lib/python2.7/socket.py", line 380, in read
    data = self._sock.recv(left)
  File "/usr/lib/python2.7/httplib.py", line 561, in read
    s = self.fp.read(amt)
  File "/usr/lib/python2.7/socket.py", line 380, in read
    data = self._sock.recv(left)
error: [Errno 104] Connection reset by peer

This only happened when installing lxml, other modules got installed with pip no problems. Anybody had the same problem?


问:
Listview not filled with data from Volley in onCreate
I'm trying to generate a list view from data together with Volley and ORMLite. The data is shown when i perform a pull to refresh or a reload of the page. When I reload the page I'm using a updateUI() function:

```<code> private void updateUI() throws SQLException {
    mAdministrationList.clear();
    mAdminstrationAdapter = new AdministrationAdapter(this, getLayoutInflater(), mAdministrationList);
    mVolleyHandler.GETAdministrations();
    mAdministrationList = mAdministrationDao.queryForAll();

    mAdminstrationListView.setAdapter(mAdminstrationAdapter);
    mAdminstrationListView.setOnItemClickListener(this);
    mAdminstrationAdapter.notifyDataSetChanged();
}
</code>```

This function works but the list is, as mentioned above, only loaded on a pull to refresh.

My onCreate looks like this:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_administration);

    mAdminstrationListView = (ListView) findViewById(R.id.administrationListView);

    mProgressSpinner = (ProgressBar) findViewById(R.id.administration_spinner);

    try {
        mAdministrationDao = getHelper().getAdministrationDao();
        mGlobalsDao = getHelper().getGlobalsDao();
        mGlobals = mGlobalsDao.queryForAll().get(0);

        mCurrentAdministration = mGlobals.getAdministration();
        mToken = mGlobals.getToken();
        mUser = mGlobals.getUser();

        mVolleyHandler = VolleyHandler.getInstance(this, mGlobals.getIpAddress(), mCurrentAdministration, mUser, mToken);

        updateUI();
        mAdminstrationAdapter.notifyDataSetChanged();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.administrationSwipe);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            try {
                updateUI();

                mAdminstrationAdapter.notifyDataSetChanged();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            mSwipeRefreshLayout.setRefreshing(false);
        }
    });
}
</code>```

The VolleyCall I'm making is getting the data from the API and parse it to a Administration Object, who is getting saved to the Database with ORMLite.

```<code>  public void ParseAdministration(String response) throws JSONException, SQLException {
    JSONObject jsonObject = new JSONObject(response);
    JSONArray results = jsonObject.getJSONArray("results");

    for (int i = 0; i < results.length(); i++) {

        JSONObject object = results.getJSONObject(i);

        Administration administration = new Administration();
        administration.setId(Long.valueOf(object.getString("id")));
        administration.setName(object.getString("name"));
        administration.setAddress1(object.getString("address1"));
        administration.setAddress2(object.getString("address2"));
        administration.setPostalCode(object.getString("postalCode"));
        administration.setCity(object.getString("city"));
        administration.setCountry(object.getString("country"));

        mDatabaseHelper.saveAdministration(administration);

    }
}
</code>```

I can't find where the problem is, so maybe some of you know what my problem is.

Thanks in Advance

EDITED:

Thanks to Shubham Goel, I have found a solution:

```<code> new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    mProgressSpinner = (ProgressBar) findViewById(R.id.administration_spinner);
                    updateUI();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                mProgressSpinner.setVisibility(View.GONE);
            }
        }, 3000);
</code>```

Maybe it's a little bit dirty but it does the job. Let me know if you think there is a better solution :)

答: This must be because in oncreate the volley loads data and takes some time to load data...till then all the updateUI functionality is performed with no data in list..before you pull to refresh the data has been loaded by the volley request and it shows up in list.</p>

Body:
I'm trying to generate a list view from data together with Volley and ORMLite. The data is shown when i perform a pull to refresh or a reload of the page. When I reload the page I'm using a updateUI() function:

 private void updateUI() throws SQLException {
    mAdministrationList.clear();
    mAdminstrationAdapter = new AdministrationAdapter(this, getLayoutInflater(), mAdministrationList);
    mVolleyHandler.GETAdministrations();
    mAdministrationList = mAdministrationDao.queryForAll();

    mAdminstrationListView.setAdapter(mAdminstrationAdapter);
    mAdminstrationListView.setOnItemClickListener(this);
    mAdminstrationAdapter.notifyDataSetChanged();
}

This function works but the list is, as mentioned above, only loaded on a pull to refresh.

My onCreate looks like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_administration);

    mAdminstrationListView = (ListView) findViewById(R.id.administrationListView);

    mProgressSpinner = (ProgressBar) findViewById(R.id.administration_spinner);

    try {
        mAdministrationDao = getHelper().getAdministrationDao();
        mGlobalsDao = getHelper().getGlobalsDao();
        mGlobals = mGlobalsDao.queryForAll().get(0);

        mCurrentAdministration = mGlobals.getAdministration();
        mToken = mGlobals.getToken();
        mUser = mGlobals.getUser();

        mVolleyHandler = VolleyHandler.getInstance(this, mGlobals.getIpAddress(), mCurrentAdministration, mUser, mToken);

        updateUI();
        mAdminstrationAdapter.notifyDataSetChanged();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.administrationSwipe);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            try {
                updateUI();

                mAdminstrationAdapter.notifyDataSetChanged();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            mSwipeRefreshLayout.setRefreshing(false);
        }
    });
}

The VolleyCall I'm making is getting the data from the API and parse it to a Administration Object, who is getting saved to the Database with ORMLite.

  public void ParseAdministration(String response) throws JSONException, SQLException {
    JSONObject jsonObject = new JSONObject(response);
    JSONArray results = jsonObject.getJSONArray("results");

    for (int i = 0; i < results.length(); i++) {

        JSONObject object = results.getJSONObject(i);

        Administration administration = new Administration();
        administration.setId(Long.valueOf(object.getString("id")));
        administration.setName(object.getString("name"));
        administration.setAddress1(object.getString("address1"));
        administration.setAddress2(object.getString("address2"));
        administration.setPostalCode(object.getString("postalCode"));
        administration.setCity(object.getString("city"));
        administration.setCountry(object.getString("country"));

        mDatabaseHelper.saveAdministration(administration);

    }
}

I can't find where the problem is, so maybe some of you know what my problem is.

Thanks in Advance

EDITED:

Thanks to Shubham Goel, I have found a solution:

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    mProgressSpinner = (ProgressBar) findViewById(R.id.administration_spinner);
                    updateUI();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                mProgressSpinner.setVisibility(View.GONE);
            }
        }, 3000);

Maybe it's a little bit dirty but it does the job. Let me know if you think there is a better solution :)


问:
Java 9 Zip End Header Not Found Exception
Edit for Googlers: this turned out to be caused by using an out-of-date beta release of Java 9.

I am trying to batch download zip files from this URL using java - SRTM files and it requires a username/password to download and I am using the following java code and it gives me the following exception

```<code>java.util.zip.ZipException: zip END header not found
at java.util.zip.ZipFile$Source.zerror(java.base@9-internal/ZipFile.java:1210)
at java.util.zip.ZipFile$Source.findEND(java.base@9-internal/ZipFile.java:1119)
at java.util.zip.ZipFile$Source.initCEN(java.base@9-internal/ZipFile.java:1126)
at java.util.zip.ZipFile$Source.<init>(java.base@9-internal/ZipFile.java:963)
at java.util.zip.ZipFile$Source.get(java.base@9-internal/ZipFile.java:933)
at java.util.zip.ZipFile.<init>(java.base@9-internal/ZipFile.java:213)
at java.util.zip.ZipFile.<init>(java.base@9-internal/ZipFile.java:145)
at java.util.zip.ZipFile.<init>(java.base@9-internal/ZipFile.java:159)
at toposwapper.rules.ZipFileDownloadAction.execute(ZipFileDownloadAction.java:29)
</code>```

This is my version of java

```<code> java openjdk version "9-internal"
 OpenJDK Runtime Environment (build 9-internal+0-2016-04-14-195246.buildd.src)
 OpenJDK 64-Bit Server VM (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode)
</code>```

This is the code that I am using to download -

```<code>    URL url1 = null;
    URLConnection conn = null;
    InputStream inputs = null;
    FileOutputStream out = null;
    try
    {
        url1 = new URL(url);
        conn = url1.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setRequestProperty("file-name", output.getName());
        conn.setRequestProperty("content-type","application/zip");
        String userpass = this.username + ":" + this.password;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
        conn.setRequestProperty("Authorization",basicAuth);
    }
  catch (MalformedURLException ex) {
           Logger.getLogger(SrtmDownloadManager.class.getName()).log(Level.SEVERE, "", ex);
    throw new TopoSwapperException(ex.getMessage());
    }
  catch (IOException ioe)
    {
    Logger.getLogger(SrtmDownloadManager.class.getName()).log(Level.SEVERE, "", ioe);
    throw new TopoSwapperException(ioe.getMessage());
    }

    try
      {
         inputs = conn.getInputStream();
         out = new FileOutputStream(output);
         byte[] b = new byte[1024];
         int count;
         while ((count = inputs.read(b)) > -1)
          {
            out.write(b,0,count);
           }
         out.flush();
         inputs.close();
         out.close();

      }
    catch (FileNotFoundException ex)
    {
        throw new TopoSwapperException(ex.getMessage());
    }
    catch (IOException ex)
    {
    Logger.getLogger(SrtmDownloadManager.class.getName()).log(Level.SEVERE, "", ex);
    throw new TopoSwapperException(ex.getMessage());
    }
finally
    {
        close(inputs);
        close(out);
    }
</code>```

Can somebody help me why this fails ?

答: This was an issue with some early beta releases of Java 9. A few (already closed) bugs for Java 9-beta mention this exception (eg.  JDK-8170276, JDK-8172872). The issues have been fixed in later beta releases and in the final release of Java 9. The issues were also not present in Java 8.</p>

Body:
Edit for Googlers: this turned out to be caused by using an out-of-date beta release of Java 9.

I am trying to batch download zip files from this URL using java - SRTM files and it requires a username/password to download and I am using the following java code and it gives me the following exception

java.util.zip.ZipException: zip END header not found
at java.util.zip.ZipFile$Source.zerror(java.base@9-internal/ZipFile.java:1210)
at java.util.zip.ZipFile$Source.findEND(java.base@9-internal/ZipFile.java:1119)
at java.util.zip.ZipFile$Source.initCEN(java.base@9-internal/ZipFile.java:1126)
at java.util.zip.ZipFile$Source.<init>(java.base@9-internal/ZipFile.java:963)
at java.util.zip.ZipFile$Source.get(java.base@9-internal/ZipFile.java:933)
at java.util.zip.ZipFile.<init>(java.base@9-internal/ZipFile.java:213)
at java.util.zip.ZipFile.<init>(java.base@9-internal/ZipFile.java:145)
at java.util.zip.ZipFile.<init>(java.base@9-internal/ZipFile.java:159)
at toposwapper.rules.ZipFileDownloadAction.execute(ZipFileDownloadAction.java:29)

This is my version of java

 java openjdk version "9-internal"
 OpenJDK Runtime Environment (build 9-internal+0-2016-04-14-195246.buildd.src)
 OpenJDK 64-Bit Server VM (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode)

This is the code that I am using to download -

    URL url1 = null;
    URLConnection conn = null;
    InputStream inputs = null;
    FileOutputStream out = null;
    try
    {
        url1 = new URL(url);
        conn = url1.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setRequestProperty("file-name", output.getName());
        conn.setRequestProperty("content-type","application/zip");
        String userpass = this.username + ":" + this.password;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
        conn.setRequestProperty("Authorization",basicAuth);
    }
  catch (MalformedURLException ex) {
           Logger.getLogger(SrtmDownloadManager.class.getName()).log(Level.SEVERE, "", ex);
    throw new TopoSwapperException(ex.getMessage());
    }
  catch (IOException ioe)
    {
    Logger.getLogger(SrtmDownloadManager.class.getName()).log(Level.SEVERE, "", ioe);
    throw new TopoSwapperException(ioe.getMessage());
    }

    try
      {
         inputs = conn.getInputStream();
         out = new FileOutputStream(output);
         byte[] b = new byte[1024];
         int count;
         while ((count = inputs.read(b)) > -1)
          {
            out.write(b,0,count);
           }
         out.flush();
         inputs.close();
         out.close();

      }
    catch (FileNotFoundException ex)
    {
        throw new TopoSwapperException(ex.getMessage());
    }
    catch (IOException ex)
    {
    Logger.getLogger(SrtmDownloadManager.class.getName()).log(Level.SEVERE, "", ex);
    throw new TopoSwapperException(ex.getMessage());
    }
finally
    {
        close(inputs);
        close(out);
    }

Can somebody help me why this fails ?


问:
c# Incorrect XML to deserialize
I have this XML, and i need deserialize but type is incorrect.

```<code><Consumer>
  <Sex type="int">Man</Sex>
</Consumer>
</code>```

How could i fix out? I like to allow int and string.

Thx in advance,

答:
Please doing folowing action.
Load your XML into Visual Studio, click the "Infer Schema" button, and run "xsd.exe /c schema.xsd" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.

check this link

Title: c# Incorrect XML to deserialize

Body:
I have this XML, and i need deserialize but type is incorrect.

<Consumer>
  <Sex type="int">Man</Sex>
</Consumer>

How could i fix out? I like to allow int and string.

Thx in advance,


问:
Using maven to output the version number to a text file
I want to generate a zip file that will update an application with maven. The zip will be hosted on a server and I am using the assembly plugin to generate the zip. However I would like maven to automatically generate a text file that stores the current version number outside the zip. How is this possible?

EDIT:
I successfully did it using the maven Assembly Plugin and two descriptors to create two custom assemblies. One has a directory-single goal and it just creates a folder with the updated version.txt based on filtering. Then another one with a single goal actually packages the zip file. This seems to be very inelegant and I guess it will not properly update the maven repo with the whole updated folder. If there is a better way to do this, please let me know.

答:
To add to Sean's answer, you can move the version file to a folder location within the jar by using the targetpath parameter within resource. The following code creates a folder called 'resources' within the jar and the text file (version.number) is found in that folder. </p>

```<code><resource>
    <directory>resources</directory>
    <targetPath>resources</targetPath>
    <filtering>true</filtering>
    <includes>
        <include>version.number</include>
    </includes>
</resource>
<resource>
    <directory>resources</directory>
    <filtering>false</filtering>
    <excludes>
        <exclude>version.number</exclude>
    </excludes>
</resource>
</code>```

Body:
To add to Sean's answer, you can move the version file to a folder location within the jar by using the targetpath parameter within resource. The following code creates a folder called 'resources' within the jar and the text file (version.number) is found in that folder.

<resource>
    <directory>resources</directory>
    <targetPath>resources</targetPath>
    <filtering>true</filtering>
    <includes>
        <include>version.number</include>
    </includes>
</resource>
<resource>
    <directory>resources</directory>
    <filtering>false</filtering>
    <excludes>
        <exclude>version.number</exclude>
    </excludes>
</resource>


问:
should a web app stay on a single page and why?
I've just noticed that several web application such as gmail, google calendar, zoho writer, etc are implemented using a single page only (not counting the logging form, just the main application)

There's no "open link in new tab"(at least the app don't need to open any new page to be functional) and such. What are the reasons to implement it like that?

答: single page web app keep a session in the front end and can offer a continuous talk with the user. and for developers, it is more simple to handle the data, no need to share the data between pages.</p>


问:
can't use local json file from my project in $http.get() function
I have this code but it keeps giving me an error

```<code>app.controller('myController',["$scope", '$location', '$http', '$rootScope',function($scope, $location, $http, $rootScope){
    $scope.gridOptions1 = {
    paginationPageSize: 15,
    columnDefs: [
      { name: 'الاسم' },
      { name: 'الجنس' },
      { name: 'الشركة' }
    ]
  };
  $http.get('/data/mydata.json')
  .then(function (data) {
    $scope.gridOptions1.data = data;
  })
</code>```

and this here is my json file:

```<code>[
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},{

    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
}
];
</code>```

the file is called mydata.json.
'pardon the language difference'.
What I think my problem is is that I'm not using $http.get() function the right way. I'm not sure weather I can use $http.get() for local urls.
Please help and thank you in advance

答:
remove the semicolon in the last line in your JSON file.

Also, data comes under data property. use data.data

```<code>$http.get('/mydata.json')
  .then(function (data.data) {
    $scope.gridOptions1.data = data.data;
  });
</code>```

Body:
I have this code but it keeps giving me an error

app.controller('myController',["$scope", '$location', '$http', '$rootScope',function($scope, $location, $http, $rootScope){
    $scope.gridOptions1 = {
    paginationPageSize: 15,
    columnDefs: [
      { name: 'الاسم' },
      { name: 'الجنس' },
      { name: 'الشركة' }
    ]
  };
  $http.get('/data/mydata.json')
  .then(function (data) {
    $scope.gridOptions1.data = data;
  })

and this here is my json file:

[
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},{

    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
}
];

the file is called mydata.json.
'pardon the language difference'.
What I think my problem is is that I'm not using $http.get() function the right way. I'm not sure weather I can use $http.get() for local urls.
Please help and thank you in advance

Body:
remove the semicolon in the last line in your JSON file.

Also, data comes under data property. use data.data

$http.get('/mydata.json')
  .then(function (data.data) {
    $scope.gridOptions1.data = data.data;
  });


问:
Integer (literal) union type, with NaN as valid return value
I have a (comparison) function with an union return type. It can return -1, 1 or 0. However, I need a special case ("result") for when at least one of the items being compared is not defined. The compiler allows me to add null as a potential return value, but not NaN (which, in some scenarios would make sense, e.g. comparing numbers or dates).

This compiles

```<code>function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | null {
   ...
}
</code>```

but for this one, the compiler says it "Cannot find name NaN":

```<code>function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | NaN {
   ...
}
</code>```

Why is NaN not allowed? Is there a way to use NaN?

答:
Unlike 1, NaN can not be used as a literal type (i.e. a type that only contain that literal value).

```<code>const n1 = 1, n2 = NaN;
typeof n1; // 1
typeof n2; // number
</code>```

We could also use number as the return type, but this would allow more return values like -2. If you wanted to limit the options, null looks good to me.

Body:
I have a (comparison) function with an union return type. It can return -1, 1 or 0. However, I need a special case ("result") for when at least one of the items being compared is not defined. The compiler allows me to add null as a potential return value, but not NaN (which, in some scenarios would make sense, e.g. comparing numbers or dates).

This compiles

function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | null {
   ...
}

but for this one, the compiler says it "Cannot find name NaN":

function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | NaN {
   ...
}

Why is NaN not allowed? Is there a way to use NaN?

Body:
Unlike 1, NaN can not be used as a literal type (i.e. a type that only contain that literal value).

const n1 = 1, n2 = NaN;
typeof n1; // 1
typeof n2; // number

We could also use number as the return type, but this would allow more return values like -2. If you wanted to limit the options, null looks good to me.


问:
how to get value of particular element when clicked on button which is having same class
here is my html

```<code><h3>IRCTC Checked Template</h3>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass"  id="btn" name="b">Send</button>
</div>
</code>```

on click on the button which is having same class i want to get respective textarea value
here my javascript

```<code>$(".btnclass").click(function(){
alert($('.txt').val());
});
</code>```

but the respective .txt class is not getting selected . for two buttons am getting same .txt class value.
i want to get respective text class on cling on the button .

答:
The issue is because you're selecting all .txt elements. Instead you need to use DOM traversal to find the one related to the clicked .btnclass element. To do that you can use prev(), like this:

$(".btnclass").click(function() {
  var value = $(this).prev('.txt').val();
  console.log(value);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>IRCTC Checked Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass" id="btn" name="b">Send</button>
</div></code>```

To get all .txt values you can use map() to build an array of them:

$(".btnclass").click(function() {
  var values = $('.txt').map(function() {
    return this.value;
  }).get();
  console.log(values);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>IRCTC Checked Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass" id="btn" name="b">Send</button>
</div></code>```

Body:
here is my html

IRCTC Checked Template

<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>

ID Created Template

<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass"  id="btn" name="b">Send</button>

on click on the button which is having same class i want to get respective textarea value
here my javascript

$(".btnclass").click(function(){
alert($('.txt').val());
});

but the respective .txt class is not getting selected . for two buttons am getting same .txt class value.
i want to get respective text class on cling on the button .

Body:
The issue is because you're selecting all .txt elements. Instead you need to use DOM traversal to find the one related to the clicked .btnclass element. To do that you can use prev(), like this:

$(".btnclass").click(function() {
  var value = $(this).prev('.txt').val();
  console.log(value);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>IRCTC Checked Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass" id="btn" name="b">Send</button>
</div>

To get all .txt values you can use map() to build an array of them:

$(".btnclass").click(function() {
  var values = $('.txt').map(function() {
    return this.value;
  }).get();
  console.log(values);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>IRCTC Checked Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
  <textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
  <button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass" id="btn" name="b">Send</button>
</div>


答:
You can use the .prev() function :

```<code>$(".btnclass").click(function(){
  alert($(this).prev().val());
});
</code>```

Title: how to get value of particular element when clicked on button which is having same class

Body:
You can use the .prev() function :

$(".btnclass").click(function(){
  alert($(this).prev().val());
});