text:
- #623 - Add support for overriding request options.

##### 12.3.0 - 17 August 2016

###### Backwards compatible changes
- Added `management.remarketingAudience.get` to `analytics` `v3` API
- Added `management.remarketingAudience.insert` to `analytics` `v3` API
- Added `management.remarketingAudience.list` to `analytics` `v3` API
- Added `management.remarketingAudience.patch` to `analytics` `v3` API
- Added `management.remarketingAudience.update` to `analytics` `v3` API
- Added `userProfiles.guardianInvitations.list` to `classroom` `v1` API
- Added `userProfiles.guardianInvitations.get` to `classroom` `v1` API
- Added `userProfiles.guardianInvitations.create` to `classroom` `v1` API
- Added `userProfiles.guardianInvitations.patch` to `classroom` `v1` API
- Added `userProfiles.guardians.list` to `classroom` `v1` API
- Added `userProfiles.guardians.get` to `classroom` `v1` API
- Added `userProfiles.guardians.delete` to `classroom` `v1` API
- Added `projects.triggers.create` to `cloudbuild` `v1` API
- Added `projects.triggers.get` to `cloudbuild` `v1` API
- Added `projects.triggers.list` to `cloudbuild` `v1` API
- Added `projects.triggers.delete` to `cloudbuild` `v1` API
- Added `projects.triggers.patch` to `cloudbuild` `v1` API
- Added `backendServices.aggregatedList` to `compute` `alpha` API
- Added `regionInstanceGroupManagers.patch` to `compute` `alpha` API
- Added `regionInstanceGroupManagers.update` to `compute` `alpha` API
- Added `networks.switchToCustomMode` to `compute` `beta` API
- Added `subnetworks.expandIpCidrRange` to `compute` `beta` API
- Added `shippingsettings.custombatch` to `content` `v2` API
- Added `shippingsettings.get` to `content` `v2` API
- Added `shippingsettings.getsupportedcarriers` to `content` `v2` API
- Added `shippingsettings.list` to `content` `v2` API
- Added `shippingsettings.patch` to `content` `v2` API
- Added `shippingsettings.update` to `content` `v2` API
- Added `datastore` `v1` API

##### 12.2.0 - 08 August 2016

###### Backwards compatible changes
- Added schema information found in discovery docs to generated documentation

##### 12.1.0 - 05 August 2016

###### Backwards compatible changes
- #612 - Upgrade request dependency, fixes #608 by @bengourley
- Added `managedconfigurationsfordevice.delete` to `androidenterprise` `v1` API
- Added `managedconfigurationsfordevice.get` to `androidenterprise` `v1` API
- Added `managedconfigurationsfordevice.list` to `androidenterprise` `v1` API
- Added `managedconfigurationsfordevice.patch` to `androidenterprise` `v1` API
- Added `managedconfigurationsfordevice.update` to `androidenterprise` `v1` API
- Added `managedconfigurationsforuser.delete` to `androidenterprise` `v1` API
- Added `managedconfigurationsforuser.get` to `androidenterprise` `v1` API
- Added `managedconfigurationsforuser.list` to `androidenterprise` `v1` API
- Added `managedconfigurationsforuser.patch` to `androidenterprise` `v1` API
- Added `managedconfigurationsforuser.update` to `androidenterprise` `v1` API
- Added `appengine` `v1` API
- Added `clientSslPolicies.testIamPermissions` to `compute` `alpha` API
- Added `instanceGroupManagers.patch` to `compute` `alpha` API
- Added `instanceGroupManagers.update` to `compute` `alpha` API
- Added `projects.disableXpnHost` to `compute` `alpha` API
- Added `projects.disableXpnResource` to `compute` `alpha` API
- Added `projects.enableXpnHost` to `compute` `alpha` API
- Added `projects.enableXpnResource` to `compute` `alpha` API
- Added `projects.getXpnHost` to `compute` `alpha` API
- Added `projects.getXpnResources` to `compute` `alpha` API
- Added `projects.listXpnHosts` to `compute` `alpha` API
- Added `regionDiskTypes.get` to `compute` `alpha` API
- Added `regionDiskTypes.list` to `compute` `alpha` API
- Added `regionDisks.createSnapshot` to `compute` `alpha` API
- Added `regionDisks.deletes` to `compute` `alpha` API
- Added `regionDisks.get` to `compute` `alpha` API
- Added `regionDisks.insert` to `compute` `alpha` API
- Added `regionDisks.list` to `compute` `alpha` API
- Added `regionDisks.setLabels` to `compute` `alpha` API
- Added `regionDisks.testIamPermissions` to `compute` `alpha` API
- Added `regionAutoscalers.delete` to `compute` `beta` API
- Added `regionAutoscalers.get` to `compute` `beta` API
- Added `regionAutoscalers.insert` to `compute` `beta` API
- Added `regionAutoscalers.list` to `compute` `beta` API
- Added `regionAutoscalers.patch` to `compute` `beta` API
- Added `regionAutoscalers.testIamPermissions` to `compute` `beta` API
- Added `regionAutoscalers.update` to `compute` `beta` API
- Added `regionInstanceGroupManagers.abandonInstances` to `compute` `beta` API
- Added `regionInstanceGroupManagers.delete` to `compute` `beta` API
- Added `regionInstanceGroupManagers.deleteInstances` to `compute` `beta` API
- Added `regionInstanceGroupManagers.get` to `compute` `beta` API
- Added `regionInstanceGroupManagers.insert` to `compute` `beta` API
- Added `regionInstanceGroupManagers.list` to `compute` `beta` API
- Added `regionInstanceGroupManagers.listManagedInstances` to `compute` `beta` API
- Added `regionInstanceGroupManagers.recreateInstances` to `compute` `beta` API
- Added `regionInstanceGroupManagers.resize` to `compute` `beta` API
- Added `regionInstanceGroupManagers.setAutoHealingPolicies` to `compute` `beta` API
- Added `regionInstanceGroupManagers.setInstanceTemplate` to `compute` `beta` API
- Added `regionInstanceGroupManagers.setTargetPools` to `compute` `beta` API
- Added `regionInstanceGroupManagers.testIamPermissions` to `compute` `beta` API
- Added `regionInstanceGroups.get` to `compute` `beta` API
- Added `regionInstanceGroups.list` to `compute` `beta` API
- Added `regionInstanceGroups.listInstances` to `compute` `beta` API
- Added `regionInstanceGroups.setNamedPorts` to `compute` `beta` API
- Added `regionInstanceGroups.testIamPermissions` to `compute` `beta` API
- Added `projects.jobs.debug.getConfig` to `dataflow` `v1b3` API
- Added `projects.jobs.debug.sendCapture` to `dataflow` `v1b3` API
- Added `projects.templates.create` to `dataflow` `v1b3` API
- Added `dfareporting` `v2.6` API
- Added `servicecontrol` `v1` API
- Added `servicemanagement` `v1` API
- Added `servicemanagement` `v1` API
- Added `spreadsheets.values.append` to `sheets` `v4` API

##### 12.0.0 - 21 July 2016

###### Breaking changes
- Removed `accounts.filterSets.getBidMetrics` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.get` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.create` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.getImpressionMetrics` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.delete` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.responsesWithoutBids.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.responsesErrors.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.losingBids.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.filteredBids.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.filteredBids.creatives.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.filteredBids.creatives.details.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.filteredBids.details.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.filteredImpressions.list` from `adexchangebuyer2` `v2beta1` API
- Removed `accounts.filterSets.filteredRequests.list` from `adexchangebuyer2` `v2beta1` API

###### Backwards compatible changes
- Added `language` `v1beta1` API
- Added `speech` `v1beta1` API
- Added `apps.create` to `appengine` `v1beta4` API
- Added `apps.locations.list` to `appengine` `v1beta4` API
- Added `apps.locations.get` to `appengine` `v1beta4` API
- Added `apps.create` to `appengine` `v1beta5` API
- Added `apps.locations.list` to `appengine` `v1beta5` API
- Added `apps.locations.get` to `appengine` `v1beta5` API
- Added `projects.events.report` to `clouderrorreporting` `v1beta1` API
- Added `surveys.delete` to `consumersurveys` `v2` API
- Added `backupRuns.insert` to `sqladmin` `v1beta4` API

##### 11.0.0 - 11 July 2016

###### Breaking changes
- Removed `appengine` `v1` API

###### Backwards compatible changes
- Added `apps.modules.versions.instances.delete` to `appengine` `v1beta4` API
- Added `apps.modules.versions.instances.get` to `appengine` `v1beta4` API
- Added `apps.modules.versions.instances.debug` to `appengine` `v1beta4` API
- Added `apps.modules.versions.instances.delete` to `appengine` `v1beta5` API
- Added `apps.modules.versions.instances.get` to `appengine` `v1beta5` API
- Added `apps.modules.versions.instances.debug` to `appengine` `v1beta5` API
- Added `routers.preview` to `compute` `beta` API

##### 10.0.0 - 06 July 2016

###### Breaking changes
- Removed `autoscaler` `v1beta2` API
- Removed `coordinate` `v1` API
- Removed `serviceregistry` `alpha` API

###### Backwards compatible changes
- Added `cloudbuild` `v2` API
- Added `accounts.filterSets.getBidMetrics` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.get` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.create` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.getImpressionMetrics` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.delete` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.responsesWithoutBids.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.responsesErrors.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.losingBids.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.filteredBids.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.filteredBids.creatives.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.filteredBids.creatives.details.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.filteredBids.details.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.filteredImpressions.list` to `adexchangebuyer2` `v2beta1` API
- Added `accounts.filterSets.filteredRequests.list` to `adexchangebuyer2` `v2beta1` API
- Added `enterprises.acknowledgeNotificationSet` to `androidenterprise` `v1` API
- Added `enterprises.completeSignup` to `androidenterprise` `v1` API
- Added `enterprises.generateSignupUrl` to `androidenterprise` `v1` API
- Added `enterprises.getServiceAccount` to `androidenterprise` `v1` API
- Added `enterprises.pullNotificationSet` to `androidenterprise` `v1` API
- Added `products.unapprove` to `androidenterprise` `v1` API
- Added `serviceaccountkeys.delete` to `androidenterprise` `v1` API
- Added `serviceaccountkeys.insert` to `androidenterprise` `v1` API
- Added `serviceaccountkeys.list` to `androidenterprise` `v1` API
- Added `users.delete` to `androidenterprise` `v1` API
- Added `users.generateAuthenticationToken` to `androidenterprise` `v1` API
- Added `users.insert` to `androidenterprise` `v1` API
- Added `users.patch` to `androidenterprise` `v1` API
- Added `users.update` to `androidenterprise` `v1` API
- Added `users.settings.getAutoForwarding` to `gmail` `v1` API
- Added `users.settings.getImap` to `gmail` `v1` API
- Added `users.settings.getPop` to `gmail` `v1` API
- Added `users.settings.getVacation` to `gmail` `v1` API
- Added `users.settings.updateAutoForwarding` to `gmail` `v1` API
- Added `users.settings.updateImap` to `gmail` `v1` API
- Added `users.settings.updatePop` to `gmail` `v1` API
- Added `users.settings.updateVacation` to `gmail` `v1` API
- Added `users.settings.filters.create` to `gmail` `v1` API
- Added `users.settings.filters.delete` to `gmail` `v1` API
- Added `users.settings.filters.get` to `gmail` `v1` API
- Added `users.settings.filters.list` to `gmail` `v1` API
- Added `users.settings.forwardingAddresses.create` to `gmail` `v1` API
- Added `users.settings.forwardingAddresses.delete` to `gmail` `v1` API
- Added `users.settings.forwardingAddresses.get` to `gmail` `v1` API
- Added `users.settings.forwardingAddresses.list` to `gmail` `v1` API
- Added `users.settings.sendAs.create` to `gmail` `v1` API
- Added `users.settings.sendAs.delete` to `gmail` `v1` API
- Added `users.settings.sendAs.get` to `gmail` `v1` API
- Added `users.settings.sendAs.list` to `gmail` `v1` API
- Added `users.settings.sendAs.patch` to `gmail` `v1` API
- Added `users.settings.sendAs.update` to `gmail` `v1` API
- Added `users.settings.sendAs.verify` to `gmail` `v1` API

