text:
package pt.up.pteid4j.pkcs.signer;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import pt.up.pteid4j.PTeID4JUtils;

/**
 * PTeID4J PKCS Signer Test Class
 *
 * @author Andre Barbosa (andremanuelbarbosa@gmail.com)
 */
public class PTeID4JPKCSSignerTest {

  private static Logger logger = Logger.getLogger(PTeID4JPKCSSignerTest.class);

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {

    logger.info("Testing PTeID4JPKCSSigner...");
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {

    logger.info("Done Testing PTeID4JPKCSSigner.");
  }

  @Before
  public void setUp() throws Exception {

  }

  @After
  public void tearDown() throws Exception {

  }

  @Test
  public void testSignWithBytes() throws PTeID4JPKCSSignerException {

    logger.info("Testing PTeID4JPKCSSigner.sign(Bytes)...");

    byte[] signature = PTeID4JPKCSSigner.sign("PTeID4J".getBytes());

    String signatureHex = "DFF1DDECA2E7ABB0231B286D05F76911C0D4F3C4547F90F86CF8CCEBCB4EC855AE8FE5165B32998F729A5A170E76C14C0ECCF7D9DF75DB1A8EDC2EB4EDBD262DBAC5EAB66C44B4129CA0BD3ED5C0004840FD4EA45BB4E40CEC0307D3DB12A5C1583338FFD42271D4134EB33B2CC01A49DB35981FEFFF28A2CFC9F59607820ED9";

    Assert.assertNotNull(signature);
    Assert.assertEquals(128, signature.length);
    Assert.assertEquals(signatureHex, PTeID4JUtils.toHexString(signature));

    logger.info("Done Testing PTeID4JPKCSSigner.sign(Bytes).");
  }

  @Test
  public void testSignWithString() throws PTeID4JPKCSSignerException {

    logger.info("Testing PTeID4JPKCSSigner.sign(String)...");

    byte[] signature = PTeID4JPKCSSigner.sign("PTeID4J");

    String signatureHex = "DFF1DDECA2E7ABB0231B286D05F76911C0D4F3C4547F90F86CF8CCEBCB4EC855AE8FE5165B32998F729A5A170E76C14C0ECCF7D9DF75DB1A8EDC2EB4EDBD262DBAC5EAB66C44B4129CA0BD3ED5C0004840FD4EA45BB4E40CEC0307D3DB12A5C1583338FFD42271D4134EB33B2CC01A49DB35981FEFFF28A2CFC9F59607820ED9";

    Assert.assertNotNull(signature);
    Assert.assertEquals(128, signature.length);
    Assert.assertEquals(signatureHex, PTeID4JUtils.toHexString(signature));

    logger.info("Done Testing PTeID4JPKCSSigner.sign(String).");
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Nest
{
	/// <summary>
	/// Marker interface for alias operation
	/// </summary>
	public interface IAliasAction { }
}


text:
<?php

$x = <<<EOT
    this is some string literal
    EOT;
echo $x;
$y = <<<'EOT'
		this is a string literal with tabs
		more tabs
		EOT;

$y = <<<"EOT"
	  this is a string literal with only tabs before EOT
	 one space
	EOT;
echo $y;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to Apereo under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Apereo licenses this file to you 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 the following location:

      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.

-->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <list>
                <bean class="org.apereo.portal.url.GuestSessionExpirationInterceptor">
                    <!--
                    <property name="unauthenticatedUserSessionTimeout" value="${org.apereo.portal.PortalSessionManager.unauthenticatedUserSessionTimeout}" />
                     -->
                </bean>
                <bean class="org.apereo.portal.url.MaxInactiveInterceptor"/>
                <ref bean="requestParameterProcessorInterceptor"/>
            </list>
        </property>
    </bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <!-- even though context:component-scan is defined in applicationContext, we need an additional reference
    for this context as it's unique to the DispatcherServlet -->
    <context:component-scan base-package="org.apereo.portal.json.rendering"/>

</beans>


text:
package uk.gov.hmrc.ct.accounts

import uk.gov.hmrc.ct.box.{CtBoxIdentifier, CtOptionalInteger, Input, MustBeNoneOrZeroOrPositive}

case class AC28(value: Option[Int]) extends CtBoxIdentifier(name = "Current Interest receivable and similar income")
                                    with CtOptionalInteger with MustBeNoneOrZeroOrPositive with Input


text:
""" Database models for bookmarks """

from django.contrib.auth.models import User
from django.db import models
from django.template import defaultfilters
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from django.utils.timezone import make_aware
from pytz import utc

from tags.models import Tag, Taggable
from tags import taggable
from bookmarks.templatetags.bookmark import bookmark
from users.models import Settings
from autotags.models import Autotag

from six.moves.html_parser import HTMLParser
from six.moves.urllib.robotparser import RobotFileParser
from six.moves.urllib.parse import urlparse
import json
import requests

from datetime import datetime
import six

_DT_FORMAT = "%a, %d %b %Y %H:%M:%S +0000"

@taggable("bookmark")
class Bookmark(Taggable):
    """ A single bookmark

    Contains:
    - owner:ForeignKey to User
    - title:TextField
    - url:TextField
    - tags:ManyToManyField to Tag
    - added:DateTimeField

    The owner of a bookmark is the user that added it. A bookmark can only be associated with one user, even if multiple
    users register the same URL.

    Bookmarks are ordered latest to oldest.
    """
    owner = models.ForeignKey(User)
    title = models.CharField(max_length=200, db_index=True)
    url = models.CharField(max_length=500, db_index=True)
    tags = models.ManyToManyField(Tag, related_name="bookmarks")
    added = models.DateTimeField(auto_now_add=True)
    valid_url = models.BooleanField(default=False)

    class Meta:
        ordering = ["-added"]

    def __str__(self):
        return ("Bookmark '"+self.title+"' for "+self.owner.username).encode("ascii", "ignore").decode("ascii")

    def save(self, *args, **kwargs):
        """ Override of save method to validate url and set the appropriate setting """
        uv = URLValidator()

        try:
            uv(self.url)
            self.valid_url = True
        except:
            self.valid_url = False

        super(Bookmark, self).save(*args, **kwargs)

    @property
    def do_link(self):
        """ Returns a boolean indicating whether the bookmark should be formatted as a link

        It takes its owners preference and whether this is a valid URL into account.
        """
        return self.valid_url or self.owner.settings.url_settings == Settings.URL_SETTINGS_LINK

    @property
    def url_domain(self):
        """ Returns the scheme and domain for this bookmark's URL or None

        That is, https://somedomain.tld/path/to/file goes to https://somedomain.tld.

        Returns None if the URL isn't a valid URL.
        """
        if self.valid_url:
            return "{uri.scheme}://{uri.netloc}".format(uri=urlparse(self.url))
        else:
            return None

    def download_title(self):
        """ Downloads the title of the bookmark

        This may fail silently. If it does, it sets the title to "Unknown Title".
        """
        self.title = "Unknown Title"

        try:
            url = urlparse(self.url)
            robots = "{}://{}/robots.txt".format(url.scheme, url.netloc)

            rfp = RobotFileParser(robots)
            rfp.read()

            if rfp.can_fetch("BMAT", self.url):
                r = requests.get(self.url, timeout=3.0, headers={"User-Agent": "BMAT"})
                r.raise_for_status()

                p = HTMLTitleReader()
                p.feed(r.text)

                self.title = p.title
                self.save()

        except:
            return

    def to_dir(self):
        """ Returns a dictionary representation of this tag

        The keys of the object are the field names, and the values are the respective values.

        Tags are a list of dicts representing tags as per Tag.to_dir().
        """
        out = {}
        out["title"] = self.title
        out["url"] = self.url
        out["id"] = self.pk
        out["added"] = self.added.astimezone(utc).strftime(_DT_FORMAT)
        out["tags"] = []
        out["valid_url"] = self.valid_url

        for t in self.tags.all():
            out["tags"].append(t.to_dir())

        return out

    def to_json(self):
        """ Produces the JSON representation of this bookmark

        It's the JSON for the output of to_dir()
        """
        return json.dumps(self.to_dir())

    @staticmethod
    def from_json(jsonData, user):
        """ Given the JSON representation of the bookmark, creates one for it

        Note that this SAVES the object to the database.

        If the "added" property of the object is absent, one will be created with the current date.
        """
        obj = json.loads(jsonData)

        bm = Bookmark(owner=user, title=obj["title"], url=obj["url"],
            valid_url=obj["valid_url"]
        )

        bm.save()

        if "added" in obj:
            bm.added = make_aware(datetime.strptime(obj["added"], _DT_FORMAT), utc)

        for t in obj["tags"]:
            if isinstance(t, six.string_types):
                bm.tag(t)
            else:
                bm.tag(t["id"])

        bm.save()

        return bm

    def autotag_rules(self):
        """ Loops through all the autotag instances, and applies them

        Basically, loops through them all and if their pattern matches, it applies all the tags.
        """
        #TODO: Should see if I should do this in the database
        for t in Autotag.check_url(self.owner, self.url):
            self.tag(t)

    @staticmethod
    def by_user(user):
        """ Get all the bookmarks owned by a given user """
        return Bookmark.objects.all().filter(owner=user)

class HTMLTitleReader(HTMLParser):
    """ A HTML parser for extracting the title of a HTML page

    It sets a flag on when it encounters a title, and closes it when the title is closed, reading the data only when
    the flag is on.
    """
    def __init__(self):
        self._title = ""
        self._open = False
        self._nomore = False
        HTMLParser.__init__(self)

    def handle_starttag(self, tag, attrs):
        if tag == "title":
            self._open = True

    def handle_endtag(self, tag):
        if tag == "title":
            self._open = False

        if tag in ["title", "head"]:
            self._nomore = True

    def handle_data(self, data):
        if self._open and not self._nomore:
            self._title += data

    @property
    def title(self):
        if self._open:
            return ""

        return self._title


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package de.tum.socialcomp.android;

public final class Manifest {
    public static final class permission {
        public static final String C2D_MESSAGE="de.tum.socialcomp.android.C2D_MESSAGE";
    }
}


text:
namespace ash::cellular_setup {

FakeOtaActivator::FakeOtaActivator(base::OnceClosure on_finished_callback)
    : OtaActivator(std::move(on_finished_callback)) {}

FakeOtaActivator::~FakeOtaActivator() = default;

void FakeOtaActivator::OnCarrierPortalStatusChange(
    mojom::CarrierPortalStatus status) {
  fake_carrier_portal_handler_.OnCarrierPortalStatusChange(status);
}

}  // namespace ash::cellular_setup


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width" />
    <meta charset="utf-8">
    <base href="https://wordbit.com">
    <title> Public Relations </title>
    <link rel="canonical" href="https://wordbit.com/categories/public-relations/">

<link rel="stylesheet" href="/css/poole.css">

<link rel="stylesheet" href="/css/lanyon.css">
<link rel="stylesheet" href="/css/custom.css">

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox"
       xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">

    Home
    All Blog Posts
    Status Updates
    About

      © 2021. All rights reserved.

      wordbit

Posts about “Public Relations”

 Canada's most livable cities

Thu, May 1, 2008

    Canadian Business magazine has just released their annual report on Canada’s best places to live. Our cold and sober capital, Ottawa, graced the number one spot based on factors like household income, unemployment rate, and new cars (New cars? Really? What does splashing out on some smoking wheels have to do with livability?). Vancouver shuffled in at number 10. And what impoverished, crappy-car-driving town came in last at number 154?

        <nobr>Read more →</nobr>


text:
package com.google.zxing.datamatrix.encoder;

import com.google.zxing.Dimension;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in
 * annex S.
 */
public final class HighLevelEncoder {

  /**
   * Padding character
   */
  private static final char PAD = 129;
  /**
   * mode latch to C40 encodation mode
   */
  static final char LATCH_TO_C40 = 230;
  /**
   * mode latch to Base 256 encodation mode
   */
  static final char LATCH_TO_BASE256 = 231;
  /**
   * FNC1 Codeword
   */
  //private static final char FNC1 = 232;
  /**
   * Structured Append Codeword
   */
  //private static final char STRUCTURED_APPEND = 233;
  /**
   * Reader Programming
   */
  //private static final char READER_PROGRAMMING = 234;
  /**
   * Upper Shift
   */
  static final char UPPER_SHIFT = 235;
  /**
   * 05 Macro
   */
  private static final char MACRO_05 = 236;
  /**
   * 06 Macro
   */
  private static final char MACRO_06 = 237;
  /**
   * mode latch to ANSI X.12 encodation mode
   */
  static final char LATCH_TO_ANSIX12 = 238;
  /**
   * mode latch to Text encodation mode
   */
  static final char LATCH_TO_TEXT = 239;
  /**
   * mode latch to EDIFACT encodation mode
   */
  static final char LATCH_TO_EDIFACT = 240;
  /**
   * ECI character (Extended Channel Interpretation)
   */
  //private static final char ECI = 241;

  /**
   * Unlatch from C40 encodation
   */
  static final char C40_UNLATCH = 254;
  /**
   * Unlatch from X12 encodation
   */
  static final char X12_UNLATCH = 254;

  /**
   * 05 Macro header
   */
  private static final String MACRO_05_HEADER = "[)>\u001E05\u001D";
  /**
   * 06 Macro header
   */
  private static final String MACRO_06_HEADER = "[)>\u001E06\u001D";
  /**
   * Macro trailer
   */
  private static final String MACRO_TRAILER = "\u001E\u0004";

  static final int ASCII_ENCODATION = 0;
  static final int C40_ENCODATION = 1;
  static final int TEXT_ENCODATION = 2;
  static final int X12_ENCODATION = 3;
  static final int EDIFACT_ENCODATION = 4;
  static final int BASE256_ENCODATION = 5;

  private HighLevelEncoder() {
  }

  /**
   * Converts the message to a byte array using the default encoding (cp437) as defined by the
   * specification
   *
   * @param msg the message
   * @return the byte array of the message
   */
  public static byte[] getBytesForMessage(String msg) {
    return msg.getBytes(Charset.forName("cp437")); //See 4.4.3 and annex B of ISO/IEC 15438:2001(E)
  }

  private static char randomize253State(char ch, int codewordPosition) {
    int pseudoRandom = ((149 * codewordPosition) % 253) + 1;
    int tempVariable = ch + pseudoRandom;
    return tempVariable <= 254 ? (char) tempVariable : (char) (tempVariable - 254);
  }

  /**
   * Performs message encoding of a DataMatrix message using the algorithm described in annex P
   * of ISO/IEC 16022:2000(E).
   *
   * @param msg the message
   * @return the encoded message (the char values range from 0 to 255)
   */
  public static String encodeHighLevel(String msg) {
    return encodeHighLevel(msg, SymbolShapeHint.FORCE_NONE, null, null);
  }

  /**
   * Performs message encoding of a DataMatrix message using the algorithm described in annex P
   * of ISO/IEC 16022:2000(E).
   *
   * @param msg     the message
   * @param shape   requested shape. May be {@code SymbolShapeHint.FORCE_NONE},
   *                {@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}.
   * @param minSize the minimum symbol size constraint or null for no constraint
   * @param maxSize the maximum symbol size constraint or null for no constraint
   * @return the encoded message (the char values range from 0 to 255)
   */
  public static String encodeHighLevel(String msg,
                                       SymbolShapeHint shape,
                                       Dimension minSize,
                                       Dimension maxSize) {
    //the codewords 0..255 are encoded as Unicode characters
    Encoder[] encoders = {
        new ASCIIEncoder(), new C40Encoder(), new TextEncoder(),
        new X12Encoder(), new EdifactEncoder(),  new Base256Encoder()
    };

    EncoderContext context = new EncoderContext(msg);
    context.setSymbolShape(shape);
    context.setSizeConstraints(minSize, maxSize);

    if (msg.startsWith(MACRO_05_HEADER) && msg.endsWith(MACRO_TRAILER)) {
      context.writeCodeword(MACRO_05);
      context.setSkipAtEnd(2);
      context.pos += MACRO_05_HEADER.length();
    } else if (msg.startsWith(MACRO_06_HEADER) && msg.endsWith(MACRO_TRAILER)) {
      context.writeCodeword(MACRO_06);
      context.setSkipAtEnd(2);
      context.pos += MACRO_06_HEADER.length();
    }

    int encodingMode = ASCII_ENCODATION; //Default mode
    while (context.hasMoreCharacters()) {
      encoders[encodingMode].encode(context);
      if (context.getNewEncoding() >= 0) {
        encodingMode = context.getNewEncoding();
        context.resetEncoderSignal();
      }
    }
    int len = context.getCodewordCount();
    context.updateSymbolInfo();
    int capacity = context.getSymbolInfo().getDataCapacity();
    if (len < capacity) {
      if (encodingMode != ASCII_ENCODATION && encodingMode != BASE256_ENCODATION) {
        context.writeCodeword('\u00fe'); //Unlatch (254)
      }
    }
    //Padding
    StringBuilder codewords = context.getCodewords();
    if (codewords.length() < capacity) {
      codewords.append(PAD);
    }
    while (codewords.length() < capacity) {
      codewords.append(randomize253State(PAD, codewords.length() + 1));
    }

    return context.getCodewords().toString();
  }

  static int lookAheadTest(CharSequence msg, int startpos, int currentMode) {
    if (startpos >= msg.length()) {
      return currentMode;
    }
    float[] charCounts;
    //step J
    if (currentMode == ASCII_ENCODATION) {
      charCounts = new float[]{0, 1, 1, 1, 1, 1.25f};
    } else {
      charCounts = new float[]{1, 2, 2, 2, 2, 2.25f};
      charCounts[currentMode] = 0;
    }

    int charsProcessed = 0;
    while (true) {
      //step K
      if ((startpos + charsProcessed) == msg.length()) {
        int min = Integer.MAX_VALUE;
        byte[] mins = new byte[6];
        int[] intCharCounts = new int[6];
        min = findMinimums(charCounts, intCharCounts, min, mins);
        int minCount = getMinimumCount(mins);

        if (intCharCounts[ASCII_ENCODATION] == min) {
          return ASCII_ENCODATION;
        }
        if (minCount == 1 && mins[BASE256_ENCODATION] > 0) {
          return BASE256_ENCODATION;
        }
        if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) {
          return EDIFACT_ENCODATION;
        }
        if (minCount == 1 && mins[TEXT_ENCODATION] > 0) {
          return TEXT_ENCODATION;
        }
        if (minCount == 1 && mins[X12_ENCODATION] > 0) {
          return X12_ENCODATION;
        }
        return C40_ENCODATION;
      }

      char c = msg.charAt(startpos + charsProcessed);
      charsProcessed++;

      //step L
      if (isDigit(c)) {
        charCounts[ASCII_ENCODATION] += 0.5;
      } else if (isExtendedASCII(c)) {
        charCounts[ASCII_ENCODATION] = (int) Math.ceil(charCounts[ASCII_ENCODATION]);
        charCounts[ASCII_ENCODATION] += 2;
      } else {
        charCounts[ASCII_ENCODATION] = (int) Math.ceil(charCounts[ASCII_ENCODATION]);
        charCounts[ASCII_ENCODATION]++;
      }

      //step M
      if (isNativeC40(c)) {
        charCounts[C40_ENCODATION] += 2.0f / 3.0f;
      } else if (isExtendedASCII(c)) {
        charCounts[C40_ENCODATION] += 8.0f / 3.0f;
      } else {
        charCounts[C40_ENCODATION] += 4.0f / 3.0f;
      }

      //step N
      if (isNativeText(c)) {
        charCounts[TEXT_ENCODATION] += 2.0f / 3.0f;
      } else if (isExtendedASCII(c)) {
        charCounts[TEXT_ENCODATION] += 8.0f / 3.0f;
      } else {
        charCounts[TEXT_ENCODATION] += 4.0f / 3.0f;
      }

      //step O
      if (isNativeX12(c)) {
        charCounts[X12_ENCODATION] += 2.0f / 3.0f;
      } else if (isExtendedASCII(c)) {
        charCounts[X12_ENCODATION] += 13.0f / 3.0f;
      } else {
        charCounts[X12_ENCODATION] += 10.0f / 3.0f;
      }

      //step P
      if (isNativeEDIFACT(c)) {
        charCounts[EDIFACT_ENCODATION] += 3.0f / 4.0f;
      } else if (isExtendedASCII(c)) {
        charCounts[EDIFACT_ENCODATION] += 17.0f / 4.0f;
      } else {
        charCounts[EDIFACT_ENCODATION] += 13.0f / 4.0f;
      }

      // step Q
      if (isSpecialB256(c)) {
        charCounts[BASE256_ENCODATION] += 4;
      } else {
        charCounts[BASE256_ENCODATION]++;
      }

      //step R
      if (charsProcessed >= 4) {
        int[] intCharCounts = new int[6];
        byte[] mins = new byte[6];
        findMinimums(charCounts, intCharCounts, Integer.MAX_VALUE, mins);
        int minCount = getMinimumCount(mins);

        if (intCharCounts[ASCII_ENCODATION] < intCharCounts[BASE256_ENCODATION]
            && intCharCounts[ASCII_ENCODATION] < intCharCounts[C40_ENCODATION]
            && intCharCounts[ASCII_ENCODATION] < intCharCounts[TEXT_ENCODATION]
            && intCharCounts[ASCII_ENCODATION] < intCharCounts[X12_ENCODATION]
            && intCharCounts[ASCII_ENCODATION] < intCharCounts[EDIFACT_ENCODATION]) {
          return ASCII_ENCODATION;
        }
        if (intCharCounts[BASE256_ENCODATION] < intCharCounts[ASCII_ENCODATION]
            || (mins[C40_ENCODATION] + mins[TEXT_ENCODATION] + mins[X12_ENCODATION] + mins[EDIFACT_ENCODATION]) == 0) {
          return BASE256_ENCODATION;
        }
        if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) {
          return EDIFACT_ENCODATION;
        }
        if (minCount == 1 && mins[TEXT_ENCODATION] > 0) {
          return TEXT_ENCODATION;
        }
        if (minCount == 1 && mins[X12_ENCODATION] > 0) {
          return X12_ENCODATION;
        }
        if (intCharCounts[C40_ENCODATION] + 1 < intCharCounts[ASCII_ENCODATION]
            && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[BASE256_ENCODATION]
            && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[EDIFACT_ENCODATION]
            && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[TEXT_ENCODATION]) {
          if (intCharCounts[C40_ENCODATION] < intCharCounts[X12_ENCODATION]) {
            return C40_ENCODATION;
          }
          if (intCharCounts[C40_ENCODATION] == intCharCounts[X12_ENCODATION]) {
            int p = startpos + charsProcessed + 1;
            while (p < msg.length()) {
              char tc = msg.charAt(p);
              if (isX12TermSep(tc)) {
                return X12_ENCODATION;
              }
              if (!isNativeX12(tc)) {
                break;
              }
              p++;
            }
            return C40_ENCODATION;
          }
        }
      }
    }
  }

  private static int findMinimums(float[] charCounts, int[] intCharCounts, int min, byte[] mins) {
    Arrays.fill(mins, (byte) 0);
    for (int i = 0; i < 6; i++) {
      intCharCounts[i] = (int) Math.ceil(charCounts[i]);
      int current = intCharCounts[i];
      if (min > current) {
        min = current;
        Arrays.fill(mins, (byte) 0);
      }
      if (min == current) {
        mins[i]++;

      }
    }
    return min;
  }

  private static int getMinimumCount(byte[] mins) {
    int minCount = 0;
    for (int i = 0; i < 6; i++) {
      minCount += mins[i];
    }
    return minCount;
  }

  static boolean isDigit(char ch) {
    return ch >= '0' && ch <= '9';
  }

  static boolean isExtendedASCII(char ch) {
    return ch >= 128 && ch <= 255;
  }

  private static boolean isNativeC40(char ch) {
    return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
  }

  private static boolean isNativeText(char ch) {
    return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z');
  }

  private static boolean isNativeX12(char ch) {
    return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z');
  }

  private static boolean isX12TermSep(char ch) {
    return (ch == '\r') //CR
        || (ch == '*')
        || (ch == '>');
  }

  private static boolean isNativeEDIFACT(char ch) {
    return ch >= ' ' && ch <= '^';
  }

  private static boolean isSpecialB256(char ch) {
    return false; //TODO NOT IMPLEMENTED YET!!!
  }

  /**
   * Determines the number of consecutive characters that are encodable using numeric compaction.
   *
   * @param msg      the message
   * @param startpos the start position within the message
   * @return the requested character count
   */
  public static int determineConsecutiveDigitCount(CharSequence msg, int startpos) {
    int count = 0;
    int len = msg.length();
    int idx = startpos;
    if (idx < len) {
      char ch = msg.charAt(idx);
      while (isDigit(ch) && idx < len) {
        count++;
        idx++;
        if (idx < len) {
          ch = msg.charAt(idx);
        }
      }
    }
    return count;
  }

  static void illegalCharacter(char c) {
    String hex = Integer.toHexString(c);
    hex = "0000".substring(0, 4 - hex.length()) + hex;
    throw new IllegalArgumentException("Illegal character: " + c + " (0x" + hex + ')');
  }

}


text:
ManageIQ.angular.app = angular.module('ManageIQ', [
  'angular.validators', // FIXME: require('angular.validators'),
  'frapontillo.bootstrap-switch', // FIXME: require('angular-bootstrap-switch'),
  'gettext', // FIXME: require('angular-gettext'),
  'miq.api',
  'miq.card',
  'miq.compat',
  'miq.util',
  'miqStaticAssets',
  'miqStaticAssets.common',
  'miqStaticAssets.dialogEditor',
  'miqStaticAssets.dialogUser',
  'miqStaticAssets.fonticonPicker',
  'miqStaticAssets.miqSelect',
  'miqStaticAssets.treeSelector',
  'miqStaticAssets.treeView',
  'ngSanitize', // FIXME: require('angular-sanitize'),
  'patternfly',
  'patternfly.charts',
  'patternfly.views',
  'ui.bootstrap',
  'ui.codemirror',
]);
miqHttpInject(ManageIQ.angular.app);

ManageIQ.constants = {
  reportData: 'report_data',
};

function miqHttpInject(angular_app) {
  angular_app.config(['$locationProvider', function($locationProvider) {
    /**
     * hashPrefix must be empty othervise it will conflict with HashRouter and create infinite loop
     * React HashRouter can be configured to have hashbang prefix,
     * but both $locationProvider and ReactRouter must have the same prefix!
     */
    $locationProvider.hashPrefix('');
  }]);
  angular_app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common['X-Angular-Request'] = true;
    $httpProvider.defaults.headers.common['X-CSRF-Token'] = function() {
      return $('meta[name=csrf-token]').attr('content');
    };

    $httpProvider.interceptors.push(['$q', function($q) {
      return {
        responseError: function(err) {
          if (err.status === 401) {
            // Unauthorized - always redirect to dashboard#login
            redirectLogin(__('$http session timed out, redirecting to the login page'));
            return $q.reject(err);
          }

          sendDataWithRx({
            serverError: err,
            source: '$http',
            backendName: __('$http'),
          });

          console.error('$http: Server returned a non-200 response:', err.status, err.statusText, err);
          return $q.reject(err);
        },
      };
    }]);
  }]);

  return angular_app;
}

