Rectangle 27 31

You have to do it the way you described. MongoDB is a non-relational database and doesn't support joins.

Seems wrong performance wise coming from a sql server background, but its maybe not that bad with a document db?

from a sql server background as well, I would appreciate MongoDB taking a 'result set' (with selected returned fields) as input for a new query in one go, much like nested queries in SQL

@terjetyl You have to really plan for it. What fields are you going be presenting on the front end, if it's a limited amount in an individual view then you take those as embedded documents. The key is to not need to do joins. If you want to do deep analysis, you do it after the fact in another database. Run a job that transforms the data into an OLAP cube for optimal performance.

From mongo 3.2 version left joins are supported.

How do I perform the SQL Join equivalent in MongoDB? - Stack Overflow

join mongodb normalization
Rectangle 27 31

You have to do it the way you described. MongoDB is a non-relational database and doesn't support joins.

Seems wrong performance wise coming from a sql server background, but its maybe not that bad with a document db?

from a sql server background as well, I would appreciate MongoDB taking a 'result set' (with selected returned fields) as input for a new query in one go, much like nested queries in SQL

@terjetyl You have to really plan for it. What fields are you going be presenting on the front end, if it's a limited amount in an individual view then you take those as embedded documents. The key is to not need to do joins. If you want to do deep analysis, you do it after the fact in another database. Run a job that transforms the data into an OLAP cube for optimal performance.

From mongo 3.2 version left joins are supported.

How do I perform the SQL Join equivalent in MongoDB? - Stack Overflow

join mongodb normalization
Rectangle 27 1

Doing it the way you described

pip install --user packagename

If you don't have pip yet, or either OS's pip or OS's easy_install doesn't work properly, first install setuptools in user's home directory, and then use its easy_install for pip.

$ wget https://bootstrap.pypa.io/ez_setup.py -O - | python3 - --user
$ easy_install-3.4 --user pip

On the other side, if you decide to use pip inside virtualenv, don't use --user option for an obvious reason.

$ pip3 install --user virtualenv
$ python3 -m virtualenv myvenv
$ cd myvenv
$ source bin/activate
(myvenv)$ python3
>>> import curl
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named curl

There is no such module inside virtualenv. Just to make sure I looked into what's in sys.path.

>>> import sys
>>> sys.path
['',
'/home/username/myvenv/lib/python27.zip',
'/home/username/myvenv/lib/python2.7',
'/home/username/myvenv/lib/python2.7/lib-dynload',
'/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2',
'/home/username/myvenv/lib/python2.7/site-packages']

Notice that there is no /usr/lib/python3.4/site-packages, just as you wanted, but /usr/lib/python3.4 is present. If that's not okay for you, use --always-copy option when creating a virtualenv.

>>> ^D # Press Control-D
(myvenv)$ ln -s /usr/lib/python3.4/site-packages/curl lib/python3.4/site-packages/

Notice that there is no trailing slash in the second argument (file or directory which symlink points to), but there is a slash in the third argument (where symlink should be created). That's because I create a symlink inside of the directory lib/python3.4/site-packages. Without a trailing slash, it would try to replace the directory.

(myvenv)$ python3
>>> import curl
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/username/myvenv/lib/python3.4/site-packages/curl/__init__.py", line 9, in <module>
    import sys, pycurl
ImportError: No module named 'pycurl'
curl
pycurl
>>> ^D
(myvenv)$ ls -1 /usr/lib/python3.4/site-packages/pycurl*
/usr/lib/python3.4/site-packages/pycurl-7.19.3.1-py3.4.egg-info
/usr/lib/python3.4/site-packages/pycurl.cpython-34m.so
(myvenv)$ ln -s /usr/lib/python3.4/site-packages/pycurl-7.19.3.1-py3.4.egg-info lib/python3.4/site-packages/
(myvenv)$ ln -s /usr/lib/python3.4/site-packages/pycurl.cpython-34m.so lib/python3.4/site-packages/
(myvenv)$ python3
>>> import curl
>>> curl
<module 'curl' from '/home/username/myvenv/lib/python3.4/site-packages/curl/__init__.py'>

Personally, I strongly discourage you from doing this because, firstly, this is a perversion.

Moreover, I doubt this method works on everything. The depth of dependencies can be scary.

Secondly, I see no reason in avoiding --system-site-packages that works like a charm in all cases I'm acknowledged about.

Packages installed by pip in user's home directory have higher priority than system-wide packages, thus, they are taken first when doing import. In virtualenv, they are only imported if virtualenv was created with --system-site-packages option. Packages installed by pip inside virtualenv have even higher priority.

Honestly, I wrote this answer just to ask, why would you want to mess with all this instead of getting pip to work. I can't yet write comments on SO, so that's why I wrote a complete answer. :)

But you'll also drag in all the other system wide packages that you don't need!

No, you won't. You load a module into memory only when doing import. If you mean the package will be present in virtualenv once again, it won't. If you had looked inside of myvenv/lib/python3.4/site-packages/ you would have seen that there are only two packages inside - pip and setuptools (the latter one is separated into several directories though). The Python interpreter inside virtualenv simply loads system-wide modules just like an ordinary interpreter does.