##### 9.0.0 - 20 June 2016

###### Breaking changes
- Removed `regionalBackendServices.testIamPermissions` from `compute` `alpha` API

###### Backwards compatible changes
- Added `appengine` `v1` API
- Added `instances.setServiceAccount` to `compute` `alpha` API
- Added `networks.switchToCustomMode` to `compute` `alpha` API
- Added `regionBackendServices.delete` to `compute` `alpha` API
- Added `regionBackendServices.get` to `compute` `alpha` API
- Added `regionBackendServices.getHealth` to `compute` `alpha` API
- Added `regionBackendServices.insert` to `compute` `alpha` API
- Added `regionBackendServices.list` to `compute` `alpha` API
- Added `regionBackendServices.patch` to `compute` `alpha` API
- Added `regionBackendServices.testIamPermissions` to `compute` `alpha` API
- Added `regionBackendServices.update` to `compute` `alpha` API
- Added `subnetworks.expandIpCidrRange` to `compute` `alpha` API
- Added `subnetworks.getIamPolicy` to `compute` `alpha` API
- Added `subnetworks.setIamPolicy` to `compute` `alpha` API
- Added `healthChecks.delete` to `compute` `beta` API
- Added `healthChecks.get` to `compute` `beta` API
- Added `healthChecks.insert` to `compute` `beta` API
- Added `healthChecks.list` to `compute` `beta` API
- Added `healthChecks.patch` to `compute` `beta` API
- Added `healthChecks.testIamPermissions` to `compute` `beta` API
- Added `healthChecks.update` to `compute` `beta` API
- Added `targetSslProxies.delete` to `compute` `beta` API
- Added `targetSslProxies.get` to `compute` `beta` API
- Added `targetSslProxies.insert` to `compute` `beta` API
- Added `targetSslProxies.list` to `compute` `beta` API
- Added `targetSslProxies.setBackendService` to `compute` `beta` API
- Added `targetSslProxies.setProxyHeader` to `compute` `beta` API
- Added `targetSslProxies.setSslCertificates` to `compute` `beta` API
- Added `targetSslProxies.testIamPermissions` to `compute` `beta` API
- Added `urlMaps.invalidateCache` to `compute` `v1` API

##### 8.2.0 - 14 June 2016

###### Backwards compatible changes
- Regenerate, now including code snippets

##### 8.1.0 - 08 June 2016

###### Backwards compatible changes
- Update generator to pull in auto generated code samples and add them to the JSDoc comments.

##### 8.0.0 - 08 June 2016

###### Breaking changes
- Removed `cloudbuild` `v1` API
- Removed `cloudlatencytest` `v2` API
- Removed `drive` `v1` API

###### Backwards compatible changes
- Added `dns` `v2beta1` API
- Added `routers.preview` to `compute` `alpha` API
- Added `instances.startWithEncryptionKey` to `compute` `v1` API
- Added `routers.aggregatedList` to `compute` `v1` API
- Added `routers.delete` to `compute` `v1` API
- Added `routers.get` to `compute` `v1` API
- Added `routers.getRouterStatus` to `compute` `v1` API
- Added `routers.insert` to `compute` `v1` API
- Added `routers.list` to `compute` `v1` API
- Added `routers.patch` to `compute` `v1` API
- Added `routers.updated` to `compute` `v1` API
- Added `mobileapppanels.get` to `consumersurveys` `v2` API
- Added `mobileapppanels.list` to `consumersurveys` `v2` API
- Added `mobileapppanels.update` to `consumersurveys` `v2` API

##### 7.1.0 - 24 May 2016

###### Backwards compatible changes
- Added `acceleratedmobilepageurl` `v1` API
- Added `reviews.get` to `androidpublisher` `v2` API
- Added `reviews.list` to `androidpublisher` `v2` API
- Added `reviews.reply` to `androidpublisher` `v2` API
- Added `courses.courseWork.create` to `classroom` `v1` API
- Added `courses.courseWork.get` to `classroom` `v1` API
- Added `courses.courseWork.list` to `classroom` `v1` API
- Added `courses.courseWork.studentSubmissions.get` to `classroom` `v1` API
- Added `courses.courseWork.studentSubmissions.patch` to `classroom` `v1` API
- Added `courses.courseWork.studentSubmissions.list` to `classroom` `v1` API
- Added `courses.courseWork.studentSubmissions.turnIn` to `classroom` `v1` API
- Added `courses.courseWork.studentSubmissions.reclaim` to `classroom` `v1` API
- Added `courses.courseWork.studentSubmissions.return` to `classroom` `v1` API
- Added `courses.courseWork.studentSubmissions.modifyAttachments` to `classroom` `v1` API
- Added `projects.getAncestry` to `cloudresourcemanager` `v1beta1` API
- Added `accounts.avails.get` to `playmoviespartner` `v1` API
- Added `accounts.components.list` to `playmoviespartner` `v1` API
- Added `accounts.components.type.get` to `playmoviespartner` `v1` API

##### 7.0.0 - 16 May 2016

###### Breaking changes
- Removed `reseller` `v1sandbox` API

###### Backwards compatible changes
- Added `namespaces.update` to `proximitybeacon` `v1beta1` API
- Added `runtimeconfig` `v4` API
- Added `sheets` `v1beta1` API

##### 6.1.0 - 11 May 2016

###### Backwards compatible changes
- Added `dfareporting` `v2.5` API
- Added ability to use authentication with `discoverAPI`

##### 6.0.0 - 10 May 2016

###### Breaking changes
- Removed `media.upload` from `dataproc` `v1` API
- Removed `media.download` from `dataproc` `v1` API
- Removed `projects.clusters.setIamPolicy` from `dataproc` `v1beta` API
- Removed `projects.clusters.getIamPolicy` from `dataproc` `v1beta` API
- Removed `projects.clusters.testIamPermissions` from `dataproc` `v1beta` API
- Removed `projects.jobs.setIamPolicy` from `dataproc` `v1beta` API
- Removed `projects.jobs.getIamPolicy` from `dataproc` `v1beta` API
- Removed `projects.jobs.testIamPermissions` from `dataproc` `v1beta` API
- Removed `dfareporting` `v1` API
- Removed `dfareporting` `v1.1` API
- Removed `dfareporting` `v1.2` API
- Removed `dfareporting` `v1.3` API
- Removed `dfareporting` `v2.0` API
- Removed `dfareporting` `v2.1` API
- Removed `gan` `v1beta1` API
- Removed `manager` `v1beta2` API

###### Backwards compatible changes
- Added `products.list` to `androidenterprise` `v1` API
- Added `projects.moveDisk` to `compute` `beta` API
- Added `projects.moveInstance` to `compute` `beta` API
- Added `v1beta1.getEidparams` to `proximitybeacon` `v1beta1` API
- Added `compute` `alpha` API
- Added `firebaserules` `v1` API
- Added `safebrowsing` `v4` API

###### Other
- Merged PR #571 by @georules - v2 does not have the create function, updating to v3

##### 5.2.0 - 21 April 2016

###### Backwards compatible changes
- Added `instances.startWithEncryptionKey` to `compute` `beta` API
- Added `images.getFromFamily` to `compute` `v1` API
- #555 - Added "discover" and "discoverAPI" methods for discovering API(s) at runtime.
  - Closes #416

###### Other
- #556 - Switched from JSHint to Semistandard
- Improved JSDocs

##### 5.1.0 - 19 April 2016

###### Backwards compatible changes
- Added `instances.list` to `appengine` `v1beta4` API
- Added `instances.list` to `appengine` `v1beta5` API
- Added `instanceGroupManagers.resizeAdvanced` to `compute` `beta` API

###### Other
- Switched from coveralls to codecov

##### 5.0.0 - 11 April 2016

###### Breaking changes
- Removed `deploymentmanager` `v2beta1` API
- Removed `deploymentmanager` `v2beta2` API

###### Backwards compatible changes
- Added `analyticsreporting` `v4` API
- Added `consumersurveys` `v2` API
- Added `datastore` `v1beta3` API
- Added `dfareporting` `v2.5beta1` API
- Removed `apis/index.js`, now the apis are loaded dynamically by `lib/googleapis.js`

##### 4.0.0 - 23 March 2016

###### Breaking changes
- `adexchangebuyer` `v1.4`: Renamed required param `private_auction_id` to `privateAuctionId`

###### Backwards compatible changes
- Added `clouderrorreporting` `v1beta1` API
- `compute` `v1`: Added `resize` method

##### 3.1.0 - 16 March 2016

###### Backwards compatible changes
- Added `monitoring` `v3` API

###### Other
- #536 - Update README URLs based on HTTP redirects (by @ReadmeCritic)
- #537 - [github template] minor edits to pull request template (by @ReadmeCritic)

##### 3.0.0 - 14 March 2016

###### Breaking changes
- Removed `admin` `email_migration_v2` API
- Removed `mapsengine` `exp2` API
- Removed `mapsengine` `v1` API

###### Backwards compatible changes
- Added `adexchangebuyer2` `v3beta1` API
- Added `appengine` `v1beta5` API
- Added `cloudbuild` `v1` API
- Added `cloudresourcemanager` `v1` API
- Added `compute` `beta` API
- Added `dfareporting` `v2`.4 API
- Added `genomics` `v1alpha2` API
- Added `iam` `v1` API
- Added `iam` `v1alpha1` API
- Added `people` `v1` API
- Added `serviceregister` `alpha` API
- Added `toolresults` `v1beta3` API
- Added `vision` `v1` API
- #488 - Added support for generating an API from a discovery doc file
- #533 - Add etag support with samples and test
- `node scripts/generate` can now accept a variable list of discovery urls and/or paths to discovery doc files

###### Backwards compatible bug fixes
- #463 - `--discovery-url` option works again.

###### Other
- #527 - Added glass mirror api sample

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace RM\ComunicacionBundle\Entity;

use Doctrine\ORM\EntityRepository;
use RM\InsightBundle\Filter\InstanciaComunicacionFilter;
use RM\PlantillaBundle\Entity\GrupoSlots;
use RM\ProductoBundle\Entity\Promocion;

class InstanciaComunicacionRepository extends EntityRepository
{

    /**
     * @param $id_instancia
     *
     * @return InstanciaComunicacion[]
     */
    public function obtenerInstanciaById($id_instancia)
    {
        return $this
            ->createQueryBuilder('i')
            ->where('i.idInstancia = :id')
            ->andWhere('i.estado > -1')
            ->setParameter('id', $id_instancia)
            ->getQuery()
            ->getResult();
    }

    /**
     * @param $id_instancia
     *
     * @return InstanciaComunicacion
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findById($id_instancia)
    {
        $instancia = $this
            ->createQueryBuilder('i')
            ->addSelect('segmento', 'fase', 'comunicacion', 'np', 'promociones', 'producto', 'tipo')
            ->join('i.idSegmentoComunicacion', 'segmento')
            ->join('i.fase', 'fase')
            ->join('segmento.idComunicacion', 'comunicacion')
            ->leftJoin('i.numPromociones', 'np')
            ->leftJoin('np.promociones', 'promociones')
            ->leftJoin('promociones.idTipoPromocion', 'tipo')
            ->leftJoin('promociones.idProducto', 'producto')
            ->where('i.idInstancia = :id_instancia')
            ->andWhere('i.estado > -1')
            ->setParameter('id_instancia', $id_instancia)
            ->getQuery()
            ->getOneOrNullResult();

        return $instancia;

    }

    /**
     * @param $id_comunicacion
     * @param $id_segmento
     * @param $fase
     * @param $fecha_inicio
     * @param $fecha_fin
     *
     * @return InstanciaComunicacion[]
     */
    public function obtenerInstanciasByFiltro($id_comunicacion, $id_segmento, $fase, $fecha_inicio, $fecha_fin)
    {
        return $this
            ->obtenerInstanciasByFiltroDQL($id_comunicacion, $id_segmento, $fase, $fecha_inicio, $fecha_fin)
            ->getResult();
    }