window.miq_bootstrap = function(selector, app) {
  app = app || 'ManageIQ';

  return angular.bootstrap($(selector), [app], { strictDi: true });
}


text:
<?php
require(__DIR__.'/../vendor/autoload.php');

use ddliu\spider\Spider;
use ddliu\spider\Pipe\NormalizeUrlPipe;
use ddliu\spider\Pipe\RequestPipe;
use ddliu\spider\Pipe\DomCrawlerPipe;

(new Spider())
    ->pipe(new NormalizeUrlPipe())
    ->pipe(new RequestPipe())
    ->pipe(new DomCrawlerPipe())
    ->pipe(function($spider, $task) {
	var_dump(array_keys($task->getData()));
        //$spider->logger->addInfo($task['url']."-pipe\n");
        if (!strpos($task['url'], 'tab=repositories')) return;
        $task['$dom']->filter('h3.repo-list-name>a')
            ->each(function($context) use ($task) {
		    $url = $context->attr('href');

        $spider->logger->addInfo($url.' frok');
                $task->fork($url);
            });
    })
    ->pipe(function($spider, $task) {
        if (!preg_match('#^https://github.com/[\w_]+/[\w_]+$#', $task['url'])) return;
        $issueCount = trim($task['$dom']->filter('li.commits span.num')->text());
        $spider->logger->addInfo($task['url'].' has '.$issueCount.' commits');
    })
    ->addTask('https://github.com/ddliu?tab=repositories')
    ->run()
    ->report();