P.S. The code above also applies to Python 2.7. Just replace pip3 with pip2, python3 with python2, 3.4 with 2.7, etc.

P.P.S. Instead of symlinking, you can copy the modules with their dependencies into virtualenv to the corresponding directories. This makes sense when using --always-copy, so that your virtualenv becomes portable.

P.P.P.S. If you decide to use virtualenv with --system-site-packages and pip, and, let's say, you want to have requests package newer than the already installed one in /usr/lib, use pip install -I, as described here.

Thanks. This part especially was really helpful and enlightening: "Packages installed by pip in user's home directory have higher priority than system-wide packages, thus, they are taken first when doing import. In virtualenv, they are only imported if virtualenv was created with --system-site-packages option. Packages installed by pip inside virtualenv have even higher priority." :) I went with --system-site-packages for now, and in other situations when I'll have more time or will to make things cleaner I'll figure out what to do to make pip work for the more "special" packages too...

ubuntu - Mix Python virtualenv packages with distro packages? - Stack ...

python ubuntu pip virtualenv
Rectangle 27 40

Bubbling and capturing are both supported by React in the same way as described by the DOM spec, except for how you go about attaching handlers.

Bubbling is as straightforward as with the normal DOM API; simply attach a handler to an eventual parent of an element, and any events triggered on that element will bubble to the parent as long as it's not stopped via stopPropagation along the way:

<div onClick={this.handleClick}>
  <button>Click me, and my parent's `onClick` will fire!</button>
</div>

Capturing is just as straightforward, though it's mentioned only briefly in the docs. Simply add Capture to the event handler property name:

<div onClickCapture={this.handleClickViaCapturing}>
  <button onClick={this.handleClick}>
    Click me, and my parent's `onClickCapture` will fire *first*!
  </button>
</div>

In this case, if handleClickViaCapturing calls stopPropagation on the event, the button's onClick handler will not be called.

stopPropagation

What is to keep in mind, all vanilla javascript events, for example from a library, are called beforehand. No matter if you register the event on Capture or Bubble phase.

What if I want the opposite ? What if I am having the onClick for the parent and I want to call that function even when child is clicked ?

