text:
<?php

namespace Oro\Bundle\ImportExportBundle\Tests\Unit\Reader;

use Doctrine\ORM\Query;
use Oro\Bundle\OrganizationBundle\Entity\Organization;
use Oro\Bundle\SecurityBundle\Owner\Metadata\OwnershipMetadata;

class EntityReaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $managerRegistry;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $contextRegistry;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $ownershipMetadataProvider;

    /**
     * @var EntityReaderTestAdapter
     */
    protected $reader;

    protected function setUp()
    {
        $this->contextRegistry = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Context\ContextRegistry')
            ->disableOriginalConstructor()
            ->setMethods(array('getByStepExecution'))
            ->getMock();

        $this->ownershipMetadataProvider =
            $this->getMockBuilder('Oro\Bundle\SecurityBundle\Owner\Metadata\OwnershipMetadataProvider')
            ->disableOriginalConstructor()
            ->getMock();

        $this->managerRegistry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
        $this->reader = new EntityReaderTestAdapter(
            $this->contextRegistry,
            $this->managerRegistry,
            $this->ownershipMetadataProvider
        );
    }

    public function testReadMockIterator()
    {
        $iterator = $this->getMock('\Iterator');
        $this->managerRegistry->expects($this->never())->method($this->anything());

        $fooEntity = $this->getMock('FooEntity');
        $barEntity = $this->getMock('BarEntity');
        $bazEntity = $this->getMock('BazEntity');

        $iterator->expects($this->at(0))->method('rewind');

        $iterator->expects($this->at(1))->method('valid')->will($this->returnValue(true));
        $iterator->expects($this->at(2))->method('current')->will($this->returnValue($fooEntity));
        $iterator->expects($this->at(3))->method('next');

        $iterator->expects($this->at(4))->method('valid')->will($this->returnValue(true));
        $iterator->expects($this->at(5))->method('current')->will($this->returnValue($barEntity));
        $iterator->expects($this->at(6))->method('next');

        $iterator->expects($this->at(7))->method('valid')->will($this->returnValue(true));
        $iterator->expects($this->at(8))->method('current')->will($this->returnValue($bazEntity));
        $iterator->expects($this->at(9))->method('next');

        $iterator->expects($this->at(10))->method('valid')->will($this->returnValue(false));
        $iterator->expects($this->at(11))->method('valid')->will($this->returnValue(false));

        $this->reader->setSomeSourceIterator($iterator);

        $context = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Context\ContextInterface')->getMock();
        $context->expects($this->exactly(3))->method('incrementReadOffset');
        $context->expects($this->exactly(3))->method('incrementReadCount');

        $stepExecution = $this->getMockStepExecution($context);
        $this->reader->setStepExecution($stepExecution);

        $this->assertEquals($fooEntity, $this->reader->read());
        $this->assertEquals($barEntity, $this->reader->read());
        $this->assertEquals($bazEntity, $this->reader->read());
        $this->assertNull($this->reader->read());
        $this->assertNull($this->reader->read());
    }

    public function testReadRealIterator()
    {
        $this->managerRegistry->expects($this->never())->method($this->anything());

        $fooEntity = $this->getMock('FooEntity');
        $barEntity = $this->getMock('BarEntity');
        $bazEntity = $this->getMock('BazEntity');

        $iterator = new \ArrayIterator(array($fooEntity, $barEntity, $bazEntity));

        $this->reader->setSomeSourceIterator($iterator);

        $context = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Context\ContextInterface')->getMock();
        $context->expects($this->exactly(3))->method('incrementReadOffset');
        $context->expects($this->exactly(3))->method('incrementReadCount');

        $stepExecution = $this->getMockStepExecution($context);
        $this->reader->setStepExecution($stepExecution);

        $this->assertEquals($fooEntity, $this->reader->read());
        $this->assertEquals($barEntity, $this->reader->read());
        $this->assertEquals($bazEntity, $this->reader->read());
        $this->assertNull($this->reader->read());
        $this->assertNull($this->reader->read());
    }

    /**
     * @expectedException \Oro\Bundle\ImportExportBundle\Exception\LogicException
     * @expectedExceptionMessage Reader must be configured with source
     */
    public function testReadFailsWhenNoSourceIterator()
    {
        $this->managerRegistry->expects($this->never())->method($this->anything());

        $stepExecution = $this->getMockBuilder('Akeneo\Bundle\BatchBundle\Entity\StepExecution')
            ->disableOriginalConstructor()
            ->getMock();
        $stepExecution->expects($this->never())->method($this->anything());
        $this->reader->read($stepExecution);
    }

    public function testSetStepExecutionWithQueryBuilder()
    {
        $this->managerRegistry->expects($this->never())->method($this->anything());

        $queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')->disableOriginalConstructor()->getMock();

        $context = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Context\ContextInterface')->getMock();
        $context->expects($this->at(0))->method('hasOption')->with('entityName')->will($this->returnValue(false));
        $context->expects($this->at(1))->method('hasOption')->with('queryBuilder')->will($this->returnValue(true));
        $context->expects($this->at(2))->method('getOption')
            ->with('queryBuilder')
            ->will($this->returnValue($queryBuilder));

        $this->reader->setStepExecution($this->getMockStepExecution($context));

        $this->assertAttributeInstanceOf(
            'Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator',
            'sourceIterator',
            $this->reader
        );

        $this->assertAttributeEquals(
            $queryBuilder,
            'source',
            self::readAttribute($this->reader, 'sourceIterator')
        );
    }

    public function testSetStepExecutionWithQuery()
    {
        $this->managerRegistry->expects($this->never())->method($this->anything());

        $query = new Query(
            $this->getMockBuilder('Doctrine\ORM\EntityManager')->disableOriginalConstructor()->getMock()
        );

        $context = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Context\ContextInterface')->getMock();
        $context->expects($this->at(0))->method('hasOption')->with('entityName')->will($this->returnValue(false));
        $context->expects($this->at(1))->method('hasOption')->with('queryBuilder')->will($this->returnValue(false));
        $context->expects($this->at(2))->method('hasOption')->with('query')->will($this->returnValue(true));
        $context->expects($this->at(3))->method('getOption')
            ->with('query')
            ->will($this->returnValue($query));

        $this->reader->setStepExecution($this->getMockStepExecution($context));

        $this->assertAttributeInstanceOf(
            'Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator',
            'sourceIterator',
            $this->reader
        );

        $this->assertAttributeEquals(
            $query,
            'source',
            self::readAttribute($this->reader, 'sourceIterator')
        );
    }

    public function testSetStepExecutionWithEntityName()
    {
        $entityName = 'entityName';

        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()
            ->getMock();

        $classMetadata->expects($this->once())->method('getAssociationMappings')->will($this->returnValue(array()));
        $classMetadata->expects($this->once())
            ->method('getIdentifierFieldNames')
            ->will($this->returnValue(['id']));

        $entityManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')->disableOriginalConstructor()->getMock();
        $entityManager->expects($this->once())->method('getClassMetadata')
            ->with($entityName)
            ->will($this->returnValue($classMetadata));

        $queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')->disableOriginalConstructor()->getMock();

        $queryBuilder->expects($this->once())->method('getEntityManager')
            ->will($this->returnValue($entityManager));

        $repository = $this->getMockBuilder('Doctrine\ORM\EntityRepository')->disableOriginalConstructor()->getMock();
        $repository->expects($this->once())->method('createQueryBuilder')
            ->with('o')
            ->will($this->returnValue($queryBuilder));

        $this->managerRegistry->expects($this->once())->method('getRepository')
            ->with($entityName)
            ->will($this->returnValue($repository));

        $context = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Context\ContextInterface')->getMock();
        $context->expects($this->at(0))->method('hasOption')->with('entityName')->will($this->returnValue(true));
        $context->expects($this->at(1))->method('getOption')
            ->with('entityName')
            ->will($this->returnValue($entityName));

        $this->reader->setStepExecution($this->getMockStepExecution($context));

        $this->assertAttributeInstanceOf(
            'Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator',
            'sourceIterator',
            $this->reader
        );

        $this->assertAttributeEquals(
            $queryBuilder,
            'source',
            self::readAttribute($this->reader, 'sourceIterator')
        );
    }

    // @codingStandardsIgnoreStart
    /**
     * @expectedException \Oro\Bundle\ImportExportBundle\Exception\InvalidConfigurationException
     * @expectedExceptionMessage Configuration of entity reader must contain either "entityName", "queryBuilder" or "query".
     */
    // @codingStandardsIgnoreEnd
    public function testSetStepExecutionFailsWhenHasNoRequiredOptions()
    {
        $this->managerRegistry->expects($this->never())->method($this->anything());

        $context = $this->getMockBuilder('Oro\Bundle\ImportExportBundle\Context\ContextInterface')->getMock();
        $context->expects($this->exactly(3))->method('hasOption')->will($this->returnValue(false));

        $this->reader->setStepExecution($this->getMockStepExecution($context));
    }

    public function testSetSourceEntityName()
    {
        $name = '\stdClass';

        $queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();

        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')
            ->disableOriginalConstructor()
            ->getMock();
        $classMetadata->expects($this->once())
            ->method('getAssociationMappings')
            ->will(
                $this->returnValue(
                    array(
                        'testSingle'   => array('fieldName' => 'testSingle'),
                        'testMultiple' => array('fieldName' => 'testMultiple'),
                    )
                )
            );
        $classMetadata->expects($this->exactly(2))
            ->method('isAssociationWithSingleJoinColumn')
            ->with($this->isType('string'))
            ->will(
                $this->returnValueMap(
                    array(
                        array('testSingle', true),
                        array('testMultiple', false),
                    )
                )
            );
        $classMetadata->expects($this->once())
            ->method('getIdentifierFieldNames')
            ->will($this->returnValue(['id']));

        $queryBuilder->expects($this->once())
            ->method('addSelect')
            ->with('_testSingle');
        $queryBuilder->expects($this->once())
            ->method('leftJoin')
            ->with('o.testSingle', '_testSingle');
        $queryBuilder->expects($this->once())
            ->method('orderBy')
            ->with('o.id', 'ASC');

        $repository = $this->getMockBuilder('Doctrine\ORM\EntityRepository')
            ->disableOriginalConstructor()
            ->getMock();
        $repository->expects($this->once())
            ->method('createQueryBuilder')
            ->with('o')
            ->will($this->returnValue($queryBuilder));

        $this->managerRegistry->expects($this->once())
            ->method('getRepository')
            ->with($name)
            ->will($this->returnValue($repository));

        $entityManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')->disableOriginalConstructor()->getMock();
        $entityManager->expects($this->once())->method('getClassMetadata')
            ->with($name)
            ->will($this->returnValue($classMetadata));

        $queryBuilder->expects($this->once())->method('getEntityManager')
            ->will($this->returnValue($entityManager));

        $organization = new Organization();
        $ownershipMetadata = new OwnershipMetadata('', '', '', 'organization');
        $this->ownershipMetadataProvider->expects($this->once())
            ->method('getMetadata')
            ->will($this->returnValue($ownershipMetadata));
        $queryBuilder->expects($this->once())
            ->method('andWhere')
            ->with('o.organization = :organization')
            ->will($this->returnValue($queryBuilder));
        $queryBuilder->expects($this->once())
            ->method('setParameter')
            ->with('organization', $organization)
            ->will($this->returnValue($queryBuilder));

        $this->reader->setSourceEntityName($name, $organization);
    }

    /**
     * @param mixed $context
     * @return \PHPUnit_Framework_MockObject_MockObject+
     */
    protected function getMockStepExecution($context)
    {
        $stepExecution = $this->getMockBuilder('Akeneo\Bundle\BatchBundle\Entity\StepExecution')
            ->disableOriginalConstructor()
            ->getMock();

        $this->contextRegistry->expects($this->any())
            ->method('getByStepExecution')
            ->with($stepExecution)
            ->will($this->returnValue($context));

        return $stepExecution;
    }
}