text:
Notes
-------
This program is part of the radare project.

Hasher allows you to calculate, check and show the hash values of each block of a target file. The block size is 32768 bytes by default. It's allowed to hash from stdin using '-' as a target file.
You can hash big files by hashing each block and later determine what part of it has been modified. Useful for filesystem analysis.
This command can be used to calculate hashes of a certain part of a file or a command line passed string.

Help Text
-------
```
Usage: rahash2 [-rBv] [-b bsize] [-a algo] [-s str] [-f from] [-t to] [file] ...
 -a algo     comma separated list of algorithms (default is 'sha1')
 -b bsize    specify the size of the block (instead of full file)
 -B          show per-block hash
 -s string   hash this string instead of files
 -f from     start hashing at given address
 -t to       stop hashing at given address
 -r          output radare commands
 -v          show version information
Supported algorithms: md4, md5, sha1, sha256, sha384, sha512, crc16,
    crc32, xor, xorpair, parity, mod255, hamdist, entropy, pcprint

```

Example Usage
-------

Links
-------


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/component/armor/shared_armor_layer_acid.iff"
	result.attribute_template_id = -1
	result.stfName("craft_clothing_ingredients_n","armor_layer_acid")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
/**
 * @fileoverview Prevent direct mutation of this.state
 * @author David Petersen
 */