    /**
     * @param $id_comunicacion
     * @param $id_segmento
     * @param $fase
     * @param $fecha_inicio
     * @param $fecha_fin
     *
     * @return \Doctrine\ORM\Query
     */
    public function obtenerInstanciasByFiltroDQL($id_comunicacion, $id_segmento, $fase, $fecha_inicio, $fecha_fin)
    {
        $qb = $this
            ->createQueryBuilder('ic')
            ->join('ic.idSegmentoComunicacion', 'sc')
            ->join('sc.idComunicacion', 'c')
            ->join('sc.idSegmento', 's')
            ->where('ic.estado > -1')
            ->orderBy('ic.idInstancia', 'ASC');

        if ($id_comunicacion != -1) {
            $qb->andWhere('c.idComunicacion = :id_comunicacion')
               ->setParameter('id_comunicacion', $id_comunicacion);
        }

        if ($id_segmento != -1) {
            $qb->andWhere('s.idSegmento = :id_segmento')
               ->setParameter('id_segmento', $id_segmento);
        }

        if ($fase != -1) {
            $qb->andWhere('ic.fase = :fase')
               ->setParameter('fase', $fase);
        }

        if ($fecha_inicio != -1 && $fecha_inicio != '') {
            $fecha_init = \DateTime::createFromFormat('d/m/Y', $fecha_inicio);
            $qb->andWhere('ic.fecEjecucion >= :fecha_inicio')
               ->setParameter('fecha_inicio', $fecha_init);
        }

        if ($fecha_fin != -1 && $fecha_fin != '') {
            $fecha_end = \DateTime::createFromFormat('d/m/Y', $fecha_fin);
            $qb->andWhere('ic.fecEjecucion <= :fecha_fin')
               ->setParameter('fecha_fin', $fecha_end);
        }

        return $qb->getQuery();

    }

    /**
     * @param InstanciaComunicacionFilter $filter
     *
     * @return InstanciaComunicacion[]
     */
    public function findInstanciasEmailByComunicacionYFechas(InstanciaComunicacionFilter $filter)
    {

        $qb = $this
            ->createQueryBuilder('i')
            ->join('i.idSegmentoComunicacion', 'sc')
            ->join('sc.idComunicacion', 'c')
            ->join('c.idCanal', 'canal')
            ->join('i.fase', 'fase')
            ->where('i.estado > -1')
            ->andwhere('fase.codigo = :finalizada')
            ->andWhere('canal.nombre = :email')
            ->andWhere('i.fechaEnvio is not null')
            ->setParameter('email', 'Email')
            ->setParameter('finalizada', InstanciaComunicacion::FASE_FINALIZADA)
            ->orderBy('i.idInstancia', 'ASC');

        if (null !== $comunicacion = $filter->getComunicacion()) {
            $qb
                ->andWhere('c.idComunicacion = :comunicacion')
                ->setParameter('comunicacion', $comunicacion->getIdComunicacion());
        }

        if (null !== $fechaInicio = $filter->getFechaInicio()) {
            $qb
                ->andWhere('i.fechaEnvio >= :fecha_inicio')
                ->setParameter('fecha_inicio', $fechaInicio);
        }

        if (null !== $fechaFin = $filter->getFechaFin()) {
            $qb
                ->andWhere('i.fechaEnvio <= :fecha_fin')
                ->setParameter('fecha_fin', $fechaFin);
        }

        return $qb->getQuery()->getResult();

    }

    /**
     * @param $id_instancia
     *
     * @return array
     */
    public function obtenerResumenPromocionesByTipo($id_instancia)
    {

        $dql = "
          SELECT gs.idGrupo, gs.nombre AS nombreGrupo,
                 cat.idCategoria, cat.nombre AS nombreCategoria,
                 np.numSegmentadas, np.numGenericas,
                 COUNT(DISTINCT pSeg.idPromocion) As num_pro_seg,
                 COUNT(DISTINCT pGen.idPromocion) As num_pro_gen,
                 gs.tipo as tipoGrupo
		    FROM RMComunicacionBundle:InstanciaComunicacion ic
		    JOIN RMProductoBundle:NumPromociones np WITH (ic.idInstancia = np.idInstancia AND np.estado > -1)
		    JOIN RMPlantillaBundle:GrupoSlots AS gs WITH (np.idGrupo = gs.idGrupo AND gs.estado > -1)
       LEFT JOIN RMCategoriaBundle:Categoria AS cat WITH (np.idCategoria = cat.idCategoria)
       LEFT JOIN RMProductoBundle:Promocion pSeg WITH ( np = pSeg.numPromocion AND pSeg.tipo = 0 AND pSeg.estado > -1)
       LEFT JOIN RMProductoBundle:Promocion pGen WITH ( np = pGen.numPromocion AND pGen.tipo = 1 AND pGen.estado > -1)
           WHERE ic.estado > -1
		     AND ic.idInstancia = :idinstancia
		GROUP BY np.idGrupo, np.idCategoria
		ORDER BY gs.nombre
		";

        $query = $this->_em->createQuery($dql);
        $query->setParameter('idinstancia', $id_instancia);

        return $query->getResult();
    }

    /**
     * @param $id_instancia
     *
     * @return array
     */
    public function obtenerResumenPromocionesByEstado($id_instancia)
    {
        $dql = "
                SELECT gs.idGrupo, cat.idCategoria,
                    SUM(CASE WHEN pro.aceptada = :aceptada THEN 1 ELSE 0 END) AS aceptadas,
                    SUM(CASE WHEN pro.aceptada = :pendiente THEN 1 ELSE 0 END) AS pendientes,
                    SUM(CASE WHEN pro.aceptada = :rechazada THEN 1 ELSE 0 END) AS rechazadas,
                    gs.tipo as tipoGrupo,
                    gs.nombre as nombreGrupo,
                    np.idNumPro as idNumPro
				FROM RMComunicacionBundle:InstanciaComunicacion ic
				JOIN RMProductoBundle:NumPromociones np WITH (np.idInstancia = ic.idInstancia)
				JOIN RMProductoBundle:Promocion pro WITH (np = pro.numPromocion AND pro.aceptada IN (:tipos) AND pro.tipo=:segmentada AND pro.estado > -1)
				JOIN RMPlantillaBundle:GrupoSlots AS gs WITH (np.idGrupo = gs.idGrupo AND gs.estado > -1)
				JOIN RMCategoriaBundle:Categoria AS cat WITH (np.idCategoria = cat.idCategoria)
				WHERE ic.estado > -1
				AND ic.idInstancia = :idinstancia
				GROUP BY np.idGrupo, np.idCategoria
				";

        $query = $this->_em->createQuery($dql);
        $query
            ->setParameter('idinstancia', $id_instancia)
            ->setParameter('aceptada', Promocion::ACEPTADA)
            ->setParameter('pendiente', Promocion::PENDIENTE)
            ->setParameter('rechazada', Promocion::RECHAZADA)
            ->setParameter('segmentada', Promocion::TIPO_SEGMENTADA)
            ->setParameter('tipos', [
                Promocion::ACEPTADA,
                Promocion::PENDIENTE,
                Promocion::RECHAZADA
            ]);

        return $query->getResult();
    }

    /**
     * @param $id_categoria
     *
     * @return InstanciaComunicacion[]
     */
    public function obtenerCampanyasByFiltro($id_categoria)
    {
        if (is_array($id_categoria) && empty($id_categoria)) {
            return [];
        }

        $qb = $this
            ->createQueryBuilder('ic')
            ->join('ic.numPromociones', 'np')
            ->join('ic.fase', 'fase')
            ->where('ic.estado > -1')
            ->andWhere('fase.codigo = :codigo')
            ->groupBy('ic.idInstancia')
            ->orderBy('ic.idInstancia', 'ASC')
            ->setParameter('codigo', InstanciaComunicacion::FASE_NEGOCIACION);

        if ($id_categoria !== null && $id_categoria > 0) {
            $qb->andWhere('np.idCategoria IN (:categoria)')
               ->setParameter('categoria', $id_categoria);
        }

        return $qb->getQuery()->getResult();
    }

    /**
     * @return InstanciaComunicacion[]
     */
    public function obtenerClosingCampaigns()
    {
        return $this
            ->createQueryBuilder('i')
            ->join('i.fase', 'fase')
            ->where('i.estado > -1')
            ->andWhere('fase.codigo = :cierre')
            ->orderBy('i.idInstancia', 'ASC')
            ->setParameter('cierre', InstanciaComunicacion::FASE_CIERRE)
            ->getQuery()
            ->getResult();
    }

    /**
     * @param $id_categoria
     *
     * @return InstanciaComunicacion[]
     */
    public function obtenerClosingCampaignsByFiltro($id_categoria)
    {

        $qb = $this
            ->createQueryBuilder('ic')
            ->join('RMComunicacionBundle:SegmentoComunicacion', 'sc', 'WITH',
                'ic.idSegmentoComunicacion = sc.idSegmentoComunicacion')
            ->join('RMComunicacionBundle:Comunicacion', 'c', 'WITH', 'sc.idComunicacion = c.idComunicacion')
            ->join('RMSegmentoBundle:Segmento', 's', 'WITH', 'sc.idSegmento = s.idSegmento')
            ->join('RMProductoBundle:NumPromociones', 'np', 'WITH',
                'ic.idInstancia = np.idInstancia AND np.estado > -1')
            ->join('ic.fase', 'f')
            ->where('ic.estado > -1')
            ->andWhere('f.codigo = :codigo')
            ->groupBy('ic.idInstancia')
            ->orderBy('ic.idInstancia', 'ASC')
            ->setParameter('codigo', InstanciaComunicacion::FASE_CIERRE);

        if ($id_categoria !== null && $id_categoria > 0) {
            $qb->andWhere('np.idCategoria = :categoria')
               ->setParameter('categoria', $id_categoria);
        }

        return $qb->getQuery()->getResult();
        /**
         * $dql = "SELECT ic
         * FROM RMComunicacionBundle:InstanciaComunicacion ic
         * JOIN RMComunicacionBundle:SegmentoComunicacion sc WITH (ic.idSegmentoComunicacion = sc.idSegmentoComunicacion)
         * JOIN RMComunicacionBundle:Comunicacion c WITH (sc.idComunicacion = c.idComunicacion)
         * JOIN RMSegmentoBundle:Segmento s WITH (sc.idSegmento = s.idSegmento)
         * JOIN RMProductoBundle:NumPromociones np WITH (ic.idInstancia = np.idInstancia AND np.estado > -1)
         * WHERE ic.estado > 0
         * AND  ic.fase = 3";
         *
         * if($id_categoria != null && $id_categoria > 0){
         * $dql .= " AND np.idCategoria IN (". $id_categoria. ")";
         * }
         *
         * $dql .= " GROUP BY ic.idInstancia
         * ORDER BY ic.idInstancia ASC";
         *
         * $query = $this->_em->createQuery($dql);
         *
         * return $query->getResult();**/
    }

    /**
     * @return InstanciaComunicacion[]
     */
    public function obtenerInstanciasCreatividad()
    {
        $dql = "SELECT ic
            FROM RMComunicacionBundle:InstanciaComunicacion ic
            JOIN ic.fase as fase
            JOIN RMComunicacionBundle:SegmentoComunicacion sc WITH (sc.idSegmentoComunicacion = ic.idSegmentoComunicacion )
            JOIN RMComunicacionBundle:Comunicacion com WITH (com.idComunicacion = sc.idComunicacion)
            JOIN RMSegmentoBundle:Segmento seg WITH (sc.idSegmento = seg.idSegmento)
            JOIN RMPlantillaBundle:Plantilla p WITH (com.plantilla = p.idPlantilla AND p.estado> -1)
    		JOIN RMProductoBundle:NumPromociones np WITH (ic.idInstancia = np.idInstancia AND np.estado > -1)
            JOIN RMPlantillaBundle:GrupoSlots gs WITH (np.idGrupo = gs.idGrupo AND gs.estado > -1 AND gs.tipo = :tipo)
            WHERE ic.estado > -1
            AND fase.codigo = :codigo_cierre
            ORDER BY ic.idInstancia
            ";

        $query = $this->_em
            ->createQuery($dql)
            ->setParameter('tipo', GrupoSlots::CREATIVIDADES)
            ->setParameter('codigo_cierre', InstanciaComunicacion::FASE_NEGOCIACION);

        return $query->getResult();
    }