text:
package org.apache.beam.sdk.io.gcp.bigquery;

import com.google.api.services.bigquery.model.TableRow;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.ShardedKeyCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Reshuffle;
import org.apache.beam.sdk.transforms.windowing.DefaultTrigger;
import org.apache.beam.sdk.transforms.windowing.GlobalWindows;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.ShardedKey;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;

/**
 * This transform takes in key-value pairs of {@link TableRow} entries and the
 * {@link TableDestination} it should be written to. The BigQuery streaming-write service is used
 * to stream these writes to the appropriate table.
 *
 * <p>This transform assumes that all destination tables already exist by the time it sees a write
 * for that table.
 */
public class StreamingWriteTables extends PTransform<
    PCollection<KV<TableDestination, TableRow>>, WriteResult> {
  private BigQueryServices bigQueryServices;
  private InsertRetryPolicy retryPolicy;

  public StreamingWriteTables() {
    this(new BigQueryServicesImpl(), InsertRetryPolicy.alwaysRetry());
  }

  private StreamingWriteTables(BigQueryServices bigQueryServices, InsertRetryPolicy retryPolicy) {
    this.bigQueryServices = bigQueryServices;
    this.retryPolicy = retryPolicy;
  }

  StreamingWriteTables withTestServices(BigQueryServices bigQueryServices) {
    return new StreamingWriteTables(bigQueryServices, retryPolicy);
  }

  StreamingWriteTables withInsertRetryPolicy(InsertRetryPolicy retryPolicy) {
    return new StreamingWriteTables(bigQueryServices, retryPolicy);
  }

  @Override
  public WriteResult expand(PCollection<KV<TableDestination, TableRow>> input) {
    // A naive implementation would be to simply stream data directly to BigQuery.
    // However, this could occasionally lead to duplicated data, e.g., when
    // a VM that runs this code is restarted and the code is re-run.

    // The above risk is mitigated in this implementation by relying on
    // BigQuery built-in best effort de-dup mechanism.

    // To use this mechanism, each input TableRow is tagged with a generated
    // unique id, which is then passed to BigQuery and used to ignore duplicates
    // We create 50 keys per BigQuery table to generate output on. This is few enough that we
    // get good batching into BigQuery's insert calls, and enough that we can max out the
    // streaming insert quota.
    PCollection<KV<ShardedKey<String>, TableRowInfo>> tagged =
        input
            .apply("ShardTableWrites", ParDo.of(new GenerateShardedTable(50)))
            .setCoder(KvCoder.of(ShardedKeyCoder.of(StringUtf8Coder.of()), TableRowJsonCoder.of()))
            .apply("TagWithUniqueIds", ParDo.of(new TagWithUniqueIds()))
            .setCoder(KvCoder.of(ShardedKeyCoder.of(StringUtf8Coder.of()), TableRowInfoCoder.of()));

    // To prevent having the same TableRow processed more than once with regenerated
    // different unique ids, this implementation relies on "checkpointing", which is
    // achieved as a side effect of having StreamingWriteFn immediately follow a GBK,
    // performed by Reshuffle.
    TupleTag<Void> mainOutputTag = new TupleTag<>("mainOutput");
    TupleTag<TableRow> failedInsertsTag = new TupleTag<>("failedInserts");
    PCollectionTuple tuple =
        tagged
            .apply(Reshuffle.of())
            // Put in the global window to ensure that DynamicDestinations side inputs are accessed
            // correctly.
            .apply(
                "GlobalWindow",
                Window.<KV<ShardedKey<String>, TableRowInfo>>into(new GlobalWindows())
                    .triggering(DefaultTrigger.of())
                    .discardingFiredPanes())
            .apply(
                "StreamingWrite",
                ParDo.of(new StreamingWriteFn(bigQueryServices, retryPolicy, failedInsertsTag))
                    .withOutputTags(mainOutputTag, TupleTagList.of(failedInsertsTag)));
    PCollection<TableRow> failedInserts = tuple.get(failedInsertsTag);
    failedInserts.setCoder(TableRowJsonCoder.of());
    return WriteResult.in(input.getPipeline(), failedInsertsTag, failedInserts);
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using NeoStore.CustomView;
using NeoStore.Droid;
using Xamarin.Forms.Platform.Android;
using Android.Graphics;

[assembly:ExportRenderer(typeof(ColorButton), typeof(ColorButtonRenderer))]

namespace NeoStore.Droid
{
    class ColorButtonRenderer:ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            var font = Typeface.CreateFromAsset(Xamarin.Forms.Forms.Context.ApplicationContext.Assets, "fontawesome-webfont.ttf");
            Control.Typeface = font;
            Control.SetBackgroundResource(Resource.Drawable.Color_Btn);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/circle_item_base"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clipChildren="false"
>
    <ImageView
        android:id="@+id/circle_item_image"
        android:layout_height="60dp"
        android:layout_width="60dp"
        android:layout_gravity="center"
        android:scaleType="centerCrop"
    />

    <TextView
        android:id="@+id/circle_item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="16sp"
    />

</FrameLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Source: https://gist.github.com/lapism/f75501edd8d32edf3eed -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:baselineAligned="false"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:minHeight="?android:attr/listPreferredItemHeightSmall"
              android:gravity="center_vertical"
              android:paddingEnd="@dimen/key_line"
              android:paddingRight="@dimen/key_line"
              android:paddingLeft="@dimen/key_line"
              android:paddingStart="@dimen/key_line"
              android:background="?android:attr/selectableItemBackground"
              android:clipToPadding="false"
              android:focusable="true">

    <LinearLayout
        android:id="@+id/icon_frame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="-4dp"
        android:layout_marginStart="-4dp"
        android:gravity="start|center_vertical"
        android:minWidth="60dp"
        android:orientation="horizontal"
        android:paddingBottom="4dp"
        android:paddingEnd="12dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingStart="12dp"
        android:paddingTop="4dp">

        <androidx.preference.internal.PreferenceImageView
            android:id="@android:id/icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:maxWidth="48dp"
            app:maxHeight="48dp"/>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingTop="16dp"
        android:paddingBottom="16dp">

        <TextView
            android:id="@android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceListItem"
            android:ellipsize="marquee"/>

        <TextView
            android:id="@android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignLeft="@android:id/title"
            android:layout_alignStart="@android:id/title"
            android:textAppearance="?android:attr/textAppearanceListItemSecondary"
            android:textColor="?android:attr/textColorSecondary"
            android:maxLines="10"/>

    </RelativeLayout>

    <LinearLayout
        android:id="@android:id/widget_frame"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="end|center_vertical"
        android:orientation="vertical"/>

</LinearLayout>


text:
package odin.demand;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import javax.ws.rs.core.MediaType;

import odin.config.Configuration;
import odin.gateway.JIRAGateway;
import odin.gateway.SendMail;
import odin.util.JEncrypt;
import odin.util.OdinResponse;

import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.mortbay.log.Log;

import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.IssueField;
import com.atlassian.jira.rest.client.api.domain.SearchResult;
import com.atlassian.util.concurrent.Promise;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

public class ManageBacklog {
	protected static Logger log = Logger.getLogger(ManageBacklog.class);
	static String baseURL = Configuration.getDefaultValue("gateway.jira.url");
	static String usr = new String(JEncrypt.decode(Configuration
			.getDefaultValue("gateway.jira.username").getBytes()));

	static String pw = new String(JEncrypt.decode(Configuration
			.getDefaultValue("gateway.jira.password").getBytes()));
	static String[] notificationList = Configuration.getDefaultValue(
			"odin.notify.prod.to").split(" ");

	public static void main(String[] args) throws Exception {
		OdinResponse res = new OdinResponse();
		try {
			log.info("Starting.. Calling updateSubtaskRanking");
			updateSubtaskRanking(res);
			log.info("Calling zeroRemainingHoursForDoneTasks");
			zeroRemainingHoursForDoneTasks(res);
			// notifyAssigneeOfOldTickets(res);
			log.info("Closing JIRA client");
			JIRAGateway.closeRestClient();

			log.info("sendJobMessage");
			sendJobMessage(res);
			log.info("JobMessage sent. Closing..");

		} catch (Exception e) {
			e.printStackTrace();
			log.error("Unable to complete job", e);
			try {
				SendMail.sendBacklogManagementMessage(notificationList, null,
						"The Job ManageBacklog Completed Abnormally",
						"The following exception occured while attempting to "
						+ "updateSubtaskRanking or zeroRemainingHoursForDoneTasks using "
						+ "JIRA URL " + Configuration.getDefaultValue("gateway.jira.url") + "  :  "
						+ e.getMessage());
			} catch (IOException ee) {
				e.printStackTrace();
				log.error("Unable to send email notification", ee);
			}
		}
	}

	private static void sendJobMessage(OdinResponse res) throws Exception {
		String header = "The Job ManageBacklog Completed Normally";
		if (res.getStatusCode() != 0) {
			header = "The Job ManageBacklog Completed Abnormally";
		}
		try {
			SendMail.sendBacklogManagementMessage(notificationList, null,
					header, res.toString());
		} catch (IOException e) {
			e.printStackTrace();
			log.error("Unable to send email notification", e);
		}
	}

	public static void updateSubtaskRanking(OdinResponse res) {
		int updatedSubtasks = 0;
		String customRankingField1 = Configuration
				.getDefaultValue("task.calibration.jira.rankfield.1");
		String customRankingField2 = Configuration
				.getDefaultValue("task.calibration.jira.rankfield.2");

		// for each project in program, update subtask ranking
		String[] projectCodes = Configuration.getDefaultValue(
				"task.calibration.jira.projects").split(",");

		for (int i = 0; i < projectCodes.length; i++) {
			List<String> parentKeys = getParentKeySelection(projectCodes[i]);

			for (String parentKey : parentKeys) {

				updatedSubtasks = updateSubtaskRanking(updatedSubtasks,
						customRankingField1, customRankingField2, parentKey);
			}
			res.setStatusCode(0);
			res.setReasonPhrase("OK");
			res.setMessageBody("
ManageBacklog.updateSubtaskRanking Completed Successfully for project "
					+ projectCodes[i] + ". UpdatedSubtasks: " + updatedSubtasks);
		}

	}

	private static int updateSubtaskRanking(int updatedSubtasks,
			String customRankingField1, String customRankingField2,
			String parentKey) {
		// 1. Get rank from parent
		log.info("Get rank from parentKey=" + parentKey);
		Issue issue = JIRAGateway.getRestClient().getIssueClient()
				.getIssue(parentKey).claim();
		int parentRank = 0;

		if (issue.getField(customRankingField1) != null) {
			IssueField field = issue.getField(customRankingField1);
			parentRank = (int) (double) field.getValue(); // TODO: Catch
			// ClassCastException or
			// NullPointerException

		} else if (issue.getField(customRankingField2) != null) {
			IssueField field = issue.getField(customRankingField2);
			if (field == null || field.getValue() == null) {
				parentRank = 9999;
			} else {
				parentRank = (int) (double) field.getValue();
			}
		}
		log.info("Parent key=" + parentKey + ", parentRank=" + parentRank);

		// 2. Get active subtasks
		String jql = "status not in (Done, Invalid) AND parent = " + parentKey;
		int maxResults = 1000;
		int startAt = 0;
		log.info("Executing JQL = " + jql);
		log.info("maxResults=" + maxResults + ", startAt=" + startAt);
		Promise<SearchResult> searchResultPromise = null;

		searchResultPromise = JIRAGateway.getRestClient().getSearchClient()
				.searchJql(jql);

		SearchResult searchResult = searchResultPromise.claim();

		Iterable<? extends Issue> subtasks = searchResult.getIssues();
		for (Issue subtask : subtasks) {
			log.info("subtask.key=" + subtask.getKey());
			// log.info("getSummary = " + subtask.getSummary());

			// 3. Update active subtasks with new rank
			if (subtask.getField(customRankingField1) != null) {
				updateRank(subtask.getKey(), parentRank, customRankingField1);
			} else if (subtask.getField(customRankingField2) != null) {
				IssueField rank = subtask.getField(customRankingField2);
				int rankValue = 0;
				if (rank.getValue() != null)
					rankValue = ((Double) rank.getValue()).intValue();
				if (rankValue != parentRank) {
					updateRank(subtask.getKey(), parentRank,
							customRankingField2);
					updatedSubtasks++;
				}
			}
		}
		return updatedSubtasks;
	}

	public static OdinResponse zeroRemainingHoursForDoneTasks(OdinResponse res) {
		// 1. Event (batch)
		// 2. Condition
		String jql = Configuration.getDefaultValue("task.calibration.jql.1"); // findDoneTasksWithRemaining

		int maxResults = 1000;
		int startAt = 0;
		log.info("Executing JQL = " + jql);
		log.info("maxResults=" + maxResults + ", startAt=" + startAt);
		Promise<SearchResult> searchResultPromise = null;

		searchResultPromise = JIRAGateway.getRestClient().getSearchClient()
				.searchJql(jql, maxResults, startAt, null);

		SearchResult searchResult = searchResultPromise.claim();

		Iterable<? extends Issue> issues = searchResult.getIssues();
		int totalToZero = 0;
		int totalZeroed = 0;
		for (Issue issue : issues) {
			int minutes = 0;
			if (issue.getField("timeestimate") != null) {
				minutes = (int) issue.getField("timeestimate").getValue();
			}
			String status = issue.getStatus().getName();
			totalToZero++;
			log.info("Issue# " + totalToZero + ": issue.key=" + issue.getKey()
					+ ". Status=" + status + ". Remaining minutes=" + minutes);

			// 3. Perfom action
			totalZeroed = totalZeroed + setRemainingToZero(issue.getKey());
		}

		// 4. Communicate
		if (totalZeroed != totalToZero) {
			res.setStatusCode(-1);
			res.setMessageBody("
ManageBacklog.zeroRemainingHoursForDoneTasks Completed Abnormally: NOT ABLE TO UPDATE ALL TASKS

Total issues found: "
					+ totalToZero
					+ "

Total issues updated to zero remaining: "
					+ totalZeroed + "

");
		} else {
			res.setStatusCode(0);
			res.setMessageBody("
ManageBacklog.zeroRemainingHoursForDoneTasks Completed Successfully.

Total issues found: "
					+ totalToZero
					+ "

Total issues updated to zero remaining: "
					+ totalZeroed + "

");
		}
		return res;
	}

	private static List<String> getParentKeySelection(String projectCode) {
		List<String> keys = new ArrayList<String>();
		String jql = Configuration
				.getDefaultValue("task.calibration.parent.selection");

		jql = jql.replaceFirst(Pattern.quote("${project}"), projectCode);
		try {
			jql = URLEncoder.encode(jql, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			log.error(e);
		}
		String url = baseURL + "/rest/api/2/search?jql=" + jql
				+ "&fields=key&startAt=0&maxResults=1000";

		log.info("Executing search = " + url);
		Client client = Client.create();
		WebResource webResource = client.resource(url);

		// client.addFilter(new
		// com.sun.jersey.api.client.filter.LoggingFilter());
		client.addFilter(new HTTPBasicAuthFilter(usr, pw));

		ClientResponse clientResponse = webResource
				.accept(MediaType.APPLICATION_JSON)
				.header("Content-Type", "application/json")
				.get(ClientResponse.class);

		// String output = clientResponse.getEntity(String.class);
		// log.info("Output from Server .... \n");
		// log.info(output);
		if (clientResponse.getStatus() != 200) {
			throw new RuntimeException("Failed : HTTP error code : "
					+ clientResponse.getStatus());
		}

		String s = clientResponse.getEntity(String.class);
		JSONObject json = null;
		try {
			json = new JSONObject(s);

			JSONArray parentList = json.getJSONArray("issues");
			if (parentList != null) {
				for (int i = 0; i < parentList.toJSONObject(parentList)
						.length(); i++) {
					JSONObject parent = parentList.optJSONObject(i);
					Log.info(parent.toString());
					keys.add(parent.get("key").toString());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return keys;

	}

	private static void updateRank(String key, int rank, String rankingField) {

		String url = baseURL + "/rest/api/2/issue/" + key;
		Client client = Client.create();
		WebResource webResource = client.resource(url);

		// client.addFilter(new
		// com.sun.jersey.api.client.filter.LoggingFilter());
		client.addFilter(new HTTPBasicAuthFilter(usr, pw));
		String jsonRequest = "{\n   \"fields\": { \n    \"" + rankingField
				+ "\": " + rank + " \n   } \n }";
		log.info("Preparing to update url=" + url + ", with JSON="
				+ jsonRequest);

		ClientResponse clientResponse = webResource
				.accept(MediaType.APPLICATION_JSON)
				.header("Content-Type", "application/json")
				.put(ClientResponse.class, jsonRequest);

		// String output = clientResponse.getEntity(String.class);
		// log.info("Output from Server .... \n");
		// log.info(output);
		if (clientResponse.getStatus() != 204) {
			throw new RuntimeException("Failed : HTTP error code : "
					+ clientResponse.getStatus());
		}
	}

	private static int setRemainingToZero(String key) {

		String url = baseURL + "/rest/api/2/issue/" + key;
		Client client = Client.create();
		WebResource webResource = client.resource(url);

		// client.addFilter(new
		// com.sun.jersey.api.client.filter.LoggingFilter());
		client.addFilter(new HTTPBasicAuthFilter(usr, pw));
		String jsonRequest = "{\n   \"fields\": { \n    \"timetracking\": {  \"remainingEstimate\": \"0\" } \n   } \n }";
		log.info("Preparing to update url=" + url + ", with JSON="
				+ jsonRequest);

		ClientResponse clientResponse = webResource
				.accept(MediaType.APPLICATION_JSON)
				.header("Content-Type", "application/json")
				.put(ClientResponse.class, jsonRequest);

		// String output = clientResponse.getEntity(String.class);
		// log.info("Output from Server .... \n");
		// log.info(output);
		if (clientResponse.getStatus() != 204) {
			log.warn(key + " failed update: HTTP error code : "
					+ clientResponse.getStatus());
			return 0;
		}
		log.info(key + " updated successfully: HTTP code : "
				+ clientResponse.getStatus());
		return 1;
	}

	static int updateStatus(String key) {
		String url = baseURL + "/rest/api/2/issue/" + key + "/transitions";

		Client client = Client.create();
		WebResource webResource = client.resource(url);

		client.addFilter(new HTTPBasicAuthFilter(usr, pw));
		String jsonRequest = "{\n   \"update\": { \n    "
				+ "\"comment\": [ { \"add\": { \"body\": \"Issue in backlog should be in status=New. Updating to reflect.\"}}]},"
				+ "\"transition\": { \"id\": \"41\"  } \n  }"; // some have 61 as id
		log.info("Preparing to update url=" + url + ", with JSON="
				+ jsonRequest);

		ClientResponse clientResponse = webResource
				.accept(MediaType.APPLICATION_JSON)
				.header("Content-Type", "application/json")
				.post(ClientResponse.class, jsonRequest);

		if (clientResponse.getStatus() != 204) {
			log.warn(key + " failed update: HTTP error code : "
					+ clientResponse.getStatus());
			return 0;
		}
		log.info(key + " updated successfully: HTTP code : "
				+ clientResponse.getStatus());
		return 1;
	}

	private static void notifyAssigneeOfOldTickets(OdinResponse res) {
		// 1. Find current sprint
		// 2. Find tickets that are NOT associated to future sprints, current
		// sprint, "Sprint *", "Product Backlog" or unassigned
		// AND where Status is NOT "invalid" or "Done".
		// FROM projects in scope.
		// 3. Group tickets by assignee
		// 4. Get email addresses of assignee, manager and JIRA project owner
		// 5. Send email notification to assignee, with CC to manager and JIRA
		// project owner.
		// 6. Insert observation into database
		// 7. Send notification to ODIN administrators.

	}

	public static OdinResponse ensureTasksInProductBacklogNewStatus(OdinResponse res) {
		String jql = Configuration.getDefaultValue("task.calibration.jql.product_backlog");

		int maxResults = 1000;
		int startAt = 0;
		log.info("Executing JQL = " + jql);
		log.info("maxResults=" + maxResults + ", startAt=" + startAt);
		Promise<SearchResult> searchResultPromise = null;

		searchResultPromise = JIRAGateway.getRestClient().getSearchClient()
				.searchJql(jql, maxResults, startAt, null);

		SearchResult searchResult = searchResultPromise.claim();

		Iterable<? extends Issue> issues = searchResult.getIssues();
		for (Issue issue : issues) {
			String status = issue.getStatus().getName();
			if (status.equalsIgnoreCase("In Progress")) {
				log.info("The following task will be updated in Product Backlog: issue.key=" + issue.getKey() + ". Status=" + status);
				updateStatus(issue.getKey());
			}
		}
		return res;
	}

}


text:
package org.apache.phoenix.hive.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.phoenix.hive.constants.PhoenixStorageHandlerConstants;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;

/**
 * @author JeongMin Ju
 *
 */
public class PhoenixConnectionUtil {

	private static final Log LOG = LogFactory.getLog(PhoenixConnectionUtil.class);

	public static Connection getInputConnection(final Configuration conf, final Properties props) throws SQLException {
		String quorum = conf.get(PhoenixStorageHandlerConstants.ZOOKEEPER_QUORUM);
		quorum = quorum == null ? props.getProperty(PhoenixStorageHandlerConstants.ZOOKEEPER_QUORUM, PhoenixStorageHandlerConstants.DEFAULT_ZOOKEEPER_QUORUM) : quorum;

		int zooKeeperClientPort = conf.getInt(PhoenixStorageHandlerConstants.ZOOKEEPER_PORT, 0);
		zooKeeperClientPort = zooKeeperClientPort == 0 ?
				Integer.parseInt(props.getProperty(PhoenixStorageHandlerConstants.ZOOKEEPER_PORT, String.valueOf(PhoenixStorageHandlerConstants.DEFAULT_ZOOKEEPER_PORT))) : zooKeeperClientPort;

		String zNodeParent = conf.get(PhoenixStorageHandlerConstants.ZOOKEEPER_PARENT);
		zNodeParent = zNodeParent == null ? props.getProperty(PhoenixStorageHandlerConstants.ZOOKEEPER_PARENT, PhoenixStorageHandlerConstants.DEFAULT_ZOOKEEPER_PARENT) : zNodeParent;

        return getConnection(quorum, zooKeeperClientPort, zNodeParent, PropertiesUtil.extractProperties(props, conf));
    }

	public static Connection getConnection(final Table table) throws SQLException {
		Map<String, String> tableParameterMap = table.getParameters();

		String zookeeperQuorum = tableParameterMap.get(PhoenixStorageHandlerConstants.ZOOKEEPER_QUORUM);
		zookeeperQuorum = zookeeperQuorum == null ? PhoenixStorageHandlerConstants.DEFAULT_ZOOKEEPER_QUORUM : zookeeperQuorum;

		String clientPortString = tableParameterMap.get(PhoenixStorageHandlerConstants.ZOOKEEPER_PORT);
		int clientPort = clientPortString == null ? PhoenixStorageHandlerConstants.DEFAULT_ZOOKEEPER_PORT : Integer.parseInt(clientPortString);

		String zNodeParent = tableParameterMap.get(PhoenixStorageHandlerConstants.ZOOKEEPER_PARENT);
		zNodeParent = zNodeParent == null ? PhoenixStorageHandlerConstants.DEFAULT_ZOOKEEPER_PARENT : zNodeParent;

		return DriverManager.getConnection(QueryUtil.getUrl(zookeeperQuorum, clientPort, zNodeParent));
    }

	private static Connection getConnection(final String quorum, final Integer clientPort, String zNodeParent, Properties props) throws SQLException {
		if (LOG.isDebugEnabled()) {
			LOG.debug("<<<<<<<<<< [quorum, port, znode] : " + quorum + ", " + clientPort + ", " + zNodeParent + " >>>>>>>>>>");
		}

        return DriverManager.getConnection(clientPort != null ? QueryUtil.getUrl(quorum, clientPort, zNodeParent) :  QueryUtil.getUrl(quorum), props);
    }

}


text:
'use strict';

/**
 * @ngdoc function
 * @name wwwApp.controller:DayCtrl
 * @description
 * # DayCtrl
 * Controller of the wwwApp
 */
angular.module('wwwApp')
    .controller('DayCtrl', function ($scope, $stateParams, Gallery) {
        var query = {
            day: $stateParams.day
        };

        if ($stateParams.country_id) {
            query.country = $stateParams.country_id;
        }

        $scope.galleries = Gallery.query(query,
            function (data) {
                angular.forEach(data, function (row) {
                    row.icons = Gallery.icons({id: row.id, limit: 10});
                });
            }
        );

    });


text:
#include "QmitkTransferFunctionCanvas.h"

#include <itkObject.h>

#include <QColorDialog>
#include <QPainter>
#include <QMouseEvent>

QmitkTransferFunctionCanvas::QmitkTransferFunctionCanvas(QWidget * parent,
    Qt::WindowFlags f) :
  QWidget(parent, f),
  m_GrabbedHandle(-1),
  m_Lower(0.0),
  m_Upper(1.0),
  m_Min(0.0),
  m_Max(1.0),
  m_Histogram(0),
  m_ImmediateUpdate(false),
  m_Range(0.0f),
  m_LineEditAvailable(false),
  m_XEdit(0),
  m_YEdit(0)
{
  setEnabled(false);
  setFocusPolicy(Qt::ClickFocus);
}

void QmitkTransferFunctionCanvas::paintEvent(QPaintEvent* ev)
{
  QWidget::paintEvent(ev);
}

std::pair<int,int> QmitkTransferFunctionCanvas::FunctionToCanvas(
    std::pair<double,double> functionPoint)
{
  //std::cout<<"F2C.first: "<<(int)((functionPoint.first - m_Lower) /  (m_Upper - m_Lower) * width())<<" F2C.second: "<<(int)(height() * (1 - functionPoint.second))<<std::endl;
  return std::make_pair((int) ((functionPoint.first - m_Lower) / (m_Upper
      - m_Lower) * contentsRect().width()) + contentsRect().x(), (int) (contentsRect().height() * (1 - functionPoint.second)) + contentsRect().y());
}

std::pair<double,double> QmitkTransferFunctionCanvas::CanvasToFunction(
    std::pair<int,int> canvasPoint)
{
  //std::cout<<"C2F.first: "<<(canvasPoint.first * (m_Upper - m_Lower) / width() + m_Lower)<<" C2F.second: "<<(1.0 - (double)canvasPoint.second / height())<<std::endl;
  return std::make_pair((canvasPoint.first - contentsRect().x()) * (m_Upper - m_Lower) / contentsRect().width()
      + m_Lower, 1.0 - (double) (canvasPoint.second - contentsRect().y()) / contentsRect().height());
}

void QmitkTransferFunctionCanvas::mouseDoubleClickEvent(QMouseEvent* mouseEvent)
{
  int nearHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
  if (nearHandle != -1)
  {
    this->DoubleClickOnHandle(nearHandle);
  }
}

/** returns index of a near handle or -1 if none is near
 */
int QmitkTransferFunctionCanvas::GetNearHandle(int /*x*/, int /*y*/,
    unsigned int /*maxSquaredDistance*/)
{
  return -1;
}

void QmitkTransferFunctionCanvas::mousePressEvent(QMouseEvent* mouseEvent)
{

  if (m_LineEditAvailable)
  {
    m_XEdit->clear();
    if(m_YEdit)
      m_YEdit->clear();
  }

  m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());

  if ( (mouseEvent->button() & Qt::LeftButton) && m_GrabbedHandle == -1)
  {
    this->AddFunctionPoint(
        this->CanvasToFunction(std::make_pair(mouseEvent->pos().x(),
            mouseEvent->pos().y())).first,
        this->CanvasToFunction(std::make_pair(mouseEvent->x(), mouseEvent->y())).second);
    m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(),
        mouseEvent->pos().y());
    mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  }
  else if ((mouseEvent->button() & Qt::RightButton) && m_GrabbedHandle != -1 && this->GetFunctionSize() > 1)
  {
     this->RemoveFunctionPoint(this->GetFunctionX(m_GrabbedHandle));
     m_GrabbedHandle = -1;
     mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  }
  update();

  // m_TransferFunction->UpdateVtkFunctions();
}

void QmitkTransferFunctionCanvas::mouseMoveEvent(QMouseEvent* mouseEvent)
{
  if (m_GrabbedHandle != -1)
  {
    std::pair<double,double>
        newPos = this->CanvasToFunction(std::make_pair(mouseEvent->x(),
            mouseEvent->y()));

    // X Clamping
    {
      // Check with predecessor
      if( m_GrabbedHandle > 0 )
        if (newPos.first <= this->GetFunctionX(m_GrabbedHandle - 1))
          newPos.first = this->GetFunctionX(m_GrabbedHandle);

      // Check with sucessor
      if( m_GrabbedHandle < this->GetFunctionSize()-1 )
        if (newPos.first >= this->GetFunctionX(m_GrabbedHandle + 1))
          newPos.first = this->GetFunctionX(m_GrabbedHandle);

      // Clamping to histogramm
           if (newPos.first < m_Min) newPos.first = m_Min;
      else if (newPos.first > m_Max) newPos.first = m_Max;
    }

    // Y Clamping
    {
           if (newPos.second < 0.0) newPos.second = 0.0;
      else if (newPos.second > 1.0) newPos.second = 1.0;
    }

    // Move selected point
    this->MoveFunctionPoint(m_GrabbedHandle, newPos);

    /*
    // Search again selected point ??????? should not be required, seems like a legacy workaround/bugfix
    // and no longer required
    m_GrabbedHandle = -1;
    for (int i = 0; i < this->GetFunctionSize(); i++)
    {
      if (this->GetFunctionX(i) == newPos.first)
      {
        m_GrabbedHandle = i;
        break;
      }
    }
    */

    update();

    //if (m_ImmediateUpdate)
      mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  }
}

void QmitkTransferFunctionCanvas::mouseReleaseEvent(QMouseEvent*)
{
  // m_GrabbedHandle = -1;
  update();
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}

void QmitkTransferFunctionCanvas::PaintHistogram(QPainter &p)
{
  if(m_Histogram)
  {
    p.save();

    p.setPen(Qt::gray);

    int displayWidth = contentsRect().width();
    int displayHeight = contentsRect().height();

    double windowLeft = m_Lower;
    double windowRight = m_Upper;

    double step = (windowRight-windowLeft)/double(displayWidth);

    double pos = windowLeft;

    for (int x = 0; x < displayWidth; x++)
    {
      double left = pos;
      double right = pos + step;

      float height = m_Histogram->GetRelativeBin( left , right );

      if (height >= 0)
        p.drawLine(x, displayHeight*(1-height), x, displayHeight);

      pos += step;
    }

    p.restore();
  }
}

void QmitkTransferFunctionCanvas::keyPressEvent(QKeyEvent * e)
{
  if( m_GrabbedHandle == -1)
    return;

  switch(e->key())
  {
    case Qt::Key_Delete:
      if(this->GetFunctionSize() > 1)
      {
        this->RemoveFunctionPoint(GetFunctionX(m_GrabbedHandle));
        m_GrabbedHandle = -1;
      }
      break;

    case Qt::Key_Left:
      this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle)-1 , GetFunctionY(m_GrabbedHandle))));
      break;

    case Qt::Key_Right:
      this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle)+1 , GetFunctionY(m_GrabbedHandle))));
      break;

    case Qt::Key_Up:
      this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle) , GetFunctionY(m_GrabbedHandle)+0.001)));
      break;

    case Qt::Key_Down:
      this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair( GetFunctionX(m_GrabbedHandle) , GetFunctionY(m_GrabbedHandle)-0.001)));
      break;
  }

  update();
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}