'use strict';

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const RuleTester = require('eslint').RuleTester;
const rule = require('../../../lib/rules/no-direct-mutation-state');

const parsers = require('../../helpers/parsers');

const parserOptions = {
  ecmaVersion: 2018,
  sourceType: 'module',
  ecmaFeatures: {
    jsx: true,
  },
};

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

const ruleTester = new RuleTester({ parserOptions });
ruleTester.run('no-direct-mutation-state', rule, {
  valid: parsers.all([
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            return
Hello {this.props.name}
;
          }
        });
      `,
    },
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            var obj = {state: {}};
            obj.state.name = "foo";
            return
Hello {obj.state.name}
;
          }
        });
      `,
    },
    {
      code: `
        var Hello = "foo";
        module.exports = {};
      `,
    },
    {
      code: `
        class Hello {
          getFoo() {
            this.state.foo = 'bar'
            return this.state.foo;
          }
        }
      `,
    },
    {
      code: `
        class Hello extends React.Component {
          constructor() {
            this.state.foo = "bar"
          }
        }
      `,
    },
    {
      code: `
        class Hello extends React.Component {
          constructor() {
            this.state.foo = 1;
          }
        }
      `,
    },
    {
      code: `
        class OneComponent extends Component {
          constructor() {
            super();
            class AnotherComponent extends Component {
              constructor() {
                super();
              }
            }
            this.state = {};
          }
        }
      `,
    },
  ]),

  invalid: parsers.all([
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            this.state.foo = "bar"
            return
Hello {this.props.name}
;
          }
        });
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            this.state.foo++;
            return
Hello {this.props.name}
;
          }
        });
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            this.state.person.name= "bar"
            return
Hello {this.props.name}
;
          }
        });
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            this.state.person.name.first = "bar"
            return
Hello
;
          }
        });
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            this.state.person.name.first = "bar"
            this.state.person.name.last = "baz"
            return
Hello
;
          }
        });
      `,
      errors: [
        {
          message: 'Do not mutate state directly. Use setState().',
          line: 4,
          column: 13,
        },
        {
          message: 'Do not mutate state directly. Use setState().',
          line: 5,
          column: 13,
        },
      ],
    },
    {
      code: `
        class Hello extends React.Component {
          constructor() {
            someFn()
          }
          someFn() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          constructor(props) {
            super(props)
            doSomethingAsync(() => {
              this.state = "bad";
            });
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          componentWillMount() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          componentDidMount() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          componentWillReceiveProps() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          shouldComponentUpdate() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          componentWillUpdate() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          componentDidUpdate() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    {
      code: `
        class Hello extends React.Component {
          componentWillUnmount() {
            this.state.foo = "bar"
          }
        }
      `,
      errors: [{ messageId: 'noDirectMutation' }],
    },
    /**
     * Would be nice to prevent this too
    {
      code: `
        var Hello = createReactClass({
          render: function() {
            var that = this;
            that.state.person.name.first = "bar"
            return
Hello
;
          }
        });
      `,
      errors: [{messageId: 'noDirectMutation'}]
    } */
  ]),
});


text:
package net.lshift.diffa.participants

import java.io.{FileFilter, File}

/**
 * Utility class for walking directories and finding all files within them.
 */
object DirWalker {
  def walk(path:String, acceptor:(File) => Boolean, handler:(File) => Unit) {
    val filter = new FileFilter {
      def accept(f: File) = {
        if (f.isDirectory) {
          walk(f, this, handler)
          false
        } else {
          acceptor(f)
        }
      }
    }
    walk(new File(path), filter, handler)
  }

  def walk(fdir:File, filter:FileFilter, handler:(File) => Unit) {
    val files = fdir.listFiles(filter)
    files.foreach(f => handler(f))
  }
}


text:
(function(angular){
    'use strict';

angular.module('ControlElectoralApp').controller('ParroquiaDialogCtrl',
    ['$scope', '$stateParams', '$uibModalInstance', 'entity', 'CantonParroquiaResource',
        function($scope, $stateParams, $modalInstance, entity, CantonParroquiaResource) {
        $scope.initData = function(id) {
            CantonParroquiaResource.get({id_canton:$stateParams.id, id : id}, function(result) {
                $scope.parroquia = result;
            });
        };
        var onSaveFinished = function (result) {
            $scope.$emit('fimepedApp:cantonUpdate', result);
            $modalInstance.close(result);
        };
        $scope.save = function () {
            if ($scope.parroquia._id != null) {
                CantonParroquiaResource.update({id_canton:$stateParams.id,id:$scope.parroquia._id}, $scope.parroquia, onSaveFinished);
            } else {
                CantonParroquiaResource.save({id_canton:$stateParams.id}, $scope.parroquia, onSaveFinished);
            }
        };
        $scope.clear = function() {
            $modalInstance.dismiss('cancel');
        };
        if(entity){
            $scope.initData(entity._id);
        }

}]);
}(window.angular));


text:
<Alloy>
	<Window class="container" layout="horizontal">
		<Label id="label">Subscribe Push Notification</Label>
		<Switch id="basicSwitch" onChange="ganti" titleOn="Nyala" titleOff="Mati" value=false></Switch>
	</Window>
</Alloy>


text:
import abc

from telemetry.page import page as page_module
from telemetry.page import traffic_setting as traffic_setting_module
from telemetry import story

# A complete list of page tags to check. This prevents misspellings and provides
# documentation of scenarios for code readers. These tags can be used to filter
# the list of pages to run using flags like --story-tag-filter=X.
_PAGE_TAGS_LIST = [
    # Audio codecs.
    'pcm',
    'mp3',
    'aac',
    'vorbis',
    'opus',
    # Video codecs.
    'av1',
    'h264',
    'vp8',
    'vp9',
    # Test types.
    'audio_video',
    'audio_only',
    'video_only',
    # Other filter tags.
    'is_50fps',
    'is_4k',
    # Play action.
    'seek',
    'beginning_to_end',
    'background',
    # Add javascript load.
    'busyjs',
    # Constrained network settings.
    'cns',
    # VideoStack API.
    'src',
    'mse'
]

