text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: cyb3r
 * Date: 24-Apr-17
 * Time: 9:35 PM
 */

namespace AppBundle\Services;

use AppBundle\Entity\Category;
use AppBundle\Entity\Product;
use AppBundle\Entity\ProductAvailability;
use AppBundle\Entity\Promotion;
use AppBundle\Entity\User;
use AppBundle\Repository\CategoryRepository;
use AppBundle\Repository\ProductAvailabilityRepository;
use AppBundle\Repository\ProductCommentRepository;
use AppBundle\Repository\ProductRepository;
use AppBundle\Repository\PromotionRepository;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class ProductsManager
{
    /**
     * @var ProductRepository
     */
    protected $products;
    /**
     * @var PromotionRepository
     */
    protected $promotions;
    /**
     * @var TokenStorage
     */
    protected $tokens;
    /**
     * @var CategoryRepository
     */
    protected $categories;
    /**
     * @var ProductAvailabilityRepository
     */
    protected $availabilities;
    /**
     * @var ProductCommentRepository
     */
    protected $comments;
    /**
     * @var Promotion[]
     */
    protected $loadedPromotions;

    public function __construct(ProductRepository $repo, PromotionRepository $promotionRepo, CategoryRepository $categories,
                                ProductAvailabilityRepository $availabilityRepo, ProductCommentRepository $commentsRepo,
                                TokenStorage $tokenStore)
    {
        $this->products = $repo;
        $this->promotions = $promotionRepo;
        $this->tokens = $tokenStore;
        $this->categories = $categories;
        $this->availabilities = $availabilityRepo;
        $this->comments = $commentsRepo;
    }

    public function getAvailability(Product $product){
        $availability = $this->availabilities->get($product);
        if($availability===null){
            return 0;
        }else{
            return $availability->getQuantity();
        }
    }

    public function newProductAvailability(Product $product, $availabilityCount){
        if(is_int($availabilityCount) || is_numeric($availabilityCount)){
            $this->availabilities->create($product, $availabilityCount);
        }
    }

    public function subtractAvailability(Product $product, $intToSubtract){
        if(is_int($intToSubtract) || is_numeric($intToSubtract)){
            $availability = $this->availabilities->get($product);
            if($availability===null){
                return 0;
            }else{
                $newAvailability = $availability->getQuantity() - $intToSubtract;
                $this->availabilities->set($product, $newAvailability);
                return $newAvailability;
            }
        }
        return false;
    }

    public function setAvailability(Product $product, ProductAvailability $availability){
        $this->availabilities->set($product, $availability->getQuantity());
    }

    /**
     * @return Category[]
     */
    public function getAvailableInAllCategories(){
        $availables = $this->categories->getAll();
        return $availables;
    }

    /**
     * @param Category $category
     * @return array
     */
    public function getAvailableInCategory(Category $category){
        return $this->products->getByCategory($category->getId());
    }

    public function addComment(Product $product, $comment, User $user){
        $comment = $this->comments->create($product, $comment, $user);
        return true;
    }

    public function putOnPromotion(Product $product){

    }

    /**
     * Applies the best available promotion to the product
     * @param Product $product
     * @param null $discount
     * @internal param int|null $amount
     */
    public function applyAvailablePromotions(Product &$product, &$discount=null){
        $bestPromotion = $this->getBestPromotion($product);
        if($bestPromotion!=null){
            $product->setPromotion($bestPromotion);
            $discount= $bestPromotion->getDiscount();
        }
    }

    /**
     * checks if the promotions are loaded
     */
    private function checkPromotions(){
        if($this->loadedPromotions!=null) return;
        $this->loadedPromotions = $this->promotions->getAvailablePromotions();
    }

    /**
     * @param Product $product
     * @return array [ product => Product, discount => Discount]
     */
    public function applyStaticDiscounts(Product $product){
        $this->checkPromotions();
        $productQualified = $this->getQualifiedPromotions($product, $this->loadedPromotions);
        $maxDiscount = -1;
        $biggestPromotion = null;
        for ($i = 0; $i < count($productQualified); $i++) {
            /** @var Promotion $p */
            $p = $productQualified[$i];
            if ($p->getDiscount() > $maxDiscount) {
                $maxDiscount = $p->getDiscount();
                $biggestPromotion = $p;
            }
        }
        $discount = 0;
        if($biggestPromotion!=null){
            $product->setPromotion($biggestPromotion);
            $discount= $biggestPromotion->getDiscount();
        }
        return [
            'product' => $product,
            'discount' => $discount
        ];
    }

    /**
     * @param Product $product
     * @return Promotion|null
     */
    protected function getBestPromotion(Product $product)    {
        $productPromotion = $this->promotions->getProductPromotion($product);
        $allSpecialPromotions = $this->promotions->getSpecialPromotions();
        $qualifiedSpecialPromotions = $this->getQualifiedCriterionPromotions($allSpecialPromotions);

        if($productPromotion==null) $productPromotion = [];
        else{
            $productPromotion = [$productPromotion];
        }
        $allPromotionsClassified = array_merge($productPromotion, $qualifiedSpecialPromotions);
        $maxDiscount = -1;
        $biggestPromotion = null;
        for ($i = 0; $i < count($allPromotionsClassified); $i++) {
            /** @var Promotion $p */
            $p = $allPromotionsClassified[$i];
            if ($p->getDiscount() > $maxDiscount) {
                $maxDiscount = $p->getDiscount();
                $biggestPromotion = $p;
            }
        }

        return $biggestPromotion;
    }

    /**
     * Gets all promotions that qualify for the given product or match a criteria
     * @param Product $product
     * @param Promotion[] $promotions
     * @return Promotion[]
     */
    public function getQualifiedPromotions(Product $product, $promotions){
        $qualifiedPromos = [];
        $user = $this->tokens->getToken()->getUser();
        foreach($promotions as $promotion){
            $valid = false;
            $promoProduct = $promotion->getProduct();
            if($promoProduct !==null && $promoProduct->getId() === $product->getId()){
                $valid = true;
            }else if($promotion->getIsGeneral()){
                $valid = true;
            }else if($promotion->getCategory()!=null && $promotion->getCategory()->getId() === $product->getCategory()->getId()){
                $valid = true;
            }else if($promotion->getCriteria()!==null){
                $criterion = $promotion->getCriteria();
                $valid = $this->promotionMatchesCriteria($criterion, $user);
            }

            if($valid){
                $qualifiedPromos[] = $promotion;
            }
        }
        return $qualifiedPromos;
    }

    /**
     * Gets all the promotions from the array which qualify for the current user.
     * Use this to filter promotions with criterias
     * @param $allSpecialPromotions
     * @return array
     */
    protected function getQualifiedCriterionPromotions($allSpecialPromotions)
    {
        $qualifiedSpecialPomotions = [];
        $user = $this->tokens->getToken()->getUser();
        //Qualify the normal promotions and the user promotions
        /** @var Promotion $specialPromotion */
        foreach ($allSpecialPromotions as $specialPromotion) {
            $criterion = $specialPromotion->getCriteria();
            $valid = $this->promotionMatchesCriteria($criterion, $user);
            if ($valid) {
                $qualifiedSpecialPomotions[] = $specialPromotion;
            }
        }
        return $qualifiedSpecialPomotions;
    }

    /**
     * @param $criterion
     * @param $user
     * @return bool
     */
    protected function promotionMatchesCriteria($criterion, User $user)
    {
        $role = $user->getRole();
        $valid = false;
        if ($criterion == "USER_IS_ADMIN") {
            if ($role == "ROLE_ADMIN") {
                $valid = true;
                return $valid;
            }
            return $valid;
        } else if ($criterion == "USER_REGISTERED_1D") {
            $registeredOn = $user->getCreatedOn();
            $now = new \DateTime();
            $diff = $now->diff($registeredOn);
            $days = $diff->format('%R%a');
            $days = ltrim($days, '+');
            $days = (int)$days;
            if ($days > 1) {
                $valid = true;
                return $valid;
            }
            return $valid;
        } else if ($criterion == "USER_CREDIT_100") {
            $userCredit = $user->getCash();
            if ($userCredit > 100) {
                $valid = true;
                return $valid;
            }
            return $valid;
        }return $valid;
    }

}


text:
> Note: Apologies about the following examples being written in CoffeeScript; this lib code is very old!