// Update immediatly while changing the transfer function
void QmitkTransferFunctionCanvas::SetImmediateUpdate(bool state)
{
  m_ImmediateUpdate = state;
}


text:
package com.spotify.heroic.querylogging.noop;

import com.spotify.heroic.Query;
import com.spotify.heroic.metric.FullQuery;
import com.spotify.heroic.metric.FullQuery.Request;
import com.spotify.heroic.metric.QueryMetrics;
import com.spotify.heroic.metric.QueryMetricsResponse;
import com.spotify.heroic.querylogging.HttpContext;
import com.spotify.heroic.querylogging.QueryContext;
import com.spotify.heroic.querylogging.QueryLogger;
import com.spotify.heroic.querylogging.QueryLoggingScope;
import org.slf4j.Logger;

@QueryLoggingScope
public class NoopQueryLogger implements QueryLogger {

    private static final Logger log = org.slf4j.LoggerFactory.getLogger(NoopQueryLogger.class);

    @Override
    public void logHttpQueryText(
        final QueryContext context, final String query
    ) {
    }

    @Override
    public void logHttpQueryJson(
        final QueryContext context, final QueryMetrics query
    ) {
    }

    public void logHttpQueryObject(
        final QueryContext context, final Object query, final HttpContext httpContext
    ) {
    }