# A list of traffic setting names to append to page names when used.
# Traffic settings is a way to constrain the network to match real-world
# scenarios.
_TRAFFIC_SETTING_NAMES = {
    traffic_setting_module.GPRS: 'GPRS',
    traffic_setting_module.REGULAR_2G: 'Regular-2G',
    traffic_setting_module.GOOD_2G: 'Good-2G',
    traffic_setting_module.REGULAR_3G: 'Regular-3G',
    traffic_setting_module.GOOD_3G: 'Good-3G',
    traffic_setting_module.REGULAR_4G: 'Regular-4G',
    traffic_setting_module.DSL: 'DSL',
    traffic_setting_module.WIFI: 'WiFi',
}

_URL_BASE = 'file://media_cases/'

#
# The following section contains base classes for pages.
#

class _MediaPage(page_module.Page):

  def __init__(self, url, page_set, tags, extra_browser_args=None,
               traffic_setting=traffic_setting_module.NONE):
    name = url.split('/')[-1]
    if traffic_setting != traffic_setting_module.NONE:
      name += '_' + _TRAFFIC_SETTING_NAMES[traffic_setting]
      tags.append('cns')
    if tags:
      for t in tags:
        assert t in _PAGE_TAGS_LIST
    assert not ('src' in tags and 'mse' in tags)
    super(_MediaPage, self).__init__(
        url=url, page_set=page_set, tags=tags, name=name,
        extra_browser_args=extra_browser_args,
        traffic_setting=traffic_setting)

  def GetExtraTracingMetrics(self):
    metrics = super(_MediaPage, self).GetExtraTracingMetrics()
    if self.ShouldMeasureMemory():
      metrics.append('memoryMetric')
    return metrics

  def ShouldMeasureMemory(self):
    """Returns whether the page should do a memory dump.

    Also controls whether the pages enables the memory metric.
    Subclasses should override to disable memory measurement.
    Memory dumps are cpu-intensive, so it is reasonable keep it off in
    some cases to avoid skewing cpu usage measurements.
    """
    return True

class _BeginningToEndPlayPage(_MediaPage):
  """A normal play page simply plays the given media until the end."""

  def __init__(self, url, page_set, tags, extra_browser_args=None,
               traffic_setting=traffic_setting_module.NONE):
    tags.append('beginning_to_end')
    tags.append('src')
    super(_BeginningToEndPlayPage, self).__init__(
        url, page_set, tags, extra_browser_args,
        traffic_setting=traffic_setting)

  def RunPageInteractions(self, action_runner):
    # Play the media until it has finished or it times out.
    action_runner.PlayMedia(playing_event_timeout_in_seconds=60,
                            ended_event_timeout_in_seconds=60)
    # Generate memory dump for memoryMetric.
    if self.ShouldMeasureMemory():
      action_runner.MeasureMemory()

class _SeekPage(_MediaPage):
  """A seek page seeks twice in the video and measures the seek time."""

  def __init__(self, url, page_set, tags, extra_browser_args=None,
               action_timeout_in_seconds=60,
               traffic_setting=traffic_setting_module.NONE):
    tags.append('seek')
    tags.append('src')
    self._action_timeout = action_timeout_in_seconds
    super(_SeekPage, self).__init__(
        url, page_set, tags, extra_browser_args,
        traffic_setting=traffic_setting)

  def RunPageInteractions(self, action_runner):
    timeout = self._action_timeout
    # Start the media playback.
    action_runner.PlayMedia(
        playing_event_timeout_in_seconds=timeout)
    # Wait for 1 second so that we know the play-head is at ~1s.
    action_runner.Wait(1)
    # Seek to before the play-head location.
    action_runner.SeekMedia(seconds=0.5, timeout_in_seconds=timeout,
                            label='seek_warm')
    # Seek to after the play-head location.
    action_runner.SeekMedia(seconds=9, timeout_in_seconds=timeout,
                            label='seek_cold')
    # Generate memory dump for memoryMetric.
    if self.ShouldMeasureMemory():
      action_runner.MeasureMemory()

class _BackgroundPlaybackPage(_MediaPage):
  """A Background playback page plays the given media in a background tab.

  The motivation for this test case is crbug.com/678663.
  """

  def __init__(self, url, page_set, tags, extra_browser_args=None,
               background_time=10,
               traffic_setting=traffic_setting_module.NONE):
    self._background_time = background_time
    tags.append('background')
    tags.append('src')
    # --disable-background-media-suspend is required since for Android,
    # background playback gets suspended. This flag makes Android work the same
    # way as desktop and not turn off video playback in the background.
    extra_browser_args = extra_browser_args or []
    extra_browser_args.append('--disable-background-media-suspend')
    super(_BackgroundPlaybackPage, self).__init__(
        url, page_set, tags, extra_browser_args)

  def RunPageInteractions(self, action_runner):
    # Steps:
    # 1. Play a video
    # 2. Open new tab overtop to obscure the video
    # 3. Close the tab to go back to the tab that is playing the video.
    action_runner.PlayMedia(
        playing_event_timeout_in_seconds=60)
    action_runner.Wait(.5)
    new_tab = action_runner.tab.browser.tabs.New()
    new_tab.Activate()
    action_runner.Wait(self._background_time)
    new_tab.Close()
    action_runner.Wait(.5)
    # Generate memory dump for memoryMetric.
    if self.ShouldMeasureMemory():
      action_runner.MeasureMemory()

class _MSEPage(_MediaPage):

  def __init__(self, url, page_set, tags, extra_browser_args=None,
               number_of_runs=10):
    assert number_of_runs >= 1
    self._number_of_runs = number_of_runs
    tags.append('mse')
    super(_MSEPage, self).__init__(
        url, page_set, tags, extra_browser_args)

  def RunPageInteractions(self, action_runner):
    # The page automatically runs the test at load time.
    self._CheckTestResult(action_runner)
    # Now run it a few more times to get more reliable data.
    # Note that each run takes ~.5s, so running a bunch of times to get reliable
    # data is reasonable.
    for _ in range(self._number_of_runs - 1):
      url = action_runner.tab.url
      action_runner.tab.ClearCache(force=True)
      action_runner.tab.Navigate(url)
      self._CheckTestResult(action_runner)

  def _CheckTestResult(self, action_runner):
    action_runner.WaitForJavaScriptCondition('window.__testDone == true')
    test_failed = action_runner.EvaluateJavaScript('window.__testFailed')
    if test_failed:
      raise RuntimeError(action_runner.EvaluateJavaScript('window.__testError'))

  def ShouldMeasureMemory(self):
    return False

def _GetDesktopOnlyMediaPages(page_set):
  return [
        _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip0.av1.mp4',
          page_set=page_set,
          tags=['av1', 'video_only']),
        _SeekPage(
          url=_URL_BASE + 'video.html?src=tulip0.av1.mp4&seek',
          page_set=page_set,
          tags=['av1', 'video_only', 'seek']),
        _MSEPage(
          url=_URL_BASE + 'mse.html?media=tulip0.av1.mp4',
          page_set=page_set,
          tags=['av1', 'video_only']),
        ]