The [A/B Test component](https://github.com/artsy/force/blob/master/src/desktop/components/split_test) enables the bucketing of users into categories. When a test is enabled, a cookie is set for each user that is also stored on the window via sharify. The cookie/SD var's name is based on the test name, and its value is set to one of the test's possible outcomes. Engineers can expose multiple variations of features, content, components etc. by hooking into a test outcome.

Rolling out a test requires a few steps:

- Add a test with name and outcomes to `running_tests.coffee`
- Create any feature variations that should be exposed based on outcome
- Configure analytics events that will be tracked as part of the test
- Enable the test via a `splitTest.view()` event

The last step is especially important! Users will still receive cookies, and analytics will operate as expected with or without a `splitTest.view()` event, but it is this call that enables the data team to parse analytics in the context of a test.

## Creating a test and outcomes

To start a test, add your configuration to the `running_tests.coffee` file:

```coffeescript
# Using an object for outcomes
header_design:
  key: 'header_design'
  outcomes:
    old: 80
    new: 20
  edge: 'new' # Optional
  dimension: 'dimension1' # Optional
  scope: 'local' # Optional

# Using an array for outcomes
  artist_collections_rail_qa:
    key: 'artist_collections_rail_qa'
    outcomes: [
      'control'
      'experiment'
    ]
    control_group: 'control'
    edge: 'experiment'
    weighting: 'equal'
```

Once this step is complete, an `sd` variable will be present for all users identified by the uppercase key of your test. For the above example, the key of the test is `header_design` and `sd.HEADER_DESIGN` will contain the outcome of the split test, in this case either `80` or `20`.

#### Options

- `key` name of your test

- `outcomes` either a hash of your outcomes, whose point values must add up to 100, or an array (when used with `weighting`: 'equal').

- `edge` is the feature that you want logged in admins to always have.

- `dimension` is a Google Analytics dimension. You can create one by logging into GA, clicking 'Admin', clicking 'Custom Definitions' in the middle column, clicking 'Custom Dimensions'. From there you can create a new custom dimension. Note that you should then name this 'dimension1', 'dimesion2', etc. - corresponding to the index of the custom definition in this UI.

- `scope` in some cases you may only want to initialize a test once a certain action is triggered (ie: landing on a specific page), if that's the case passing `scope: 'local'` will not globally intialize the test.

- `control_group` is what crawlers will see. Defaults to 'control'.

- `weighting` when specified as 'equal', will equally weight `outcomes`.

Tests are by default initialized globally meaning as soon as there is a configuration in the running tests file you'll get access to a Sharify variable the same name as your configuration key with the outcome and the test will set itself up client-side.

A test is not enabled from the analytics side without a `view` event. This must be triggered on the client.

## Examples

```javascript
// On the client!
const splitTest = require("desktop/components/split_test/index.coffee")

splitTest("header_design").view()
```

### Manually access a test on the client-side (optional)

In some cases, especially when dealing with legacy Backbone apps, you may want to access variables from your test on the client. You can use the below methods to access an outcome without `sd`, or generate a css class based on your test outcome.

```javascript
const splitTest = require("desktop/components/split_test/index.coffee")

// Call the required fn with the key to your configuration
const test = splitTest("header_design")

// You can then call outcome (as many times as you like, you will get the same outcome for the same user)
test.outcome() // => 'new'

// Do something with your outcome
// Another useful method is `cssClass` which will output a class name for use in stylesheets
test.cssClass() // => 'is-splittest-header_design--new'
```

## Ensuring a test is correctly configured

For local and staging environments analytics events will be printed to the browser console. For production, you can use the developer tools and click the network tab, filter request by "segment", and verify that you see the "Experiment Viewed" and other associated analytics events. You can also check looker as stated below.

### Notes on QA:

1. Once a test is added to [`runningTests`](TKTKTK), cookies will be set for all users.
2. It is possible to enable a test without exposing new features to users with an admin only flags to keep the display internal.
3. However, because we do not want to infect our results tracking with data that is not part of the official test it is recommended you use a dummy name during qa and rename when the test is officially launched (i.e. `sd.MY_TEST_QA`)

### Forcing a test down a specific path (optional)

#### Via url params

Logged in Artsy admins can override the outcome of a particular split test by passing query params.

For forcing the test "my_test" to have the outcome "experiment":
`http://www.artsy.net?split_test[my_test]=experiment`

#### Client-side

```coffeescript
splitTest = require '../../../components/split_test/index.coffee'
test = splitTest 'header_design'
test.set 'old' # Force down 'old' path
```

#### Server-side

```coffeescript
SplitTest = require '../../components/split_test/server_split_test'
runningTests = require '../../components/split_test/running_tests'
testConfig = runningTests.header_design
test = new SplitTest req, res, testConfig
test.set 'old'
res.locals.sd[testConfig.key.toUpperCase()] = 'old' # manually set the Sharify variable
```

### Confirm tracking data is received

Tests should deliver data to Looker ~ 2 hours after going into production. To confirm that data is being received, look for the test's 'experiment_id' at:
https://artsy.looker.com/sql/cgkgxbnzmf26cw

redpajama_set_name: RedPajamaGithub


text:
describe "hash" do
  describe "except" do
    it "should remove key" do
      original = { :a => 'x', :b => 'y', :c => 10 }
      expected = { :a => 'x', :b => 'y' }

      original.except(:c).should == expected
      original.should.not == expected
    end

    it "should remove more than one key" do
      original = { :a => 'x', :b => 'y', :c => 10 }
      expected = { :a => 'x' }
      original.except(:b, :c).should == expected
    end

    it "should work on frozen hash" do
      original = { :a => 'x', :b => 'y' }
      original.freeze
      lambda { original.except(:a) }.should.not.raise
    end
  end

  describe "except!" do
    it "should remove key in place" do
      original = { :a => 'x', :b => 'y', :c => 10 }
      expected = { :a => 'x', :b => 'y' }

      original.should.not == expected
      original.except!(:c).should == expected
      original.should == expected
    end

    it "should remove more than one key in place" do
      original = { :a => 'x', :b => 'y', :c => 10 }
      expected = { :a => 'x' }

      original.should.not == expected
      original.except!(:b, :c).should == expected
      original.should == expected
    end
  end
end


text:
/*
 * reserved comment block
 * DO NOT REMOVE OR ALTER!
 */
/*
 * Copyright  1999-2004 The Apache Software Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.sun.org.apache.xml.internal.security.utils.resolver;

import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import org.w3c.dom.Attr;

/**
 * This Exception is thrown if something related to the
 * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} goes wrong.
 *
 * @author $Author: mullan $
 */
public class ResourceResolverException extends XMLSecurityException {

   /**
         *
         */
        private static final long serialVersionUID = 1L;
   /**
    * Constructor ResourceResolverException
    *
    * @param _msgID
    * @param uri
    * @param BaseURI
    */
   public ResourceResolverException(String _msgID, Attr uri, String BaseURI) {

      super(_msgID);

      this._uri = uri;
      this._BaseURI = BaseURI;
   }

   /**
    * Constructor ResourceResolverException
    *
    * @param _msgID
    * @param exArgs
    * @param uri
    * @param BaseURI
    */
   public ResourceResolverException(String _msgID, Object exArgs[], Attr uri,
                                    String BaseURI) {

      super(_msgID, exArgs);

      this._uri = uri;
      this._BaseURI = BaseURI;
   }

   /**
    * Constructor ResourceResolverException
    *
    * @param _msgID
    * @param _originalException
    * @param uri
    * @param BaseURI
    */
   public ResourceResolverException(String _msgID, Exception _originalException,
                                    Attr uri, String BaseURI) {

      super(_msgID, _originalException);

      this._uri = uri;
      this._BaseURI = BaseURI;
   }

   /**
    * Constructor ResourceResolverException
    *
    * @param _msgID
    * @param exArgs
    * @param _originalException
    * @param uri
    * @param BaseURI
    */
   public ResourceResolverException(String _msgID, Object exArgs[],
                                    Exception _originalException, Attr uri,
                                    String BaseURI) {

      super(_msgID, exArgs, _originalException);

      this._uri = uri;
      this._BaseURI = BaseURI;
   }

   //J-
   Attr _uri = null;
   /**
    *
    * @param uri
    */
   public void setURI(Attr uri) {
      this._uri = uri;
   }

   /**
    *
    * @return the uri
    */
   public Attr getURI() {
      return this._uri;
   }

   String _BaseURI;

   /**
    *
    * @param BaseURI
    */
   public void setBaseURI(String BaseURI) {
      this._BaseURI = BaseURI;
   }

   /**
    *
    * @return the basUri
    */
   public String getBaseURI() {
      return this._BaseURI;
   }
   //J+
}


text:
package gov.hhs.fha.nhinc.patientdiscovery.nhin.deferred.request;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hl7.v3.MCCIIN000002UV01;
import org.hl7.v3.PRPAIN201305UV02;
import org.hl7.v3.PRPAIN201306UV02;
import org.hl7.v3.RespondingGatewayPRPAIN201305UV02RequestType;

import gov.hhs.fha.nhinc.async.AsyncMessageProcessHelper;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.generic.GenericFactory;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.patientdiscovery.PatientDiscoveryAuditor;
import gov.hhs.fha.nhinc.patientdiscovery.PolicyChecker;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.error.proxy.AdapterPatientDiscoveryDeferredReqErrorProxy;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.proxy.AdapterPatientDiscoveryDeferredReqProxy;
import gov.hhs.fha.nhinc.properties.ServicePropertyAccessor;
import gov.hhs.fha.nhinc.transform.subdisc.HL7PRPA201306Transforms;

/**
 *
 * @author jhoppesc
 */
public class NhinPatientDiscoveryDeferredReqOrchImpl implements NhinPatientDiscoveryDeferredReqOrch {
    private static Log log = LogFactory.getLog(NhinPatientDiscoveryDeferredReqOrchImpl.class);

    private final ServicePropertyAccessor servicePropertyAccessor;

    private final PatientDiscoveryAuditor auditLogger;

    private final GenericFactory<AdapterPatientDiscoveryDeferredReqProxy> proxyFactory;

    private final GenericFactory<AdapterPatientDiscoveryDeferredReqErrorProxy> proxyErrorFactory;

    private final PolicyChecker<RespondingGatewayPRPAIN201305UV02RequestType, PRPAIN201305UV02> policyChecker;

    NhinPatientDiscoveryDeferredReqOrchImpl(ServicePropertyAccessor servicePropertyAccessor,
            PatientDiscoveryAuditor auditLogger, GenericFactory<AdapterPatientDiscoveryDeferredReqProxy> proxyFactory,
            GenericFactory<AdapterPatientDiscoveryDeferredReqErrorProxy> proxyErrorFactory,
            PolicyChecker<RespondingGatewayPRPAIN201305UV02RequestType, PRPAIN201305UV02> policyChecker) {
        super();
        this.servicePropertyAccessor = servicePropertyAccessor;
        this.auditLogger = auditLogger;
        this.proxyFactory = proxyFactory;
        this.proxyErrorFactory = proxyErrorFactory;
        this.policyChecker = policyChecker;
    }

    protected AsyncMessageProcessHelper createAsyncProcesser() {
        return new AsyncMessageProcessHelper();
    }

    @Override
    public MCCIIN000002UV01 respondingGatewayPRPAIN201305UV02(PRPAIN201305UV02 request, AssertionType assertion) {
        MCCIIN000002UV01 resp = new MCCIIN000002UV01();

        // Audit the incoming Nhin 201305 Message
        auditLogger.auditNhinDeferred201305(request, assertion, NhincConstants.AUDIT_LOG_INBOUND_DIRECTION);
        if (isInPassThroughMode()) {
            // Send the 201305 to the Adapter Interface
            resp = sendToAgency(request, assertion);
        } else {
            resp = serviceInternal(request, assertion);
        }

        // Audit the responding ack Message
        auditLogger.auditAck(resp, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION,
                NhincConstants.AUDIT_LOG_NHIN_INTERFACE);

        return resp;
    }

    /**
     * Checks to see if the query should be handled internally or passed through to an adapter.
     *
     * @return Returns true if the patientDiscoveryPassthroughAsyncReq property of the gateway.properties file is true.
     */
    protected boolean isInPassThroughMode() {
        return servicePropertyAccessor.isInPassThroughMode();
    }

    /**
     * Checks the policy of the passed in request.
     *
     * @param request
     * @param assertion
     * @return
     */
    protected boolean checkPolicy(PRPAIN201305UV02 request, AssertionType assertion) {
        return policyChecker.checkIncomingPolicy(request, assertion);
    }

    /**
     *
     * @param request
     * @param assertion
     * @param homeCommunityId
     * @return MCCIIN000002UV01
     */
    private MCCIIN000002UV01 serviceInternal(PRPAIN201305UV02 request, AssertionType assertion) {
        MCCIIN000002UV01 response = null;
        // HomeCommunityType hcId = new HomeCommunityType();
        String errMsg = null;

        // hcId.setHomeCommunityId(homeCommunityId);
        if (checkPolicy(request, assertion)) {
            log.debug("Adapter patient discovery deferred policy check successful");
            response = sendToAgency(request, assertion);
        } else {
            errMsg = "Policy Check Failed";
            log.error(errMsg);
            response = sendToAgencyError(request, assertion, errMsg);
        }

        return response;
    }

    protected MCCIIN000002UV01 sendToAgency(PRPAIN201305UV02 request, AssertionType assertion) {
        auditLogger.auditAdapterDeferred201305(request, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION);

        AdapterPatientDiscoveryDeferredReqProxy proxy = proxyFactory.create();

        MCCIIN000002UV01 resp = proxy.processPatientDiscoveryAsyncReq(request, assertion);

        auditLogger.auditAck(resp, assertion, NhincConstants.AUDIT_LOG_INBOUND_DIRECTION,
                NhincConstants.AUDIT_LOG_ADAPTER_INTERFACE);

        return resp;
    }

    protected MCCIIN000002UV01 sendToAgencyError(PRPAIN201305UV02 request, AssertionType assertion, String errMsg) {
        auditLogger.auditAdapterDeferred201305(request, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION);

        PRPAIN201306UV02 response = new HL7PRPA201306Transforms().createPRPA201306ForPatientNotFound(request);

        MCCIIN000002UV01 adapterResp = proxyErrorFactory.create().processPatientDiscoveryAsyncReqError(request,
                response, assertion, errMsg);

        auditLogger.auditAck(adapterResp, assertion, NhincConstants.AUDIT_LOG_INBOUND_DIRECTION,
                NhincConstants.AUDIT_LOG_ADAPTER_INTERFACE);

        return adapterResp;
    }

}


text:
namespace chatterino {

class EmoteInputItem : public GenericListItem
{
    using ActionCallback = std::function<void(const QString &)>;

public:
    EmoteInputItem(const EmotePtr &emote, const QString &text,
                   ActionCallback action);

    // GenericListItem interface
public:
    virtual void action() override;
    virtual void paint(QPainter *painter, const QRect &rect) const override;
    virtual QSize sizeHint(const QRect &rect) const override;

private:
    EmotePtr emote_;
    QString text_;
    ActionCallback action_;
};

}  // namespace chatterino


text:
<?php

/**
 *
 * @package    sfErrorNotifier
 * @subpackage test
 *
 * @author     Maksim Kotlyar <mkotlar@ukr.net>
 */
class sfErrorNotifierTestCase extends sfBasePhpunitTestCase
{
  protected $notifierBackup;

  protected function _start()
  {
    $this->notifierBackup = sfErrorNotifier::getInstance();

    $notifier = new sfErrorNotifier(new sfEventDispatcher());
    sfErrorNotifier::setInstance($notifier);
  }

  protected function _end()
  {
    sfErrorNotifier::setInstance($this->notifierBackup);
  }

  public function testDispather()
  {
    $dispather = new sfEventDispatcher();

    $notifier = new sfErrorNotifier($dispather);

    $this->assertSame($dispather, $notifier->dispather());
  }

  public function testDriver()
  {
    $expectedOptions = array('foo' => 'bar');
    $mock = $this->getMockForAbstractClass(
      'sfBaseErrorNotifierDriver', array($expectedOptions));

    sfConfig::set('sf_notify_driver', array(
      'class' => get_class($mock),
      'options' => $expectedOptions));

    $notifier = new sfErrorNotifier(new sfEventDispatcher());

    $driver = $notifier->driver();

    $this->assertType(get_class($mock), $driver);
    $this->assertAttributeEquals($expectedOptions, '_options', $driver);
  }

  public function testHelper()
  {
    $mock = $this->getMock('sfErrorNotifierMessageHelper');
    sfConfig::set('sf_notify_helper', array('class' => get_class($mock)));

    $notifier = new sfErrorNotifier(new sfEventDispatcher());

    $helper = $notifier->helper();

    $this->assertType(get_class($mock), $helper);
  }

  /**
   *
   * @depends testHelper
   */
  public function testMessage()
  {
    $mock = $this->getMockForAbstractClass('sfBaseErrorNotifierMessage');
    sfConfig::set('sf_notify_message', array('class' => get_class($mock)));

    $notifier = new sfErrorNotifier(new sfEventDispatcher());

    $message = $notifier->message('title');

    $this->assertType(get_class($mock), $message);

//    $stub = $this->getStubStrict('sfBaseErrorNotifierMessageHelper', array(
//      'summarySection' => array('foo' => 'bar'),
//      'formatSubject' => 'Foo Subject'));
//
//    sfConfig::set('sf_notify_helper', array('class' => get_class($mock)));
  }

  public function testHandler()
  {
    $expectedOptions = array(
      'error_reporting' => 5,
      'ignore_errors' => array('E_ALL' => array('info')),
      'ignore_exceptions' => array('FooException'),
      'log_ignored' => 1);
    $mock = $this->getMockForAbstractClass(
      'sfErrorNotifierHandler', array($expectedOptions));

    sfConfig::set('sf_notify_handler', array(
      'class' => get_class($mock),
      'options' => $expectedOptions));

    $notifier = new sfErrorNotifier(new sfEventDispatcher());

    $handler = $notifier->handler();

    $this->assertType(get_class($mock), $handler);
    $this->assertAttributeEquals($expectedOptions, 'options', $handler);
  }

  public function testDecorator()
  {
    $stubMessage = new sfErrorNotifierMessage('Foo Title');

    $mock = $this->getMockForAbstractClass(
      'sfBaseErrorNotifierDecorator', array(), '', false);
    sfConfig::set('sf_notify_decorator', array('class' => get_class($mock)));

    $notifier = new sfErrorNotifier(new sfEventDispatcher());
    $decorator = $notifier->decorator($stubMessage);

    $this->assertType(get_class($mock), $decorator);
    $this->assertAttributeEquals($stubMessage, 'message', $decorator);
  }

  /**
   *
   * @depends testDecorator
   * @depends testMessage
   */
  public function testDecoratedMessage()
  {
    $decoratorMock = $this->getMockForAbstractClass(
      'sfBaseErrorNotifierDecorator', array(), '', false);
    sfConfig::set('sf_notify_decorator', array('class' => get_class($decoratorMock)));

    $messageMock = $this->getMockForAbstractClass('sfBaseErrorNotifierMessage');
    sfConfig::set('sf_notify_message', array('class' => get_class($messageMock)));

    $notifier = new sfErrorNotifier(new sfEventDispatcher());

    $decoratedMessage = $notifier->decoratedMessage('Foo Title');

    $this->assertType(get_class($decoratorMock), $decoratedMessage);
    $this->assertAttributeType(get_class($messageMock), 'message', $decoratedMessage);
  }
}


text:
var p1 = new Promise(resolve => { setTimeout(resolve, 1000, "one"); });
var p2 = new Promise(resolve => { setTimeout(resolve, 3000, "two"); });
var p2 = new Promise(resolve => { setTimeout(resolve, 2000, "three"); });

Promise.all([p1, p2, p3])
  .then(function (value) {
    console.log(value); // ["one", "two", "three"]
  })
  .catch(err => {
    console.log(err); // not called
  });


text:
"use strict";
var ensureNotHandled = require("./errors.js").ensureNotHandled;
var util = require("./util.js");
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
var keys = require("./es5.js").keys;

function CatchFilter(instances, callback, promise) {
    this._instances = instances;
    this._callback = callback;
    this._promise = promise;
}

function CatchFilter$_safePredicate(predicate, e) {
    var safeObject = {};
    var retfilter = tryCatch1(predicate, safeObject, e);

    if (retfilter === errorObj) return retfilter;

    var safeKeys = keys(safeObject);
    if (safeKeys.length) {
        errorObj.e = new TypeError(
            "Catch filter must inherit from Error "
          + "or be a simple predicate function");
        return errorObj;
    }
    return retfilter;
}

CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) {
    var cb = this._callback;

    for (var i = 0, len = this._instances.length; i < len; ++i) {
        var item = this._instances[i];
        var itemIsErrorType = item === Error ||
            (item != null && item.prototype instanceof Error);

        if (itemIsErrorType && e instanceof item) {
            var ret = tryCatch1(cb, this._promise._boundTo, e);
            if (ret === errorObj) {
                throw ret.e;
            }
            return ret;
        } else if (typeof item === "function" && !itemIsErrorType) {
            var shouldHandle = CatchFilter$_safePredicate(item, e);
            if (shouldHandle === errorObj) {
                this._promise._attachExtraTrace(errorObj.e);
                e = errorObj.e;
                break;
            } else if (shouldHandle) {
                var ret = tryCatch1(cb, this._promise._boundTo, e);
                if (ret === errorObj) {
                    throw ret.e;
                }
                return ret;
            }
        }
    }
    ensureNotHandled(e);
    throw e;
};