    @Override
    public void logQuery(final QueryContext context, final Query query) {
    }

    @Override
    public void logOutgoingRequestToShards(
        final QueryContext context, final FullQuery.Request request
    ) {
    }

    @Override
    public void logIncomingRequestAtNode(
        final QueryContext context, final FullQuery.Request request
    ) {
    }

    @Override
    public void logBigtableQueryTimeout(QueryContext context, Request request) {

    }

    @Override
    public void logOutgoingResponseAtNode(final QueryContext context, final FullQuery response) {
    }

    @Override
    public void logIncomingResponseFromShard(
        final QueryContext context, final FullQuery response
    ) {
    }

    @Override
    public void logFinalResponse(
        final QueryContext context, final QueryMetricsResponse queryMetricsResponse
    ) {
    }
}


text:
package org.jbehave.jbel.evaluator;

import java.io.IOException;
import java.io.InputStream;

import org.junit.Assert;

public class JBelTestUtils {

	public static void testScenario(String scenarioName) throws IOException {
		assertEqual(scenarioName, new JBelScenarioEvaluator(readJBel(scenarioName)));
	}

	public static void testStory(String storyName) throws IOException {
		assertEqual(storyName, new JBelStoryEvaluator(readJBel(storyName)));
	}

	private static String readJBel(String name) throws IOException {
		return readString(name, "jbel");
	}