def _GetCrossPlatformMediaPages(page_set):
  return [
      # 1080p 50fps crowd test cases. High non-60fps frame rate is good for
      # finding rendering and efficiency regressions.
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=crowd1080.webm',
          page_set=page_set,
          tags=['is_50fps', 'vp8', 'vorbis', 'audio_video']),
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=crowd1080.mp4',
          page_set=page_set,
          tags=['is_50fps', 'h264', 'aac', 'audio_video']),
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=crowd1080_vp9.webm',
          page_set=page_set,
          tags=['is_50fps', 'vp9', 'video_only']),

      # Audio only test cases. MP3 and OGG are important to test since they are
      # unstructured containers and thus are prone to efficiency regressions.
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip2.ogg&type=audio',
          page_set=page_set,
          tags=['vorbis', 'audio_only']),
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip2.mp3&type=audio',
          page_set=page_set,
          tags=['mp3', 'audio_only']),
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip2.m4a&type=audio',
          page_set=page_set,
          tags=['aac', 'audio_only']),

      # Baseline + busyjs test.
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip2.mp4',
          page_set=page_set,
          tags=['h264', 'aac', 'audio_video']),
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip2.mp4&busyjs',
          page_set=page_set,
          tags=['h264', 'aac', 'audio_video', 'busyjs']),

      # Baseline + WiFi test.
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip2.vp9.webm',
          page_set=page_set,
          tags=['vp9', 'opus', 'audio_video']),
      _BeginningToEndPlayPage(
          url=_URL_BASE + 'video.html?src=tulip2.vp9.webm',
          page_set=page_set,
          tags=['vp9', 'opus', 'audio_video'],
          traffic_setting=traffic_setting_module.WIFI),

      # Seek tests in MP3 and OGG are important since they don't have seek
      # indices and thus show off efficiency regressions easily.
      _SeekPage(
          url=_URL_BASE + 'video.html?src=tulip2.ogg&type=audio&seek',
          page_set=page_set,
          tags=['vorbis', 'audio_only']),
      _SeekPage(
          url=_URL_BASE + 'video.html?src=tulip2.mp3&type=audio&seek',
          page_set=page_set,
          tags=['mp3', 'audio_only']),

      # High resolution seek test cases which will exaggerate any decoding
      # efficiency or buffering regressions.
      _SeekPage(
          url=_URL_BASE + 'video.html?src=garden2_10s.webm&seek',
          page_set=page_set,
          tags=['is_4k', 'vp8', 'vorbis', 'audio_video']),
      _SeekPage(
          url=_URL_BASE + 'video.html?src=garden2_10s.mp4&seek',
          page_set=page_set,
          tags=['is_4k', 'h264', 'aac', 'audio_video']),
      _SeekPage(
          url=(_URL_BASE + 'video.html?src='
               'smpte_3840x2160_60fps_vp9.webm&seek'),
          page_set=page_set,
          tags=['is_4k', 'vp9', 'video_only'],
          action_timeout_in_seconds=120),

      # Basic test that ensures background playback works properly.
      _BackgroundPlaybackPage(
          url=_URL_BASE + 'video.html?src=tulip2.vp9.webm&background',
          page_set=page_set,
          tags=['vp9', 'opus', 'audio_video']),

      # Basic MSE test pages for common configurations. Note: By default the
      # test will only append the first 128k of the specified files, so when
      # adding tests ensure that is enough to trigger a timeupdate event. If not
      # you'll need to specify an additional appendSize parameter.
      _MSEPage(
          url=_URL_BASE + 'mse.html?media=aac_audio.mp4,h264_video.mp4',
          page_set=page_set,
          tags=['h264', 'aac', 'audio_video']),
      _MSEPage(
          url=_URL_BASE + 'mse.html?media=tulip2.vp9.webm',
          page_set=page_set,
          tags=['vp9', 'opus', 'audio_video']),
      _MSEPage(
          url=_URL_BASE + 'mse.html?media=aac_audio.mp4',
          page_set=page_set,
          tags=['aac', 'audio_only']),
      _MSEPage(
          url=_URL_BASE + 'mse.html?media=h264_video.mp4',
          page_set=page_set,
          tags=['h264', 'video_only']),
      ]

class _MediaCasesStorySet(story.StorySet):
  """Abstract Media Cases Story Set to be overriden."""
  def __init__(self, measure_memory=False):
    super(_MediaCasesStorySet, self).__init__(
            cloud_storage_bucket=story.PARTNER_BUCKET)
    self.measure_memory = measure_memory
    for page in self._BuildPages():
      self.AddStory(page)

  @abc.abstractmethod
  def _BuildPages(self):
    """Subclasses should implement this to return an iterator of pages."""

class MediaCasesDesktopStorySet(_MediaCasesStorySet):
  """
  Description: Video Stack Perf pages that report time_to_play, seek time and
  many other media-specific and generic metrics.
  """
  def _BuildPages(self):
    return iter(
        _GetCrossPlatformMediaPages(self) + _GetDesktopOnlyMediaPages(self))

class MediaCasesMobileStorySet(_MediaCasesStorySet):
  """
  Description: Video Stack Perf pages that report time_to_play, seek time and
  many other media-specific and generic metrics.

  The mobile story set removes stories that are too difficult for mobile
  devices.
  """
  def _BuildPages(self):
    for page in _GetCrossPlatformMediaPages(self):
      if 'is_4k' in page.tags or 'is_50fps' in page.tags:
        continue
      yield page


text:
import os
import stat
import time
import shutil
import datetime
from operator import itemgetter, attrgetter

from dulwich.objects import Commit, Blob, Tree
from dulwich.repo import Repo

from vacuous.backends.base import BaseBackend
from vacuous.exceptions import FileDoesNotExist, BranchDoesNotExist, BranchDoesAlreadyExist, CommitDoesNotExist
from vacuous.constants import WRITE, RENAME, DELETE

from vacuous.backends.dulwich.utils import clean_path, iter_blob_paths, tree_diff, get_by_path, is_same_object
from vacuous.backends.dulwich.commit import DulwichCommit

class Backend(BaseBackend):
    default_branch = 'master'
    null_revision = 'null'
    file_mode = 0100644
    directory_mode = 040755

    @property
    def repo(self):
        if not hasattr(self, '_repo'):
            self._repo = Repo(self.path)
        return self._repo

    def _get_commit(self, revision=None, branch=None):
        repo = self.repo
        if not revision:
            try:
                revision = repo.refs['refs/heads/%s' % branch]
            except KeyError:
                raise BranchDoesNotExist(self, branch)
        elif isinstance(revision, DulwichCommit):
            revision = revision.revision
        try:
            commit = repo[revision]
            if not isinstance(commit, Commit):
                raise CommitDoesNotExist(self, revision)
            return commit
        except KeyError:
            raise CommitDoesNotExist(self, revision)

    def _collect(self, tree, path, cache=None):
        result = [(None, None, tree)]
        bits = filter(None, path.split(os.path.sep))
        repo = self.repo
        for i, bit in enumerate(bits):
            found = False
            for mode, name, hexsha in tree.items():
                if name == bit:
                    found = True
                    if cache and hexsha in cache:
                        tree = cache[hexsha]
                    else:
                        tree = repo[hexsha]
                    result.append((mode, name, tree))
                    break
            if not found:
                result += [(self.directory_mode, bit, Tree()) for bit in bits[i:]]
                break
        return result

    def _link(self, seq):
        cache = {}
        for i in xrange(len(seq) - 1, -1, -1):
            mode, name, obj = seq[i]
            cache[obj.id] = obj
            if i > 0:
                seq[i - 1][2][name] = (mode, obj.id)
        return cache

    ### repo ###

    def init_repo(self):
        if os.path.exists(self.path):
            return
        os.mkdir(self.path)
        self._repo = Repo.init_bare(self.path)

    def delete_repo(self):
        shutil.rmtree(self.path)

    ### branches ###

    def has_branch(self, name):
        return 'refs/heads/%s' % name in self.repo.refs

    def create_branch(self, name, revision=None):
        if self.has_branch(name):
            raise BranchDoesAlreadyExist(self, name)
        self.repo.refs['refs/heads/%s' % name] = self._get_commit(revision, 'master').id

    def delete_branch(self, name):
        try:
            del self.repo.refs['refs/heads/%s' % name]
        except KeyError:
            raise BranchDoesNotExist(self, name)

    def rename_branch(self, old_name, new_name):
        if old_name == new_name:
            return
        if not self.has_branch(old_name):
            raise BranchDoesNotExist(self, old_name)
        if self.has_branch(new_name):
            raise BranchDoesAlreadyExist(new_name)
        self.create_branch(new_name, 'refs/heads/%s' % old_name)
        self.delete_branch(old_name)

    ### api ###

    def revision(self, revision=None, branch='master'):
        return DulwichCommit(self, self._get_commit(revision, branch))

    def _walk(self, path, tree):
        repo = self.repo
        blobs, subtrees = [], []
        for mode, name, hexsha in tree.items():
            if stat.S_ISREG(mode):
                blobs.append(name)
            elif stat.S_ISDIR(mode):
                subtrees.append(name)
        yield (path, subtrees, blobs)
        for name in subtrees:
            mode, hexsha = tree[name]
            for t in self._walk(os.path.join(path, name), repo[hexsha]):
                yield t

    def walk(self, path, revision=None, branch='master'):
        root = repo[self._get_commit(revision, branch).tree]
        return self._walk(path, root)

    def history(self, path=None, revision=None, branch='master', since_revision=None, since=None, sort=True):
        if revision == self.null_revision:
            return []

        if path is not None:
            path = clean_path(path)

        if since_revision:
            ctime = self.revision(since_revision).commit_time
            if since:
                since = max(ctime, since)
            else:
                since = ctime

        if revision or branch:
            pending = set([self._get_commit(revision, branch).id])
        else:
            pending = set(self._repo.get_refs().values())

        visited = set()
        result = []
        repo = self.repo

        while pending:
            commit_id = pending.pop()
            commit = self.revision(commit_id)

            if commit_id in visited:
                continue
            visited.add(commit_id)

            if since and since > commit.commit_time:
                continue

            if commit_id != since_revision:
                pending.update(commit._commit.parents)

            if path:
                tree = repo[commit._commit.tree]
                found = False
                parents = commit._commit.parents
                for parent in parents:
                    parent_tree = repo[repo[parent].tree]
                    if not is_same_object(repo, tree, parent_tree, path):
                        found = True
                        break
                if not parents and get_by_path(repo, tree, path):
                    found = True
                if not found:
                    continue
            result.append(commit)
        if sort:
            result.sort(key=attrgetter('commit_time'), reverse=True)
        return result

    def do_read(self, path, revision=None, branch='master'):
        path = clean_path(path)
        repo = self.repo
        if revision == self.null_revision:
            raise FileDoesNotExist(self, "'%s' does not exist at revision null" % path)
        c = self._get_commit(revision, branch)
        obj = get_by_path(repo, repo[c.tree], path)
        if not obj:
            raise FileDoesNotExist(self, "'%s' does not exist" % path)
        if not isinstance(obj, Blob):
            raise FileDoesNotExist(self, "'%s' is not a regular file" % path)
        data = obj.as_pretty_string()
        return data

    def do_commit(self, message='', author=None, committer=None, branch='master', parent=None):
        if isinstance(message, unicode):
            message = message.encode('utf-8')
        repo = self.repo
        try:
            parent = self._get_commit(parent, branch)
            root = repo[parent.tree]
        except BranchDoesNotExist:
            if branch == 'master': # initial commit
                root = Tree()
            else:
                raise

        cache = {}
        paths = set()
        objects = set()

        for path, (action, data) in self.changes.iteritems():
            path = clean_path(path)
            paths.add(path)
            dirname, filename = os.path.split(path)
            trees = self._collect(root, dirname, cache)

            if action == WRITE:
                blob = Blob.from_string(data)
                trees[-1][2][filename] = (self.file_mode, blob.id)
                cache[blob.id] = blob

            elif action == DELETE:
                del trees[-1][2][filename]

            elif action == RENAME:
                old = self._collect(root, data, cache)
                mode, name, obj = old[-1]
                del old[-2][2][name]
                trees[-1][2][filename] = (mode, obj.id)
                cache.update(self._link(old[:-1]))
                paths.add(data)

            cache.update(self._link(trees))
        else:
            objects.add(root)

        # collect all objects that have to be committed
        for path in paths:
            objects.update([obj for mode, name, obj in self._collect(root, path, cache)])

        # create the commit
        c = Commit()
        if parent:
            c.parents = [parent.id]
        c.tree = root.id
        c.committer = committer or self.committer
        c.author = author or c.committer

        t = time.localtime()
        c.commit_time = c.author_time = int(time.mktime(t))
        c.commit_timezone = c.author_timezone = t.tm_isdst * 3600 - time.timezone
        c.encoding = "UTF-8"
        c.message = message
        objects.add(c)

        # write everything to disk
        for obj in objects:
            repo.object_store.add_object(obj)

        repo.refs['refs/heads/%s' % branch] = c.id

        return DulwichCommit(self, c)