module.exports = CatchFilter;


text:
package net.bis5.mattermost.model.config;

import lombok.Data;

/**
 * Guest account settings.
 *
 * @author Takayuki Maruyama
 * @since Mattermost Server 5.16
 */
@Data
public class GuestAccountsSettings {
  private boolean enable;
  private boolean allowEmailAccounts = true;
  private boolean enforceMultifactorAuthentication;
  private String restrictCreationToDomains;

}


text:
"""
Created on Sun Feb 22 02:28:35 2015

@author: Enes Kemal Ergin

List Examples from A Byte of Python
"""

shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase.')

print('These items are: ', end= ' ')

for item in shoplist:
    print(item, end= ' ')

print('\n also have to buy rice.')
shoplist.append('rice')
print('My Shopping list is now', shoplist)

print('I want to sort my list')
shoplist.sort()
print('Sorted list: ', shoplist)

print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]

del shoplist[0]

print('I bought the', olditem)
print('My shopping list is now', shoplist)


text:
To locally run the provided Postman collection against your backend, execute:

```
APIURL=http://localhost:3000/api ./run-api-tests.sh
```

For more details, see [`run-api-tests.sh`](run-api-tests.sh).


text:
package owl.owlapi;

public class Log {
    private long now;
    private long prec;

    public Log() {
        this.now = System.currentTimeMillis();
        this.prec = 0L;
    }