@Dane That is normal event bubbling, as described in the first of the two examples above (the parent div's onClick is triggered when you click on the child button).

javascript - Example for Bubbling and Capturing in React.js - Stack Ov...

javascript reactjs event-bubbling event-capturing
Rectangle 27 5

Lazy loading doesn't create a separate dependency tree - at least, not in the way you're describing.

As you are probably aware, Angular's dependency injection system is actually a tree of injectors - one for each component in the view hierarchy. When you request a dependency, Angular walks this tree of injectors, starting from the component that's requesting the dependency until it finds the first injector that's able to provide that dependency. This gives you a lot of power if you need it, since at any level of the component tree, you can specify a provider for a dependency on the component and have that component get its own instance of that dependency. Furthermore, any children of that component will also share that same instance of the dependency.

That's the basic synopsis of how the hierarchal dependency injection works with respect to components. When it comes to modules, however, things are a bit different. By default, any dependencies provided by an NgModule are added to the root injector, meaning that a single instance of that dependency will be shared by the entire application. The exception to this is if the NgModule is lazy loaded. In that case, the dependencies provided by the lazy loaded module won't be added to the root injector. Instead, those dependencies will be added to the root component of the lazy loaded module (i learned this the hard way - if you have multiple 'root components' of your lazy loaded module, each 'root component' will get its own instance of the dependency).

So, it's still the same basic hierarchy - it's just that eager loaded modules add their dependencies to the root injector, whereas lazy loaded modules add theirs to the root component of their module. In addition, if a lazy loaded module imports an NgModule that also provides dependencies (for eg your SharedModule), those dependencies will also be added to that root component of the module. (Note that if SharedModule is also eager-loaded, its dependencies will also be added to the root injector - leading to multiple instances of those dependencies being available).

That last point is why you're seeing the behaviour you're seeing. When your lazy module imports SharedModule, SharedModules provided dependencies get added to the root component of the lazy module - leading to duplicate instances of those dependencies.

Great answer. By the way, from a practical standpoint its worth noting that if the service is always loaded by any eagerly loaded ngModule then there is no reason to import it in the lazily loaded one. On the other hand, if you keep state out of your services, then this issue won't affect you at all.

@AluanHaddad very good point about keeping state out of the services. I mean, sometimes it's unavoidable - you're using the service as a state sharing mechanism between 2 disparate components - but that's more the exception than the rule

Angular 2 Lazy Module and Shared modules singleton - Stack Overflow

angular
Rectangle 27 2

It is possible to reuse an AU Graph exactly in the same way as described in the question.

The problem why it did not work for me was that I had a bug which caused interferences/overwritings between my two AUGraph instances. I found these bugs only by chance. Since I fixed them, the AUGraphs work as intended.

When keeping the two AUGraph instances completely separate, you can use and reuse as many AUGraph instances as you like. I did not test if they can be used simultaneously.

iphone - Reusability of an AudioUnit Graph in iOS - Stack Overflow

iphone ios audiounit
Rectangle 27 73

HTML is not about presentation. It is a way of describing data. If you have some text that represents a label for an input, you wrap it in label tags not for presentation but because that's what it is. Without the label tag, that text is almost meaningless. With the label tag and its for attribute (or not*) you are providing meaning and structure and forming a relationship between your markup that can be better understood by computers/parsers/browsers/people.

* you don't necessarily need the for if you wrap the label around the input:

<label>My input
  <input type="text" id="my-input" />
</label>

+1 Just because you whined for an upvote.

html - Why use

html
Rectangle 27 23

Assuming progress guarantees, a retain cycle might be exactly what you want. You explicitly break the retain cycle at the end of the block, so it's not a permanent retain cycle: when the block is called, the cycle is broken.

If you have something else keeping the operation around, though, you can store a reference into either a __weak or __unsafe_unretained variable and then use that from within your block. There's no need to __block-qualify the variable unless you for some reason need to change the variable's binding during the block; since you don't have a retain cycle to break any more, you shouldn't need to assign anything to the weak variable.

I've got the 'no retain cycle' thing hammered into my mind, I didn't even think about it the way you described. Duh. Next question - any way to silence the compiler warning? It'll drive me mad.

See "Controlling Diagnostics via Pragmas" in the Clang user's manual. You'll just need to figure out which warning flag to ignore.

#pragma clang diagnostic ignored "-Warc-retain-cycles"

Sorry, I know I'm late to the party, but it is important to pay close attention to @JeremyW.Sherman's opening statement ("Assuming progress guarantees"), especially with AFNetworking, because this is not the case. In your sample, you are returning before setting the operation to nil if the operation is canceled, and similarly in AFHTTPRequestOperation.m:setCompletionBlockWithSuccess:... if the operation is canceled neither the completion or error blocks are called, leaving your operation retained.

Even assuming progress guarantees, a reference cycle is usually not "exactly what you want", though it might be acceptable.

iphone - ARC, Blocks and Retain Cycles - Stack Overflow

iphone ios ios5 automatic-ref-counting afnetworking
Rectangle 27 23

Assuming progress guarantees, a retain cycle might be exactly what you want. You explicitly break the retain cycle at the end of the block, so it's not a permanent retain cycle: when the block is called, the cycle is broken.

If you have something else keeping the operation around, though, you can store a reference into either a __weak or __unsafe_unretained variable and then use that from within your block. There's no need to __block-qualify the variable unless you for some reason need to change the variable's binding during the block; since you don't have a retain cycle to break any more, you shouldn't need to assign anything to the weak variable.

I've got the 'no retain cycle' thing hammered into my mind, I didn't even think about it the way you described. Duh. Next question - any way to silence the compiler warning? It'll drive me mad.

See "Controlling Diagnostics via Pragmas" in the Clang user's manual. You'll just need to figure out which warning flag to ignore.

#pragma clang diagnostic ignored "-Warc-retain-cycles"

Sorry, I know I'm late to the party, but it is important to pay close attention to @JeremyW.Sherman's opening statement ("Assuming progress guarantees"), especially with AFNetworking, because this is not the case. In your sample, you are returning before setting the operation to nil if the operation is canceled, and similarly in AFHTTPRequestOperation.m:setCompletionBlockWithSuccess:... if the operation is canceled neither the completion or error blocks are called, leaving your operation retained.

Even assuming progress guarantees, a reference cycle is usually not "exactly what you want", though it might be acceptable.

iphone - ARC, Blocks and Retain Cycles - Stack Overflow

iphone ios ios5 automatic-ref-counting afnetworking
Rectangle 27 8

you're misunderstanding the process of working with south. South isn't just another application, it's a managing tool. Your app needs to be a South application from the begining or converted to one. That being said, the process is like so:

  • run syncdb for the first time

run the south initialization command:

python manage.py schemamigration myapp --initial
python manage.py migrate

If you want to convert a project:

manage.py convert_to_south myapp

*p.s. - you can add both south and your own app at the same time, if you keep in mind to put south before your own apps. That's because django reads INSTALLED_APPS in order - it runs syncdb on all apps, but after installing south it won't install the rest and instead tell you to use the south commands to handle those

I misled you. Since you put so much emphasis on the south thing I didn't realize the problem was you were trying to use models as a directory module instead of a normal file. This is a recognized problem in django, and the workaround is actually exactly as you though in the first place:

project/
       myapp/
            models/
                  __init__.py
                  bar.py
bar.py
from django.db import models

class Foo(models.Model):
    # fields...

    class Meta:
        app_label = 'myapp' #you need this!
__init__.py
from bar import Foo

The ticket has changed to wontfix, because apparently the bigger issue with the app_label has been fixed. Huzza!

I am using --initial because it's a new app with no models in db. I tried "manage.py convert_to_south myapp" just to see what happened and it said "This application has no models; this command is for applications that already have models syncdb'd. Make some models, and then use ./manage.py schemamigration myapp --initial instead." As mentioned, I can run --initial and it executes as expected aside from the fact the generated file has nothing in it, it does not detect any of the models. These are new models none of which are in db.

1. The way you described it in your post is not the way I described it 2. Can you share models.py? Also any additional information you think is relevant. I don't think I see the entire problem yet

I have now removed the references from __init__.py in "models" folder as per your recommendation. Thanks for that, though it didn't change my issue as stated with no models being detected.

Cool, I have now added an example of one of the models to the description of the issue above.

python - Django not creating db tables for models (neither with syncdb...

python django django-south syncdb
Rectangle 27 1

No, it isn't possible - at least not in the way you've described, and not in any regular expression engine I've ever used. The closest you could get for a succinct approximation of the effect you seek is to chain the replacements. In JavaScript for example:

var newString = '05 Jan 2013'.replace(/Jan/i, '01').replace(/Feb/i, '02').replace(/Mar/i, '03').replace(/Apr/i, '01'); //And so on

regex - Regular expression mulit replace. Replace Mmm->dd - Stack Over...

regex replace expression
Rectangle 27 22

Simple Injector lacks this a factory interface facility. The idea behind is omission that when applying Dependency Injection correctly, the need for using factories is minimized, which makes the usefulness of such feature limited.

In Simple Injector you have to write an implementation yourself, but this is usually trivial. Example:

private sealed class SimpleInjectorBarFactory : IBarFactory {
    private readonly Container container; 

    public SimpleInjectorBarFactory(Container container) {
        this.container = container;
    }

    public Bar CreateBar() {
        return this.container.GetInstance<Bar>();
    }
}
container.RegisterSingleton<IBarFactory, SimpleInjectorBarFactory>();

Or -if you're lazy- you can register a Func<Bar> to be injected as follows:

container.RegisterSingleton<Func<Bar>>(() => container.GetInstance<Bar>());

Note that since this SimpleInjectorBarFactory implementation depends on the Container instance, it should be part of the Composition Root to prevent using the Container as a Service Locator. By placing the classes inside your Composition Root it becomes merely a piece of infrastructure.

So the feature is excluded deliberately, but the library can be extended quite easily to allow this, with a limited amount of code:

using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;

public static class AutomaticFactoryExtensions {
    public static void RegisterFactory<TFactory>(this Container container) {
        if (!typeof(TFactory).IsInterface)
            throw new ArgumentException(typeof(TFactory).Name + " is no interface");

        container.ResolveUnregisteredType += (s, e) => {
            if (e.UnregisteredServiceType == typeof(TFactory)) {
                e.Register(Expression.Constant(
                    value: CreateFactory(typeof(TFactory), container),
                    type: typeof(TFactory)));
            }
        };
    }

    private static object CreateFactory(Type factoryType, Container container) {
        var proxy = new AutomaticFactoryProxy(factoryType, container);
        return proxy.GetTransparentProxy();
    }

    private sealed class AutomaticFactoryProxy : RealProxy {
        private readonly Type factoryType;
        private readonly Container container;

        public AutomaticFactoryProxy(Type factoryType, Container container)
            : base(factoryType) {
            this.factoryType = factoryType;
            this.container = container;
        }

        public override IMessage Invoke(IMessage msg) {
            if (msg is IMethodCallMessage) {
                return this.InvokeFactory(msg as IMethodCallMessage);
            }

            return msg;
        }

        private IMessage InvokeFactory(IMethodCallMessage msg) {
            if (msg.MethodName == "GetType")
                return new ReturnMessage(this.factoryType, null, 0, null, msg);

            if (msg.MethodName == "ToString")
                return new ReturnMessage(this.factoryType.Name, null, 0, null, msg);

            var method = (MethodInfo)msg.MethodBase;
            object instance = this.container.GetInstance(method.ReturnType);
            return new ReturnMessage(instance, null, 0, null, msg);
        }
    }
}

Using the extension method above, you can do the registration for the factory in a way very similar to Ninject's registration:

container.RegisterFactory<IBarFactory>();

How can you unit test such a factory, if it is dependent on the Container?

@Boris: You would typically have a few unit/integration tests that test the container's configuration (example because verifying the container is important. In the same way as described here you can test this factory. Since those tests test the container, you obviously need an initialized container.

c# - Factory Interface in Simple Injector - Stack Overflow

c# dependency-injection simple-injector
Rectangle 27 3

I think that the best way to do it is to overriding the default ExceptionController. Just extend it, and override the findTemplate method. Check from the request's attribute if there's _route or _controller set, and do something with it.

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController;

class ExceptionController extends BaseExceptionController
{
    protected function findTemplate(Request $request, $format, $code, $showException)
    {
        $routeName = $request->attributes->get('_route');

        // You can inject these routes in the construct of the controller
        // so that you can manage them from the configuration file instead of hardcode them here
        $routesAdminSection = ['admin', 'admin_ban', 'admin_list'];

        // This is a poor implementation with in_array.
        // You can implement more advanced options using regex 
        // so that if you pass "^admin" you can match all the routes that starts with admin.

        // If the route name match, then we want use a different template: admin_error_CODE.FORMAT.twig
        // example: admin_error_404.html.twig
        if (!$showException && in_array($routeName, $routesAdminSection, true)) {
            $template = sprintf('@AppBundle/Exception/admin_error_%s.%s.twig', $code, format);
            if ($this->templateExists($template)) {
                return $template;
            }

            // What you want to do if the template doesn't exist?
            // Just use a generic HTML template: admin_error.html.twig
            $request->setRequestFormat('html');
            return sprintf('@AppBundle/Exception/admin_error.html.twig');
        }

        // Use the default findTemplate method
        return parent::findTemplate($request, $format, $code, $showException);
    }
}
twig.exception_controller
# app/config/services.yml
services:
    app.exception_controller:
        class: AppBundle\Controller\ExceptionController
        arguments: ['@twig', '%kernel.debug%']
# app/config/config.yml
twig:
    exception_controller:  app.exception_controller:showAction

You can then override the template in the same way:

A simpler way to do this is to specify the section of the website inside the defaults collection of your routes. Example:

# app/config/routing.yml
home:
    path:      /
    defaults:
        _controller: AppBundle:Main:index
        section:     web
blog:
    path:      /blog/{page}
    defaults:
        _controller: AppBundle:Main:blog
        section:     web
dashboard:
    path:      /admin
    defaults:
        _controller: AppBundle:Admin:dashboard
        section:     admin
stats:
    path:      /admin/stats
    defaults:
        _controller: AppBundle:Admin:stats
        section:     admin
namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController;

class ExceptionController extends BaseExceptionController
{
    protected function findTemplate(Request $request, $format, $code, $showException)
    {
        $section = $request->attributes->get('section');
        $template = sprintf('@AppBundle/Exception/%s_error_%s.%s.twig', $section, $code, format);
        if ($this->templateExists($template)) {
            return $template;
        }

        return parent::findTemplate($request, $format, $code, $showException);
    }
}

And configure twig.exception_controller in the same way as described above. Now you just need to define a template for each section, code and format.

php - Symfony - Different error pages for public and admin sections - ...

php symfony
Rectangle 27 55

When we set out with the goal to Java EE 6 certify Apache Tomcat as Apache TomEE, here are some of the gaps we had to fill in order to finally pass the Java EE 6 TCK.

Not a complete list, but some highlights that might not be obvious even with the existing answers.

Transaction Management is definitely required for any certified server. In any web component (servlet, filter, listener, jsf managed bean) you should be able to get a UserTransaction injected like so:

@Resource UserTransaction transaction;

You should be able use the javax.transaction.UserTransaction to create transactions. All the resources you touch in the scope of that transaction should all be enrolled in that transaction. This includes, but is not limited to, the following objects:

javax.sql.DataSource
javax.persistence.EntityManager
javax.jms.ConnectionFactory
javax.jms.QueueConnectionFactory
javax.jms.TopicConnectionFactory
javax.ejb.TimerService

For example, if in a servlet you start a transaction then:

  • Fire a JMS message to a topic or queue

.. and then one of those things fails or you simply choose to call rollback() on the UserTransaction, then all of those things are undone.

To be very clear there are two kinds of connection pooling:

The Java EE specs do not strictly require connection pooling, however if you have connection pooling, it should be transaction aware or you will lose your transaction management.

  • Everyone in the same transaction should have the same connection from the pool
  • The connection should not be returned to the pool until the transaction completes (commit or rollback) regardless if someone called close() or any other method on the DataSource.

A common library used in Tomcat for connection pooling is commons-dbcp. We wanted to also use this in TomEE, however it did not support transaction-aware connection pooling, so we actually added that functionality into commons-dbcp (yay, Apache) and it is there as of commons-dbc version 1.4.

Note, that adding commons-dbcp to Tomcat is still not enough to get transactional connection pooling. You still need the transaction manager and you still need the container to do the plumbing of registering connections with the TransactionManager via Synchronization objects.

In Java EE 7 there's talk of adding a standard way to encrypt DB passwords and package them with the application in a secure file or external storage. This will be one more feature that Tomcat will not support.

WebServices security, JAX-RS SecurityContext, EJB security, JAAS login and JAAC are all security concepts that by default are not "hooked up" in Tomcat even if you individually add libraries like CXF, OpenEJB, etc.

These APIs are all of course suppose to work together in a Java EE server. There was quite a bit of work we had to do to get all these to cooperate and to do it on top of the Tomcat Realm API so that people could use all the existing Tomcat Realm implementations to drive their "Java EE" security. It's really still Tomcat security, it's just very well integrated.

Yes, you can drop a JPA provider into a .war file and use it without Tomcat's help. With this approach you will not get:

@PersistenceUnit EntityManagerFactory
@PersistenceContext EntityManager
EntityManager

JTA-Managed EntityManager basically mean that two objects in the same transaction that wish to use an EntityManager will both see the same EntityManager and there is no need to explicitly pass the EntityManager around. All this "passing" is done for you by the container.

How is this achieved? Simple, the EntityManager you got from the container is a fake. It's a wrapper. When you use it, it looks in the current transaction for the real EntityManager and delegates the call to that EntityManager. This is the reason for the mysterious EntityManager.getDelegate() method, so users can get the real EntityManager if they want and make use of any non-standard APIs. Do so with great care of course and never keep a reference to the delegate EntityManager or you will have a serious memory leak. The delegate EntityManager will normally be flushed, closed, cleaned up and discarded when a transaction completes. If you're still holding onto a reference, you will prevent garbage collection of that EntityManager and possibly all the data it holds.

  • It's always safe to hold a reference to a EntityManager you got from the container
EntityManager.getDelegate()
  • Be very careful holding a reference to an EntityManager you created yourself via an EntityManagerFactory -- you are 100% responsible for its management.

I don't want to over simplify CDI, but I find it is a little too big and many people have not take a serious look -- it's on the "someday" list for many people :) So here is just a couple highlights that I think a "web guy" would want to know about.

You know all the putting and getting you do in a typical webapp? Pulling things in and out of HttpSession all day? Using String for the key and continuously casting objects you get from the HttpSession. You've probably go utility code to do that for you.

CDI has this utility code too, it's called @SessionScoped. Any object annotated with @SessionScoped gets put and tracked in the HttpSession for you. You just request the object to be injected into your Servlet via @Inject FooObject and the CDI container will track the "real" FooObject instance in the same way I described the transactional tracking of the EntitityManager. Abracadabra, now you can delete a bunch of code :)

HttpServletRequest
@RequestScoped
@ApplicationScoped
getAttribute
setAttribute
ServletContext

To make things even cooler, any object tracked like this can implement a @PostConstruct which gets invoked when the bean gets created and a @PreDestroy method to be notified when said "scope" is finished (the session is done, the request is over, the app is shutting down).

CDI can do a lot more, but that's enough to make anyone want to re-write an old webapp.

There are some things added in Java EE 6 that are in Tomcats wheelhouse that were not added. They don't require big explanations, but did account for a large chunk of the "filling in the gaps".

@DataSourceDefinition
java:global
java:app
java:module
@Resource MyEnum myEnum
@Resource Class myPluggableClass
@Resource(lookup="foo")

Minor points, but it can be incredibly useful to define DataSource in the app in a portable way, share JNDI entries between webapps, and have the simple power to say "look this thing up and inject it"

As mentioned, not a complete list. No mention of EJB, JMS, JAX-RS, JAX-WS, JSF, Bean Validation and other useful things. But at least some idea of the things often overlooked when people talk about what Tomcat is and is not.

Also be aware that what you might have thought of as "Java EE" might not match the actual definition. With the Web Profile, Java EE has shrank. This was deliberately to address "Java EE is too heavy and I don't need all that".

If you cut EJB out of the Web Profile, here's what you have left:

It's a pretty darn useful stack.

The connection should not be returned to the pool until the transaction completes

<persistence-unit transaction-type="RESOURCE_LOCAL">
javax.persistence.Persistence
EntityManagerFactory
javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory(PersistenceUnitInfo, Map)
PersistenceUnitInfo

The first one says explicitely: For an application server JTA datasource, use after_statement to aggressively release connections after every JDBC call.. Am I missing something?

I suspect the Hibernate docs recommend releasing the connection after every call when using an application server JTA datasource because they know they'll always get the same connection for all future calls as long as the transaction is active. Sort of an dont-bother-managing-whats-already-managed approach.

Besides EAR and EJB, what do I get from a Java EE app server that I do...

java tomcat java-ee application-server
Rectangle 27 1

If you only want to share info you can use UIActivityViewController,

//Include an array of things being attached to the ActivityViewController
  //The Array cannot be nil, you must provide something. Either an image or text or both

  NSArray *activityItems = @[@"Hello Share",[UIImage imageNamed:@"someImage"]];
  UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
  activityViewController.excludedActivityTypes = @[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact ];    // means this item you dont want to show while sharing 
  [self presentViewController:activityViewController animated:YES completion:NULL];

Thank you but I still wish do it the way i described above.

objective c - How to present resized UIViewController in UITableViewCo...

iphone objective-c uiviewcontroller uitableview
Rectangle 27 1

Here is a good explanation as to why you can't do it the way you have described. Essentially CodeIgniter looks for ['subclass_prefix'] . $Classname, e.g. 'MY_' . 'Controller'. And here is the same question for CI2

MY_Controller
MY_AdminController
MY_Controller.php
class MY_Controller extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

    ...
}