    /**
     * @param $idInstancia
     *
     * @return InstanciaComunicacion[]
     */
    public function findNumRegistrosNumPromocionesPorGrupoSlotsByIdInstancia($idInstancia)
    {
        $dql = "
            SELECT gs.idGrupo as idGrupoSlot , COUNT( DISTINCT np.idNumPro ) as numPro
            FROM RMComunicacionBundle:InstanciaComunicacion ic
            JOIN RMComunicacionBundle:SegmentoComunicacion sc WITH (sc.idSegmentoComunicacion = ic.idSegmentoComunicacion AND sc.estado > -1)
            JOIN  RMComunicacionBundle:Comunicacion c WITH (c.idComunicacion = sc.idComunicacion AND c.estado > -1)
            JOIN RMPlantillaBundle:Plantilla p WITH(c.plantilla = p.idPlantilla AND p.estado > -1)
            JOIN RMPlantillaBundle:GrupoSlots  gs WITH (gs.idPlantilla = p.idPlantilla AND gs.estado > -1)
            LEFT JOIN RMProductoBundle:NumPromociones np WITH(np.idGrupo = gs.idGrupo AND np.idInstancia = ic.idInstancia)
            WHERE ic.idInstancia = :idInstancia
            AND ic.estado > -1
            GROUP BY gs.idGrupo
            ORDER BY gs.idGrupo
        ";

        $query = $this->_em->createQuery($dql);
        $query->setParameter('idInstancia', $idInstancia);
        $res = $query->getResult();

        return $res;

    }

}


text:
class Deletion < ActiveRecord::Base
  belongs_to :user

  validates :user, :rubygem, :number, presence: true
  validates :version, presence: true
  validate :version_is_indexed

  before_validation :record_metadata
  after_create :remove_from_index, :set_yanked_info_checksum
  after_commit :remove_from_storage
  after_commit :expire_cache
  after_commit :update_search_index

  attr_accessor :version

  private

  def version_is_indexed
    errors.add(:base, "#{rubygem_name} #{version} has already been deleted") unless @version.indexed?
  end

  def rubygem_name
    @version.rubygem.name
  end

  def record_metadata
    self.rubygem = rubygem_name
    self.number = @version.number
    self.platform = @version.platform
  end

  def expire_cache
    GemCachePurger.call(rubygem)
  end

  def remove_from_index
    @version.update!(indexed: false, yanked_at: Time.now.utc)
    Delayed::Job.enqueue Indexer.new, priority: PRIORITIES[:push]
  end

  def remove_from_storage
    RubygemFs.instance.remove("gems/#{@version.full_name}.gem")
    RubygemFs.instance.remove("quick/Marshal.4.8/#{@version.full_name}.gemspec.rz")
    Fastly.delay.purge("gems/#{@version.full_name}.gem")
    Fastly.delay.purge("quick/Marshal.4.8/#{@version.full_name}.gemspec.rz")
  end

  def update_search_index
    @version.rubygem.delay.update_document
  end

  def set_yanked_info_checksum
    # expire info cache of last version
    Rails.cache.delete("info/#{rubygem}")
    gem_info = GemInfo.new(version.rubygem.name)
    checksum = Digest::MD5.hexdigest(CompactIndex.info(gem_info.compact_index_info))
    version.update_attribute :yanked_info_checksum, checksum
  end
end


text:
package com.google.template.soy.jssrc.internal;

import com.google.template.soy.base.internal.IdGenerator;
import com.google.template.soy.data.SanitizedContent.ContentKind;
import com.google.template.soy.html.IncrementalHtmlAttributeNode;
import com.google.template.soy.passes.BuildAllDependeesMapVisitor;
import com.google.template.soy.soytree.AbstractSoyNodeVisitor;
import com.google.template.soy.soytree.LetContentNode;
import com.google.template.soy.soytree.MsgFallbackGroupNode;
import com.google.template.soy.soytree.SoyFileSetNode;
import com.google.template.soy.soytree.SoyNode;
import com.google.template.soy.soytree.SoyNode.BlockNode;
import com.google.template.soy.soytree.SoyNode.LocalVarInlineNode;
import com.google.template.soy.soytree.SoyNode.ParentSoyNode;
import com.google.template.soy.soytree.SoyNode.RenderUnitNode;
import com.google.template.soy.soytree.SoyTreeUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Moves {@link MsgFallbackGroupNode}s to separate {let} and print nodes. We then move
 * the let node to the nearest block ancestor, so that the print node can be emitted as an
 * expression instead of a statement. After this pass, all MsgFallbackGroupNodes will only appear
 * inside {@link LetContentNodes}.
 *
 *
TODO(slaks): Generalize to extract all nodes that create statements but must appear in
 * expression context ({@link MsgHtmlTagNode}, {@link CallParamNode}, {@link LogNode}, & idom
 * attribute values) to variables. This will let us completely remove the many paths in jssrc that
 * conditionally emit temporary variables.
 *
 *
{@link #exec} must be called on a full parse tree.
 *
 */
public class ExtractMsgVariablesVisitor extends AbstractSoyNodeVisitor<Void> {

  /** The list of MsgFallbackGroupNodes found in the given node's subtree. */
  private List<MsgFallbackGroupNode> msgFbGrpNodes;

  private Map<SoyNode, List<SoyNode>> allDependeesMap;

  @Override
  public Void exec(SoyNode node) {
    msgFbGrpNodes = new ArrayList<>();
    visit(node);
    return null;
  }

  // -----------------------------------------------------------------------------------------------
  // Implementations for specific nodes.

  @Override
  protected void visitSoyFileSetNode(SoyFileSetNode node) {

    // We find all the MsgFallbackGroupNodes before replacing them because we don't want the
    // modifications to interfere with the traversal.

    // This pass simply finds all the MsgFallbackGroupNodes.
    visitChildren(node);

    // Help figure out where we can move each MsgFallbackGroupNode to.
    allDependeesMap = new BuildAllDependeesMapVisitor().exec(node);

    // Perform the replacements.
    IdGenerator nodeIdGen = node.getNearestAncestor(SoyFileSetNode.class).getNodeIdGenerator();
    for (MsgFallbackGroupNode msgFbGrpNode : msgFbGrpNodes) {
      wrapMsgFallbackGroupNodeHelper(msgFbGrpNode, nodeIdGen);
    }
  }

  @Override
  protected void visitMsgFallbackGroupNode(MsgFallbackGroupNode node) {
    msgFbGrpNodes.add(node);
    visitChildren(node);
  }

  // -----------------------------------------------------------------------------------------------
  // Fallback implementation.

  @Override
  protected void visitSoyNode(SoyNode node) {
    if (node instanceof ParentSoyNode<?>) {
      visitChildren((ParentSoyNode<?>) node);
    }
  }

  // -----------------------------------------------------------------------------------------------
  // Helpers.

  protected void wrapMsgFallbackGroupNodeHelper(
      MsgFallbackGroupNode msgFbGrpNode, IdGenerator nodeIdGen) {
    String varName = "msg_" + nodeIdGen.genId();

    // Find the actual content kind that this node prints in.
    RenderUnitNode container = msgFbGrpNode.getNearestAncestor(RenderUnitNode.class);
    ContentKind kind = container.getContentKind();
    IncrementalHtmlAttributeNode containingAttribute =
        msgFbGrpNode.getNearestAncestor(IncrementalHtmlAttributeNode.class);
    if (containingAttribute != null
        && SoyTreeUtils.isDescendantOf(containingAttribute, container)) {
      kind = ContentKind.TEXT;
    }

    // In traditional JS codegen, we will not infer a meaningful ContentKind (other than text).  But
    // that does not matter, since ContextAutoesc has already added appropriate escaping directives.
    // At this point, ContentKind only matters for idom, which uses it to figure out how to emit the
    // output (as itext, as parsed HTML or as attribute parameters).
    LetContentNode letNode =
        LetContentNode.forVariable(
            nodeIdGen.genId(), msgFbGrpNode.getSourceLocation(), varName, kind);

    msgFbGrpNode
        .getParent()
        .replaceChild(msgFbGrpNode, msgFbGrpNode.makePrintNode(nodeIdGen, letNode.getVar()));

    letNode.addChild(msgFbGrpNode);
    insertWrappingLetNode(letNode, allDependeesMap.get(msgFbGrpNode));
  }

  /** Inserts a wrapping {let} node in the nearest block ancestor. */
  private void insertWrappingLetNode(LetContentNode letNode, List<SoyNode> allDependees) {
    BlockNode newParent;
    int indexUnderNewParent;

    SoyNode nearestDependee = allDependees.get(0);
    if (nearestDependee instanceof LocalVarInlineNode) {
      newParent = (BlockNode) nearestDependee.getParent();
      indexUnderNewParent = newParent.getChildIndex((LocalVarInlineNode) nearestDependee) + 1;
    } else if (nearestDependee instanceof BlockNode) {
      newParent = (BlockNode) nearestDependee;
      indexUnderNewParent = 0;
    } else {
      throw new AssertionError();
    }
    // TODO(slaks): Move after earlier inserted nodes in case {msg}s reference each-other.
    newParent.addChild(indexUnderNewParent, letNode);
  }
}


text:
package remotecommand

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/util/httpstream"
	"k8s.io/kubernetes/pkg/util/httpstream/spdy"
)

type streamAndReply struct {
	httpstream.Stream
	replySent <-chan struct{}
}

func waitStreamReply(replySent <-chan struct{}, notify chan<- struct{}, stop <-chan struct{}) {
	select {
	case <-replySent:
		notify <- struct{}{}
	case <-stop:
	}
}