    public void write(String msg) {
        this.prec = this.now;
        this.now = System.currentTimeMillis();

        System.out.println("<time: " + (this.now - this.prec) + " msec> " + msg + "\n");
    }
}


text:
package io.quarkus.panache.common.deployment;

import java.util.Set;

import io.quarkus.builder.item.MultiBuildItem;

/**
 * Build item to indicate that those classes are Panache-enhanced and will get
 * getters/setters generated for public fields, even if they're not visible in the index.
 */
public final class PanacheEntityClassesBuildItem extends MultiBuildItem {

    private final Set<String> entityClasses;

    public PanacheEntityClassesBuildItem(Set<String> entityClasses) {
        this.entityClasses = entityClasses;
    }

    public Set<String> getEntityClasses() {
        return entityClasses;
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>start (Spec::Runner::Reporter)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/spec/runner/reporter.rb, line 48
      def start(number_of_examples)
        @start_time = Time.new
        formatters.each{|f| f.start(number_of_examples)}
      end


text:
UPDATE WHITELIST_TYPE SET TENANT_ID='1';
UPDATE WHITELIST_APP SET TENANT_ID='1';
UPDATE WHITELIST_HOST SET TENANT_ID='1';
UPDATE WHITELIST_IP SET TENANT_ID='1';


text:
package kea;

/**
 * A stemmer for German words. The algorithm is based on the report
 * "A Fast and Simple Stemming Algorithm for German Words" by Jörg
 * Caumanns (joerg.caumanns@isst.fhg.de).
 *
 * Changed stem() from protected to public.
 * Changed coding for umlaute to unicode.
 *
 * @author    Gerhard Schwarz
 * @version   $Id: GermanStemmer.java,v 1.3 2005/02/03 12:52:20 valyt Exp $
 */
public class GermanStemmer extends Stemmer
{
    /**
     * Buffer for the terms while stemming them.
     */
    private StringBuffer sb = new StringBuffer();

    /**
     * Indicates if a term is handled as a noun.
     */
    private boolean uppercase = false;

    /**
     * Amount of characters that are removed with <tt>substitute()</tt> while stemming.
     */
    private int substCount = 0;

    /**
     * Stemms the given term to an unique <tt>discriminator</tt>.
     *
     * @param term  The term that should be stemmed.
     * @return      Discriminator for <tt>term</tt>
     */
    public String stem( String term )
    {
  // Mark a possible noun.
  uppercase = Character.isUpperCase( term.charAt( 0 ) );
  // Use lowercase for medium stemming.
  term = term.toLowerCase();
  if ( !isStemmable( term ) )
      return term;
  // Reset the StringBuffer.
  sb.delete( 0, sb.length() );
  sb.insert( 0, term );
  // Stemming starts here...
  substitute( sb );
  strip( sb );
  optimize( sb );
  resubstitute( sb );
  removeParticleDenotion( sb );
  return sb.toString();
    }

    /**
     * Checks if a term could be stemmed.
     *
     * @return  true if, and only if, the given term consists in letters.
     */
    private boolean isStemmable( String term )
    {
  for ( int c = 0; c < term.length(); c++ ) {
      if ( !Character.isLetter( term.charAt( c ) ) ) return false;
  }
  return true;
    }

    /**
     * suffix stripping (stemming) on the current term. The stripping is reduced
     * to the seven "base" suffixes "e", "s", "n", "t", "em", "er" and * "nd",
     * from which all regular suffixes are build of. The simplification causes
     * some overstemming, and way more irregular stems, but still provides unique.
     * discriminators in the most of those cases.
     * The algorithm is context free, except of the length restrictions.
     */
    private void strip( StringBuffer buffer )
    {
  boolean doMore = true;
  while ( doMore && buffer.length() > 3 ) {
      if ( ( buffer.length() + substCount > 5 ) &&
    buffer.substring( buffer.length() - 2, buffer.length() ).equals( "nd" ) )
      {
    buffer.delete( buffer.length() - 2, buffer.length() );
      }
      else if ( ( buffer.length() + substCount > 4 ) &&
    buffer.substring( buffer.length() - 2, buffer.length() ).equals( "em" ) ) {
    buffer.delete( buffer.length() - 2, buffer.length() );
      }
      else if ( ( buffer.length() + substCount > 4 ) &&
    buffer.substring( buffer.length() - 2, buffer.length() ).equals( "er" ) ) {
    buffer.delete( buffer.length() - 2, buffer.length() );
      }
      else if ( buffer.charAt( buffer.length() - 1 ) == 'e' ) {
    buffer.deleteCharAt( buffer.length() - 1 );
      }
      else if ( buffer.charAt( buffer.length() - 1 ) == 's' ) {
    buffer.deleteCharAt( buffer.length() - 1 );
      }
      else if ( buffer.charAt( buffer.length() - 1 ) == 'n' ) {
    buffer.deleteCharAt( buffer.length() - 1 );
      }
      // "t" occurs only as suffix of verbs.
      else if ( buffer.charAt( buffer.length() - 1 ) == 't' && !uppercase ) {
    buffer.deleteCharAt( buffer.length() - 1 );
      }
      else {
    doMore = false;
      }
  }
    }

    /**
     * Does some optimizations on the term. This optimisations are
     * contextual.
     */
    private void optimize( StringBuffer buffer )
    {
  // Additional step for female plurals of professions and inhabitants.
  if ( buffer.length() > 5 && buffer.substring( buffer.length() - 5, buffer.length() ).equals( "erin*" ) ) {
      buffer.deleteCharAt( buffer.length() -1 );
      strip( buffer );
  }
  // Additional step for irregular plural nouns like "Matrizen -> Matrix".
  if ( buffer.charAt( buffer.length() - 1 ) == ( 'z' ) ) {
      buffer.setCharAt( buffer.length() - 1, 'x' );
  }
    }

    /**
     * Removes a particle denotion ("ge") from a term.
     */
    private void removeParticleDenotion( StringBuffer buffer )
    {
  if ( buffer.length() > 4 ) {
      for ( int c = 0; c < buffer.length() - 3; c++ ) {
    if ( buffer.substring( c, c + 4 ).equals( "gege" ) ) {
        buffer.delete( c, c + 2 );
        return;
    }
      }
  }
    }

    /**
     * Do some substitutions for the term to reduce overstemming:
     *
     * - Substitute Umlauts with their corresponding vowel: äöü -> aou,
     *   "ß" is substituted by "ss"
     * - Substitute a second char of a pair of equal characters with
     *   an asterisk: ?? -> ?*
     * - Substitute some common character combinations with a token:
     *   sch/ch/ei/ie/ig/st -> $/§/%/&/#/!
     */
    private void substitute( StringBuffer buffer )
    {
  substCount = 0;
  for ( int c = 0; c < buffer.length(); c++ ) {
      // Replace the second char of a pair of the equal characters with an asterisk
      if ( c > 0 && buffer.charAt( c ) == buffer.charAt ( c - 1 )  ) {
    buffer.setCharAt( c, '*' );
      }
      // Substitute Umlauts.
      else if ( buffer.charAt( c ) == '\u00E4' ) {
    buffer.setCharAt( c, 'a' );
      }
      else if ( buffer.charAt( c ) == '\u00F6' ) {
    buffer.setCharAt( c, 'o' );
      }
      else if ( buffer.charAt( c ) == '\u00FC' ) {
    buffer.setCharAt( c, 'u' );
      }
      // Take care that at least one character is left left side from the current one
      if ( c < buffer.length() - 1 ) {
    if ( buffer.charAt( c ) == '\u00DF' ) {
        buffer.setCharAt( c, 's' );
        buffer.insert( c + 1, 's' );
        substCount++;
    }
    // Masking several common character combinations with an token
    else if ( ( c < buffer.length() - 2 ) && buffer.charAt( c ) == 's' &&
        buffer.charAt( c + 1 ) == 'c' && buffer.charAt( c + 2 ) == 'h' )
    {
        buffer.setCharAt( c, '$' );
        buffer.delete( c + 1, c + 3 );
        substCount =+ 2;
    }
    else if ( buffer.charAt( c ) == 'c' && buffer.charAt( c + 1 ) == 'h' ) {
        buffer.setCharAt( c, '§' );
        buffer.deleteCharAt( c + 1 );
        substCount++;
    }
    else if ( buffer.charAt( c ) == 'e' && buffer.charAt( c + 1 ) == 'i' ) {
        buffer.setCharAt( c, '%' );
        buffer.deleteCharAt( c + 1 );
        substCount++;
    }
    else if ( buffer.charAt( c ) == 'i' && buffer.charAt( c + 1 ) == 'e' ) {
        buffer.setCharAt( c, '&' );
        buffer.deleteCharAt( c + 1 );
        substCount++;
    }
    else if ( buffer.charAt( c ) == 'i' && buffer.charAt( c + 1 ) == 'g' ) {
        buffer.setCharAt( c, '#' );
        buffer.deleteCharAt( c + 1 );
        substCount++;
    }
    else if ( buffer.charAt( c ) == 's' && buffer.charAt( c + 1 ) == 't' ) {
        buffer.setCharAt( c, '!' );
        buffer.deleteCharAt( c + 1 );
        substCount++;
    }
      }
  }
    }

    /**
     * Undoes the changes made by substitute(). That are character pairs and
     * character combinations. Umlauts will remain as their corresponding vowel,
     * as "ß" remains as "ss".
     */
    private void resubstitute( StringBuffer buffer )
    {
  for ( int c = 0; c < buffer.length(); c++ ) {
      if ( buffer.charAt( c ) == '*' ) {
    char x = buffer.charAt( c - 1 );
    buffer.setCharAt( c, x );
      }
      else if ( buffer.charAt( c ) == '$' ) {
    buffer.setCharAt( c, 's' );
    buffer.insert( c + 1, new char[]{'c', 'h'}, 0, 2 );
      }
      else if ( buffer.charAt( c ) == '§' ) {
    buffer.setCharAt( c, 'c' );
    buffer.insert( c + 1, 'h' );
      }
      else if ( buffer.charAt( c ) == '%' ) {
    buffer.setCharAt( c, 'e' );
    buffer.insert( c + 1, 'i' );
      }
      else if ( buffer.charAt( c ) == '&' ) {
    buffer.setCharAt( c, 'i' );
    buffer.insert( c + 1, 'e' );
      }
      else if ( buffer.charAt( c ) == '#' ) {
    buffer.setCharAt( c, 'i' );
    buffer.insert( c + 1, 'g' );
      }
      else if ( buffer.charAt( c ) == '!' ) {
    buffer.setCharAt( c, 's' );
    buffer.insert( c + 1, 't' );
      }
  }
    }
}


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

// Safer use of UnicodeString.
#ifndef UNISTR_FROM_CHAR_EXPLICIT
#   define UNISTR_FROM_CHAR_EXPLICIT explicit
#endif

// Less important, but still a good idea.
#ifndef UNISTR_FROM_STRING_EXPLICIT
#   define UNISTR_FROM_STRING_EXPLICIT explicit
#endif

#include "reslist.h"
#include "unewdata.h"
#include "unicode/ures.h"
#include "errmsg.h"
#include "filestrm.h"
#include "cstring.h"
#include "unicode/ucnv.h"
#include "genrb.h"
#include "rle.h"
#include "uhash.h"
#include "uresimp.h"
#include "unicode/ustring.h"
#include "unicode/uchar.h"
#include "ustr.h"
#include "prscmnts.h"
#include "unicode/unistr.h"
#include "unicode/utf8.h"
#include "unicode/utf16.h"
#include <time.h>

U_NAMESPACE_USE

static int tabCount = 0;

static FileStream* out=NULL;
static struct SRBRoot* srBundle ;
static const char* outDir = NULL;
static const char* enc ="";
static UConverter* conv = NULL;

const char* const* ISOLanguages;
const char* const* ISOCountries;
const char* textExt = ".txt";
const char* xliffExt = ".xlf";

static int32_t write_utf8_file(FileStream* fileStream, UnicodeString outString)
{
    UErrorCode status = U_ZERO_ERROR;
    int32_t len = 0;

    // preflight to get the destination buffer size
    u_strToUTF8(NULL,
                0,
                &len,
                toUCharPtr(outString.getBuffer()),
                outString.length(),
                &status);

    // allocate the buffer
    char* dest = (char*)uprv_malloc(len);
    status = U_ZERO_ERROR;

    // convert the data
    u_strToUTF8(dest,
                len,
                &len,
                toUCharPtr(outString.getBuffer()),
                outString.length(),
                &status);

    // write data to out file
    int32_t ret = T_FileStream_write(fileStream, dest, len);
    uprv_free(dest);
    return (ret);
}

/*write indentation for formatting*/
static void write_tabs(FileStream* os){
    int i=0;
    for(;i<=tabCount;i++){
        write_utf8_file(os,UnicodeString("    "));
    }
}

/*get ID for each element. ID is globally unique.*/
static char* getID(const char* id, const char* curKey, char* result) {
    if(curKey == NULL) {
        result = (char *)uprv_malloc(sizeof(char)*uprv_strlen(id) + 1);
        uprv_memset(result, 0, sizeof(char)*uprv_strlen(id) + 1);
        uprv_strcpy(result, id);
    } else {
        result = (char *)uprv_malloc(sizeof(char)*(uprv_strlen(id) + 1 + uprv_strlen(curKey)) + 1);
        uprv_memset(result, 0, sizeof(char)*(uprv_strlen(id) + 1 + uprv_strlen(curKey)) + 1);
        if(id[0]!='\0'){
            uprv_strcpy(result, id);
            uprv_strcat(result, "_");
        }
        uprv_strcat(result, curKey);
    }
    return result;
}

/*compute CRC for binary code*/
/* The code is from  http://www.theorem.com/java/CRC32.java
 * Calculates the CRC32 - 32 bit Cyclical Redundancy Check
 * <P> This check is used in numerous systems to verify the integrity
 * of information.  It's also used as a hashing function.  Unlike a regular
 * checksum, it's sensitive to the order of the characters.
 * It produces a 32 bit
 *
 * @author Michael Lecuyer (mjl@theorem.com)
 * @version 1.1 August 11, 1998
 */

/* ICU is not endian portable, because ICU data generated on big endian machines can be
 * ported to big endian machines but not to little endian machines and vice versa. The
 * conversion is not portable across platforms with different endianess.
 */

uint32_t computeCRC(const char *ptr, uint32_t len, uint32_t lastcrc){
    int32_t crc;
    uint32_t temp1;
    uint32_t temp2;

    int32_t crc_ta[256];
    int i = 0;
    int j = 0;
    uint32_t crc2 = 0;

#define CRC32_POLYNOMIAL 0xEDB88320

    /*build crc table*/
    for (i = 0; i <= 255; i++) {
        crc2 = i;
        for (j = 8; j > 0; j--) {
            if ((crc2 & 1) == 1) {
                crc2 = (crc2 >> 1) ^ CRC32_POLYNOMIAL;
            } else {
                crc2 >>= 1;
            }
        }
        crc_ta[i] = crc2;
    }

    crc = lastcrc;
    while(len--!=0) {
        temp1 = (uint32_t)crc>>8;
        temp2 = crc_ta[(crc^*ptr) & 0xFF];
        crc = temp1^temp2;
        ptr++;
    }
    return(crc);
}

static void strnrepchr(char* src, int32_t srcLen, char s, char r){
    int32_t i = 0;
    for(i=0;i<srcLen;i++){
        if(src[i]==s){
            src[i]=r;
        }
    }
}
/* Parse the filename, and get its language information.
 * If it fails to get the language information from the filename,
 * use "en" as the default value for language
 */
static char* parseFilename(const char* id, char* /*lang*/) {
    int idLen = (int) uprv_strlen(id);
    char* localeID = (char*) uprv_malloc(idLen);
    int pos = 0;
    int canonCapacity = 0;
    char* canon = NULL;
    int canonLen = 0;
    /*int i;*/
    UErrorCode status = U_ZERO_ERROR;
    const char *ext = uprv_strchr(id, '.');

    if(ext != NULL){
        pos = (int) (ext - id);
    } else {
        pos = idLen;
    }
    uprv_memcpy(localeID, id, pos);
    localeID[pos]=0; /* NUL terminate the string */

    canonCapacity =pos*3;
    canon = (char*) uprv_malloc(canonCapacity);
    canonLen = uloc_canonicalize(localeID, canon, canonCapacity, &status);

    if(U_FAILURE(status)){
        fprintf(stderr, "Could not canonicalize the locale ID: %s. Error: %s\n", localeID, u_errorName(status));
        exit(status);
    }
    strnrepchr(canon, canonLen, '_', '-');
    return canon;
}

static const char* xmlHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
#if 0
static const char* bundleStart = "<xliff version = \"1.2\" "
                                        "xmlns='urn:oasis:names:tc:xliff:document:1.2' "
                                        "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
                                        "xsi:schemaLocation='urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd'>\n";
#else
static const char* bundleStart = "<xliff version = \"1.1\" "
                                        "xmlns='urn:oasis:names:tc:xliff:document:1.1' "
                                        "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
                                        "xsi:schemaLocation='urn:oasis:names:tc:xliff:document:1.1 http://www.oasis-open.org/committees/xliff/documents/xliff-core-1.1.xsd'>\n";
#endif
static const char* bundleEnd   = "</xliff>\n";

void res_write_xml(struct SResource *res, const char* id, const char* language, UBool isTopLevel, UErrorCode *status);

static char* convertAndEscape(char** pDest, int32_t destCap, int32_t* destLength,
                              const UChar* src, int32_t srcLen, UErrorCode* status){
    int32_t srcIndex=0;
    char* dest=NULL;
    char* temp=NULL;
    int32_t destLen=0;
    UChar32 c = 0;

    if(status==NULL || U_FAILURE(*status) || pDest==NULL  || srcLen==0 || src == NULL){
        return NULL;
    }
    dest =*pDest;
    if(dest==NULL || destCap <=0){
        destCap = srcLen * 8;
        dest = (char*) uprv_malloc(sizeof(char) * destCap);
        if(dest==NULL){
            *status=U_MEMORY_ALLOCATION_ERROR;
            return NULL;
        }
    }

    dest[0]=0;

    while(srcIndex<srcLen){
        U16_NEXT(src, srcIndex, srcLen, c);

        if (U16_IS_LEAD(c) || U16_IS_TRAIL(c)) {
            *status = U_ILLEGAL_CHAR_FOUND;
            fprintf(stderr, "Illegal Surrogate! \n");
            uprv_free(dest);
            return NULL;
        }

        if((destLen+U8_LENGTH(c)) < destCap){

            /* ASCII Range */
            if(c <=0x007F){
                switch(c) {
                case '\x26':
                    uprv_strcpy(dest+( destLen),"\x26\x61\x6d\x70\x3b"); /* &*/
                    destLen+=(int32_t)uprv_strlen("\x26\x61\x6d\x70\x3b");
                    break;
                case '\x3c':
                    uprv_strcpy(dest+(destLen),"\x26\x6c\x74\x3b"); /* <*/
                    destLen+=(int32_t)uprv_strlen("\x26\x6c\x74\x3b");
                    break;
                case '\x3e':
                    uprv_strcpy(dest+(destLen),"\x26\x67\x74\x3b"); /* >*/
                    destLen+=(int32_t)uprv_strlen("\x26\x67\x74\x3b");
                    break;
                case '\x22':
                    uprv_strcpy(dest+(destLen),"\x26\x71\x75\x6f\x74\x3b"); /* "*/
                    destLen+=(int32_t)uprv_strlen("\x26\x71\x75\x6f\x74\x3b");
                    break;
                case '\x27':
                    uprv_strcpy(dest+(destLen),"\x26\x61\x70\x6f\x73\x3b"); /* ' */
                    destLen+=(int32_t)uprv_strlen("\x26\x61\x70\x6f\x73\x3b");
                    break;

                 /* Disallow C0 controls except TAB, CR, LF*/
                case 0x00:
                case 0x01:
                case 0x02:
                case 0x03:
                case 0x04:
                case 0x05:
                case 0x06:
                case 0x07:
                case 0x08:
                /*case 0x09:*/
                /*case 0x0A: */
                case 0x0B:
                case 0x0C:
                /*case 0x0D:*/
                case 0x0E:
                case 0x0F:
                case 0x10:
                case 0x11:
                case 0x12:
                case 0x13:
                case 0x14:
                case 0x15:
                case 0x16:
                case 0x17:
                case 0x18:
                case 0x19:
                case 0x1A:
                case 0x1B:
                case 0x1C:
                case 0x1D:
                case 0x1E:
                case 0x1F:
                    *status = U_ILLEGAL_CHAR_FOUND;
                    fprintf(stderr, "Illegal Character \\u%04X!\n",(int)c);
                    uprv_free(dest);
                    return NULL;
                default:
                    dest[destLen++]=(char)c;
                }
            }else{
                UBool isError = FALSE;
                U8_APPEND((unsigned char*)dest,destLen,destCap,c,isError);
                if(isError){
                    *status = U_ILLEGAL_CHAR_FOUND;
                    fprintf(stderr, "Illegal Character \\U%08X!\n",(int)c);
                    uprv_free(dest);
                    return NULL;
                }
            }
        }else{
            destCap += destLen;

            temp = (char*) uprv_malloc(sizeof(char)*destCap);
            if(temp==NULL){
                *status=U_MEMORY_ALLOCATION_ERROR;
                uprv_free(dest);
                return NULL;
            }
            uprv_memmove(temp,dest,destLen);
            destLen=0;
            uprv_free(dest);
            dest=temp;
            temp=NULL;
        }

    }
    *destLength = destLen;
    return dest;
}

#define ASTERISK 0x002A
#define SPACE    0x0020
#define CR       0x000A
#define LF       0x000D
#define AT_SIGN  0x0040

static void
trim(char **src, int32_t *len){

    char *s = NULL;
    int32_t i = 0;
    if(src == NULL || *src == NULL){
        return;
    }
    s = *src;
    /* trim from the end */
    for( i=(*len-1); i>= 0; i--){
        switch(s[i]){
        case ASTERISK:
        case SPACE:
        case CR:
        case LF:
            s[i] = 0;
            continue;
        default:
            break;
        }
        break;

    }
    *len = i+1;
}

static void
print(UChar* src, int32_t srcLen,const char *tagStart,const char *tagEnd,  UErrorCode *status){
    int32_t bufCapacity   = srcLen*4;
    char *buf       = NULL;
    int32_t bufLen = 0;

    if(U_FAILURE(*status)){
        return;
    }

    buf = (char*) (uprv_malloc(bufCapacity));
    if(buf==0){
        fprintf(stderr, "Could not allocate memory!!");
        exit(U_MEMORY_ALLOCATION_ERROR);
    }
    buf = convertAndEscape(&buf, bufCapacity, &bufLen, src, srcLen,status);
    if(U_SUCCESS(*status)){
        trim(&buf,&bufLen);
        write_utf8_file(out,UnicodeString(tagStart));
        write_utf8_file(out,UnicodeString(buf, bufLen, "UTF-8"));
        write_utf8_file(out,UnicodeString(tagEnd));
        write_utf8_file(out,UnicodeString("\n"));

    }
}
static void
printNoteElements(const UString *src, UErrorCode *status){

#if UCONFIG_NO_REGULAR_EXPRESSIONS==0 /* donot compile when no RegularExpressions are available */

    int32_t capacity = 0;
    UChar* note = NULL;
    int32_t noteLen = 0;
    int32_t count = 0,i;

    if(src == NULL){
        return;
    }

    capacity = src->fLength;
    note  = (UChar*) uprv_malloc(U_SIZEOF_UCHAR * capacity);

    count = getCount(src->fChars,src->fLength, UPC_NOTE, status);
    if(U_FAILURE(*status)){
        uprv_free(note);
        return;
    }
    for(i=0; i < count; i++){
        noteLen =  getAt(src->fChars,src->fLength, &note, capacity, i, UPC_NOTE, status);
        if(U_FAILURE(*status)){
            uprv_free(note);
            return;
        }
        if(noteLen > 0){
            write_tabs(out);
            print(note, noteLen,"<note>", "</note>", status);
        }
    }
    uprv_free(note);
#else

    fprintf(stderr, "Warning: Could not output comments to XLIFF file. ICU has been built without RegularExpression support.\n");

#endif /* UCONFIG_NO_REGULAR_EXPRESSIONS */

}

static void printAttribute(const char *name, const char *value, int32_t /*len*/)
{
    write_utf8_file(out, UnicodeString(" "));
    write_utf8_file(out, UnicodeString(name));
    write_utf8_file(out, UnicodeString(" = \""));
    write_utf8_file(out, UnicodeString(value));
    write_utf8_file(out, UnicodeString("\""));
}

static void printAttribute(const char *name, const UnicodeString value, int32_t /*len*/)
{
    write_utf8_file(out, UnicodeString(" "));
    write_utf8_file(out, UnicodeString(name));
    write_utf8_file(out, UnicodeString(" = \""));
    write_utf8_file(out, value);
    write_utf8_file(out, UnicodeString("\""));
}

static void
printComments(struct UString *src, const char *resName, UBool printTranslate, UErrorCode *status){

#if UCONFIG_NO_REGULAR_EXPRESSIONS==0 /* donot compile when no RegularExpressions are available */

    if(status==NULL || U_FAILURE(*status)){
        return;
    }

    int32_t capacity = src->fLength + 1;
    char* buf = NULL;
    int32_t bufLen = 0;
    UChar* desc  = (UChar*) uprv_malloc(U_SIZEOF_UCHAR * capacity);
    UChar* trans = (UChar*) uprv_malloc(U_SIZEOF_UCHAR * capacity);

    int32_t descLen = 0, transLen=0;
    if(desc==NULL || trans==NULL){
        *status = U_MEMORY_ALLOCATION_ERROR;
        uprv_free(desc);
        uprv_free(trans);
        return;
    }
    // TODO: make src const, stop modifying it in-place, make printContainer() take const resource, etc.
    src->fLength = removeCmtText(src->fChars, src->fLength, status);
    descLen  = getDescription(src->fChars,src->fLength, &desc, capacity, status);
    transLen = getTranslate(src->fChars,src->fLength, &trans, capacity, status);

    /* first print translate attribute */
    if(transLen > 0){
        if(printTranslate){
            /* print translate attribute */
            buf = convertAndEscape(&buf, 0, &bufLen, trans, transLen, status);
            if(U_SUCCESS(*status)){
                printAttribute("translate", UnicodeString(buf, bufLen, "UTF-8"), bufLen);
                write_utf8_file(out,UnicodeString(">\n"));
            }
        }else if(getShowWarning()){
            fprintf(stderr, "Warning: Tranlate attribute for resource %s cannot be set. XLIFF prohibits it.\n", resName);
            /* no translate attribute .. just close the tag */
            write_utf8_file(out,UnicodeString(">\n"));
        }
    }else{
        /* no translate attribute .. just close the tag */
        write_utf8_file(out,UnicodeString(">\n"));
    }

    if(descLen > 0){
        write_tabs(out);
        print(desc, descLen, "<!--", "-->", status);
    }

    uprv_free(desc);
    uprv_free(trans);
#else

    fprintf(stderr, "Warning: Could not output comments to XLIFF file. ICU has been built without RegularExpression support.\n");

#endif /* UCONFIG_NO_REGULAR_EXPRESSIONS */

}

/*
 * Print out a containing element, like:
 * <trans-unit id = "blah" resname = "blah" restype = "x-id-alias" translate = "no">
 * <group id "calendar_gregorian" resname = "gregorian" restype = "x-icu-array">
 */
static char *printContainer(SResource *res, const char *container, const char *restype, const char *mimetype, const char *id, UErrorCode *status)
{
    const char *resname = NULL;
    char *sid = NULL;

    write_tabs(out);

    resname = res->getKeyString(srBundle);
    if (resname != NULL && *resname != 0) {
        sid = getID(id, resname, sid);
    } else {
        sid = getID(id, NULL, sid);
    }

    write_utf8_file(out, UnicodeString("<"));
    write_utf8_file(out, UnicodeString(container));
    printAttribute("id", sid, (int32_t) uprv_strlen(sid));

    if (resname != NULL) {
        printAttribute("resname", resname, (int32_t) uprv_strlen(resname));
    }

    if (mimetype != NULL) {
        printAttribute("mime-type", mimetype, (int32_t) uprv_strlen(mimetype));
    }

    if (restype != NULL) {
        printAttribute("restype", restype, (int32_t) uprv_strlen(restype));
    }

    tabCount += 1;
    if (res->fComment.fLength > 0) {
        /* printComments will print the closing ">\n" */
        printComments(&res->fComment, resname, TRUE, status);
    } else {
        write_utf8_file(out, UnicodeString(">\n"));
    }

    return sid;
}

/* Writing Functions */

static const char *trans_unit = "trans-unit";
static const char *close_trans_unit = "</trans-unit>\n";
static const char *source = "<source>";
static const char *close_source = "</source>\n";
static const char *group = "group";
static const char *close_group = "</group>\n";

static const char *bin_unit = "bin-unit";
static const char *close_bin_unit = "</bin-unit>\n";
static const char *bin_source = "<bin-source>\n";
static const char *close_bin_source = "</bin-source>\n";
static const char *external_file = "<external-file";
/*static const char *close_external_file = "</external-file>\n";*/
static const char *internal_file = "<internal-file";
static const char *close_internal_file = "</internal-file>\n";

static const char *application_mimetype = "application"; /* add "/octet-stream"? */

static const char *alias_restype     = "x-icu-alias";
static const char *array_restype     = "x-icu-array";
static const char *binary_restype    = "x-icu-binary";
static const char *integer_restype   = "x-icu-integer";
static const char *intvector_restype = "x-icu-intvector";
static const char *table_restype     = "x-icu-table";

static void
string_write_xml(StringResource *res, const char* id, const char* /*language*/, UErrorCode *status) {

    char *sid = NULL;
    char* buf = NULL;
    int32_t bufLen = 0;

    if(status==NULL || U_FAILURE(*status)){
        return;
    }

    sid = printContainer(res, trans_unit, NULL, NULL, id, status);

    write_tabs(out);

    write_utf8_file(out, UnicodeString(source));

    buf = convertAndEscape(&buf, 0, &bufLen, res->getBuffer(), res->length(), status);

    if (U_FAILURE(*status)) {
        return;
    }

    write_utf8_file(out, UnicodeString(buf, bufLen, "UTF-8"));
    write_utf8_file(out, UnicodeString(close_source));

    printNoteElements(&res->fComment, status);

    tabCount -= 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(close_trans_unit));

    uprv_free(buf);
    uprv_free(sid);
}

static void
alias_write_xml(AliasResource *res, const char* id, const char* /*language*/, UErrorCode *status) {
    char *sid = NULL;
    char* buf = NULL;
    int32_t bufLen=0;

    sid = printContainer(res, trans_unit, alias_restype, NULL, id, status);

    write_tabs(out);

    write_utf8_file(out, UnicodeString(source));

    buf = convertAndEscape(&buf, 0, &bufLen, res->getBuffer(), res->length(), status);

    if(U_FAILURE(*status)){
        return;
    }
    write_utf8_file(out, UnicodeString(buf, bufLen, "UTF-8"));
    write_utf8_file(out, UnicodeString(close_source));

    printNoteElements(&res->fComment, status);

    tabCount -= 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(close_trans_unit));