text:
@implementation ColumnModel

-(id)initWithDictionary:(NSDictionary *)dictionary
{
    if (self=[super init]) {

        self.cate_id=dictionary[@"cate_id"];
        self.game_name=dictionary[@"game_name"];
        self.short_name=dictionary[@"short_name"];
        self.game_url=dictionary[@"game_url"];
        self.game_src=dictionary[@"game_src"];
        self.game_icon=dictionary[@"game_icon"];
        self.online_room=dictionary[@"online_room"];
        self.online_room_ios=dictionary[@"online_room_ios"];

    }

    return self;
}

@end


text:
package org.apache.hadoop.hdfs.protocolPB;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.protocol.proto.ClientDatanodeProtocolProtos.ClientDatanodeProtocolService;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenSelector;
import org.apache.hadoop.ipc.ProtocolInfo;
import org.apache.hadoop.security.KerberosInfo;
import org.apache.hadoop.security.token.TokenInfo;

@KerberosInfo(
    serverPrincipal = HdfsClientConfigKeys.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY)
@TokenInfo(BlockTokenSelector.class)
@ProtocolInfo(protocolName =
    "org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol",
    protocolVersion = 1)
@InterfaceAudience.Private
public interface ClientDatanodeProtocolPB extends
    ClientDatanodeProtocolService.BlockingInterface {
}


text:
import unittest

import IECore

import GafferTest
import GafferScene
import GafferSceneTest
import GafferOSL
import GafferArnold

class ArnoldDisplacementTest( GafferSceneTest.SceneTestCase ) :

	def test( self ) :

		n = GafferArnold.ArnoldShader()
		n.loadShader( "noise" )

		d = GafferArnold.ArnoldDisplacement()
		d["map"].setInput( n["out"] )
		d["height"].setValue( 2.5 )
		d["padding"].setValue( 25 )
		d["zeroValue"].setValue( .25 )
		d["autoBump"].setValue( True )

		na = n.attributes()
		da = d.attributes()

		self.assertEqual(
			da,
			IECore.CompoundObject( {
				"ai:disp_map" : na["ai:surface"],
				"ai:disp_height" : IECore.FloatData( 2.5 ),
				"ai:disp_padding" : IECore.FloatData( 25 ),
				"ai:disp_zero_value" : IECore.FloatData( .25 ),
				"ai:disp_autobump" : IECore.BoolData( True ),
			} )
		)

		d["enabled"].setValue( False )
		self.assertEqual( d.attributes(), IECore.CompoundObject() )

	def testDirtyPropagation( self ) :

		n = GafferArnold.ArnoldShader()
		n.loadShader( "noise" )

		d = GafferArnold.ArnoldDisplacement()
		cs = GafferTest.CapturingSlot( d.plugDirtiedSignal() )

		d["height"].setValue( 10 )
		self.assertTrue( d["out"] in [ x[0] for x in cs ] )

		del cs[:]
		d["map"].setInput( n["out"] )
		self.assertTrue( d["out"] in [ x[0] for x in cs ] )

	def testOSLShaderInput( self ) :

		n = GafferOSL.OSLShader()
		n.loadShader( "Pattern/Noise" )

		d = GafferArnold.ArnoldDisplacement()

		d["map"].setInput( n["out"] )
		self.assertTrue( d["map"].getInput().isSame( n["out"] ) )

		na = n.attributes()
		da = d.attributes()

		self.assertEqual(
			da,
			IECore.CompoundObject( {
				"ai:disp_map" : na["osl:shader"],
				"ai:disp_height" : IECore.FloatData( 1 ),
				"ai:disp_padding" : IECore.FloatData( 0 ),
				"ai:disp_zero_value" : IECore.FloatData( 0 ),
				"ai:disp_autobump" : IECore.BoolData( False ),
			} )
		)

	def testNoInput( self ) :

		d = GafferArnold.ArnoldDisplacement()
		self.assertTrue( "ai:disp_map" not in d.attributes() )

	def testAssignment( self ) :

		s = GafferScene.Sphere()

		n = GafferArnold.ArnoldShader()
		n.loadShader( "noise" )

		d = GafferArnold.ArnoldDisplacement()
		d["map"].setInput( n["out"] )
		d["height"].setValue( 2.5 )

		f = GafferScene.PathFilter()
		f["paths"].setValue( IECore.StringVectorData( [ "/sphere" ] ) )

		a = GafferScene.ShaderAssignment()
		a["in"].setInput( s["out"] )
		a["shader"].setInput( d["out"] )
		a["filter"].setInput( f["out"] )

		self.assertEqual(
			a["out"].attributes( "/sphere" )["ai:disp_height"],
			IECore.FloatData( 2.5 )
		)

		d["height"].setValue( 5 )

		self.assertEqual(
			a["out"].attributes( "/sphere" )["ai:disp_height"],
			IECore.FloatData( 5 )
		)

if __name__ == "__main__":
	unittest.main()


text:
scp -P 33 -r pbeukema@fileserver2.sibr.cmu.edu:/home/pbeukema/coax_Images/$file_id/ /data/modMap/subjects/$sid/$session/
# ssh-keygen

# MUST USE MATLAB R2013 for this particular dataset

#Directory structure4
# -modMap
#   -subjects
#     -sid
#       -Pre
#       -Post
#       -searchlights
#       -analysis

# Convert dcms to nifti
matlab -nodesktop -nosplash -r "mm_convert_dcms(${sid}, $sess)"

# Grab onsets from ~/Dropbox
python /data/modMap/bin/mm_onsets.py $sub $sesms

# Run GLM
matlab -nodesktop -nosplash -r "preprocess_and_glm(${sid}, $sess)"