class MY_AdminController extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

    ...
}

I will try that. Not including the class on the same file, but using a require inside it, I like to keep controllers files visible.

inheritance - Extending CodeIgniter core classes - Stack Overflow

codeigniter inheritance codeigniter-3
Rectangle 27 3

The functionality you are looking for is actually part of a build tool called "linker". Despite the fact that besides some unresolved symbol errors it throws from time to time its presence often goes unnoticed it's one of the most important components of any build-chain.

Here some ideas how to proceed in to somehow get your binary to run.

Any of the methods described below will only work if

The machine code doesn't contain any jumps with absolute addresses as patching them to the right destinations would require relocation info.

The program starts at the very beginning of the binary file used as input

This should be easy to circumvent either by adding an additional (relative) jump instruction to the "right" spot at the start of the file of by using an offset into the binary data.

In case of a very simple "self-contained" contained binary given just by a bunch of raw machine instructions without any external dependencies and without (!) any absolute jump instructions instead of doing it by hand it might be easier to just use an already existing linker instead.

Given a file consisting of the raw machine instructions (main.bin in the following example) the first step would involve generating a shared object (main.o in the example) from it:

objcopy -I binary -B i386 -O elf32-i386 --rename-section .data=.text main.bin main.o
readelf -S
Symbol table '.symtab' contains 5 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND 
     1: 00000000     0 SECTION LOCAL  DEFAULT    1 
     2: 00000000     0 NOTYPE  GLOBAL DEFAULT    1 _binary_main_bin_start
     3: 0000000c     0 NOTYPE  GLOBAL DEFAULT    1 _binary_main_bin_end
     4: 0000000c     0 NOTYPE  GLOBAL DEFAULT  ABS _binary_main_bin_size