    uprv_free(buf);
    uprv_free(sid);
}

static void
array_write_xml(ArrayResource *res, const char* id, const char* language, UErrorCode *status) {
    char* sid = NULL;
    int index = 0;

    struct SResource *current = NULL;

    sid = printContainer(res, group, array_restype, NULL, id, status);

    current = res->fFirst;

    while (current != NULL) {
        char c[256] = {0};
        char* subId = NULL;

        itostr(c, index, 10, 0);
        index += 1;
        subId = getID(sid, c, subId);

        res_write_xml(current, subId, language, FALSE, status);
        uprv_free(subId);
        subId = NULL;

        if(U_FAILURE(*status)){
            return;
        }

        current = current->fNext;
    }

    tabCount -= 1;
    write_tabs(out);
    write_utf8_file(out, UnicodeString(close_group));

    uprv_free(sid);
}

static void
intvector_write_xml(IntVectorResource *res, const char* id, const char* /*language*/, UErrorCode *status) {
    char* sid = NULL;
    char* ivd = NULL;
    uint32_t i=0;
    uint32_t len=0;
    char buf[256] = {'0'};

    sid = printContainer(res, group, intvector_restype, NULL, id, status);

    for(i = 0; i < res->fCount; i += 1) {
        char c[256] = {0};

        itostr(c, i, 10, 0);
        ivd = getID(sid, c, ivd);
        len = itostr(buf, res->fArray[i], 10, 0);

        write_tabs(out);
        write_utf8_file(out, UnicodeString("<"));
        write_utf8_file(out, UnicodeString(trans_unit));

        printAttribute("id", ivd, (int32_t)uprv_strlen(ivd));
        printAttribute("restype", integer_restype, (int32_t) strlen(integer_restype));

        write_utf8_file(out, UnicodeString(">\n"));

        tabCount += 1;
        write_tabs(out);
        write_utf8_file(out, UnicodeString(source));

        write_utf8_file(out, UnicodeString(buf, len));

        write_utf8_file(out, UnicodeString(close_source));
        tabCount -= 1;
        write_tabs(out);
        write_utf8_file(out, UnicodeString(close_trans_unit));

        uprv_free(ivd);
        ivd = NULL;
    }

    tabCount -= 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(close_group));
    uprv_free(sid);
    sid = NULL;
}