	private static String readString(String name, String type) throws IOException {
		InputStream s = JBelScenarioEvaluatorBehaviour.class.getResourceAsStream("/" + type + "/" + name + '.' + type);
		try {
			java.util.Scanner scanner = new java.util.Scanner(s).useDelimiter("\\A");
			return scanner.next();
		}
		finally {
			if (s != null) {
				s.close();
			}
		}
	}

	private static void assertEqual(String name, JBelEvaluator jBelEvaluator) throws IOException {
		try {
			Assert.assertEquals(readString(name, "story").trim(), jBelEvaluator.getResult().trim());
		}
		catch (NullPointerException e) {
			System.out.println("error");
			System.out.println(jBelEvaluator.getResult());
			throw e;
		}

	}
}


text:
Smooth Scroll has three types of licenses:

1. **[Open Source](#open-source-license)**, for personal and open source projects.
2. **[Commercial](#commercial-license)**, for commercial projects and applications.
3. **[OEM](#oem-license)**, for when this Smooth Scroll will be bundled with a commercial interface builder, SDK, or toolkit.

## Open Source License

If you're looking to use Smooth Scroll on an open source or personal project, the code is available under the [GPLv3 License](https://gomakethings.com/gpl/). GPLv3 has many terms, but the most important one is that it [requires you to license you entire project under the terms of GPLv3 as well](https://gomakethings.com/gpl/#5-conveying-modified-source-versions):

> You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged.

You can absolutely use the open source license for commercial projects, but those projects must also be open sourced in their entirety with a GPLv3 license.

## Commercial License

The Commercial License let's you use Smooth Scroll in commercial projects and applications without the provisions of GPLv3. With this license, your code is kept proprietary.

- You can modify the source code.
- You can include it in your own commercial products and applications, such as premium CMS themes, plugins, or templates.
- Customers and users of your products do not need to purchase their own license, as long as they're not developing their own commercial products with Smooth Scroll.

### Buy a Commercial License

Commercial Licenses are priced based on the number of websites, applications, or other products that use Smooth Scroll. Pay with credit card and instantly receive a PDF of your Commercial License.

			Description
			Price

			1 Site or App
			Buy a 1 Site License now for $29

			5 Sites or Apps
			Buy a 5 Site License now for $59

			25 Sites or Apps
			Buy a 25 Site License now for $119

You can read the full text of the Commercial License below. Email me at chris@gomakethings.com with any questions you have about licensing.

### The Commercial License Agreement

This Software License Agreement (the **"Agreement"**) is between Go Make Things, LLC (**"Go Make Things"**) and You (including your agents and affiliates), a commercial licensee of Go Make Things's software. If you have not purchased a Smooth Scroll Commercial License from Go Make Things, these terms do not apply to you, and your use of the Go Make Things software is instead governed by the [GNU General Public License, version 3](https://gomakethings.com/gpl/).

#### 1. Definitions

- **"Application"** means any software, application, or elements that Your Licensed Developers develop using the Software or Modifications in accordance with this Agreement.
- **"End User"** means an end user of Your Application who acquires a license to such solely for their own use and not for distribution, resale, user interface design, or software development purposes.
- **"Licensed Developer"** shall mean an individual person permitted to use the Software and make Modifications for your Applications, whether such person is Your employee or a consultant or contractor providing services to You.
- **"Modification"** means any revision, adaptation, or derivative of the Software produced by You.
- The **"Software"** means Smooth Scroll version 11.

#### 2. Commercial license grant

Subject to the terms of this Agreement, Go Make Things grants to You a revocable, non-exclusive, non-transferable license:
- for Licensed Developers to use the Software to create Modifications and [n—varies based on the license you purchase] Applications;
- for You to distribute the Software and/or Modifications to an unlimited number of End Users solely as integrated into the Applications;
- and for End Users to use the Software as incorporated into Your Applications in accordance with the terms of this Agreement.

You are entitled to receive all updates to the major version of the Software licensed by you, as well as any later version of the Software that Go Make Things, in writing, explicitly authorizes you to use. (For illustration purposes only, if you purchased a license for version 2.0, this licenses authorizes you to use version 2.9, but not 3.0.) Go Make Things makes no representation that any update will be compatible with your Application.

#### 3. Ownership

This is a license agreement and not an agreement for sale. Go Make Things reserves ownership of all intellectual property rights inherent in or relating to the Software and corresponding source code, which include all copyright, patent rights, all rights in relation to registered and unregistered trademarks (including service marks), confidential information (including trade secrets and know-how) and all rights other than those expressly granted by this Agreement.

You must not remove, obscure or interfere with any copyright, acknowledgment, attribution, trademark, warning or disclaimer statement affixed to, incorporated in or otherwise applied in connection with the Software. Notwithstanding the above, you are permitted to produce, use, and distribute compressed or "minified" copies of the Software that do not bear the notices contained in the Software's source code, so long as you otherwise comply with the terms of this license.

#### 4. Prohibited Uses

Your Application must have substantially different functionality than, and must not compete directly with, the Software.

You may not distribute the Software or Modifications except as included within Your Application.

If You produce an Application for a customer, You are responsible for ensuring that your customer does not make use of the Software except with Applications licensed herein.

Your Application must not enable End Users to produce separate applications that incorporate the Software or Modifications. For example, if Your Application is a development toolkit or library, an application builder, a website builder that can be used to incorporate the Software into a new Application, You must obtain a separate OEM license from Go Make Things.

#### 5. Termination

This Agreement and the license granted hereunder shall continue until terminated in accordance with this Section. Unless otherwise specified in this Agreement, the license shall last as long as Your use of the Software is in compliance with the terms herein.

Go Make Things shall have the right to terminate this Agreement and the license granted hereunder immediately if You breach any of the material terms of this Agreement. Upon termination of this Agreement, all licenses granted to You in this Agreement shall terminate automatically and You shall immediately cease use and distribution of the Software.

Upon termination of this Agreement, You must cease all use of the Software. If, prior to your breach of this Agreement, you delivered Applications incorporating the Software to Your End Users, those End Users' licenses shall survive termination.

#### 6. Disclaimer of Warranties

TO THE EXTENT PERMITTED BY LAW, GO MAKE THINGS DISCLAIMS ALL WARRANTIES AND CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT, WITH REGARD TO THE SOFTWARE. WE DO NOT GUARANTEE THAT THE OPERATION OF THE SOFTWARE OR YOUR APPLICATION WILL BE UNINTERRUPTED OR ERROR-FREE, AND YOU ACKNOWLEDGE THAT IT IS NOT TECHNICALLY PRACTICABLE FOR US TO DO SO.

#### 7. Limitation of Liabilities

TO THE EXTENT PERMITTED BY LAW, IN NO EVENT SHALL GO MAKE THINGS BE LIABLE UNDER ANY LEGAL OR EQUITABLE THEORY FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LAW) ARISING OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE OR THE CODE IT PRODUCES OR ANY OTHER SUBJECT MATTER RELATING TO THIS AGREEMENT, EVEN IF GO MAKE THINGS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY CASE, GO MAKE THINGS'S ENTIRE LIABILITY WITH RESPECT TO ANY SUBJECT MATTER RELATING TO THIS AGREEMENT SHALL BE LIMITED TO THE GREATER OF: (I) THE AMOUNT ACTUALLY PAID BY YOU FOR THE LICENSE, OR (II) FIVE HUNDRED DOLLARS ($500).

#### 8. Indemnification

While redistributing the Software or Modifications thereof as part of Your Application, You may choose to offer acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this Agreement. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, and not on Go Make Things's behalf.

You agree to indemnify, hold harmless, and defend Go Make Things and its owners, officers, agents, and affiliates from and against any and all claims, lawsuits and proceedings (collectively "Claims"), and all expenses, costs (including attorney's fees), judgments, damages and other liabilities resulting from such Claims, that arise or result from:
- your use of the Software in violation of this Agreement;
- the use or distribution of Your Application, except to the extent such claim is based solely on the inclusion of the Software therein;
- your Modification of the Software's source code; or
- your accepting support, warranty, indemnity, or additional liability as described in the preceding paragraph.

#### 9. Payment and Taxes

All payments under this Agreement are due to Go Make Things upon Your purchase of a license to the Software.

Each party shall be responsible for all taxes (including, but not limited to, taxes based upon its income) or levies imposed on it under applicable laws, regulations and tax treaties as a result of this Agreement and any payments made hereunder (including those required to be withheld or deducted from payments); provided that You shall be responsible for any value added tax, use tax, sales tax, or similar tax, and shall pay or reimburse Go Make Things for the same upon invoice. Each party shall furnish evidence of such paid taxes as is sufficient to enable the other party to obtain any credits available to it, including original tax withholding certificates.

#### 10. Miscellaneous

Software Updates and Upgrades. The license granted herein applies only to the version of the Software available when purchased in connection with the terms of this Agreement, and to any updates and/or upgrades to which You may be entitled. Any previous or subsequent license granted to You for use of the Software shall be governed by the terms and conditions of the agreement entered in connection with purchase or download of that version of the Software.

**Survival.** The provisions of sections 4 through 10 will survive termination of this Agreement.

**Compliance with Applicable Laws.** You agree that You will comply with all applicable laws and regulations with respect to the Software, including without limitation all export control laws and regulations.

**Marketing.** You agree to Go Make Things's use of Your name, trade name, and trademark, for use in Go Make Things's marketing materials and its website, solely to identify you as a customer of Go Make Things.

**Assignment.** This Agreement may be assigned by Go Make Things in whole or in part and will inure to the benefit of Go Make Things's successors and assigns. You may not assign or transfer this Agreement without Go Make Things's prior written consent. Notwithstanding the foregoing, however, if You transfer ownership of an Application to a customer for which it was developed, You may assign this Agreement to that customer (the "Assignee") provided:
1. You provide written notice to Go Make Things prior to the effective date of such assignment; and
2. there is a written agreement, wherein the Assignee accepts the terms of this Agreement.

**Entire Agreement.** The terms and conditions stated herein set forth the entire agreement of the parties and replace and supersede all other contracts, agreements, and understandings, written or oral, relating to the subject matter hereof.

**Severability.** In the event that any portion of this Agreement is held to be unenforceable, such portions shall not limit or otherwise modify or affect any other portion of this Agreement.

**Modification; Waiver.** This Agreement cannot be amended except by a written instrument executed by Go Make Things.

 All Additional Terms are hereby incorporated into this Agreement by this reference.

 The failure of Go Make Things to enforce any provision of this Agreement may not be deemed a waiver of that or any other provision of this Agreement.

**Governing Law.** This Agreement is subject to, and shall be interpreted and enforced in accordance with, the laws of the Commonwealth of Massachusetts in all respects without regard to conflict of law principles. The Courts of Bristol County, Massachusetts and Norfolk County, Massachusetts shall be the sole and exclusive Courts in which either party may attempt to enforce or establish the existence or scope of any rights, benefits or obligations under this Agreement. The UN Convention on Contracts for the International Sale of Goods is expressly excluded.

**Government Use.** If the Software or any related documentation is licensed to the U.S. Government or any agency thereof, it will be considered to be "commercial computer software" or "commercial computer software documentation," as those terms are used in 48 CFR § 12.212 or 48 CFR § 227.7202, and is being licensed with only those rights as are granted to all other licensees as set forth in this Agreement.

## OEM License

If you'll be including Smooth Scroll in a project that can be used to build new products, websites, or applications—such as a commercial interface builder, SDK, or toolkit—you need to purchase an OEM License.

The OEM License is customized for you. Please content me chris@gomakethings.com to discuss your project.


text:
layout: post
title: ChEMBL Goes to A Conference - Fall ACS 2009
date: '2009-03-26T12:14:00.004Z'
author: John Overington
tags:
- Conferences
modified_time: '2009-03-29T10:53:56.624+01:00'
thumbnail: http://4.bp.blogspot.com/_SlPG9DIz_AA/Scty9MRizRI/AAAAAAAAANA/wUext9Zv4yo/s72-c/ZxjsbuErUYuZ.jpg
blogger_id: tag:blogger.com,1999:blog-2546008714740235720.post-7237376397918322841
blogger_orig_url: http://chembl.blogspot.com/2009/03/chembl-goes-to-conference.html
---

We are going to speak at the 238th ACS National Meeting, Washington, DC, August 16-20, 2009, on "ChEMBL: Large-scale Mapping of Medicinal Chemistry and Pharmacology Data to Genomes". The Abstract for the talk is:

Although the majority of effective therapeutics are small molecules,
there is relatively little readily accessible public domain data
mapping drugs to their molecular targets. When one considers clinical
trial stage, or discovery stage data, the situation deteriorates
further. However, this type of data is essential for Chemical Biology
experiments, and is crucial for informed target selection in drug
discovery. To address this issue, we have built a series of large
scale databases, known as ChEMBL, that map small molecule structures
to their target genes and also their functional effects. This data
also captures a large ammount of human and model organism
pharmacological data, systems often used in pre-clinical validation
and safety pharmacology testing. A variety of applications of these
databases in the area of target prioritisation, lead discovery, lead
optimisation and drug repurposing will be described.


text:
[![Gem Version](https://badge.fury.io/rb/jirasync.svg)](http://badge.fury.io/rb/jirasync)

## Installation

    gem install jirasync

## Usage

### Initial Fetch

The following command will start synchronising the project `MYPROJ` from the server at
`https://jira.myorganisation.com`. The issues from that project will be written to the
`issues/MYPROJ` folder:

    jira-sync \
        --baseurl https://jira.myorganisation.com \
        --project MYPROJ  \
        --user jira_user \
        --password jira_password \
        --target issues/MYPROJ/raw \
        fetch

When this passes successfully the `issues/MYPROJ/raw` directory will contain the following structure:

    MYPROJ-1.json
    MYPROJ-2.json
    MYPROJ-3.json
    MYPROJ-4.json
    …
    sync_state.json

Each issue file contains a pretty-printed json representation of the ticket. The modified date of the files is set to
the value of the `updated` field of the corresponding ticket, so that a makefile can be used to render the
json files incrementally into a more readable representation.

The `sync_state.json` file contains information about the last sync, such as the time and errors that occurred.

### Updating

The following statement will sync issues that have changed or where added during the last sync:

~~~ {.bash}

jira-sync \
    --baseurl https://jira.myorganisation.com \
    --project MYPROJ  \
    --user jira_user \
    --password jira_password \
    --target issues/MYPROJ/raw \
    update

~~~

### Fetching and Storing Attachments

Passing in the `--store-attachments` option leads to attachments being fetched and stored in the local filesystem.
They will we be stored in the `attachments/` sub-directory of the target directory.

### Formatting Issues

While JSON files are very handy to use in code, they are not very readable. The `jira-format-issues` command
formats JSON issues to markdown. It is invoked as follows:

~~~ {.sh}

jira-format-issues \
    --source  issues/MYPROJ/raw\
    --target  issues/MYPROJ/markdown

~~~

This will create the following structure in the `issues/MYPROJ/markdown`:

    MYPROJ-1.md
    MYPROJ-2.md
    MYPROJ-3.md
    MYPROJ-4.md
    …

The individual files look like this:

~~~ {.md}
[MYPROJ-1](https://jira.myorganisation.com/browse/MYPROJ-1): Build a working System
===================================================================================

Type
:   Story

Status
:   Closed

Reporter
:   fleipold

Labels
:   triaged

Updated
:   20. Jan 2014 11:30 (UTC)

Created
:   01. Aug 2013 12:29 (UTC)

Description
-----------

The myproj system shall be built to be *delpoyable* and *working*.

Comments
--------

### fleipold - 20. Jan 2014 12:19 (UTC):

Is this still relevant?

~~~

These files can be easily searched by ensuring they get indexed by a desktop search engine, e.g.
[spotlight](https://gist.github.com/gereon/3150445) on the Mac.

 There is also the possibility to render custom jira fields by supplying a *custom data* file, which declares *simple
 data* fields which are rendered as definitions at the top of the ticket and *sections* that are rendered as one or more paragraphs
 with a heading. Here is an example file, `custom-data.json`:

~~~ {.json}
{
    "simple_fields" : {
         "Audience" : ["customfield_10123", "value"]
    },
    "sections" : {
         "Release Notes" : ["customfield_10806"]
    }
}

~~~

This file can be passed in like this:

~~~ {.bash}

jira-format-issues \
    --source  issues/MYPROJECT/json \
    --target  issues/MYPROJECT/markdown \
    --custom-data-path custom-data.json

~~~

## Using Cookie-Authentication

If a single-sign-on solution is used, `jira-sync` can also use the session
cookie to authenticate requests to jira, likeso:

    jira-sync \
        --baseurl https://jira.myorganisation.com \
        --project MYPROJ  \
        --cookie JSESSIONID=… \
        --target issues/MYPROJ/raw \
        fetch

## Motivation

Having a local, unix-friendly copy of all tickets to avoid JIRA performance issues and
make information available offline.

## Potential Future Work

- [X] Make progress bar work
- [X] Make output less noisy
- [X] Download attachments
- [ ] Produce tabular output
- [ ] Deal with authentication problems explicitly
- [ ] Remove tickets that have been moved to a different project
- [ ] Use OAuth authentication


text:
package com.eixox.data.common;

import com.eixox.data.ColumnSchema;
import com.eixox.data.DataDelete;

public class TableDelete extends DataDelete {

	public final Table table;

	public TableDelete(Table table) {
		this.table = table;
	}

	@Override
	public long execute() {
		int counter = 0;
		if (this.filter == null) {
			counter = table.rows.size();
			this.table.rows.clear();
		} else {
			for (int i = 0; i < this.table.rows.size(); i++) {
				TableRow row = this.table.rows.get(i);
				if (filter.testRow(row.cells)) {
					table.rows.remove(i);
					counter++;
				}
			}
		}
		return counter;
	}

	@Override
	public ColumnSchema<?> getSchema() {
		return this.table.schema;
	}

}


text:
package VMOMI::VmwareDistributedVirtualSwitch;
use parent 'VMOMI::DistributedVirtualSwitch';

use strict;
use warnings;

our @class_ancestors = (
    'DistributedVirtualSwitch',
    'ManagedEntity',
    'ExtensibleManagedObject',
    'ManagedObject',
);

our @class_members = ( );

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
<?php

class Dotdigitalgroup_Email_Block_Adminhtml_Widget_Chooser_Product
    extends Mage_Adminhtml_Block_Widget_Grid
{

    /**
     * Dotdigitalgroup_Email_Block_Adminhtml_Widget_Chooser_Product constructor.
     * @param array $arguments
     */
    public function __construct($arguments = array())
    {
        parent::__construct($arguments);

        if ($this->getRequest()->getParam('current_grid_id')) {
            $this->setId($this->getRequest()->getParam('current_grid_id'));
        } else {
            $this->setId('skuChooserGrid_' . $this->getId());
        }

        //change to 10
        $this->setDefaultLimit(10);
        $form = $this->getJsFormObject();
        $this->setRowClickCallback("$form.chooserGridRowClick.bind($form)");
        $this->setCheckboxCheckCallback(
            "$form.chooserGridCheckboxCheck.bind($form)"
        );
        $this->setRowInitCallback("$form.chooserGridRowInit.bind($form)");
        $this->setDefaultSort('entity_id');
        $this->setUseAjax(true);
        if ($this->getRequest()->getParam('collapse')) {
            $this->setIsCollapsed(true);
        }
    }

    /**
     * Retrieve quote store object
     *
     * @return Mage_Core_Model_Store
     */
    public function getStore()
    {
        return Mage::app()->getStore();
    }

    /**
     * @param $column
     * @return $this
     */
    protected function _addColumnFilterToCollection($column)
    {
        // Set custom filter for in product flag
        if ($column->getId() == 'in_products') {
            $selected = $this->_getSelectedProducts();
            if (empty($selected)) {
                $selected = '';
            }

            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter(
                    'entity_id', array('in' => $selected)
                );
            } else {
                $this->getCollection()->addFieldToFilter(
                    'entity_id', array('nin' => $selected)
                );
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }

        return $this;
    }

    /**
     * Prepare Catalog Product Collection for attribute SKU in Promo Conditions SKU chooser
     *
     * @return Mage_Adminhtml_Block_Widget_Grid
     */
    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('catalog/product_collection')
            ->setStoreId(0)
            ->addAttributeToSelect('name', 'type_id', 'attribute_set_id');

        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    /**
     * Define Cooser Grid Columns and filters
     *
     * @return Mage_Adminhtml_Block_Widget_Grid
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'in_products', array(
                'header_css_class' => 'a-center',
                'type'             => 'checkbox',
                'name'             => 'in_products',
                'values'           => $this->_getSelectedProducts(),
                'align'            => 'center',
                'index'            => 'entity_id',
                'use_index'        => true,
            )
        );

        $this->addColumn(
            'entity_id', array(
                'header'   => Mage::helper('sales')->__('ID'),
                'sortable' => true,
                'width'    => '60px',
                'index'    => 'entity_id'
            )
        );

        $this->addColumn(
            'type',
            array(
                'header'  => Mage::helper('catalog')->__('Type'),
                'width'   => '60px',
                'index'   => 'type_id',
                'type'    => 'options',
                'options' => Mage::getSingleton('catalog/product_type')
                    ->getOptionArray(),
            )
        );

        $sets = Mage::getResourceModel('eav/entity_attribute_set_collection')
            ->setEntityTypeFilter(
                Mage::getModel('catalog/product')->getResource()->getTypeId()
            )
            ->load()
            ->toOptionHash();

        $this->addColumn(
            'set_name',
            array(
                'header'  => Mage::helper('catalog')->__('Attrib. Set Name'),
                'width'   => '100px',
                'index'   => 'attribute_set_id',
                'type'    => 'options',
                'options' => $sets,
            )
        );

        $this->addColumn(
            'chooser_sku', array(
                'header' => Mage::helper('sales')->__('SKU'),
                'name'   => 'chooser_sku',
                'width'  => '80px',
                'index'  => 'sku'
            )
        );
        $this->addColumn(
            'chooser_name', array(
                'header' => Mage::helper('sales')->__('Product Name'),
                'name'   => 'chooser_name',
                'index'  => 'name'
            )
        );

        return parent::_prepareColumns();
    }

    /**
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl(
            '*/*/product', array(
                '_current'        => true,
                'current_grid_id' => $this->getId(),
                'collapse'        => null
            )
        );
    }

    /**
     * @return mixed
     */
    protected function _getSelectedProducts()
    {
        $products = $this->getRequest()->getPost('selected', array());

        return $products;
    }

    /**
     * Set default limit.
     *
     * @param $limit
     *
     * @return $this
     */
    public function setDefaultLimit($limit)
    {
        $this->_defaultLimit = $limit;

        return $this;
    }
}


text:
package com.fly.firefly.ui.activity.ManageFlight;

import android.app.FragmentManager;
import android.os.Bundle;

import com.fly.firefly.MainFragmentActivity;
import com.fly.firefly.R;
import com.fly.firefly.ui.activity.FragmentContainerActivity;
import com.fly.firefly.ui.fragment.ManageFlight.ManageFlight_SentItineraryFragment;

import butterknife.ButterKnife;

//import android.view.WindowManager;

public class ManageFlight_SentItinerary extends MainFragmentActivity implements FragmentContainerActivity {

    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.inject(this);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().add(R.id.main_activity_fragment_container, ManageFlight_SentItineraryFragment.newInstance()).commit();

        hideTitle();
    }

    @Override
    public int getFragmentContainerId() {
        return R.id.main_activity_fragment_container;
    }

}


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2019 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.runtime;

import static android.Manifest.permission.CALL_PHONE;
import static android.Manifest.permission.PROCESS_OUTGOING_CALLS;
import static android.Manifest.permission.READ_CALL_LOG;
import static android.Manifest.permission.READ_PHONE_STATE;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.telephony.TelephonyManager;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.util.BulkPermissionRequest;
import com.google.appinventor.components.runtime.util.PhoneCallUtil;

/**
 * ![PhoneCall component icon](images/phonecall.png)
 *
 * A non-visible component that makes a phone call to the number specified in the
 * {@link #PhoneNumber()} property, which can be set either in the Designer or Blocks Editor.
 * The component has a {@link #MakePhoneCall()} method, enabling the program to launch a phone call.
 * You may also use {@link #MakePhoneCallDirect()} to directly initiate a phone call without user
 * interaction. However, apps using this block may require further review by Google if submitted
 * to the Play Store so it is advised to use {@link #MakePhoneCall()} instead.
 *
 * Often, this component is used with the {@link ContactPicker} component, which lets the user
 * select a contact from the ones stored on the phone and sets the
 * {@link #PhoneNumber()} property to {@link ContactPicker#PhoneNumber()} property.
 *
 * To directly specify the phone number (e.g., 650-555-1212), set the {@link #PhoneNumber()}
 * property to a Text with the specified digits (e.g., "6505551212"). Dashes, dots, and parentheses
 * may be included (e.g., "(650)-555-1212") but will be ignored; spaces may not be included.
 *
 * @internaldoc
 *
 * TODO(markf): Note that the initial carrier for Android phones only supports 3 participants
 *              in a conference call, so that's all that the current implementation of this
 *              component supports.  In the future we can generalize this to more participants.
 *
 * @author markf@google.com (Mark Friedman)
 * @author rekygx@gmail.com (Xian Gao)
 */
@DesignerComponent(version = YaVersion.PHONECALL_COMPONENT_VERSION,
    description = "
A non-visible component that makes a phone call to " +
        "the number specified in the PhoneNumber property, which " +
        "can be set either in the Designer or Blocks Editor. The component " +
        "has a MakePhoneCall method, enabling the program to launch " +
        "a phone call.
" +
        "
Often, this component is used with the ContactPicker " +
        "component, which lets the user select a contact from the ones stored " +
        "on the phone and sets the PhoneNumber property to the " +
        "contact's phone number.
" +
        "
To directly specify the phone number (e.g., 650-555-1212), set " +
        "the PhoneNumber property to a Text with the specified " +
        "digits (e.g., \"6505551212\").  Dashes, dots, and parentheses may be " +
        "included (e.g., \"(650)-555-1212\") but will be ignored; spaces may " +
        "not be included.
",
    category = ComponentCategory.SOCIAL,
    nonVisible = true,
    iconName = "images/phoneCall.png")
@SimpleObject
public class PhoneCall extends AndroidNonvisibleComponent implements Component, OnDestroyListener,
    ActivityResultListener {

  /**
   * Magic number "PHON" used to report when a phone call has been initiated
   */
  private static final int PHONECALL_REQUEST_CODE = 0x50484F4E;
  private String phoneNumber;
  private final Context context;
  private final CallStateReceiver callStateReceiver;
  private boolean havePermission = false;
  private boolean didRegisterReceiver = false;

  /**
   * Creates a Phone Call component.
   *
   * @param container container, component will be placed in
   */
  public PhoneCall(ComponentContainer container) {
    super(container.$form());
    context = container.$context();
    form.registerForOnDestroy(this);
    form.registerForActivityResult(this, PHONECALL_REQUEST_CODE);
    PhoneNumber("");
    callStateReceiver = new CallStateReceiver();
  }

  @SuppressWarnings({"unused"})
  public void Initialize() {
    if (form.doesAppDeclarePermission(READ_CALL_LOG)) {
      form.askPermission(new BulkPermissionRequest(this, "Initialize",
          PROCESS_OUTGOING_CALLS, READ_PHONE_STATE, READ_CALL_LOG) {
        @Override
        public void onGranted() {
          registerCallStateMonitor();
        }
      });
    }
  }

  /**
   * PhoneNumber property getter method.
   */
  @SimpleProperty(
      category = PropertyCategory.BEHAVIOR)
  public String PhoneNumber() {
    return phoneNumber;
  }

  /**
   * Specifies the phone number to call.
   *
   * @param phoneNumber a phone number to call
   */
  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING)
  @SimpleProperty
  public void PhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
  }

  /**
   * Launches the default dialer app set to start a phone call using the number in the
   * {@link #PhoneNumber()} property.
   */
  @SimpleFunction(description = "Launches the default dialer app set to start a phone call using"
      + "the number in the PhoneNumber property.")
  public void MakePhoneCall() {
    Intent i = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", this.phoneNumber, null));
    if (i.resolveActivity(form.getPackageManager()) != null) {
      form.startActivityForResult(i, PHONECALL_REQUEST_CODE);
    }
  }

  /**
   * Directly initiates a phone call using the number in the {@link #PhoneNumber()} property,
   * bypassing user interaction to start the call. **Most apps should use
   * {@link #MakePhoneCall()} instead, which requires no permissions.**
   */
  @UsesPermissions(CALL_PHONE)
  @SimpleFunction(description = "Directly initiates a phone call using the number in the "
      + "PhoneNumber property.")
  public void MakePhoneCallDirect() {
    // Check that we have permission and ask for it if we don't
    if (!havePermission) {
      form.askPermission(CALL_PHONE,
        new PermissionResultHandler() {
          @Override
          public void HandlePermissionResponse(String permission, boolean granted) {
            if (granted) {
              PhoneCall.this.havePermission = true;
              PhoneCall.this.MakePhoneCallDirect();
            } else {
              form.dispatchPermissionDeniedEvent(PhoneCall.this, "MakePhoneCall", CALL_PHONE);
            }
          }
        });
    } else {
      PhoneCallUtil.makePhoneCall(context, phoneNumber);
    }
  }

  /**
   * Event indicating that a phone call has started. The `status`{:.variable.block} can be any of:
   *
   *   - `1`: Incoming call is ringing
   *   - `2`: Outgoing call is dialled
   *
   * @param status 1:incoming call is ringing; 2:outgoing call is dialled.
   * @param phoneNumber incoming/outgoing call phone number
   */
  @SimpleEvent(
      description =
          "Event indicating that a phonecall has started." +
              " If status is 1, incoming call is ringing; " +
              "if status is 2, outgoing call is dialled. " +
              "phoneNumber is the incoming/outgoing phone number.")
  @UsesPermissions({
      PROCESS_OUTGOING_CALLS,  // Deprecated SDK 29
      READ_CALL_LOG,  // minSDK 16, needed on SDK 29
      READ_PHONE_STATE
  })
  public void PhoneCallStarted(int status, String phoneNumber) {
    // invoke the application's "PhoneCallStarted" event handler.
    EventDispatcher.dispatchEvent(this, "PhoneCallStarted", status, phoneNumber);
  }

  /**
   * Event indicating that a phone call has ended. The `status`{:.variable.block} can be any of:
   *
   *   - `1`: Incoming call was missed or rejected
   *   - `2`: Incoming call was answered and hung up
   *   - `3`: Outgoing call was hung up.
   *
   * @param status 1:incoming call is missed or rejected; 2:incoming call is answered before
   *               hanging up; 3:Outgoing call is hung up.
   * @param phoneNumber ended call phone number
   */
  @SimpleEvent(
      description =
          "Event indicating that a phone call has ended. " +
              "If status is 1, incoming call is missed or rejected; " +
              "if status is 2, incoming call is answered before hanging up; " +
              "if status is 3, outgoing call is hung up. " +
              "phoneNumber is the ended call phone number.")
  @UsesPermissions({
      PROCESS_OUTGOING_CALLS,  // Deprecated SDK 29
      READ_CALL_LOG,  // minSDK 16, needed on SDK 29
      READ_PHONE_STATE,
  })
  public void PhoneCallEnded(int status, String phoneNumber) {
    // invoke the application's "PhoneCallEnded" event handler.
    EventDispatcher.dispatchEvent(this, "PhoneCallEnded", status, phoneNumber);
  }

  /**
   * Event indicating that an incoming phone call is answered. `phoneNumber`{:.variable.block} is
   * the incoming call phone number.
   *
   * @param phoneNumber incoming call phone number
   */
  @SimpleEvent(
      description =
          "Event indicating that an incoming phone call is answered. " +
              "phoneNumber is the incoming call phone number.")
  @UsesPermissions({
      PROCESS_OUTGOING_CALLS,  // Deprecated SDK 29
      READ_CALL_LOG,  // minSDK 16, needed on SDK 29
      READ_PHONE_STATE,
  })
  public void IncomingCallAnswered(String phoneNumber) {
    // invoke the application's "IncomingCallAnswered" event handler.
    EventDispatcher.dispatchEvent(this, "IncomingCallAnswered", phoneNumber);
  }

  @Override
  public void resultReturned(int requestCode, int resultCode, Intent data) {
    if (requestCode == PHONECALL_REQUEST_CODE) {
      PhoneCallStarted(2, "");
    }
  }

  /**
   * BroadcastReceiver for incomming/outgoing phonecall state changes
   *
   */
  private class CallStateReceiver extends BroadcastReceiver {
    private int status; // 0:undetermined, 1:incoming ringed, 2:outgoing dialled,
                        // 3: incoming answered
    private String number; // phone call number
    public CallStateReceiver() {
      status = 0;
      number = "";
    }

    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)){
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        if(TelephonyManager.EXTRA_STATE_RINGING.equals(state)){
          // Incoming call rings
          status = 1;
          number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
          if (number == null) {
            // This gets called first with null, then with the actual number.
            // Ignore the first invocation.
            return;
          }
          PhoneCallStarted(1, number);
        }else if(TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)){
          // Call off-hook
          if(status == 1){
            // Incoming call answered
            status = 3;
            IncomingCallAnswered(number);
          }
        }else if(TelephonyManager.EXTRA_STATE_IDLE.equals(state)){
          // Incomming/Outgoing Call ends
          if(status == 1){
            // Incoming Missed or Rejected
            PhoneCallEnded(1, number);
          }else if(status == 3){
            // Incoming Answer Ended
            PhoneCallEnded(2, number);
          }else if(status == 2){
            // Outgoing Ended
            PhoneCallEnded(3, number);
          }
          status = 0;
          number = "";
        }
      }else if(Intent.ACTION_NEW_OUTGOING_CALL.equals(action)){
        // Outgoing call dialled
        status = 2;
        number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        PhoneCallStarted(2, number);
      }
    }
  }

  /**
   * Registers phonecall state monitor
   */
  private void registerCallStateMonitor(){
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    context.registerReceiver(callStateReceiver, intentFilter);
    didRegisterReceiver = true;
  }

  /**
   * Unregisters phonecall state monitor
   */
  private void unregisterCallStateMonitor() {
    if (didRegisterReceiver) {
      context.unregisterReceiver(callStateReceiver);
      didRegisterReceiver = false;
    }
  }

  @Override
  public void onDestroy() {
    unregisterCallStateMonitor();
  }
}