You'll notice that the symbols _binary_..._start, _binary_..._end and _binary_..._size according to start, end and size of the input file were added. These can be used to hand the entry point to the executable down to the linker.

ld --entry=_binary_main_bin_start main.o -o main

should produce the executable you are looking for.

Alternatively you might want to manually create an elf file just containing necessary information to get a running executable.

If you're not too familiar with the elf format you might want to take a look at the specs (available on: http://refspecs.linuxfoundation.org/). Also the manual page (man elf) is very exhaustive, so this might be good source of information too.

Taking a look into the specs you'll see the only component required under any circumstances is the elf header. A section header table is only required for shared objects, a program header table only for executables.

As we want to create an executable we'll only use the program header table with one single entry of type PT_LOAD describing the whole memory layout of the executable.

To meet alignment constrains the process image will contain the whole contents of the binary.(source: man elf).

... Loadable process segments must have congruent values for p_vaddr and p_offset, modulo the page size.

This being said it should be clear why the final layout of the elf file will look like this:

struct Binary {
  Elf32_Ehdr ehdr;
  Elf32_Phdr phdr;
  char code[];
};

Most fields of Elf32_Ehdr an Elf32_Phdr are fixed, so they can already be set in the initializer. The only fields that require later adjustments are the fields describing the sizes (.p_filesz and .p_memsz) of the loaded segment in the program header table entry.