static void
int_write_xml(IntResource *res, const char* id, const char* /*language*/, UErrorCode *status) {
    char* sid = NULL;
    char buf[256] = {0};
    uint32_t len = 0;

    sid = printContainer(res, trans_unit, integer_restype, NULL, id, status);

    write_tabs(out);

    write_utf8_file(out, UnicodeString(source));

    len = itostr(buf, res->fValue, 10, 0);
    write_utf8_file(out, UnicodeString(buf, len));

    write_utf8_file(out, UnicodeString(close_source));

    printNoteElements(&res->fComment, status);

    tabCount -= 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(close_trans_unit));

    uprv_free(sid);
    sid = NULL;
}

static void
bin_write_xml(BinaryResource *res, const char* id, const char* /*language*/, UErrorCode *status) {
    const char* m_type = application_mimetype;
    char* sid = NULL;
    uint32_t crc = 0xFFFFFFFF;

    char fileName[1024] ={0};
    int32_t tLen = ( outDir == NULL) ? 0 :(int32_t)uprv_strlen(outDir);
    char* fn =  (char*) uprv_malloc(sizeof(char) * (tLen+1024 +
                                                    (res->fFileName !=NULL ?
                                                    uprv_strlen(res->fFileName) :0)));
    const char* ext = NULL;

    char* f = NULL;

    fn[0]=0;

    if(res->fFileName != NULL){
        uprv_strcpy(fileName, res->fFileName);
        f = uprv_strrchr(fileName, '\\');

        if (f != NULL) {
            f++;
        } else {
            f = fileName;
        }

        ext = uprv_strrchr(fileName, '.');

        if (ext == NULL) {
            fprintf(stderr, "Error: %s is an unknown binary filename type.\n", fileName);
            exit(U_ILLEGAL_ARGUMENT_ERROR);
        }

        if(uprv_strcmp(ext, ".jpg")==0 || uprv_strcmp(ext, ".jpeg")==0 || uprv_strcmp(ext, ".gif")==0 ){
            m_type = "image";
        } else if(uprv_strcmp(ext, ".wav")==0 || uprv_strcmp(ext, ".au")==0 ){
            m_type = "audio";
        } else if(uprv_strcmp(ext, ".avi")==0 || uprv_strcmp(ext, ".mpg")==0 || uprv_strcmp(ext, ".mpeg")==0){
            m_type = "video";
        } else if(uprv_strcmp(ext, ".txt")==0 || uprv_strcmp(ext, ".text")==0){
            m_type = "text";
        }

        sid = printContainer(res, bin_unit, binary_restype, m_type, id, status);

        write_tabs(out);

        write_utf8_file(out, UnicodeString(bin_source));

        tabCount+= 1;
        write_tabs(out);

        write_utf8_file(out, UnicodeString(external_file));
        printAttribute("href", f, (int32_t)uprv_strlen(f));
        write_utf8_file(out, UnicodeString("/>\n"));
        tabCount -= 1;
        write_tabs(out);

        write_utf8_file(out, UnicodeString(close_bin_source));

        printNoteElements(&res->fComment, status);
        tabCount -= 1;
        write_tabs(out);
        write_utf8_file(out, UnicodeString(close_bin_unit));
    } else {
        char temp[256] = {0};
        uint32_t i = 0;
        int32_t len=0;

        sid = printContainer(res, bin_unit, binary_restype, m_type, id, status);

        write_tabs(out);
        write_utf8_file(out, UnicodeString(bin_source));

        tabCount += 1;
        write_tabs(out);

        write_utf8_file(out, UnicodeString(internal_file));
        printAttribute("form", application_mimetype, (int32_t) uprv_strlen(application_mimetype));

        while(i <res->fLength){
            len = itostr(temp, res->fData[i], 16, 2);
            crc = computeCRC(temp, len, crc);
            i++;
        }

        len = itostr(temp, crc, 10, 0);
        printAttribute("crc", temp, len);

        write_utf8_file(out, UnicodeString(">"));

        i = 0;
        while(i <res->fLength){
            len = itostr(temp, res->fData[i], 16, 2);
            write_utf8_file(out, UnicodeString(temp));
            i += 1;
        }

        write_utf8_file(out, UnicodeString(close_internal_file));

        tabCount -= 2;
        write_tabs(out);

        write_utf8_file(out, UnicodeString(close_bin_source));
        printNoteElements(&res->fComment, status);

        tabCount -= 1;
        write_tabs(out);
        write_utf8_file(out, UnicodeString(close_bin_unit));

        uprv_free(sid);
        sid = NULL;
    }

    uprv_free(fn);
}