func fakeExecServer(t *testing.T, i int, stdinData, stdoutData, stderrData, errorData string, tty bool, messageCount int) http.HandlerFunc {
	// error + stdin + stdout
	expectedStreams := 3
	if !tty {
		// stderr
		expectedStreams++
	}

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		protocol, err := httpstream.Handshake(req, w, []string{StreamProtocolV2Name}, StreamProtocolV1Name)
		if err != nil {
			t.Fatal(err)
		}
		if protocol != StreamProtocolV2Name {
			t.Fatalf("unexpected protocol: %s", protocol)
		}
		streamCh := make(chan streamAndReply)

		upgrader := spdy.NewResponseUpgrader()
		conn := upgrader.UpgradeResponse(w, req, func(stream httpstream.Stream, replySent <-chan struct{}) error {
			streamCh <- streamAndReply{Stream: stream, replySent: replySent}
			return nil
		})
		// from this point on, we can no longer call methods on w
		if conn == nil {
			// The upgrader is responsible for notifying the client of any errors that
			// occurred during upgrading. All we can do is return here at this point
			// if we weren't successful in upgrading.
			return
		}
		defer conn.Close()

		var errorStream, stdinStream, stdoutStream, stderrStream httpstream.Stream
		receivedStreams := 0
		replyChan := make(chan struct{})
		stop := make(chan struct{})
		defer close(stop)
	WaitForStreams:
		for {
			select {
			case stream := <-streamCh:
				streamType := stream.Headers().Get(api.StreamType)
				switch streamType {
				case api.StreamTypeError:
					errorStream = stream
					go waitStreamReply(stream.replySent, replyChan, stop)
				case api.StreamTypeStdin:
					stdinStream = stream
					go waitStreamReply(stream.replySent, replyChan, stop)
				case api.StreamTypeStdout:
					stdoutStream = stream
					go waitStreamReply(stream.replySent, replyChan, stop)
				case api.StreamTypeStderr:
					stderrStream = stream
					go waitStreamReply(stream.replySent, replyChan, stop)
				default:
					t.Errorf("%d: unexpected stream type: %q", i, streamType)
				}

				if receivedStreams == expectedStreams {
					break WaitForStreams
				}
			case <-replyChan:
				receivedStreams++
				if receivedStreams == expectedStreams {
					break WaitForStreams
				}
			}
		}

		if len(errorData) > 0 {
			n, err := fmt.Fprint(errorStream, errorData)
			if err != nil {
				t.Errorf("%d: error writing to errorStream: %v", i, err)
			}
			if e, a := len(errorData), n; e != a {
				t.Errorf("%d: expected to write %d bytes to errorStream, but only wrote %d", i, e, a)
			}
			errorStream.Close()
		}

		if len(stdoutData) > 0 {
			for j := 0; j < messageCount; j++ {
				n, err := fmt.Fprint(stdoutStream, stdoutData)
				if err != nil {
					t.Errorf("%d: error writing to stdoutStream: %v", i, err)
				}
				if e, a := len(stdoutData), n; e != a {
					t.Errorf("%d: expected to write %d bytes to stdoutStream, but only wrote %d", i, e, a)
				}
			}
			stdoutStream.Close()
		}
		if len(stderrData) > 0 {
			for j := 0; j < messageCount; j++ {
				n, err := fmt.Fprint(stderrStream, stderrData)
				if err != nil {
					t.Errorf("%d: error writing to stderrStream: %v", i, err)
				}
				if e, a := len(stderrData), n; e != a {
					t.Errorf("%d: expected to write %d bytes to stderrStream, but only wrote %d", i, e, a)
				}
			}
			stderrStream.Close()
		}
		if len(stdinData) > 0 {
			data := make([]byte, len(stdinData))
			for j := 0; j < messageCount; j++ {
				n, err := io.ReadFull(stdinStream, data)
				if err != nil {
					t.Errorf("%d: error reading stdin stream: %v", i, err)
				}
				if e, a := len(stdinData), n; e != a {
					t.Errorf("%d: expected to read %d bytes from stdinStream, but only read %d", i, e, a)
				}
				if e, a := stdinData, string(data); e != a {
					t.Errorf("%d: stdin: expected %q, got %q", i, e, a)
				}
			}
			stdinStream.Close()
		}
	})
}

func TestRequestExecuteRemoteCommand(t *testing.T) {
	testCases := []struct {
		Stdin        string
		Stdout       string
		Stderr       string
		Error        string
		Tty          bool
		MessageCount int
	}{
		{
			Error: "bail",
		},
		{
			Stdin:  "a",
			Stdout: "b",
			Stderr: "c",
			// TODO bump this to a larger number such as 100 once
			// https://github.com/docker/spdystream/issues/55 is fixed and the Godep
			// is bumped. Sending multiple messages over stdin/stdout/stderr results
			// in more frames being spread across multiple spdystream frame workers.
			// This makes it more likely that the spdystream bug will be encountered,
			// where streams are closed as soon as a goaway frame is received, and
			// any pending frames that haven't been processed yet may not be
			// delivered (it's a race).
			MessageCount: 1,
		},
		{
			Stdin:  "a",
			Stdout: "b",
			Tty:    true,
		},
	}

	for i, testCase := range testCases {
		localOut := &bytes.Buffer{}
		localErr := &bytes.Buffer{}

		server := httptest.NewServer(fakeExecServer(t, i, testCase.Stdin, testCase.Stdout, testCase.Stderr, testCase.Error, testCase.Tty, testCase.MessageCount))

		url, _ := url.ParseRequestURI(server.URL)
		c := client.NewRESTClient(url, "", client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Group: "x"}}, -1, -1, nil)
		req := c.Post().Resource("testing")
		req.SetHeader(httpstream.HeaderProtocolVersion, StreamProtocolV2Name)
		req.Param("command", "ls")
		req.Param("command", "/")
		conf := &client.Config{
			Host: server.URL,
		}
		e, err := NewExecutor(conf, "POST", req.URL())
		if err != nil {
			t.Errorf("%d: unexpected error: %v", i, err)
			continue
		}
		err = e.Stream(strings.NewReader(strings.Repeat(testCase.Stdin, testCase.MessageCount)), localOut, localErr, testCase.Tty)
		hasErr := err != nil

		if len(testCase.Error) > 0 {
			if !hasErr {
				t.Errorf("%d: expected an error", i)
			} else {
				if e, a := testCase.Error, err.Error(); !strings.Contains(a, e) {
					t.Errorf("%d: expected error stream read '%v', got '%v'", i, e, a)
				}
			}

			// TODO: Uncomment when fix #19254
			// server.Close()
			continue
		}

		if hasErr {
			t.Errorf("%d: unexpected error: %v", i, err)
			// TODO: Uncomment when fix #19254
			// server.Close()
			continue
		}

		if len(testCase.Stdout) > 0 {
			if e, a := strings.Repeat(testCase.Stdout, testCase.MessageCount), localOut; e != a.String() {
				t.Errorf("%d: expected stdout data '%s', got '%s'", i, e, a)
			}
		}

		if testCase.Stderr != "" {
			if e, a := strings.Repeat(testCase.Stderr, testCase.MessageCount), localErr; e != a.String() {
				t.Errorf("%d: expected stderr data '%s', got '%s'", i, e, a)
			}
		}

		// TODO: Uncomment when fix #19254
		// server.Close()
	}
}

// TODO: this test is largely cut and paste, refactor to share code
func TestRequestAttachRemoteCommand(t *testing.T) {
	testCases := []struct {
		Stdin  string
		Stdout string
		Stderr string
		Error  string
		Tty    bool
	}{
		{
			Error: "bail",
		},
		{
			Stdin:  "a",
			Stdout: "b",
			Stderr: "c",
		},
		{
			Stdin:  "a",
			Stdout: "b",
			Tty:    true,
		},
	}

	for i, testCase := range testCases {
		localOut := &bytes.Buffer{}
		localErr := &bytes.Buffer{}

		server := httptest.NewServer(fakeExecServer(t, i, testCase.Stdin, testCase.Stdout, testCase.Stderr, testCase.Error, testCase.Tty, 1))

		url, _ := url.ParseRequestURI(server.URL)
		c := client.NewRESTClient(url, "", client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Group: "x"}}, -1, -1, nil)
		req := c.Post().Resource("testing")

		conf := &client.Config{
			Host: server.URL,
		}
		e, err := NewExecutor(conf, "POST", req.URL())
		if err != nil {
			t.Errorf("%d: unexpected error: %v", i, err)
			continue
		}
		err = e.Stream(strings.NewReader(testCase.Stdin), localOut, localErr, testCase.Tty)
		hasErr := err != nil

		if len(testCase.Error) > 0 {
			if !hasErr {
				t.Errorf("%d: expected an error", i)
			} else {
				if e, a := testCase.Error, err.Error(); !strings.Contains(a, e) {
					t.Errorf("%d: expected error stream read '%v', got '%v'", i, e, a)
				}
			}

			// TODO: Uncomment when fix #19254
			// server.Close()
			continue
		}

		if hasErr {
			t.Errorf("%d: unexpected error: %v", i, err)
			// TODO: Uncomment when fix #19254
			// server.Close()
			continue
		}

		if len(testCase.Stdout) > 0 {
			if e, a := testCase.Stdout, localOut; e != a.String() {
				t.Errorf("%d: expected stdout data '%s', got '%s'", i, e, a)
			}
		}

		if testCase.Stderr != "" {
			if e, a := testCase.Stderr, localErr; e != a.String() {
				t.Errorf("%d: expected stderr data '%s', got '%s'", i, e, a)
			}
		}

		// TODO: Uncomment when fix #19254
		// server.Close()
	}
}

type fakeUpgrader struct {
	req           *http.Request
	resp          *http.Response
	conn          httpstream.Connection
	err, connErr  error
	checkResponse bool

	t *testing.T
}

func (u *fakeUpgrader) RoundTrip(req *http.Request) (*http.Response, error) {
	u.req = req
	return u.resp, u.err
}

func (u *fakeUpgrader) NewConnection(resp *http.Response) (httpstream.Connection, error) {
	if u.checkResponse && u.resp != resp {
		u.t.Errorf("response objects passed did not match: %#v", resp)
	}
	return u.conn, u.connErr
}

type fakeConnection struct {
	httpstream.Connection
}