Taking input from stdin and writing to stdout (thus used like ./a.out <main.bin >executable) this is the way the described setup could be implemented:

#include <stdio.h>
#include <stddef.h>
#include <elf.h>
#include <string.h>
#include <stdlib.h>

#define BUFFER_SIZE 1024
char buffer[BUFFER_SIZE];

void *read_all (int *filesize) {
  void *data = NULL;
  int offset = 0;
  int size = 0;

  while ((size = fread (buffer, 1, sizeof (buffer), stdin)) > 0) {
    if ((data = realloc (data, offset + size)) == NULL)
      exit (-1);
    memcpy (data + offset, buffer, size);
    offset += size;
  }
  *filesize = offset;
  return data;
}


#define LOAD_ADDRESS 0x8048000

struct Binary {
  Elf32_Ehdr ehdr;
  Elf32_Phdr phdr;
  char code[];
};

int main (int argc, char *argv[]) {

  void *code;
  int code_size;

  struct Binary binary = {
    /* ELF HEADER */
    .ehdr = {
      /* general */
      .e_ident   = {
        ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
        ELFCLASS32, 
        ELFDATA2LSB,
        EV_CURRENT,
        ELFOSABI_LINUX,
      },
      .e_type    = ET_EXEC,
      .e_machine = EM_386,
      .e_version = EV_CURRENT,
      .e_entry   = LOAD_ADDRESS + (offsetof (struct Binary, code)),
      .e_phoff   = offsetof (struct Binary, phdr),
      .e_shoff   = 0,
      .e_flags   = 0,
      .e_ehsize   = sizeof (Elf32_Ehdr),
      /* program header */
      .e_phentsize = sizeof (Elf32_Phdr),
      .e_phnum     = 1,
      /* section header */
      .e_shentsize = sizeof (Elf32_Shdr),
      .e_shnum     = 0,
      .e_shstrndx  = 0
    },

    /* PROGRAM HEADER */
    .phdr = {
      .p_type   = PT_LOAD,
      .p_offset = 0,
      .p_vaddr = LOAD_ADDRESS,
      .p_paddr = LOAD_ADDRESS,
      .p_filesz = 0,
      .p_memsz = 0,
      .p_flags = PF_R | PF_X,
      .p_align = 0x1000
    }
  };

  if ((code = read_all (&code_size)) == NULL)
    return -1;

  /* fix program header */
  binary.phdr.p_filesz = sizeof (struct Binary) + code_size;
  binary.phdr.p_memsz = sizeof (struct Binary) + code_size;

  /* write binary */
  fwrite (&binary, sizeof (struct Binary), 1, stdout);
  fwrite (code, 1, code_size, stdout);

  free (code);

  return 0;
}