static void
table_write_xml(TableResource *res, const char* id, const char* language, UBool isTopLevel, UErrorCode *status) {

    uint32_t  i         = 0;

    struct SResource *current = NULL;
    char* sid = NULL;

    if (U_FAILURE(*status)) {
        return ;
    }

    sid = printContainer(res, group, table_restype, NULL, id, status);

    if(isTopLevel) {
        sid[0] = '\0';
    }

    current = res->fFirst;
    i = 0;

    while (current != NULL) {
        res_write_xml(current, sid, language, FALSE, status);

        if(U_FAILURE(*status)){
            return;
        }

        i += 1;
        current = current->fNext;
    }

    tabCount -= 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(close_group));

    uprv_free(sid);
    sid = NULL;
}

void
res_write_xml(struct SResource *res, const char* id,  const char* language, UBool isTopLevel, UErrorCode *status) {

    if (U_FAILURE(*status)) {
        return ;
    }

    if (res != NULL) {
        switch (res->fType) {
        case URES_STRING:
             string_write_xml    (static_cast<StringResource *>(res), id, language, status);
             return;

        case URES_ALIAS:
             alias_write_xml     (static_cast<AliasResource *>(res), id, language, status);
             return;

        case URES_INT_VECTOR:
             intvector_write_xml (static_cast<IntVectorResource *>(res), id, language, status);
             return;

        case URES_BINARY:
             bin_write_xml       (static_cast<BinaryResource *>(res), id, language, status);
             return;

        case URES_INT:
             int_write_xml       (static_cast<IntResource *>(res), id, language, status);
             return;

        case URES_ARRAY:
             array_write_xml     (static_cast<ArrayResource *>(res), id, language, status);
             return;

        case URES_TABLE:
             table_write_xml     (static_cast<TableResource *>(res), id, language, isTopLevel, status);
             return;

        default:
            break;
        }
    }

    *status = U_INTERNAL_PROGRAM_ERROR;
}