text:
bash_profile
============

.bash_profile of my Mac


text:
package coreapi_test

import (
	"context"
	"io"
	"math/rand"
	"testing"
	"time"

	ipath "github.com/ipfs/go-ipfs/path"

	coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
	opt "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
)

var rnd = rand.New(rand.NewSource(0x62796532303137))

func addTestObject(ctx context.Context, api coreiface.CoreAPI) (coreiface.Path, error) {
	return api.Unixfs().Add(ctx, &io.LimitedReader{R: rnd, N: 4092})
}

func TestBasicPublishResolve(t *testing.T) {
	ctx := context.Background()
	n, api, err := makeAPIIdent(ctx, true)
	if err != nil {
		t.Fatal(err)
		return
	}

	p, err := addTestObject(ctx, api)
	if err != nil {
		t.Fatal(err)
		return
	}

	e, err := api.Name().Publish(ctx, p)
	if err != nil {
		t.Fatal(err)
		return
	}

	if e.Name() != n.Identity.Pretty() {
		t.Errorf("expected e.Name to equal '%s', got '%s'", n.Identity.Pretty(), e.Name())
	}

	if e.Value().String() != p.String() {
		t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
	}

	resPath, err := api.Name().Resolve(ctx, e.Name())
	if err != nil {
		t.Fatal(err)
		return
	}

	if resPath.String() != p.String() {
		t.Errorf("expected paths to match, '%s'!='%s'", resPath.String(), p.String())
	}
}