c - How to use libelf to generate an ELF file for my own compiler? - S...

c file assembly x86 elf
Rectangle 27 6

Mostly. In the real world: YES.

Can you use PHP sessions if you disable cookies in your browser?

as long as the browser identity is obtained somehow and yields a unique value

  • session ID in GET (which is the "standard" PHP way if cookies are not allowed, and the "other" way you described). This value is then propagated automatically by PHP, e.g. added to all A HREF's and so on. Where it is not propagated because the automagical link recognition failed (e.g. complex URL built in Javascript), it is your responsibility to provide accordingly.

Or - and here we're not in Kansas anymore:

  • recognizing the browser some other way ("fingerprinting") (this is normally(1) suicidal)
  • Use LSO (Local Shared Objects) to generate a random UUID if it's not there already, and store it so that it can be retrieved on subsequent accesses.

(1) if you were in a LAN where you can trust the IPs, you could associate a "session" to the user IP. You might enforce a strict "no cookies" policy in a small firm and still have user sessions without resorting to _GET/_POST for your session ID.

PHP Sessions with disabled cookies, does it work? - Stack Overflow

php session cookies
Rectangle 27 6

Mostly. In the real world: YES.

Can you use PHP sessions if you disable cookies in your browser?

as long as the browser identity is obtained somehow and yields a unique value

  • session ID in GET (which is the "standard" PHP way if cookies are not allowed, and the "other" way you described). This value is then propagated automatically by PHP, e.g. added to all A HREF's and so on. Where it is not propagated because the automagical link recognition failed (e.g. complex URL built in Javascript), it is your responsibility to provide accordingly.