void
bundle_write_xml(struct SRBRoot *bundle, const char *outputDir,const char* outputEnc, const char* filename,
                  char *writtenFilename, int writtenFilenameLen,
                  const char* language, const char* outFileName, UErrorCode *status) {

    char* xmlfileName = NULL;
    char* outputFileName = NULL;
    char* originalFileName = NULL;
    const char* fileStart = "<file xml:space = \"preserve\" source-language = \"";
    const char* file1 = "\" datatype = \"x-icu-resource-bundle\" ";
    const char* file2 = "original = \"";
    const char* file4 = "\" date = \"";
    const char* fileEnd = "</file>\n";
    const char* headerStart = "<header>\n";
    const char* headerEnd = "</header>\n";
    const char* bodyStart = "<body>\n";
    const char* bodyEnd = "</body>\n";

    const char *tool_start = "<tool";
    const char *tool_id = "genrb-" GENRB_VERSION "-icu-" U_ICU_VERSION;
    const char *tool_name = "genrb";

    char* temp = NULL;
    char* lang = NULL;
    const char* pos = NULL;
    int32_t first, index;
    time_t currTime;
    char timeBuf[128];

    outDir = outputDir;

    srBundle = bundle;

    pos = uprv_strrchr(filename, '\\');
    if(pos != NULL) {
        first = (int32_t)(pos - filename + 1);
    } else {
        first = 0;
    }
    index = (int32_t)(uprv_strlen(filename) - uprv_strlen(textExt) - first);
    originalFileName = (char *)uprv_malloc(sizeof(char)*index+1);
    uprv_memset(originalFileName, 0, sizeof(char)*index+1);
    uprv_strncpy(originalFileName, filename + first, index);

    if(uprv_strcmp(originalFileName, srBundle->fLocale) != 0) {
        fprintf(stdout, "Warning: The file name is not same as the resource name!\n");
    }

    temp = originalFileName;
    originalFileName = (char *)uprv_malloc(sizeof(char)* (uprv_strlen(temp)+uprv_strlen(textExt)) + 1);
    uprv_memset(originalFileName, 0, sizeof(char)* (uprv_strlen(temp)+uprv_strlen(textExt)) + 1);
    uprv_strcat(originalFileName, temp);
    uprv_strcat(originalFileName, textExt);
    uprv_free(temp);
    temp = NULL;

    if (language == NULL) {
/*        lang = parseFilename(filename, lang);
        if (lang == NULL) {*/
            /* now check if locale name is valid or not
             * this is to cater for situation where
             * pegasusServer.txt contains
             *
             * en{
             *      ..
             * }
             */
             lang = parseFilename(srBundle->fLocale, lang);
             /*
              * Neither  the file name nor the table name inside the
              * txt file contain a valid country and language codes
              * throw an error.
              * pegasusServer.txt contains
              *
              * testelements{
              *     ....
              * }
              */
             if(lang==NULL){
                 fprintf(stderr, "Error: The file name and table name do not contain a valid language code. Please use -l option to specify it.\n");
                 exit(U_ILLEGAL_ARGUMENT_ERROR);
             }
       /* }*/
    } else {
        lang = (char *)uprv_malloc(sizeof(char)*uprv_strlen(language) +1);
        uprv_memset(lang, 0, sizeof(char)*uprv_strlen(language) +1);
        uprv_strcpy(lang, language);
    }

    if(outFileName) {
        outputFileName = (char *)uprv_malloc(sizeof(char)*uprv_strlen(outFileName) + 1);
        uprv_memset(outputFileName, 0, sizeof(char)*uprv_strlen(outFileName) + 1);
        uprv_strcpy(outputFileName,outFileName);
    } else {
        outputFileName = (char *)uprv_malloc(sizeof(char)*uprv_strlen(srBundle->fLocale) + 1);
        uprv_memset(outputFileName, 0, sizeof(char)*uprv_strlen(srBundle->fLocale) + 1);
        uprv_strcpy(outputFileName,srBundle->fLocale);
    }

    if(outputDir) {
        xmlfileName = (char *)uprv_malloc(sizeof(char)*(uprv_strlen(outputDir) + uprv_strlen(outputFileName) + uprv_strlen(xliffExt) + 1) +1);
        uprv_memset(xmlfileName, 0, sizeof(char)*(uprv_strlen(outputDir)+ uprv_strlen(outputFileName) + uprv_strlen(xliffExt) + 1) +1);
    } else {
        xmlfileName = (char *)uprv_malloc(sizeof(char)*(uprv_strlen(outputFileName) + uprv_strlen(xliffExt)) +1);
        uprv_memset(xmlfileName, 0, sizeof(char)*(uprv_strlen(outputFileName) + uprv_strlen(xliffExt)) +1);
    }

    if(outputDir){
        uprv_strcpy(xmlfileName, outputDir);
        if(outputDir[uprv_strlen(outputDir)-1] !=U_FILE_SEP_CHAR){
            uprv_strcat(xmlfileName,U_FILE_SEP_STRING);
        }
    }
    uprv_strcat(xmlfileName,outputFileName);
    uprv_strcat(xmlfileName,xliffExt);

    if (writtenFilename) {
        uprv_strncpy(writtenFilename, xmlfileName, writtenFilenameLen);
    }

    if (U_FAILURE(*status)) {
        goto cleanup_bundle_write_xml;
    }

    out= T_FileStream_open(xmlfileName,"w");

    if(out==NULL){
        *status = U_FILE_ACCESS_ERROR;
        goto cleanup_bundle_write_xml;
    }
    write_utf8_file(out, UnicodeString(xmlHeader));

    if(outputEnc && *outputEnc!='\0'){
        /* store the output encoding */
        enc = outputEnc;
        conv=ucnv_open(enc,status);
        if(U_FAILURE(*status)){
            goto cleanup_bundle_write_xml;
        }
    }
    write_utf8_file(out, UnicodeString(bundleStart));
    write_tabs(out);
    write_utf8_file(out, UnicodeString(fileStart));
    /* check if lang and language are the same */
    if(language != NULL && uprv_strcmp(lang, srBundle->fLocale)!=0){
        fprintf(stderr,"Warning: The top level tag in the resource and language specified are not the same. Please check the input.\n");
    }
    write_utf8_file(out, UnicodeString(lang));
    write_utf8_file(out, UnicodeString(file1));
    write_utf8_file(out, UnicodeString(file2));
    write_utf8_file(out, UnicodeString(originalFileName));
    write_utf8_file(out, UnicodeString(file4));

    time(&currTime);
    strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&currTime));
    write_utf8_file(out, UnicodeString(timeBuf));
    write_utf8_file(out, UnicodeString("\">\n"));

    tabCount += 1;
    write_tabs(out);
    write_utf8_file(out, UnicodeString(headerStart));

    tabCount += 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(tool_start));
    printAttribute("tool-id", tool_id, (int32_t) uprv_strlen(tool_id));
    printAttribute("tool-name", tool_name, (int32_t) uprv_strlen(tool_name));
    write_utf8_file(out, UnicodeString("/>\n"));

    tabCount -= 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(headerEnd));

    write_tabs(out);
    tabCount += 1;

    write_utf8_file(out, UnicodeString(bodyStart));

    res_write_xml(bundle->fRoot, bundle->fLocale, lang, TRUE, status);

    tabCount -= 1;
    write_tabs(out);

    write_utf8_file(out, UnicodeString(bodyEnd));
    tabCount--;
    write_tabs(out);
    write_utf8_file(out, UnicodeString(fileEnd));
    tabCount--;
    write_tabs(out);
    write_utf8_file(out, UnicodeString(bundleEnd));
    T_FileStream_close(out);

    ucnv_close(conv);

cleanup_bundle_write_xml:
    uprv_free(originalFileName);
    uprv_free(lang);
    if(xmlfileName != NULL) {
        uprv_free(xmlfileName);
    }
    if(outputFileName != NULL){
        uprv_free(outputFileName);
    }
}


text:
@interface EMViewController ()

@end

@implementation EMViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    EMCalculatorView *calc = [[[NSBundle mainBundle]loadNibNamed:@"EMCalculatorView" owner:self options:nil] objectAtIndex:0];
    [self.view addSubview:calc];
    [EMStyles styleCalculator:calc];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//memanggil file base untuk melakukan penurunan
require_once 'application/controllers/base/base.php';
class login extends base {
	//membuat construktor
	public function __construct() {
		parent::__construct();
	}
	public function index() {
		echo '
403 : FORBIDEN
';
	}
	public function facebook(){
	}
}