# Make surfaces from t1/t2 if sess=Pre (start this process in new shell)
modmap_hcp.sh ${sid} && sh /data/modMap/bin/batch_surface_extract.sh ${sid}
cp -r /data/modMap/surfaces/${sidT1w/${sid} /usr/local/freesurfer/subjects/
matlab -nodesktop -nosplash -r "modMap_ss_voxel_extraction(${sid})"

# run mri_qc # requires python3 and data to be organized according to BIDS
mriqc /path/to/BIDS/dir/ /out/path/ participant #will run all subs

# Transfer files to cluster
rsync -zavr -e ssh --delete --include '*/' --include='*urRER_Run*.nii' --include='mask.*' --in='surface_voxels.mat' --include='SPM.mat' --exclude='*' /data/modMap/subjects/${sid} --prune-empty-dirs pbeukema@psych-o.hpc1.cs.cmu.edu:/home/pbeukema/modMap/subjects

# write and submit a pbs job for this subject (this is run on the cluster)
qsub -v SID=${sid} mm_searchlight // mm_searchligh_simple

# copy files back from cluster to local computer
scp pbeukema@psych-o.hpc1.cs.cmu.edu:/home/pbeukema/modMap/subjects/${sid}/ss* /data/modMap/subjects/${sid}/searchlights/

# align individual volumes to freesurfer space with BB alignment then align to group surface with spherical registration
Smooth images in the volume
sh /data/modMap/bin/bb_and_surf2vol.sh ${sid}

# Generate figures with pycortex
# Run from within a jupyter notebook and the ~/pyCortex directory
pyCortex_show.sh

# make an average subject out of modMap
make_average_subject --s subs --out modMap


text:
First Item

Active Item

Last Item


text:
'''
Plugin to generate better enums for cocos2d
'''

__docformat__ = 'restructuredtext'

# python modules
import re

# plugin modules
from generate_jsb import JSBGenerateConstants, JSBGenerateFunctions, JSBGenerateClasses

#
#
# Plugin to generate better constants for cocos2d
#
#
class JSBGenerateConstants_CC(JSBGenerateConstants):

    def get_name_for_constant(self, name):
        ok = False
        if name.startswith('kCC'):
            name = name[3:]
            ok = True

        if name.startswith('CC'):
            name = name[2:]
            ok = True

        if ok:
            n = []
            array = re.findall('[A-Z][^A-Z]*', name)
            if array and len(array) > 0:
                prev = ''
                prev_e_len = 0
                for e in array:
                    e = e.upper()
                    # Append all single letters together
                    if re.match('[A-Z][_0-9]?$', e) and len(n) >= 1 and prev_e_len == 1:
                        prev = prev + e
                        n[-1] = prev
                    else:
                        n.append(e)
                        prev = e
                    prev_e_len = len(e)
            name = '_'.join(n)
            name = name.replace('__', '_')
        else:
            name = None

        return name

#
#
# OpenGL ES 2.0 / WebGL function plugin
#
#
class JSBGenerateFunctions_CC(JSBGenerateFunctions):

    def convert_function_name_to_js(self, function_name):

        if function_name.startswith('ccGL'):
            return 'gl' + function_name[4:]
        return super(JSBGenerateFunctions_CC, self).convert_function_name_to_js(function_name)

#
#
# OpenGL ES 2.0 / WebGL function plugin
#
#
class JSBGenerateClasses_CC(JSBGenerateClasses):

    def __init__(self, config):
        super(JSBGenerateClasses_CC, self).__init__(config)

        # Extend supported types
        self.args_js_special_type_conversions['cc_fontdef'] = ['JSB_jsval_to_CCFontDefinition', 'CCFontDefinition*']
        self.supported_declared_types['CCFontDefinition*'] = 'cc_fontdef'

    #
    # Overriden methods
    #
    def validate_argument(self, arg):
        # Treat GLchar* as null-terminated char*
        if arg['declared_type'] == 'GLchar*' or arg['declared_type'] == 'char*' or arg['declared_type'] == 'char*':
            return ('char*', 'char*')
        # if arg['declared_type'] == 'CCFontDefinition*':
        #     return ('cc_fontdef','CCFontDefinition')

        return super(JSBGenerateClasses_CC, self).validate_argument(arg)

    def convert_js_to_objc(self, js_type, objc_type):
        # print js_type, objc_type
        return super(JSBGenerateClasses_CC, self).convert_js_to_objc(js_type, objc_type)


text:
package com.xhsoft.framework.common.chart.fusionChart.utils.fcsample;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.fusioncharts.FusionChartsHelper;
import com.fusioncharts.database.DBConnection;

/**
 * Bean containing sample chart data. Default values for all the fields have
 * been set. These can be changed using the set methods. This class has been
 * used as a backing bean in JSF examples.
 *
 * @author Infosoft Global (P) Ltd.
 *
 */
public class FactoriesWithLinkToDetailedBean {

	protected String chartId = "FactorySum";

	protected String width = "600";
	protected String height = "300";
	protected String filename = ChartType.PIE3D.getFileName();

	protected String xml = null;
	// We need to use single quotes in the fc:render tag because, we are using
	// dom to create the xml
	// and hence the values for attributes are in double quotes.
	protected String useSingleQuotes = "true";

	public FactoriesWithLinkToDetailedBean() {
	}

	public String getChartId() {
		return chartId;
	}

	private String getFactoryXML() {
		// strXML will be used to store the entire XML document generated
		String strXML = "";
		try {
			DBConnection dbConn = new DBConnection();
			Connection oConn = dbConn.getConnection();
			// Database Objects - Initialization
			Statement st1 = null, st2 = null;
			ResultSet rs1 = null, rs2 = null;

			String strQuery = "";

			Map<String, String> chartAttributes = new HashMap<String, String>();
			;
			chartAttributes.put("caption", "Factory Output report");
			chartAttributes.put("subCaption", "By Quantity");
			chartAttributes.put("pieSliceDepth", "30");
			chartAttributes.put("showBorder", "1");
			chartAttributes.put("formatNumberScale", "0");
			chartAttributes.put("numberSuffix", " Units");

			DOMHelper domHelper = new DOMHelper();
			Document chartDoc = domHelper.getDocument();
			Element rootElement = chartDoc.createElement("chart");
			domHelper.addAttributesToElement(rootElement, chartAttributes);

			// Generate the chart element
			// strXML =
			// "<chart caption='Factory Output report' subCaption='By Quantity' pieSliceDepth='30' showBorder='1' formatNumberScale='0' numberSuffix=' Units' >";

			// Iterate through each factory
			strQuery = "select * from Factory_Master";
			st1 = oConn.createStatement();
			rs1 = st1.executeQuery(strQuery);

			String factoryId = null;
			String factoryName = null;
			String totalOutput = "";

			while (rs1.next()) {
				totalOutput = "";
				factoryId = rs1.getString("FactoryId");
				factoryName = rs1.getString("FactoryName");
				// Now create second recordset to get details for this factory
				strQuery = "select sum(Quantity) as TotOutput from Factory_Output where FactoryId="
						+ factoryId;
				st2 = oConn.createStatement();
				rs2 = st2.executeQuery(strQuery);
				if (rs2.next()) {
					totalOutput = rs2.getString("TotOutput");
				}
				// Generate <set label='..' value='..'/>
				// strXML += "<set label='" + factoryName + "' value='"
				// +totalOutput+ "' link='javaScript:updateChart("+factoryId +
				// ")'/>";
				Element setElem = chartDoc.createElement("set");
				setElem.setAttribute("label", factoryName);
				setElem.setAttribute("value", totalOutput);
				// Encoding the URL since it has a parameter
				String strDataURL = FusionChartsHelper.encodeDataURL(
						"Detailed.jsp?factoryId=" + factoryId, false);
				setElem.setAttribute("link", strDataURL);
				rootElement.appendChild(setElem);
				// close the resultset,statement
				// enclose them in try catch block
				try {
					if (null != rs2) {
						rs2.close();
						rs2 = null;
					}
				} catch (java.sql.SQLException e) {
					System.out.println("Could not close the resultset");
				}
				try {
					if (null != st2) {
						st2.close();
						st2 = null;
					}
				} catch (java.sql.SQLException e) {
					System.out.println("Could not close the statement");
				}
			}
			// Finally, close <chart> element
			// strXML += "</chart>";
			chartDoc.appendChild(rootElement);
			strXML = domHelper.getXMLString(chartDoc);
			// close the resultset,statement,connection
			// enclose them in try catch block
			try {
				if (null != rs1) {
					rs1.close();
					rs1 = null;
				}
			} catch (java.sql.SQLException e) {
				System.out.println("Could not close the resultset");
			}
			try {
				if (null != st1) {
					st1.close();
					st1 = null;
				}
			} catch (java.sql.SQLException e) {
				System.out.println("Could not close the statement");
			}
			try {
				if (null != oConn) {
					oConn.close();
					oConn = null;
				}
			} catch (java.sql.SQLException e) {
				System.out.println("Could not close the connection");
			}

		} catch (java.sql.SQLException e) {
			System.out.println("Could not close the statement");
		}
		// not required since we will useSingleQuotes in fc:renderHTML tag
		// strXML = strXML.replaceAll("\"", "\\\\\"");
		return strXML;

	}

	public String getFilename() {
		return filename;
	}

	public String getHeight() {
		return height;
	}

	/**
	 * @return the useSingleQuotes
	 */
	public String getUseSingleQuotes() {
		return useSingleQuotes;
	}

	public String getWidth() {
		return width;
	}

	/**
	 * @return the xml
	 */
	public String getXml() {
		xml = getFactoryXML();
		return xml;
	}

	public void setChartId(String chartId) {
		this.chartId = chartId;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public void setHeight(String height) {
		this.height = height;
	}

	/**
	 * @param useSingleQuotes
	 *            the useSingleQuotes to set
	 */
	public void setUseSingleQuotes(String useSingleQuotes) {
		this.useSingleQuotes = useSingleQuotes;
	}

	public void setWidth(String width) {
		this.width = width;
	}

	/**
	 * @param xml
	 *            the xml to set
	 */
	public void setXml(String xml) {
		this.xml = xml;
	}

}