Or - and here we're not in Kansas anymore:

  • recognizing the browser some other way ("fingerprinting") (this is normally(1) suicidal)
  • Use LSO (Local Shared Objects) to generate a random UUID if it's not there already, and store it so that it can be retrieved on subsequent accesses.

(1) if you were in a LAN where you can trust the IPs, you could associate a "session" to the user IP. You might enforce a strict "no cookies" policy in a small firm and still have user sessions without resorting to _GET/_POST for your session ID.

PHP Sessions with disabled cookies, does it work? - Stack Overflow

php session cookies
Rectangle 27 23

The problem is your dataType and the format of your data parameter. I just tested this in a sandbox and the following works:

[HttpPost]
    public string ConvertLogInfoToXml(string jsonOfLog)
    {
        return Convert.ToString(jsonOfLog);
    }
<input type="button" onclick="test()"/>

    <script type="text/javascript">

        function test() {
            data = { prop: 1, myArray: [1, "two", 3] };
            //'data' is much more complicated in my real application
            var jsonOfLog = JSON.stringify(data);

            $.ajax({
                type: 'POST',
                dataType: 'text',
                url: "Home/ConvertLogInfoToXml",
                data: "jsonOfLog=" + jsonOfLog,
                success: function (returnPayload) {
                    console && console.log("request succeeded");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console && console.log("request failed");
                },

                processData: false,
                async: false
            });
        }

    </script>

Pay special attention to data, when sending text, you need to send a variable that matches the name of your parameter. It's not pretty, but it will get you your coveted unformatted string.

jsonOfLog   "{\"prop\":1,\"myArray\":[1,\"two\",3]}"    string
Key Value
Request POST /Home/ConvertLogInfoToXml HTTP/1.1
Accept  text/plain, */*; q=0.01
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest
Referer http://localhost:50189/
Accept-Language en-US
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host    localhost:50189
Content-Length  42
DNT 1
Connection  Keep-Alive
Cache-Control   no-cache
Cookie  EnableSSOUser=admin
jsonOfLog={"prop":1,"myArray":[1,"two",3]}
Key Value
Cache-Control   private
Content-Type    text/html; charset=utf-8
Date    Fri, 28 Jun 2013 18:49:24 GMT
Response    HTTP/1.1 200 OK
Server  Microsoft-IIS/8.0
X-AspNet-Version    4.0.30319
X-AspNetMvc-Version 4.0
X-Powered-By    ASP.NET
X-SourceFiles   =?UTF-8?B?XFxwc2ZcaG9tZVxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXE12YzRQbGF5Z3JvdW5kXE12YzRQbGF5Z3JvdW5kXEhvbWVcQ29udmVydExvZ0luZm9Ub1htbA==?=
{"prop":1,"myArray":[1,"two",3]}

What you suggested does work (with a problem). But not because of the data property of the ajax object. Instead, it is the removal of the contentType property. By removing it, the default of "application/x-www-form-urlencoded" is used. The problem with this is, once the data posted gets 'large', it gets truncated -- I think by the server. I found the same solution early and was very happy with it until I ran into that problem.

There is a 48KB limit on application/x-ww-form-urlencoded. You normally need to fall-back to multipart/form-data for larger data sets... but you're right. In this instance it does not work. You may be hitting the square peg/round hole point in the architecture. I'll be curious if you work something out as it will be a nice tidbit to know in the future. Good luck.

Thanks for your comments, and for spending the time on my question. Your solution is good, except for the large data set issue (which was not specified in the original question). Maybe I should enter a new question, then you can get credit for this one...

After banging my head further, I could not find a way to make this work other than the way you described. This leads to the truncation issue. I ended up switching to Web API. Doing so, I could pass my stringified JSON via a regular application/json content type and I didn't run into the length issue. I don't know why ASP .NET MVC controller actions doesn't work this way (I'm guessing the model binder is getting in the way). I'm going to accept your answer, with the note re: content length.

asp.net mvc - Posting JSON data via jQuery to ASP .NET MVC 4 controlle...

jquery asp.net-mvc json