func TestBasicPublishResolveKey(t *testing.T) {
	ctx := context.Background()
	_, api, err := makeAPIIdent(ctx, true)
	if err != nil {
		t.Fatal(err)
		return
	}

	k, err := api.Key().Generate(ctx, "foo")
	if err != nil {
		t.Fatal(err)
		return
	}

	p, err := addTestObject(ctx, api)
	if err != nil {
		t.Fatal(err)
		return
	}

	e, err := api.Name().Publish(ctx, p, opt.Name.Key(k.Name()))
	if err != nil {
		t.Fatal(err)
		return
	}

	if ipath.Join([]string{"/ipns", e.Name()}) != k.Path().String() {
		t.Errorf("expected e.Name to equal '%s', got '%s'", e.Name(), k.Path().String())
	}

	if e.Value().String() != p.String() {
		t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
	}

	resPath, err := api.Name().Resolve(ctx, e.Name())
	if err != nil {
		t.Fatal(err)
		return
	}

	if resPath.String() != p.String() {
		t.Errorf("expected paths to match, '%s'!='%s'", resPath.String(), p.String())
	}
}

func TestBasicPublishResolveTimeout(t *testing.T) {
	t.Skip("ValidTime doesn't appear to work at this time resolution")

	ctx := context.Background()
	n, api, err := makeAPIIdent(ctx, true)
	if err != nil {
		t.Fatal(err)
		return
	}

	p, err := addTestObject(ctx, api)
	if err != nil {
		t.Fatal(err)
		return
	}

	e, err := api.Name().Publish(ctx, p, opt.Name.ValidTime(time.Millisecond*100))
	if err != nil {
		t.Fatal(err)
		return
	}

	if e.Name() != n.Identity.Pretty() {
		t.Errorf("expected e.Name to equal '%s', got '%s'", n.Identity.Pretty(), e.Name())
	}

	if e.Value().String() != p.String() {
		t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
	}

	time.Sleep(time.Second)

	_, err = api.Name().Resolve(ctx, e.Name())
	if err == nil {
		t.Fatal("Expected an error")
		return
	}
}

//TODO: When swarm api is created, add multinode tests