// Dial is the common functionality between any stream based upgrader, regardless of protocol.
// This method ensures that someone can use a generic stream executor without being dependent
// on the core Kube client config behavior.
func TestDial(t *testing.T) {
	upgrader := &fakeUpgrader{
		t:             t,
		checkResponse: true,
		conn:          &fakeConnection{},
		resp: &http.Response{
			StatusCode: http.StatusSwitchingProtocols,
			Body:       ioutil.NopCloser(&bytes.Buffer{}),
		},
	}
	var called bool
	testFn := func(rt http.RoundTripper) http.RoundTripper {
		if rt != upgrader {
			t.Fatalf("unexpected round tripper: %#v", rt)
		}
		called = true
		return rt
	}
	exec, err := NewStreamExecutor(upgrader, testFn, "POST", &url.URL{Host: "something.com", Scheme: "https"})
	if err != nil {
		t.Fatal(err)
	}
	conn, protocol, err := exec.Dial("protocol1")
	if err != nil {
		t.Fatal(err)
	}
	if conn != upgrader.conn {
		t.Errorf("unexpected connection: %#v", conn)
	}
	if !called {
		t.Errorf("wrapper not called")
	}
	_ = protocol
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Coverage Report Classes</title>
<link title="Style" type="text/css" rel="stylesheet" href="css/main.css"/>

org.jsimpledb.kv.raft.msg

Classes

AbstractPingMessage (0%)

AppendRequest (76%)

AppendResponse (81%)

CommitRequest (75%)

CommitResponse (82%)

GrantVote (71%)

InstallSnapshot (85%)

Message (69%)

MessageSwitch (N/A)

PingRequest (0%)

PingResponse (0%)

RequestVote (83%)

package-info (N/A)


text:
import Ember from 'ember';

const {
  Component
} = Ember;

export default Component.extend({
  classNames: [ 'newCard' ],

  click: function() {
    this.sendAction('create');
  }
});


text:
require 'spec_helper'

describe ErrorPresenter do
  it "renders a blank field error" do
    invalid_record = User.new
    invalid_record.valid?

    presenter = ErrorPresenter.new(invalid_record.errors)

    rendered = Hashie::Mash.new(presenter.as_json)

    rendered.username.BLANK.should == {}
  end

  it "renders additional data associated with an error" do
    invalid_record = User.new
    invalid_record.password = "shrt"
    invalid_record.valid?

    presenter = ErrorPresenter.new(invalid_record.errors)

    rendered = Hashie::Mash.new(presenter.as_json)

    rendered.password.TOO_SHORT['count'].should == 6
  end
end


text:
/**
 * @file
 *
 * @brief Measure context switch time between cooperative threads
 *
 * This file contains thread (coop) context switch time measurement.
 * The thread starts two cooperative thread. One thread waits on a semaphore. The other,
 * after starting, releases a semaphore which enable the first thread to run.
 * Each thread increases a common global counter and context switch back and
 * forth by yielding the cpu. When counter reaches the maximal value, threads
 * stop and the average time of context switch is displayed.
 */

#include "timestamp.h"
#include "utils.h"

#include <arch/cpu.h>

/* number of context switches */
#define NCTXSWITCH   10000
#ifndef STACKSIZE
#define STACKSIZE    (512 + CONFIG_TEST_EXTRA_STACKSIZE)
#endif

/* stack used by the threads */
static K_THREAD_STACK_DEFINE(thread_one_stack, STACKSIZE);
static K_THREAD_STACK_DEFINE(thread_two_stack, STACKSIZE);
static struct k_thread thread_one_data;
static struct k_thread thread_two_data;

static u32_t timestamp;

/* context switches counter */
static volatile u32_t ctx_switch_counter;

/* context switch balancer. Incremented by one thread, decremented by another*/
static volatile int ctx_switch_balancer;

K_SEM_DEFINE(sync_sema, 0, 1);

/**
 *
 * thread_onne
 *
 * Fiber makes all the test preparations: registers the interrupt handler,
 * gets the first timestamp and invokes the software interrupt.
 *
 * @return N/A
 */
static void thread_one(void)
{
	k_sem_take(&sync_sema, K_FOREVER);
	timestamp = TIME_STAMP_DELTA_GET(0);
	while (ctx_switch_counter < NCTXSWITCH) {
		k_yield();
		ctx_switch_counter++;
		ctx_switch_balancer--;
	}
	timestamp = TIME_STAMP_DELTA_GET(timestamp);
}

/**
 *
 * @brief Check the time when it gets executed after the semaphore
 *
 * Fiber starts, waits on semaphore. When the interrupt handler releases
 * the semaphore, thread  measures the time.
 *
 * @return 0 on success
 */
static void thread_two(void)
{
	k_sem_give(&sync_sema);
	while (ctx_switch_counter < NCTXSWITCH) {
		k_yield();
		ctx_switch_counter++;
		ctx_switch_balancer++;
	}
}

/**
 *
 * @brief The test main function
 *
 * @return 0 on success
 */
int coop_ctx_switch(void)
{
	PRINT_FORMAT(" 6 - Measure average context switch time between threads (coop)");
	ctx_switch_counter = 0U;
	ctx_switch_balancer = 0;

	bench_test_start();
	k_thread_create(&thread_one_data, thread_one_stack, STACKSIZE,
			(k_thread_entry_t) thread_one, NULL, NULL, NULL,
			6, 0, K_NO_WAIT);
	k_thread_create(&thread_two_data, thread_two_stack, STACKSIZE,
			(k_thread_entry_t) thread_two, NULL, NULL, NULL,
			6, 0, K_NO_WAIT);

	if (ctx_switch_balancer > 3 || ctx_switch_balancer < -3) {
		PRINT_FORMAT(" Balance is %d. FAILED", ctx_switch_balancer);
	} else if (bench_test_end() != 0) {
		error_count++;
		PRINT_OVERFLOW_ERROR();
	} else {
		PRINT_FORMAT(" Average context switch time is %u tcs = %u"
			     " nsec",
			     timestamp / ctx_switch_counter,
			     SYS_CLOCK_HW_CYCLES_TO_NS_AVG(timestamp,
							   ctx_switch_counter));
	}

	return 0;
}


text:
'''
Atomix project, oros.py, (TODO: summary)
Copyright (c) 2015 Stanford University
Released under the Apache License v2.0. See the LICENSE file for details.
Author(s): Manu Bansal
'''
from java.lang import *
from java.util import *
from com.ti.debug.engine.scripting import *
from com.ti.ccstudio.scripting.environment import *
#import argparse
import optparse

def pause(s):
  print s, 'Print any key to continue...'
  raw_input()

def create_script():
  # Create our scripting environment object - which is the main entry point into any script and
  # the factory for creating other Scriptable Servers and Sessions
  script = ScriptingEnvironment.instance()

  # Create a log file in the current directory to log script execution
  script.traceBegin("dss_py.xml", "DefaultStylesheet.xsl")

  # Set our TimeOut
  #script.setScriptTimeout(15000)

  # Log everything
  script.traceSetConsoleLevel(TraceLevel.ALL)
  script.traceSetFileLevel(TraceLevel.ALL)

  return script

#def startup(script):
#  # Get the Debug Server and start a Debug Session
#  debugServer = script.getServer("DebugServer.1")
#  debugServer.setConfig("tisim_c64xple.ccxml");
#
#  debugSession = debugServer.openSession()
#
#  # Load program
#  debugSession.memory.loadProgram("modem.out")
#
#  # Set a breakpoint at "main"
#  main = debugSession.symbol.getAddress("main")
#  bp1 = debugSession.breakpoint.add(main)
#
#  # Set another breakpoint
#  address = debugSession.symbol.getAddress("ReadNextData")
#  bp2 = debugSession.breakpoint.add(address)
#
#  # Restart our Target
#  debugSession.target.restart()
#
#  # Run if already not automatically halted at main.  Should halt at first BP
#  if debugSession.expression.evaluate("PC") != main:
#	  debugSession.target.run()
#
#  # Using an expression - get the current value of the PC
#  nPC = debugSession.expression.evaluate("PC")
#
#  # Verify we halted at the correct address.  Use hex() to convert the
#  # result to a hex string when logging messages
#  if nPC == main:
#	  script.traceWrite("SUCCESS: Halted at correct location")
#  else:
#	  script.traceWrite("FAIL: Expected halt at " + hex(address) + ", actually halted at " + hex(nPC))
#	  script.traceSetConsoleLevel(TraceLevel.INFO)
#	  script.traceWrite("TEST FAILED!")
#	  script.traceEnd()
#	  System.exit(1);
#
#  # Run again.  Should halt at our breakpoint
#  debugSession.target.run()
#
#  #  Using an expression - get the current value of the PC
#  nPC = debugSession.expression.evaluate("PC")
#
#  # Verify we halted at the correct address.
#  if nPC == address:
#	  script.traceWrite("SUCCESS: Halted at correct location")
#  else:
#	  script.traceWrite("FAIL: Expected halt at " + hex(address) + ", actually halted at " + hex(nPC))
#	  script.traceSetConsoleLevel(TraceLevel.INFO)
#	  script.traceWrite("TEST FAILED!")
#	  script.traceEnd()
#	  System.exit(1);
#
#  # All done
#  debugSession.terminate()
#  debugServer.stop()

def startup_debugServer(script, options):
  # Start up CCS
  ccsServer = None
  ccsSession = None
  if ((not options.cleanup) and options.gui):
    #pause("Press enter to launch CCS...")
    ccsServer = script.getServer("CCSServer.1")
    ccsSession = ccsServer.openSession(".*")

  # Start up the debugger with the C64 simulator; it will start up the session in CCS
  debugServer = script.getServer("DebugServer.1")
  #debugServer.setConfig("../C64/tisim_c64xple.ccxml")
  #debugServer.setConfig("../targetconfs/evmbe6670_28K.ccxml")
  debugServer.setConfig(options.tcf); #"../targetconfs/evmbe6670_28K.ccxml")

  return (ccsServer, ccsSession, debugServer)

def startup_debugSessions(debugServer, SESSION_IDS):
  #debugSession = debugServer.openSession(".*")

  #pause("Press enter to open debug sessions...")

  pause("Press enter to open debug session 1")
  debugSession0 = debugServer.openSession("Blackhawk XDS560v2-USB System Trace Emulator_0/C66xx_00")

  ##pause("Press enter to open debug session 2")
  ##debugSession1 = debugServer.openSession("Blackhawk XDS560v2-USB System Trace Emulator_0/C66xx_1")

  ##pause("Press enter to open debug session 3")
  ##debugSession2 = debugServer.openSession("Blackhawk XDS560v2-USB System Trace Emulator_0/C66xx_2")

  ##pause("Press enter to open debug session 4")
  ##debugSession3 = debugServer.openSession("Blackhawk XDS560v2-USB System Trace Emulator_0/C66xx_3")

  debugSessions = []
  ##for i, session_id in enumerate(SESSION_IDS):
  ##  pause("Press enter to open debug session " + str(i))
  ##  print "Opening", session_id
  ##  debugSession = debugServer.openSession(session_id)
  ##  debugSessions.append(debugSession)

  return debugSessions

def connectAndRun():
  pause("Press enter to connect to target...")

  debugSession0.target.connect()
  debugSession1.target.connect()
  debugSession2.target.connect()
  debugSession3.target.connect()

  # Load a program
  #var isaName = "../C64"
  ##script.setScriptTimeout(15000);
  #debugSession.memory.loadProgram(isaName + "/modem/Debug/modem.out")
  #debugSession0.memory.loadProgram("../build/app/wifirx54mc/app_wifirx54mc.out")
  #debugSession1.memory.loadProgram("../build/app/wifirx54mc/app_wifirx54mc.out")
  #debugSession2.memory.loadProgram("../build/app/wifirx54mc/app_wifirx54mc.out")
  #debugSession3.memory.loadProgram("../build/app/wifirx54mc/app_wifirx54mc.out")
  print("++++++ loading " + options.prog)
  script.traceWrite("++++++ loading " + options.prog)
  pause("Press enter to load program...")
  debugSession0.memory.loadProgram(options.prog);
  debugSession1.memory.loadProgram(options.prog);
  debugSession2.memory.loadProgram(options.prog);
  debugSession3.memory.loadProgram(options.prog);

  pause("Press enter to run program...")
  debugSession0.target.runAsynch()
  debugSession1.target.runAsynch()
  debugSession2.target.runAsynch()
  debugSession3.target.runAsynch()

def cleanup():
  cleanup_debug()
  cleanup_ccs()
  cleanup_script(script)

def cleanup_debug(debugServer):
  pause("Press enter to terminate sessions...")
  # terminate the debugger
  ##debugSession3.terminate()
  ##debugSession2.terminate()
  ##debugSession1.terminate()
  ##debugSession0.terminate()

  debugServer.stop()

def cleanup_ccs(ccsServer, ccsSession, options):
  # Terminate CCS
  if ((not options.cleanup) and options.gui):
    pause("Press enter to terminate CCS...")
    ccsSession.terminate()
    ccsServer.stop()

def cleanup_script(script):
  # stop the Logging
  script.traceSetConsoleLevel(TraceLevel.INFO)
  script.traceWrite("TEST SUCCEEDED!")
  script.traceEnd()

def main():
    # my code here
    #parser = argparse.ArgumentParser(description='Process some integers.')
    #parser.add_argument("-c", "--tcf",
    #	help="target configuration file", action="store")
    #parser.add_argument("-p", "--prog",
    #	help="program to load", action="store")
    #parser.add_argument("-g", "--gui",
    #	help="attach and launch CCS GUI", action="store_true")
    #parser.add_argument("-C", "--cleanup",
    #	help="cleanup debug sessions", action="store_true")

    #options = parser.parse_args()
    #print options

    parser = optparse.OptionParser()
    parser.add_option("-c", "--tcf",
    	help="target configuration file", action="store")
    parser.add_option("-p", "--prog",
    	help="program to load", action="store")
    parser.add_option("-g", "--gui", default=False,
    	help="attach and launch CCS GUI", action="store_true")
    parser.add_option("-C", "--cleanup", default=False,
    	help="cleanup debug sessions", action="store_true")

    (options, args) = parser.parse_args()
    print options
    print args

    SESSION_PREFIX = "Blackhawk XDS560v2-USB System Trace Emulator_0/C66xx_0"
    #SESSION_PREFIX = "Blackhawk XDS560v2-USB .*"
    SESSION_IDS = [SESSION_PREFIX + str(i) for i in range(4)]
    print SESSION_IDS

    script = create_script()
    (ccsServer, ccsSession, debugServer) = startup_debugServer(script, options)

    #cleanup_debug(debugServer)
    #cleanup_script(script)
    #return

    debugSessions = startup_debugSessions(debugServer, SESSION_IDS)

    cleanup_debug(debugServer)
    #cleanup_ccs(ccsServer, ccsSession, options)
    cleanup_script(script)

    return

    if (options.cleanup):
      pass
    else:
      connectAndRun();

    cleanup()

if __name__ == "__main__":
    main()


text:
package org.mifos.config;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.mifos.accounts.loan.persistance.LegacyLoanDao;
import org.mifos.application.servicefacade.ApplicationContextProvider;
import org.mifos.config.business.MifosConfigurationManager;
import org.mifos.config.exceptions.ConfigurationException;
import org.mifos.config.persistence.ConfigurationPersistence;
import org.mifos.config.util.helpers.ConfigConstants;
import org.mifos.core.MifosRuntimeException;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.util.helpers.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientRules {
    public static final String ClientRulesCenterHierarchyExists = "ClientRules.CenterHierarchyExists";
    public static final String ClientRulesClientCanExistOutsideGroup = "ClientRules.ClientCanExistOutsideGroup";
    public static final String ClientRulesGroupCanApplyLoans = "ClientRules.GroupCanApplyLoans";
    public static final String ClientRulesNameSequence = "ClientRules.NameSequence";
    public static final String ClientCanExistOutsideGroupKey = "ClientCanExistOutsideGroup";
    public static final String GroupCanApplyLoansKey = "GroupCanApplyLoans";
    public static final String AgeCheckWarningInsteadOfErrorKey = "ClientRules.AgeCheckWarningInsteadOfError";
    public static final String MaximumAgeForNewClients = "ClientRules.MaximumAgeForNewClients";
    public static final String MinimumAgeForNewClients = "ClientRules.MinimumAgeForNewClients";
    private static Boolean centerHierarchyExists;
    private static Boolean groupCanApplyLoans;
    private static Boolean clientCanExistOutsideGroup;
    private static Boolean ageCheckWarningInsteadOfError;
    private static int minimumAgeForNewClient;
    private static int maximumAgeForNewClient;
    private static boolean ageCheckEnabled;
    private static int maximumNumberOfFamilyMembers;
    public static int getMaximumNumberOfFamilyMembers() {
        return maximumNumberOfFamilyMembers;
    }

    public static void setMaximumNumberOfFamilyMembers(int maximumNumberOfFamilyMembers) {
        ClientRules.maximumNumberOfFamilyMembers = maximumNumberOfFamilyMembers;
    }

    private static boolean familyDetailsRequired=false;

    public static boolean isFamilyDetailsRequired() {
        return familyDetailsRequired;
    }

    public static void setFamilyDetailsRequired(boolean familyDetailsRequired) {
        ClientRules.familyDetailsRequired = familyDetailsRequired;
    }

    /**
     * A name sequence is the order in which client names are displayed.
     * Example: first name, then middle name, then last name.
     *

     * This member variable stores which of the {@link #allowedNameParts} are to
     * be used when displaying a client's name.
     */
    private static String[] nameSequence;

    /**
     * Stores strings that are allowed to be part of {@link #nameSequence}.
     */
    private static Set<String> allowedNameParts;

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

    private static ConfigurationPersistence configPersistence;

    public static ConfigurationPersistence getConfigPersistence() {
        if (configPersistence == null) {
            configPersistence = new ConfigurationPersistence();
        }

        return configPersistence;
    }

    public static void setConfigPersistence(ConfigurationPersistence configPersistence) {
        ClientRules.configPersistence = configPersistence;
    }

    static {
        allowedNameParts = new HashSet<String>();
        allowedNameParts.add(ConfigConstants.FIRST_NAME);
        allowedNameParts.add(ConfigConstants.MIDDLE_NAME);
        allowedNameParts.add(ConfigConstants.LAST_NAME);
        allowedNameParts.add(ConfigConstants.SECOND_LAST_NAME);
    }

    /**
     * Performs startup sanity checks. While not a requirement, it is considered
     * good practice to call this method prior to any other methods in this
     * class.
     */
    public static void init() throws ConfigurationException {
        if (!isValidNameSequence()) {
            throw new ConfigurationException("error in configured value for " + ClientRulesNameSequence);
        }
        // If the configuration is invalid with respect to Client Rules, this
        // will force discovery of the problem upon initialization
        refresh();
    }

    // "protected" visibility so it can be unit tested; it would otherwise
    // be private
    protected static void refresh() throws ConfigurationException {
        centerHierarchyExists = null;
        groupCanApplyLoans = null;
        ageCheckWarningInsteadOfError = null;
        clientCanExistOutsideGroup = null;
        nameSequence = null;
        centerHierarchyExists = getCenterHierarchyExists();
        groupCanApplyLoans = getGroupCanApplyLoans();
        clientCanExistOutsideGroup = getClientCanExistOutsideGroup();
        ageCheckWarningInsteadOfError = isAgeCheckWarningInsteadOfErrorEnabled();
        nameSequence = getNameSequence();
        initializeAges();
        intializeFamilyConfig();
    }

    public static void setAgeCheckWarningInsteadOfError(boolean exists) {
    	ageCheckWarningInsteadOfError = exists;
    }

    private static Boolean getAgeCheckWarningInsteadOfErrorFromConfig() {
        MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
		return configMgr.getBoolean(AgeCheckWarningInsteadOfErrorKey);
    }

    public static boolean isAgeCheckWarningInsteadOfErrorEnabled() {
        if (ageCheckWarningInsteadOfError == null) {
        	ageCheckWarningInsteadOfError = getAgeCheckWarningInsteadOfErrorFromConfig();
        }
        return ageCheckWarningInsteadOfError;
    }

    public static Boolean getCenterHierarchyExists() {
        if (centerHierarchyExists == null) {
            centerHierarchyExists = getCenterHierarchyExistsFromConfig();
        }
        return centerHierarchyExists;
    }

    public static void setCenterHierarchyExists(boolean exists) {
        centerHierarchyExists = exists;
    }

    public static void setGroupCanApplyLoans(boolean flag) {
        groupCanApplyLoans = flag;
    }

    public static void setClientCanExistOutsideGroup(boolean flag){
        clientCanExistOutsideGroup = flag;
    }

    /** Can group loans exist? */
    public static Boolean getGroupCanApplyLoans() {
        if (groupCanApplyLoans == null) {
            groupCanApplyLoans = getGroupCanApplyLoansFromConfig();
        }
        return groupCanApplyLoans;
    }

    public static boolean getClientCanExistOutsideGroup() {
        if (clientCanExistOutsideGroup == null) {
            clientCanExistOutsideGroup = getClientCanExistOutsideGroupFromConfig();
        }
        return clientCanExistOutsideGroup;
    }

    private static Boolean getCenterHierarchyExistsFromConfig() {
        MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
        return configMgr.getBoolean(ClientRulesCenterHierarchyExists);
    }

    private static String getBadOverrideMsg(String key, String detailMsg) {
        return "The value for key " + key + " in the file " + MifosConfigurationManager.CUSTOM_CONFIG_PROPS_FILENAME
                + " must to be set to 1 because it was set to 1"
                + " in the database, hence can't be set to to 0 in the custom"
                + " configuration file as this might invalidate existing data. " + detailMsg + " Also, "
                + MifosConfigurationManager.DEFAULT_CONFIG_PROPS_FILENAME + " must never be changed--make sure this"
                + " file is untouched.";
    }

    private static boolean getGroupCanApplyLoansFromConfig() {
        boolean cfgValue;
        try {
            int dbValue = getConfigPersistence().getConfigurationValueInteger(GroupCanApplyLoansKey);
            MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
            cfgValue = configMgr.getBoolean(ClientRulesGroupCanApplyLoans);

            if (dbValue == Constants.NO && cfgValue == true) {
                getConfigPersistence().updateConfigurationKeyValueInteger(GroupCanApplyLoansKey, Constants.YES);
            } else if (dbValue == Constants.YES && cfgValue == false) {

                if (ApplicationContextProvider.getBean(LegacyLoanDao.class).countOfGroupLoanAccounts() > 0) {

                    // Trying to override db value of "true/yes" with "false/no"
                    // in the config file violates business rules.
                    throw new MifosRuntimeException(getBadOverrideMsg(GroupCanApplyLoansKey, "Group loans may already exist."));
                }

                makeDatabaseConfigMatchFilebasedConfig();
            }
        } catch (PersistenceException ex) {
            throw new MifosRuntimeException(ex);
        }

        return cfgValue;
    }

    private static void makeDatabaseConfigMatchFilebasedConfig() throws PersistenceException {
        getConfigPersistence().updateConfigurationKeyValueInteger(GroupCanApplyLoansKey, Constants.NO);
    }

    private static boolean getClientCanExistOutsideGroupFromConfig() {
        boolean cfgValue;
        try {
            int dbValue = getConfigPersistence().getConfigurationValueInteger(ClientCanExistOutsideGroupKey);
            MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
            cfgValue = configMgr.getBoolean(ClientRulesClientCanExistOutsideGroup);

            if (dbValue == Constants.NO && cfgValue == true) {
                getConfigPersistence().updateConfigurationKeyValueInteger(ClientCanExistOutsideGroupKey, Constants.YES);
            } else if (dbValue == Constants.YES && cfgValue == false) {
                // Trying to override db value of "true/yes" with "false/no"
                // in the config file violates business rules.
                throw new MifosRuntimeException(getBadOverrideMsg(ClientCanExistOutsideGroupKey, "Clients outside of groups may already exist."));
            }
        } catch (PersistenceException ex) {
            throw new MifosRuntimeException(ex);
        }

        return cfgValue;
    }

    public static void setNameSequence(String[] nameSequence) {
        ClientRules.nameSequence = nameSequence;
    }

    /*
     * Fetches and populates ClientRules#nameSequence.
     */
    public static String[] getNameSequence() {
        if (nameSequence == null) {
            MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
            nameSequence = configMgr.getStringArray(ClientRulesNameSequence);
        }
        return nameSequence;
    }

    /**
     * Check that the given nameSequence is valid.
     *

     * A name sequence is the order in which client names are displayed.
     * Example: first name, then middle name, then last name.
     *

     * Throws no exceptions, but reasons for invalid sequences are logged as
     * errors.
     */
    public static boolean isValidNameSequence(String[] nameSequence) {
        // a null or empty part would cause errors when a name format when, for
        // instance, ClientNameDetailDto.getDisplayName() is called
        if (null == nameSequence) {
            logger.error("nameSequence must not be null");
            return false;
        }
        if (nameSequence.length < 1) {
            logger.error("nameSequence must contain elements");
            return false;
        }

        // disallowed parts would cause errors when a name format when, for
        // instance, ClientNameDetailDto.getDisplayName() is called
        for (String s : nameSequence) {
            if (!allowedNameParts.contains(s)) {
                String allowed = StringUtils.join(allowedNameParts, ",");
                logger.error(s + " is not a known name part. Allowed values are: " + allowed
                        + ". Any ordering is allowed.");
                return false;
            }
        }

        return true;
    }

    /**
     * Delegates to {@link #isValidNameSequence(String[])} to check that the
     * configured nameSequence is valid. Automatically fetches and populates
     * nameSequence if necessary.
     *

     * A name sequence is the order in which client names are displayed.
     * Example: first name, then middle name, then last name.
     */
    public static boolean isValidNameSequence() {
        return isValidNameSequence(getNameSequence());
    }

    /*
     * will initialize the client minimum age and maximum age constants, Also if
     * both of them are set to zero it will initialize the client constants.age
     * check to zero
     */
    public static void initializeAges() throws ConfigurationException {
        setMinimumAgeForNewClient(getMinimumAge());
        setMaximumAgeForNewClient(getMaximumAge());
        if (getMaximumAge() < getMinimumAge()) {
            throw new ConfigurationException("The minimum age for clients cannot be greater than the maximum age in "
                    + MifosConfigurationManager.DEFAULT_CONFIG_PROPS_FILENAME);
        }

        updateAgeCheckEnabled();
    }

    private static void updateAgeCheckEnabled() {
        if ((getMaximumAgeForNewClient() == 0) && (getMinimumAgeForNewClient() == 0)) {
            setAgeCheckEnabled(false);
        } else {
            setAgeCheckEnabled(true);
        }
    }

    public static int getMinimumAgeForNewClient() {
        return minimumAgeForNewClient;
    }

    public static void setMinimumAgeForNewClient(int minimumAgeForNewClient) {
        ClientRules.minimumAgeForNewClient = minimumAgeForNewClient;
        updateAgeCheckEnabled();
    }

    public static int getMaximumAgeForNewClient() {
        return maximumAgeForNewClient;
    }

    public static void setMaximumAgeForNewClient(int maximumAgeForNewClient) {
        ClientRules.maximumAgeForNewClient = maximumAgeForNewClient;
        updateAgeCheckEnabled();
    }

    public static boolean isAgeCheckEnabled() {
        return ageCheckEnabled;
    }

    public static void setAgeCheckEnabled(boolean ageCheckEnabled) {
        ClientRules.ageCheckEnabled = ageCheckEnabled;
    }

    /*
     * reads the maximum age specified in the application configuration file,
     * Also Checks if its in the range of 0 to 150
     */
    public static int getMinimumAge() throws ConfigurationException {
        int minimumAge = 0;
        MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
        if (configMgr.containsKey(ClientRules.MinimumAgeForNewClients)) {
            minimumAge = Integer.parseInt(configMgr.getString(ClientRules.MinimumAgeForNewClients));
        } else {
            throw new ConfigurationException("The Minimum Age for a client is not defined in "
                    + MifosConfigurationManager.DEFAULT_CONFIG_PROPS_FILENAME);
        }

        if (minimumAge < 0 || minimumAge > 150) {
            throw new ConfigurationException("The Minimum Age defined in the "
                    + MifosConfigurationManager.DEFAULT_CONFIG_PROPS_FILENAME
                    + "is not within the acceptable range (0 to 150)");
        }

        return minimumAge;

    }

    /*
     * Gets the minimum age specified in the application configuration file,
     * Also Checks if its in the range of 0 to 150
     */
    public static int getMaximumAge() throws ConfigurationException {
        int maximumAge = 0;
        MifosConfigurationManager configMgr = MifosConfigurationManager.getInstance();
        if (configMgr.containsKey(ClientRules.MaximumAgeForNewClients)) {
            maximumAge = Integer.parseInt(configMgr.getString(ClientRules.MaximumAgeForNewClients));
        } else {
            throw new ConfigurationException("The Maximum Age for a client is not defined in "
                    + MifosConfigurationManager.DEFAULT_CONFIG_PROPS_FILENAME);
        }

        if (maximumAge > 150 || maximumAge < 0) {
            throw new ConfigurationException("The Maximum Age defined in the "
                    + MifosConfigurationManager.DEFAULT_CONFIG_PROPS_FILENAME
                    + "is not within the acceptable range (0 to 150)");
        }
        return maximumAge;

    }

    public static void intializeFamilyConfig() throws ConfigurationException {
        setFamilyDetailsRequired(ClientFamilyInfoConfig.getAreFamilyDetailsRequired());
        setMaximumNumberOfFamilyMembers(ClientFamilyInfoConfig.getMaximumNumberOfFamilyMembers());
    }
}


text:
"""
.. module:: mlpy.auxiliary.array
   :platform: Unix, Windows
   :synopsis: Numpy array utility functions.

.. moduleauthor:: Astrid Jackson <ajackson@eecs.ucf.edu>
"""
from __future__ import division, print_function, absolute_import

from itertools import product
import numpy as np

def accum(accmap, a, func=None, size=None, fill_value=0, dtype=None):
    # noinspection PyTypeChecker
    """An accumulation function similar to Matlab's `accumarray` function.

    Parameters
    ----------
    accmap : array_like
        This is the "accumulation map".  It maps input (i.e. indices into
        `a`) to their destination in the output array.  The first `a.ndim`
        dimensions of `accmap` must be the same as `a.shape`.  That is,
        `accmap.shape[:a.ndim]` must equal `a.shape`.  For example, if `a`
        has shape (15,4), then `accmap.shape[:2]` must equal (15,4).  In this
        case `accmap[i,j]` gives the index into the output array where
        element (i,j) of `a` is to be accumulated.  If the output is, say,
        a 2D, then `accmap` must have shape (15,4,2).  The value in the
        last dimension give indices into the output array. If the output is
        1D, then the shape of `accmap` can be either (15,4) or (15,4,1)
    a : array_like or float or int
        The input data to be accumulated.
    func : callable or None
        The accumulation function.  The function will be passed a list
        of values from `a` to be accumulated.
        If None, numpy.sum is assumed.
    size : array_like or tuple
        The size of the output array.  If None, the size will be determined
        from `accmap`.
    fill_value : scalar
        The default value for elements of the output array.
    dtype : dtype
        The data type of the output array.  If None, the data type of
        `a` is used.

    Returns
    -------
    array_like :
        The accumulated results.

        The shape of `out` is `size` if `size` is given.  Otherwise the
        shape is determined by the (lexicographically) largest indices of
        the output found in `accmap`.

    Examples
    --------

    >>> from numpy import array, prod, float64
    >>> a = array([[1,2,3],[4,-1,6],[-1,8,9]])
    >>> a
    array([[ 1,  2,  3],
           [ 4, -1,  6],
           [-1,  8,  9]])

    Sum the diagonals:

    >>> accmap = array([[0,1,2],[2,0,1],[1,2,0]])
    >>> s = accum(accmap, a)
    array([9, 7, 15])

    A 2D output, from sub-arrays with shapes and positions like this:

    | [ (2,2) (2,1)]
    | [ (1,2) (1,1)]

    >>> accmap = array([
    ...     [[0,0],[0,0],[0,1]],
    ...     [[0,0],[0,0],[0,1]],
    ...     [[1,0],[1,0],[1,1]],
    ... ])

    Accumulate using a product:

    >>> accum(accmap, a, func=prod, dtype=float64)
    array([[ -8.,  18.],
           [ -8.,   9.]])

    Same accmap, but create an array of lists of values:

    >>> accum(accmap, a, func=lambda x: x, dtype='O')
    array([[[1, 2, 4, -1], [3, 6]],
           [[-1, 8], [9]]], dtype=object)

    .. note::
        Adapted from

        | Project: Code from `SciPy Cookbook <http://wiki.scipy.org/Cookbook/AccumarrayLike>`_.
        | Code author: Warren Weckesser
        | License: `CC-Wiki <http://creativecommons.org/licenses/by-sa/3.0/>`_

    """

    # Check for bad arguments and handle the defaults.
    if hasattr(a, "__len__") and accmap.shape[:a.ndim] != a.shape:
        raise ValueError("The initial dimensions of accmap must be the same as a.shape")
    if func is None:
        func = np.sum
    if dtype is None:
        dtype = np.float64
        if hasattr(a, "__len__"):
            # noinspection PyUnresolvedReferences
            dtype = a.dtype
    if hasattr(a, "__len__") and accmap.shape == a.shape:
        accmap = np.expand_dims(accmap, -1)

    if not hasattr(a, "__len__"):
        c = np.ascontiguousarray(accmap).view(np.dtype((np.void, accmap.dtype.itemsize * accmap.shape[1])))
        unique_x = np.unique(c).view(accmap.dtype).reshape(-1, accmap.shape[1])

        if size is None:
            adims = unique_x.shape[1]
            size = (adims, adims)
        size = np.atleast_1d(size)
        out = np.zeros(size, dtype=dtype)

        for seq in unique_x:
            cmd = "accmap[np.where("
            idx = ""
            for i, ele in enumerate(seq):
                if i > 0:
                    cmd += " * "
                    idx += ", "
                cmd += "(accmap[:,%d] == %d)" % (i, ele)
                idx += "%d" % ele
            cmd += ")]"
            out[eval(idx)] = eval(cmd).shape[0]

        return out

    adims = tuple(range(a.ndim))
    if size is None:
        size = 1 + np.squeeze(np.apply_over_axes(np.max, accmap, axes=adims))
    size = np.atleast_1d(size)

    # Create an array of python lists of values.
    vals = np.empty(size, dtype='O')
    for s in product(*[range(k) for k in size]):
        vals[s] = []
    for s in product(*[range(k) for k in a.shape]):
        indx = tuple(accmap[s])
        # noinspection PyUnresolvedReferences
        val = a[s]
        vals[indx].append(val)

    # Create the output array.
    out = np.empty(size, dtype=dtype)
    for s in product(*[range(k) for k in size]):
        if not vals[s]:
            out[s] = fill_value
        else:
            # noinspection PyCallingNonCallable
            out[s] = func(vals[s])

    return out

def normalize(a, axis=None, return_scale=False):
    """Normalize the input array to sum to `1`.

    Parameters
    ----------
    a : array_like, shape (`nsamples`, `nfeatures`)
        Non-normalized input data array.
    axis : int
        Dimension along which normalization is performed.

    Returns
    -------
    array_like, shape (`nsamples`, `nfeatures`) :
        An array with values normalized (summing to 1) along the
        prescribed axis.

    Examples
    --------
    >>>

    .. attention::
        The input array `a` is modified inplace.

    """
    a += np.finfo(float).eps
    asum = a.sum(axis)
    if axis and a.ndim > 1:
        # Make sure we don't divide by zero.
        asum[asum == 0] = 1
        shape = list(a.shape)
        shape[axis] = 1
        asum.shape = shape
    a = np.true_divide(a, asum)
    # TODO: should return nothing, since the operation is inplace.
    if not return_scale:
        ret = a
    else:
        ret = (a,)
        ret += (asum,)
    return ret

def nunique(x, axis=None):
    """Efficiently count the unique elements of `x` along the given axis.

    Parameters
    ----------
    x : array_like
        The array for which to count the unique elements.
    axis : int
        Dimension along which to count the unique elements.

    Returns
    -------
    int or array_like :
        The number of unique elements along the given axis.

    Examples
    --------
    >>>

    .. note::
        Ported from Matlab:

        | Project: `Probabilistic Modeling Toolkit for Matlab/Octave <https://github.com/probml/pmtk3>`_.
        | Copyright (2010) Kevin Murphy and Matt Dunham
        | License: `MIT <https://github.com/probml/pmtk3/blob/5fefd068a2e84ae508684d3e4750bd72a4164ba0/license.txt>`_

    """
    axis = 0 if axis is None else axis
    n = np.sum(np.diff(np.sort(x, axis=axis), axis=axis) > 0, axis=axis) + 1
    return n


text:
package org.swing.on.steroids.wizard.presenters;

import org.swing.on.steroids.wizard.model.WizardPageID;

/**
 * @author Paul Merlin
 */
public final class TransitionChange
{

    private final WizardPageID previousID;
    private final WizardPageID nextID;
    private final boolean enabled;

    public TransitionChange( WizardPageID previousID, WizardPageID nextID, boolean enabled )
    {
        this.previousID = previousID;
        this.nextID = nextID;
        this.enabled = enabled;
    }

    boolean isEnabled()
    {
        return enabled;
    }

    WizardPageID getNextID()
    {
        return nextID;
    }

    WizardPageID getPreviousID()
    {
        return previousID;
    }

}


text:
{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell   #-}
module Phb.Types.Event where

import BasePrelude hiding (index)
import Prelude     ()

import Control.Lens
import Data.Text        (Text)
import Data.Time        (LocalTime)
import Database.Persist (Entity, Key)

import qualified Phb.Db.Internal as D

data Event = Event
  { _eventKey       :: Key D.Event
  , _eventName      :: Text
  , _eventCustomers :: [Entity D.Customer]
  , _eventDesc      :: [Text]
  , _eventImpact    :: [Text]
  , _eventDuration  :: (LocalTime,Maybe LocalTime)
  , _eventStatuses  :: [Entity D.EventStatus]
  , _eventNotes     :: [Entity D.EventNote]
  } deriving Show
makeLenses ''Event

eventStatusLatest :: IndexedTraversal' Int Event (Entity D.EventStatus)
eventStatusLatest = eventStatuses . traversed . index 0

eventNoteLatest :: IndexedTraversal' Int Event (Entity D.EventNote)
eventNoteLatest = eventNotes . traversed . index 0


text:
void* LuaCallbacks::ReallocWrapper(void* pUserData, void* pMemory, size_t oldSize, size_t newSize)
{
	DESIRE_UNUSED(pUserData);
	DESIRE_UNUSED(oldSize);
	return MemorySystem::Realloc(pMemory, newSize);
}

int32_t LuaCallbacks::LuaPanicFunc(lua_State* L)
{
	lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(L, -1));
	return 0;	// Return to Lua to abort
}


text:
import os.path

DEBUG = True
TEMPLATE_DEBUG = DEBUG

PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))

ADMINS = (
    ('foo', 'foo@bar.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'dev.db',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Los_Angeles'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = False

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'site_media', 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/site_media/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'site_media', 'static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/site_media/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'static'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'lq(x2^--*bc474eyd@8$62ae60weo(t602zr%it0mf$)-d8u#j'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.request",
    "django.core.context_processors.debug",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
)

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',

    'fancytree',
    'apps.categories',
)