text:
euler
=====
http://projecteuler.net

redpajama_set_name: RedPajamaGithub


text:
copyright:
  year: 2015, 2016

lastupdated: "2016-10-20"

---

{:new_window: target="_blank"}

# Risoluzione dei problemi
{: #troubleshooting}

Se riscontri dei problemi con l'utilizzo di {{site.data.keyword.Bluemix}},
puoi utilizzare le attività di risoluzione dei problemi per determinare l'azione correttiva da
eseguire.

Accedi alla console {{site.data.keyword.Bluemix_notm}} e fai clic sulla voce **Account** dalla barra dei menu. Puoi visualizzare lo stato dei runtime e dei servizi in esecuzione e visualizzare le notifiche. Puoi inoltre selezionare **Supporto** > **Richiedi assistenza**, dove puoi eseguire ricerche nella documentazione e nei forum di Stack Overflow o developerWorks (dW) Answers per cercare risposte o contattare il supporto.

Se stai utilizzando un account che è collegato tra {{site.data.keyword.Bluemix_notm}} e {{site.data.keyword.BluSoftlayer}}, puoi accedere alla console Bluemix console e fare clic su **Stato** per visualizzare lo stato dei servizi e runtime in esecuzione. Inoltre, puoi fare clic sul link **Supporto** nella barra dei menu per aprire il widget Supporto e selezionare quindi **Aggiungi ticket** > **Trova risposte**. Puoi anche andare direttamente ai forum *Stack Overflow* o *developerWorks (dW) Answers* per cercare risposte o pubblicare delle domande.


text:
/* eslint-env browser */
import _ from 'lodash'
import Immutable from 'immutable'
import PlayerActions from '../actions/PlayerActions.js'
import DataFetcher from './DataFetcher.js'

let AudioAPIUtils = function (audioElementId) {
  this.player = document.getElementById(audioElementId)
  this.player.volume = 0.1

  // Player data.
  this.currentSong     = null
  this.playlist        = null
  this.backupSongs     = null
  this.index           = 0

  // Player State.
  this.playerIsLooped  = false
  this.playerIsRandom  = false
  this.playerIsPlaying = false
  this.playerIsMuted   = false

/* Event handlers */

  // Handle the end of a song.
  this.onSongEnded = () => {
    let playlistSize = this.playlist.get('songs').count()

    // Loop through the same song.
    if (this.playerIsLooped) {
      this.play()
    }
    // Keep playing the rest of the playlist.
    else if (this.index !== (playlistSize - 1)) {
      this.playNext()
    }
    //Stop Playing since it reached the playlist's end.
    else {
      this.playerIsPlaying = false
      PlayerActions.pause()
      PlayerActions.updateCurrentTime(0)
    }
  }

  // Handle the song time update.
  this.onTimeUpdate = () => {
    PlayerActions.updateCurrentTime(this.player.currentTime)
  }

  // Update the song duration when the browser gets it
  this.onLoadedMetadata = () => {
    PlayerActions.updateDuration(this.player.duration)
  }

/* Setters */
  // Set the current playlist to a given one.
  this.setPlaylist = (playlist) => {
    this.playlist        = playlist
    this.currentSong     = null
    this.backupSongs     = null
    this.index           = 0
    this.playerIsLooped  = false
    this.playerIsRandom  = false
    this.playerIsPlaying = false

    PlayerActions.updatePlaylist(this.playlist)
  }

  // Set the song time to a given one.
  this.setCurrentTime = (time) => {
    this.player.currentTime = time
    PlayerActions.updateCurrentTime(this.player.currentTime)
  }

  // Set the volume level to a given one.
  this.setVolumeLevel = (level) => {
    this.player.volume = level
    PlayerActions.updateVolumeLevel(this.player.volume)
  }

  // Toggle the player's loop state.
  this.toggleLoop = () => {
    this.playerIsLooped = !this.playerIsLooped
    PlayerActions.toggleLoop(this.playerIsLooped)
  }

  // Toggle the player's random state.
  this.toggleRandom = () => {
    this.playerIsRandom = !this.playerIsRandom
    this.shufflePlaylist.call(this)
    PlayerActions.toggleRandom(this.playerIsRandom)
  }

  // Toggle the player's mute state.
  this.toggleMute = () => {
    this.player.muted = !this.player.muted
    this.playerIsMuted = this.player.muted
    PlayerActions.toggleMute(this.playerIsMuted)
  }

/* Player manipulation methods */

  // Play if it's paused, otherwise paused it.
  this.play = () => {
    let songs = this.playlist.get('songs')

    // Make sure it has loaded the current song.
    if (!this.player.src) {
      this.currentSong = songs.get(this.index)
      this.reloadAudio.call(this)
    } else if (this.player.paused) {
      this.player.play()
      this.playerIsPlaying = true
      PlayerActions.play()
    } else {
      this.player.pause()
      this.playerIsPlaying = false
      PlayerActions.pause()
    }
  }

  // Force pause.
  this.pause = () => {
    this.player.pause()
    PlayerActions.pause()
  }

  // If there's a playlist loaded, play next song on playlist.
  this.playNext = () => {
    // Do nothing if there is no playlist loaded.
    if (!this.playlist) { return }

    let songs = this.playlist.get('songs')

    // If it isn't at the last song, then play next.
    if (this.index < (songs.count() - 1)) {
      this.currentSong = songs.get(++this.index)
      PlayerActions.playNext()
    }

    // If it's the last one, then play then loops and play the first one.
    else {
      this.index = 0
      this.currentSong = songs.get(0)
      PlayerActions.playSongAt(0, true)
    }

    this.reloadAudio.call(this)
  }

  // If theres' a playlist loaded. Play previous song on playlist.
  this.playPrev = () => {
    // Do nothing if there is no playlist loaded.
    if (!this.playlist) { return }

    let songs  = this.playlist.get('songs')

    // If it has been playing for more than 5s, just reset the current song.
    if (this.player.currentTime > 5) {
      this.player.currentTime = 0
      PlayerActions.updateCurrentTime(0)
    }

    // Go back one song (as long as it isn't the first one).
    else if ( this.index > 0 ) {
      this.currentSong = songs.get(--this.index)
      this.reloadAudio.call(this)
      PlayerActions.playPrev()
    }

    // If it's the first song in playlist and it hasn't been 3 seconds
    // since it started playing the current song, then go back to the
    // last song in playlist. (You know, like when you're fast skipping
    // every song trying to find one song at the end of the playlist.)
    else {
      this.index       = songs.count() - 1
      this.currentSong = songs.get(this.index)

      this.reloadAudio.call(this)
      PlayerActions.playSongAt(this.index, true)
    }
  }

  // Play the song at a given index in the current playlist.
  this.playSongAt = (index, forceReload) => {
    let songs = this.playlist.get('songs')

    // Play song only if it's between the playlist's bounds and
    // it isn't the current one.
    if (songs && index >= 0 && index < songs.count() && this.index !== index)
    {
      this.index = index
      this.currentSong = songs.get(index)
      this.reloadAudio.call(this)
      PlayerActions.playSongAt(index, true)
    }

    // If it's the same one, just play/pause it.
    else if (this.index === index) {
      if (forceReload === true) {
        this.currentSong = songs.get(index)
        this.reloadAudio.call(this)
      } else {
        this.play.call(this)
      }
    }

    // Otherwise just log a warning.
    else {
      console.warn('Requested index was off playlist\'s bounds. Action skipped.')
      console.warn('Btw, if you see this then you broke the app. Congrats!!, and don\'t forget to tell at aoitsu3@gmail.com how you did it :)')
    }
  }

  // Shuffle / Unshuffle current Playlist.
  this.shufflePlaylist = () => {
    let currentSongs = this.playlist.get('songs').toJS()
    let currentSong  = this.currentSong.toJS()

    // Change to Shuffle State.
    if (this.playerIsRandom) {
      let shuffledSongs = _.shuffle(currentSongs)
      this.backupSongs  = _.clone(currentSongs, true)
      this.index        = _.findIndex(shuffledSongs, currentSong)

      this.playlist = this.playlist.set('songs', Immutable.fromJS(shuffledSongs))
    }

    // Back to normal state.
    else {
      this.index    = _.findIndex(this.backupSongs, currentSong)
      this.playlist = this.playlist.set('songs', Immutable.fromJS(this.backupSongs))
    }

    // Notify the playlist change to the store.
    PlayerActions.updatePlaylist(this.playlist)
    // Update the index on the store.
    PlayerActions.playSongAt(this.index, false)
  }

  // Fetch playlist from db.
  this.fetchPlaylist = (playlistURL) => {
    DataFetcher
      .fetchPlaylist(playlistURL)
      .then((playlist) => { this.setPlaylist.call(this, playlist) })
      .catch()
  }

/* Utility methods */

  // Load the current song (which should be stored at this.currentSong).
  this.reloadAudio = () => {
    this.player.src = this.currentSong.get('url') // Make sure it has the right song.
    this.player.load()
    this.player.play()
    PlayerActions.play()
    this.playerIsPlaying = true
  }

  this.player.addEventListener('ended', this.onSongEnded.bind(this), false)
  this.player.addEventListener('timeupdate', this.onTimeUpdate.bind(this), false)
  this.player.addEventListener('loadedmetadata', this.onLoadedMetadata, false)

}

export default new AudioAPIUtils('player')


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.adwords.jaxws.v201809.cm;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CriterionUserList.MembershipStatus.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="CriterionUserList.MembershipStatus">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="OPEN"/>
 *     <enumeration value="CLOSED"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "CriterionUserList.MembershipStatus")
@XmlEnum
public enum CriterionUserListMembershipStatus {

    /**
     *
     *                 Open status - list is accruing members and can be targeted to.
     *
     *
     */
    OPEN,

    /**
     *
     *                 Closed status - No new members being added. Can not be used for targeting a new campaign.
     *                 Existing campaigns can still work as long as the list is not removed as a targeting criteria.
     *
     *
     */
    CLOSED;

    public String value() {
        return name();
    }

    public static CriterionUserListMembershipStatus fromValue(String v) {
        return valueOf(v);
    }

}


text:
layout: post
date:	2006-04-23 15:39:00
title:  I *CANNOT* believe this...
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
<LJ user="Amoghavarsha"> and Sanath,as I said, went off to BRT. I specifically told them, since they were going without me they were bound to spot a tiger. They scoffed at this remark.

Amogh called just now...guess what....*AND* no photos, I think, I couldn't hear him clearly enough.

I am torn between feeling ecstatic that they spotted a south indian tiger and despair that I am never ever going to see one...If I could get my hands on that William Blake I would teach him how to write poetry. "Tiger, tiger, burning bright,/In the forests of the night", inDEED!!

Hereis MY version of the first few lines:

Tiger,tiger, hiding low
Not a stripe of you doth show
What immortal hand or eye
Couldst feel or see you? Not I, not I!!

Waiting for all the details...all my wildlifer friends have taken to either saying "Sorry!" outright, or announcing their sighting in an apologetic tone of voice to me!!

Sigh....

For all non-wildlifers..the tigers in Bannerghatta National Park don't count ( I don't mean they are anumerate, I mean they are too used to humans and lack that authentic "tiger in the wild" look.)


text:
define([
    'jquery',
    'underscore',
    'jquery.multiselect',
    'jquery.multiselect.filter'
], function($, _) {
    'use strict';

    /**
     * Multiselect decorator class.
     * Wraps multiselect widget and provides design modifications
     *
     * @export orofilter/js/multiselect-decorator
     * @class  orofilter.MultiselectDecorator
     */
    function MultiselectDecorator(options) {
        this.initialize(options);
    }

    MultiselectDecorator.prototype = {
        /**
         * Multiselect widget element container
         *
         * @property {Object}
         */
        element: null,

        /**
         * @property {Object}
         */
        multiselectFilterParameters: {},

        /**
         * @property {Boolean}
         */
        contextSearch: true,

        /**
         * Initialize all required properties
         */
        initialize: function(options) {
            if (!options.element) {
                throw new Error('Select element must be defined');
            }
            this.element = options.element;

            if (_.has(options, 'contextSearch')) {
                this.contextSearch = options.contextSearch;
            }

            options.parameters = options.parameters || {};
            _.defaults(options.parameters, this.parameters);

            // initialize multiselect widget
            this.multiselect(options.parameters);

            if (this.contextSearch) {
                const multiselectFilterDefaults = {
                    label: '',
                    placeholder: '',
                    autoReset: true
                };

                // initialize multiselect filter
                this.multiselectfilter(
                    _.extend(multiselectFilterDefaults, this.multiselectFilterParameters)
                );
            }
        },

        /**
         * Destroys decorator
         *  - removes created widgets
         *  - removes reference on element
         */
        dispose: function() {
            if (this.contextSearch && this.element.data('ech-multiselectfilter')) {
                this.multiselectfilter('destroy');
            }
            if (this.element.data('ech-multiselect')) {
                this.multiselect('destroy');
            }
            this.element.remove();
            delete this.element;
        },

        /**
         * Set design for view
         *
         * @param {Backbone.View} view
         */
        setViewDesign: function(view) {
            view.$('.ui-multiselect').removeClass('ui-widget').removeClass('ui-state-default');
            view.$('.ui-multiselect span.ui-icon').remove();
        },

        /**
         * Fix dropdown design
         *
         * @protected
         */
        _setDropdownDesign: function() {
            const widget = this.getWidget();
            widget.addClass('dropdown-menu');
            widget.removeClass('ui-widget-content');
            widget.removeClass('ui-widget');
            widget.find('.ui-widget-header').removeClass('ui-widget-header');
            widget.find('.ui-multiselect-filter').removeClass('ui-multiselect-filter');
            widget.find('ul li label').removeClass('ui-corner-all');
        },

        onBeforeOpenDropdown: function() {
            this._setDropdownDesign();
        },

        /**
         * Action performed on dropdown open
         */
        onOpenDropdown: function() {
            this.getWidget().find('input[type="search"]').focus();
        },

        /**
         * Action on multiselect widget refresh
         */
        onRefresh: function() {
            const widget = this.getWidget();
            widget.find('.ui-multiselect-checkboxes').addClass('fixed-li');
            widget.inputWidget('seekAndCreate');
        },

        /**
         * Get minimum width of dropdown menu
         *
         * @return {Number}
         */
        getMinimumDropdownWidth: function() {
            let minimumWidth = 0;
            this.getWidget().find('.ui-multiselect-checkboxes').removeClass('fixed-li');
            const elements = this.getWidget().find('.ui-multiselect-checkboxes li');
            _.each(elements, function(element) {
                const width = this._getTextWidth($(element).find('label'));
                if (width > minimumWidth) {
                    minimumWidth = width;
                }
            }, this);
            this.getWidget().find('.ui-multiselect-checkboxes').addClass('fixed-li');
            return minimumWidth;
        },

        /**
         * Get element width
         *
         * @param {Object} element
         * @return {Integer}
         * @protected
         */
        _getTextWidth: function(element) {
            const htmlOrg = element.html();
            const htmlCalc = '<span>' + htmlOrg + '</span>';
            element.html(htmlCalc);
            const width = element.outerWidth();
            element.html(htmlOrg);
            return width;
        },

        /**
         * Get multiselect widget
         *
         * @return {Object}
         */
        getWidget: function() {
            return this.multiselect('widget');
        },

        /**
         * Proxy for multiselect method
         *
         * @param functionName
         * @return {Object}
         */
        multiselect: function(...args) {
            const elem = this.element;
            return elem.multiselect(...args);
        },

        /**
         * Proxy for multiselectfilter method
         *
         * @param functionName
         * @return {Object}
         */
        multiselectfilter: function(...args) {
            const elem = this.element;
            return elem.multiselectfilter(...args);
        },

        /**
         *  Set dropdown position according to button element
         */
        updateDropdownPosition: function(position) {
            this.multiselect('updatePos', position);
        }
    };

    return MultiselectDecorator;
});


text:
package com.google.android.apps.gutenberg;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.apps.gutenberg.util.AccountManagerCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;

import java.io.IOException;

public class BaseActivity extends ActionBarActivity implements
        AccountSelectionDialogFragment.OnAccountSelectedListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "BaseActivity";

    private static final String FRAGMENT_ACCOUNT_SELECTION_DIALOG = "account_selection_dialog";

    private static final int REQUEST_AUTHENTICATE = 0x101;
    private static final int REQUEST_CODE_RESOLVE_ERROR = 0x102;

    private GoogleApiClient mApiClient;
    private ConnectionResult mConnectionResult;
    private ProgressDialog mConnectionProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Google+ Sign in
        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN)
                .addScope(Plus.SCOPE_PLUS_PROFILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mConnectionProgressDialog = new ProgressDialog(this);
        mConnectionProgressDialog.setMessage(getString(R.string.signing_in));
        GutenbergApplication app = GutenbergApplication.from(this);
        if (!app.isUserLoggedIn()) {
            selectAccount(false);
        } else {
            app.requestSync(false);
        }
        adjustTaskDescription();
    }

    private void adjustTaskDescription() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setTaskDescription(new ActivityManager.TaskDescription(
                    getTitle().toString(),
                    BitmapFactory.decodeResource(getResources(), R.drawable.ic_task),
                    getResources().getColor(R.color.primary)));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_AUTHENTICATE: {
                if (RESULT_CANCELED == resultCode) {
                    Toast.makeText(this, getString(R.string.need_to_login),
                            Toast.LENGTH_SHORT).show();
                    finish();
                } else if (RESULT_OK == resultCode) {
                    fetchTokenForAccount(GutenbergApplication.from(this).getAccount());
                }
                break;
            }
            default: {
                super.onActivityResult(requestCode, resultCode, data);
                break;
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mApiClient.connect();
    }

    @Override
    protected void onStop() {
        if (mApiClient.isConnected()) {
            mApiClient.disconnect();
        }
        super.onStop();
    }

    private Account[] getAccounts() {
        AccountManager accountManager = AccountManager.get(getApplicationContext());
        return accountManager.getAccountsByType("com.google");
    }

    protected void selectAccount(boolean force) {
        Account[] accounts = getAccounts();
        if (0 == accounts.length) {
            Toast.makeText(this, getString(R.string.account_required), Toast.LENGTH_SHORT).show();
            finish();
        } else if (1 == accounts.length && !force) {
            fetchTokenForAccount(accounts[0]);
        } else {
            AccountSelectionDialogFragment.newInstance(accounts)
                    .show(getSupportFragmentManager(), FRAGMENT_ACCOUNT_SELECTION_DIALOG);
        }
    }

    private void fetchTokenForAccount(Account account) {
        GutenbergApplication.from(this).setAccount(account);
        AccountManager accountManager = AccountManager.get(getApplicationContext());
        AccountManagerCompat.getAuthToken(accountManager, account, "ah", null, false,
                mAccountManagerCallback, null);
    }

    private AccountManagerCallback<Bundle> mAccountManagerCallback
            = new AccountManagerCallback<Bundle>() {
        @Override
        public void run(AccountManagerFuture<Bundle> bundleAccountManagerFuture) {
            try {
                Bundle result = bundleAccountManagerFuture.getResult();
                Intent intent = (Intent) result.get(AccountManager.KEY_INTENT);
                if (intent == null) {
                    String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
                    GutenbergApplication app = GutenbergApplication.from(BaseActivity.this);
                    app.setAuthToken(authToken);
                    app.requestSync(false);
                } else {
                    startActivityForResult(intent, REQUEST_AUTHENTICATE);
                }
            } catch (OperationCanceledException | IOException | AuthenticatorException e) {
                Log.e(TAG, "Error authenticating.", e);
            }
        }
    };

    @Override
    public void onConnected(Bundle bundle) {
        mConnectionProgressDialog.dismiss();
        supportInvalidateOptionsMenu();
    }

    @Override
    public void onConnectionSuspended(int i) {
        mApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mConnectionProgressDialog.isShowing()) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERROR);
                } catch (IntentSender.SendIntentException e) {
                    mApiClient.connect();
                }
            }
        }
        mConnectionResult = connectionResult;
        signIn();
    }

    @Override
    public void onAccountSelected(Account account) {
        fetchTokenForAccount(account);
    }

    @Override
    public void onCancelAccountSelection() {
        GutenbergApplication app = GutenbergApplication.from(this);
        if (!app.isUserLoggedIn()) {
            finish();
        }
    }

    private void signIn() {
        if (mApiClient.isConnected()) {
            return;
        }
        if (mConnectionResult == null) {
            mConnectionProgressDialog.show();
        } else {
            try {
                mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERROR);
            } catch (IntentSender.SendIntentException e) {
                // Retry connecting
                mConnectionResult = null;
                mApiClient.connect();
            }
        }
    }

}


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

internal static partial class SdkInfo
{
    public static IEnumerable<Tuple<string, string, string>> ApiInfo_ContainerInstanceManagementClient
    {
        get
        {
            return new Tuple<string, string, string>[]
            {
                new Tuple<string, string, string>("ContainerInstance", "ContainerGroupUsage", "2018-04-01"),
                new Tuple<string, string, string>("ContainerInstance", "ContainerGroups", "2018-04-01"),
                new Tuple<string, string, string>("ContainerInstance", "ContainerLogs", "2018-04-01"),
                new Tuple<string, string, string>("ContainerInstance", "Operations", "2018-04-01"),
                new Tuple<string, string, string>("ContainerInstance", "StartContainer", "2018-04-01"),
            }.AsEnumerable();
        }
    }
}


text:
package net.sandius.rembulan.parser.ast;

public class NilLiteral extends Literal {

	public static final NilLiteral INSTANCE = new NilLiteral();

	private NilLiteral() {
	}

	@Override
	public Literal accept(Transformer tf) {
		return tf.transform(this);
	}

}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Business'
        db.create_table(u'employer_business', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)),
            ('number_offices', self.gf('django.db.models.fields.PositiveSmallIntegerField')()),
            ('is_mso', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('number_employees', self.gf('django.db.models.fields.PositiveSmallIntegerField')()),
        ))
        db.send_create_signal(u'employer', ['Business'])

        # Adding model 'Praxis'
        db.create_table(u'employer_praxis', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('is_active', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('business', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['employer.Business'])),
            ('company_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('contact_first_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('contact_last_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('address', self.gf('django.db.models.fields.CharField')(max_length=200)),
            ('zip_code', self.gf('django.db.models.fields.DecimalField')(max_digits=5, decimal_places=0)),
            ('city', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('state', self.gf('django.db.models.fields.CharField')(max_length=2)),
            ('solo_practitioner', self.gf('django.db.models.fields.BooleanField')()),
            ('multi_practitioner', self.gf('django.db.models.fields.BooleanField')()),
            ('corporate', self.gf('django.db.models.fields.BooleanField')()),
            ('fee_for_service', self.gf('django.db.models.fields.BooleanField')()),
            ('insurance', self.gf('django.db.models.fields.BooleanField')()),
            ('capitation_medicaid', self.gf('django.db.models.fields.BooleanField')()),
        ))
        db.send_create_signal(u'employer', ['Praxis'])

        # Adding model 'JobPosting'
        db.create_table(u'employer_jobposting', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('is_active', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('praxis', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['employer.Praxis'])),
            ('position_name', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('posting_title', self.gf('django.db.models.fields.CharField')(max_length=300)),
            ('job_position', self.gf('django.db.models.fields.PositiveSmallIntegerField')()),
            ('schedule_type', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('monday_daytime', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('monday_evening', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('tuesday_daytime', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('tuesday_evening', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('wednesday_daytime', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('wednesday_evening', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('thursday_daytime', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('thursday_evening', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('friday_daytime', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('friday_evening', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('saturday_daytime', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('saturday_evening', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('sunday_daytime', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('sunday_evening', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('compensation_type', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('hourly_wage', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)),
            ('annualy_wage', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)),
            ('production', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('collection', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('experience_years', self.gf('django.db.models.fields.PositiveSmallIntegerField')()),
            ('benefit_1', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('benefit_2', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('benefit_3', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('benefit_4', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('benefit_5', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('benefit_6', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('benefit_other', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('benefit_other_text', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('visa', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('additional_comments', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('is_posted', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal(u'employer', ['JobPosting'])

    def backwards(self, orm):
        # Deleting model 'Business'
        db.delete_table(u'employer_business')

        # Deleting model 'Praxis'
        db.delete_table(u'employer_praxis')

        # Deleting model 'JobPosting'
        db.delete_table(u'employer_jobposting')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'employer.business': {
            'Meta': {'object_name': 'Business'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_mso': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'number_employees': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
            'number_offices': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
            'user': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True'})
        },
        u'employer.jobposting': {
            'Meta': {'object_name': 'JobPosting'},
            'additional_comments': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'annualy_wage': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'benefit_1': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'benefit_2': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'benefit_3': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'benefit_4': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'benefit_5': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'benefit_6': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'benefit_other': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'benefit_other_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'collection': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'compensation_type': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'experience_years': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
            'friday_daytime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'friday_evening': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'hourly_wage': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_posted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'job_position': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
            'monday_daytime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'monday_evening': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'position_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'posting_title': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
            'praxis': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['employer.Praxis']"}),
            'production': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'saturday_daytime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'saturday_evening': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'schedule_type': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'sunday_daytime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'sunday_evening': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'thursday_daytime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'thursday_evening': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'tuesday_daytime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'tuesday_evening': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'visa': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'wednesday_daytime': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'wednesday_evening': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
        },
        u'employer.praxis': {
            'Meta': {'object_name': 'Praxis'},
            'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'business': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['employer.Business']"}),
            'capitation_medicaid': ('django.db.models.fields.BooleanField', [], {}),
            'city': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'company_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'contact_first_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'contact_last_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'corporate': ('django.db.models.fields.BooleanField', [], {}),
            'fee_for_service': ('django.db.models.fields.BooleanField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'insurance': ('django.db.models.fields.BooleanField', [], {}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'multi_practitioner': ('django.db.models.fields.BooleanField', [], {}),
            'solo_practitioner': ('django.db.models.fields.BooleanField', [], {}),
            'state': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
            'zip_code': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '0'})
        }
    }

    complete_apps = ['employer']


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 48(2): 214 (1996)

#### Original name
Cercospora zambalesica Petr., 1957

### Remarks
null


text:
package org.apache.hadoop.hbase.mapreduce;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.ImportTsv.TsvParser.BadTsvLineException;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

/**
 * Tool to import data from a TSV file.
 *
 * This tool is rather simplistic - it doesn't do any quoting or
 * escaping, but is useful for many data loads.
 *
 * @see ImportTsv#usage(String)
 */
public class ImportTsv {
  final static String NAME = "importtsv";

  final static String SKIP_LINES_CONF_KEY = "importtsv.skip.bad.lines";
  final static String BULK_OUTPUT_CONF_KEY = "importtsv.bulk.output";
  final static String COLUMNS_CONF_KEY = "importtsv.columns";
  final static String SEPARATOR_CONF_KEY = "importtsv.separator";
  final static String DEFAULT_SEPARATOR = "\t";

  static class TsvParser {
    /**
     * Column families and qualifiers mapped to the TSV columns
     */
    private final byte[][] families;
    private final byte[][] qualifiers;

    private final byte separatorByte;

    private int rowKeyColumnIndex;

    public static String ROWKEY_COLUMN_SPEC="HBASE_ROW_KEY";

    /**
     * @param columnsSpecification the list of columns to parser out, comma separated.
     * The row key should be the special token TsvParser.ROWKEY_COLUMN_SPEC
     */
    public TsvParser(String columnsSpecification, String separatorStr) {
      // Configure separator
      byte[] separator = Bytes.toBytes(separatorStr);
      Preconditions.checkArgument(separator.length == 1,
        "TsvParser only supports single-byte separators");
      separatorByte = separator[0];

      // Configure columns
      ArrayList<String> columnStrings = Lists.newArrayList(
        Splitter.on(',').trimResults().split(columnsSpecification));

      families = new byte[columnStrings.size()][];
      qualifiers = new byte[columnStrings.size()][];

      for (int i = 0; i < columnStrings.size(); i++) {
        String str = columnStrings.get(i);
        if (ROWKEY_COLUMN_SPEC.equals(str)) {
          rowKeyColumnIndex = i;
          continue;
        }
        String[] parts = str.split(":", 2);
        if (parts.length == 1) {
          families[i] = str.getBytes();
          qualifiers[i] = HConstants.EMPTY_BYTE_ARRAY;
        } else {
          families[i] = parts[0].getBytes();
          qualifiers[i] = parts[1].getBytes();
        }
      }
    }

    public int getRowKeyColumnIndex() {
      return rowKeyColumnIndex;
    }
    public byte[] getFamily(int idx) {
      return families[idx];
    }
    public byte[] getQualifier(int idx) {
      return qualifiers[idx];
    }

    public ParsedLine parse(byte[] lineBytes, int length)
    throws BadTsvLineException {
      // Enumerate separator offsets
      ArrayList<Integer> tabOffsets = new ArrayList<Integer>(families.length);
      for (int i = 0; i < length; i++) {
        if (lineBytes[i] == separatorByte) {
          tabOffsets.add(i);
        }
      }
      tabOffsets.add(length);
      if (tabOffsets.size() > families.length) {
        throw new BadTsvLineException("Bad line:\n");
      }

      return new ParsedLine(tabOffsets, lineBytes);
    }

    class ParsedLine {
      private final ArrayList<Integer> tabOffsets;
      private byte[] lineBytes;

      ParsedLine(ArrayList<Integer> tabOffsets, byte[] lineBytes) {
        this.tabOffsets = tabOffsets;
        this.lineBytes = lineBytes;
      }

      public int getRowKeyOffset() {
        return getColumnOffset(rowKeyColumnIndex);
      }
      public int getRowKeyLength() {
        return getColumnLength(rowKeyColumnIndex);
      }
      public int getColumnOffset(int idx) {
        if (idx > 0)
          return tabOffsets.get(idx - 1) + 1;
        else
          return 0;
      }
      public int getColumnLength(int idx) {
        return tabOffsets.get(idx) - getColumnOffset(idx);
      }
      public int getColumnCount() {
        return tabOffsets.size();
      }
      public byte[] getLineBytes() {
        return lineBytes;
      }
    }

    public static class BadTsvLineException extends Exception {
      public BadTsvLineException(String err) {
        super(err);
      }
      private static final long serialVersionUID = 1L;
    }
  }

  /**
   * Write table content out to files in hdfs.
   */
  static class TsvImporter
  extends Mapper<LongWritable, Text, ImmutableBytesWritable, Put>
  {

    /** Timestamp for all inserted rows */
    private long ts;

    /** Should skip bad lines */
    private boolean skipBadLines;
    private Counter badLineCount;

    private TsvParser parser;

    @Override
    protected void setup(Context context) {
      Configuration conf = context.getConfiguration();
      parser = new TsvParser(conf.get(COLUMNS_CONF_KEY),
                             conf.get(SEPARATOR_CONF_KEY, DEFAULT_SEPARATOR));
      if (parser.getRowKeyColumnIndex() == -1) {
        throw new RuntimeException("No row key column specified");
      }
      ts = System.currentTimeMillis();

      skipBadLines = context.getConfiguration().getBoolean(
        SKIP_LINES_CONF_KEY, true);
      badLineCount = context.getCounter("ImportTsv", "Bad Lines");
    }

    /**
     * Convert a line of TSV text into an HBase table row.
     */
    @Override
    public void map(LongWritable offset, Text value,
      Context context)
    throws IOException {
      byte[] lineBytes = value.getBytes();

      try {
        TsvParser.ParsedLine parsed = parser.parse(
            lineBytes, value.getLength());
        ImmutableBytesWritable rowKey =
          new ImmutableBytesWritable(lineBytes,
              parsed.getRowKeyOffset(),
              parsed.getRowKeyLength());

        Put put = new Put(rowKey.copyBytes());
        for (int i = 0; i < parsed.getColumnCount(); i++) {
          if (i == parser.getRowKeyColumnIndex()) continue;
          KeyValue kv = new KeyValue(
              lineBytes, parsed.getRowKeyOffset(), parsed.getRowKeyLength(),
              parser.getFamily(i), 0, parser.getFamily(i).length,
              parser.getQualifier(i), 0, parser.getQualifier(i).length,
              ts,
              KeyValue.Type.Put,
              lineBytes, parsed.getColumnOffset(i), parsed.getColumnLength(i));
          put.add(kv);
        }
        context.write(rowKey, put);
      } catch (BadTsvLineException badLine) {
        if (skipBadLines) {
          System.err.println(
              "Bad line at offset: " + offset.get() + ":\n" +
              badLine.getMessage());
          badLineCount.increment(1);
          return;
        } else {
          throw new IOException(badLine);
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * Sets up the actual job.
   *
   * @param conf  The current configuration.
   * @param args  The command line parameters.
   * @return The newly created job.
   * @throws IOException When setting up the job fails.
   */
  public static Job createSubmittableJob(Configuration conf, String[] args)
  throws IOException {
    String tableName = args[0];
    Path inputDir = new Path(args[1]);
    Job job = new Job(conf, NAME + "_" + tableName);
    job.setJarByClass(TsvImporter.class);
    FileInputFormat.setInputPaths(job, inputDir);
    job.setInputFormatClass(TextInputFormat.class);
    job.setMapperClass(TsvImporter.class);

    String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
    if (hfileOutPath != null) {
      HTable table = new HTable(conf, tableName);
      job.setReducerClass(PutSortReducer.class);
      Path outputDir = new Path(hfileOutPath);
      FileOutputFormat.setOutputPath(job, outputDir);
      job.setMapOutputKeyClass(ImmutableBytesWritable.class);
      job.setMapOutputValueClass(Put.class);
      HFileOutputFormat.configureIncrementalLoad(job, table);
    } else {
      // No reducers.  Just write straight to table.  Call initTableReducerJob
      // to set up the TableOutputFormat.
      TableMapReduceUtil.initTableReducerJob(tableName, null, job);
      job.setNumReduceTasks(0);
    }

    TableMapReduceUtil.addDependencyJars(job);
    return job;
  }

  /*
   * @param errorMsg Error message.  Can be null.
   */
  private static void usage(final String errorMsg) {
    if (errorMsg != null && errorMsg.length() > 0) {
      System.err.println("ERROR: " + errorMsg);
    }
    String usage =
      "Usage: " + NAME + " -Dimporttsv.columns=a,b,c <tablename> <inputdir>\n" +
      "\n" +
      "Imports the given input directory of TSV data into the specified table.\n" +
      "\n" +
      "The column names of the TSV data must be specified using the -Dimporttsv.columns\n" +
      "option. This option takes the form of comma-separated column names, where each\n" +
      "column name is either a simple column family, or a columnfamily:qualifier. The special\n" +
      "column name HBASE_ROW_KEY is used to designate that this column should be used\n" +
      "as the row key for each imported record. You must specify exactly one column\n" +
      "to be the row key.\n" +
      "\n" +
      "In order to prepare data for a bulk data load, pass the option:\n" +
      "  -D" + BULK_OUTPUT_CONF_KEY + "=/path/for/output\n" +
      "\n" +
      "Other options that may be specified with -D include:\n" +
      "  -D" + SKIP_LINES_CONF_KEY + "=false - fail if encountering an invalid line\n" +
      "  '-D" + SEPARATOR_CONF_KEY + "=|' - eg separate on pipes instead of tabs";
    System.err.println(usage);
  }

  /**
   * Main entry point.
   *
   * @param args  The command line parameters.
   * @throws Exception When running the job fails.
   */
  public static void main(String[] args) throws Exception {
    Configuration conf = HBaseConfiguration.create();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
      usage("Wrong number of arguments: " + otherArgs.length);
      System.exit(-1);
    }

    // Make sure columns are specified
    String columns[] = conf.getStrings(COLUMNS_CONF_KEY);
    if (columns == null) {
      usage("No columns specified. Please specify with -D" +
            COLUMNS_CONF_KEY+"=...");
      System.exit(-1);
    }

    // Make sure they specify exactly one column as the row key
    int rowkeysFound=0;
    for (String col : columns) {
      if (col.equals(TsvParser.ROWKEY_COLUMN_SPEC)) rowkeysFound++;
    }
    if (rowkeysFound != 1) {
      usage("Must specify exactly one column as " + TsvParser.ROWKEY_COLUMN_SPEC);
      System.exit(-1);
    }

    Job job = createSubmittableJob(conf, otherArgs);
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }

}


text:
from __future__ import print_function
import argparse
import os
import random
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
import dcgan
import numpy as np
np.random.seed(43)
from multiprocessing import Pool
import h5py

#Change workdir to where you want the files output
work_dir = os.path.expandvars('$PBS_O_WORKDIR/berea_test')

parser = argparse.ArgumentParser()
parser.add_argument('--dataset', required=True, help='3D')
parser.add_argument('--dataroot', required=True, help='path to dataset')
parser.add_argument('--workers', type=int, help='number of data loading workers', default=2)
parser.add_argument('--batchSize', type=int, default=64, help='input batch size')
parser.add_argument('--imageSize', type=int, default=64, help='the height / width of the input image to network')
parser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')
parser.add_argument('--ngf', type=int, default=64)
parser.add_argument('--ndf', type=int, default=64)
parser.add_argument('--cuda'  , action='store_true', help='enables cuda')
parser.add_argument('--ngpu'  , type=int, default=1, help='number of GPUs to use')
parser.add_argument('--netG', default='', help="path to netG (to continue training)")
parser.add_argument('--netD', default='', help="path to netD (to continue training)")
work_dir = os.path.expandvars('$PBS_O_WORKDIR/filters/')
opt = parser.parse_args()
print(opt)

ngpu = int(opt.ngpu)
nz = int(opt.nz)
ngf = int(opt.ngf)
ndf = int(opt.ndf)
nc = 1

def save_hdf5(tensor, weights, filename):
    """
    Saves a given Tensor into an image file.
    If given a mini-batch tensor, will save the tensor as a grid of images.
    """
    tensor = tensor.cpu()
    ndarr = tensor.float().numpy()
    with h5py.File(filename, 'w') as f:
        f.create_dataset('data', data=ndarr, compression="gzip")
	f.create_dataset('weights', data=weights.cpu().float().numpy(), compression='gzip')

def load_img(filepath):
    img = None
    with h5py.File(filepath, "r") as f:
        img = f['data'][()]
    img = np.expand_dims(img, axis=0)
    img = np.expand_dims(img, axis=0)
    torch_img = Tensor(img)
    torch_img = torch_img.div(255).sub(0.5).div(0.5)
    return torch_img

# custom weights initialization called on netG and netD
def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

netD = dcgan.DCGAN3D_D(opt.imageSize, nz, nc, ngf, ngpu)
netD.apply(weights_init)
if opt.netD != '':
    netD.load_state_dict(torch.load(opt.netD))
print(netD)

netG = dcgan.DCGAN3D_G(opt.imageSize, nz, nc, ngf, ngpu)
netG.apply(weights_init)
if opt.netG != '':
    netG.load_state_dict(torch.load(opt.netG))
print(netG)

def counter_init(mod='layer_'):
    counter = 0
    def printnorm(self, input, output):
        # input is a tuple of packed inputs
        # output is a Variable. output.data is the Tensor we are interested
        print('Inside ' + self.__class__.__name__ + ' forward')
        print('')
        print('input: ', type(input))
        print('input[0]: ', type(input[0]))
        print('output: ', type(output))
        print('')
        print('output size:', output.data.size())

        try:
            print(self.weight.__class__.__name__, self.weight.data.__class__.__name__, self.parameters().__class__.__name__)
            print(self.weight)
            save_hdf5(output.data, self.weight.data, work_dir+mod+self.__class__.__name__+'_'+str(output.data.size())+'.hdf5')
        except:
            pass
    return printnorm

printnorm = counter_init()
for module in netD.modules():
    print(module)
    module.register_forward_hook(printnorm)

img = load_img("berea_1.hdf5")
img = img.cuda()
input = Variable(img)
netD = netD.cuda()
netD.forward(input)
print('forwarded')

printnorm = counter_init(mod='gen_')
for module in netG.modules():
    print(module)
    module.register_forward_hook(printnorm)
fixed_noise = Variable(torch.FloatTensor(1, nz, 9, 9, 9).normal_(0, 1).cuda())
netG = netG.cuda()
netG.forward(fixed_noise)
print('forwarded')


text:
local Whichkey = {
  WhichKey = { fg = C.purple },
  WhichKeySeperator = { fg = C.green },
  WhichKeyGroup = { fg = C.cyan },
  WhichKeyDesc = { fg = C.blue },
  WhichKeyFloat = { bg = C.dark },
}

return Whichkey


text:
<!DOCTYPE html>
<html>
  <head>
      <!--<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-8">-->
      <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-5">
      <script src="/resources/testharness.js"></script>
      <script src="/resources/testharnessreport.js"></script>
  </head>
  <body>
    <script>
      "use strict";
      test(() => {
        assert_equals(document.characterSet, "ISO-8859-5");
      }, "document.characterSet should be determined by meta charset");
    </script>
  </body>
</html>


text:
<?php
// Database filename
$db_filename = '/var/www/localhost/ET/et_db.txt';
// Seperators to use in the database
$table_sep = '=.=.=';
$cell_sep = '';
// DateTime format
$dt_fmt = 'o-m-d H:i';
// Base path in docroot
$base_path = '/';

// Table names
$loans_table = 'Loans';
$objects_table = 'Objects';
?>


text:
package com.twitter.hraven;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.hadoop.io.WritableComparable;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * Represents the row key for a given job. Row keys are stored as: username !
 * appid ! version ! runid ! jobid
 */
public class JobKey extends FlowKey implements WritableComparable<Object>{

  /**
   * Fully qualified cluster + parsed job identifier
   */
  private final QualifiedJobId jobId;

  /**
   * Constructor.
   *
   * @param cluster
   *          the Hadoop cluster on which the job ran.
   * @param userName
   *          the Hadoop user name that ran a job
   * @param appId
   *          The thing that identifies an application, such as Pig script
   *          identifier, or Scalding identifier.
   * @param runId
   *          The identifier that ties the various runs for this job together
   * @param jobId
   *          The Hadoop generated MapReduce JobID.
   */
  public JobKey(String cluster, String userName, String appId, long runId,
      String jobId) {
    // TODO: Change contract to allow for nulls and advertise strings.
    this(new QualifiedJobId(cluster, jobId), userName, appId, runId);
  }

  @JsonCreator
  public JobKey(@JsonProperty("cluster") String cluster,
                @JsonProperty("userName") String userName,
                @JsonProperty("appId") String appId,
                @JsonProperty("runId") long runId,
                @JsonProperty("jobId") JobId jobId) {
    this(new QualifiedJobId(cluster, jobId), userName, appId, runId);
  }

  /**
   * Creates a new JobKey from the given parameters
   *
   * @param qualifiedJobId The combined cluster + job ID
   * @param userName The user name that ran the job
   * @param appId The application identifier
   * @param runId The run timestamp
   */
  public JobKey(QualifiedJobId qualifiedJobId, String userName, String appId,
      long runId) {
    super(qualifiedJobId.getCluster(), userName, appId, runId);
    this.jobId = qualifiedJobId;
  }

  /**
   * Constructor.
   *
   * @param jobDesc
   *          from which to construct this JobKey.
   */
  public JobKey(JobDesc jobDesc) {
    this(jobDesc.getCluster(), jobDesc.getUserName(), jobDesc.getAppId(),
        jobDesc.getRunId(), jobDesc.getJobId());
  }

  /**
   * @return The fully qualified cluster + parsed job ID
   */
  public QualifiedJobId getQualifiedJobId() {
    return jobId;
  }

  /**
   * @return The Hadoop map-reduce Job identifier as run on the JobTracker.
   */
  public JobId getJobId() {
    return jobId;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#toString()
   */
  public String toString() {
    return super.toString() + Constants.SEP + this.jobId.getJobIdString();
  }
  /**
   * Compares two JobKey QualifiedJobId
   *
   * @param other
   * @return 0 if the Qualified Job Ids are equal,
   * 		 1 if this QualifiedJobId greater than other QualifiedJobId,
   * 		-1 if this QualifiedJobId is less than other QualifiedJobId
   */
  @Override
  public int compareTo(Object other) {
    if (other == null) {
      return -1;
    }
    JobKey otherKey = (JobKey)other;
    return new CompareToBuilder().appendSuper(super.compareTo(otherKey))
        .append(this.jobId, otherKey.getJobId())
        .toComparison();
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof JobKey) {
      return compareTo((JobKey)other) == 0;
    }
    return false;
  }

  @Override
  public int hashCode(){
      return new HashCodeBuilder().appendSuper(super.hashCode())
          .append(this.jobId)
          .toHashCode();
  }

  @Override
  public void write(DataOutput out) throws IOException {
    super.write(out);
    this.jobId.write(out);
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    super.readFields(in);
    this.jobId.readFields(in);
  }

}


text:
package com.github.tx.archetype.modules.sys.dao;

import com.github.tx.archetype.modules.core.BaseRepository;
import com.github.tx.archetype.modules.sys.entity.User;

/**
 * User DAO
 *
 * @author tangx
 * @since 2015年1月27日
 */

public interface UserRepository extends BaseRepository<User, Long> {

	User findByLoginName(String loginName);
}


text:
import boto3

#1. get current cluster
client = boto3.client('es')
response = client.delete_elasticsearch_domain(DomainName='histograph-staging')
print(response)


text:
package org.apache.ddlutils.platform;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Wrapper class for database meta data that stores additional info.
 *
 * @version $Revision: 329426 $
 */
public class DatabaseMetaDataWrapper
{
    /** The database meta data. */
    private DatabaseMetaData _metaData;
    /** The catalog to acess in the database. */
    private String _catalog;
    /** The schema(s) to acess in the database. */
    private String _schemaPattern;
    /** The table types to process. */
    private String[] _tableTypes;

    /**
     * Returns the database meta data.
     *
     * @return The meta data
     */
    public DatabaseMetaData getMetaData()
    {
        return _metaData;
    }

    /**
     * Sets the database meta data.
     *
     * @param metaData The meta data
     */
    public void setMetaData(DatabaseMetaData metaData)
    {
        _metaData = metaData;
    }

    /**
     * Returns the catalog in the database to read.
     *
     * @return The catalog
     */
    public String getCatalog()
    {
        return _catalog;
    }

    /**
     * Sets the catalog in the database to read.
     *
     * @param catalog The catalog
     */
    public void setCatalog(String catalog)
    {
        _catalog = catalog;
    }

    /**
     * Returns the schema in the database to read.
     *
     * @return The schema
     */
    public String getSchemaPattern()
    {
        return _schemaPattern;
    }

    /**
     * Sets the schema in the database to read.
     *
     * @param schema The schema
     */
    public void setSchemaPattern(String schema)
    {
        _schemaPattern = schema;
    }

    /**
     * Returns the table types to recognize.
     *
     * @return The table types
     */
    public String[] getTableTypes()
    {
        return _tableTypes;
    }

    /**
     * Sets the table types to recognize.
     *
     * @param types The table types
     */
    public void setTableTypes(String[] types)
    {
        _tableTypes = types;
    }

    /**
     * Convenience method to return the table meta data using the configured catalog,
     * schema pattern and table types.
     *
     * @param tableNamePattern The pattern identifying for which tables to return info
     * @return The table meta data
     * @throws SQLException If an error occurred retrieving the meta data
     * @see DatabaseMetaData#getTables(java.lang.String, java.lang.String, java.lang.String, java.lang.String[])
     */
    public ResultSet getTables(String tableNamePattern) throws SQLException
    {
        return getMetaData().getTables(getCatalog(), getSchemaPattern(), tableNamePattern, getTableTypes());
    }

    /**
     * Convenience method to return the column meta data using the configured catalog and
     * schema pattern.
     *
     * @param tableNamePattern  The pattern identifying for which tables to return info
     * @param columnNamePattern The pattern identifying for which columns to return info
     * @return The column meta data
     * @throws SQLException If an error occurred retrieving the meta data
     * @see DatabaseMetaData#getColumns(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    public ResultSet getColumns(String tableNamePattern, String columnNamePattern) throws SQLException
    {
        return getMetaData().getColumns(getCatalog(), getSchemaPattern(), tableNamePattern, columnNamePattern);
    }

    /**
     * Convenience method to return the primary key meta data using the configured catalog and
     * schema pattern.
     *
     * @param tableNamePattern The pattern identifying for which tables to return info
     * @return The primary key meta data
     * @throws SQLException If an error occurred retrieving the meta data
     * @see DatabaseMetaData#getPrimaryKeys(java.lang.String, java.lang.String, java.lang.String)
     */
    public ResultSet getPrimaryKeys(String tableNamePattern) throws SQLException
    {
        return getMetaData().getPrimaryKeys(getCatalog(), getSchemaPattern(), tableNamePattern);
    }

    /**
     * Convenience method to return the foreign key meta data using the configured catalog and
     * schema pattern.
     *
     * @param tableNamePattern The pattern identifying for which tables to return info
     * @return The foreign key meta data
     * @throws SQLException If an error occurred retrieving the meta data
     * @see DatabaseMetaData#getImportedKeys(java.lang.String, java.lang.String, java.lang.String)
     */
    public ResultSet getForeignKeys(String tableNamePattern) throws SQLException
    {
        return getMetaData().getImportedKeys(getCatalog(), getSchemaPattern(), tableNamePattern);
    }

    /**
     * Convenience method to return the index meta data using the configured catalog and
     * schema pattern.
     *
     * @param tableNamePattern The pattern identifying for which tables to return info
     * @param unique           Whether to return only indices for unique values
     * @param approximate      Whether the result is allowed to reflect approximate or out of data values
     * @return The index meta data
     * @throws SQLException If an error occurred retrieving the meta data
     * @see DatabaseMetaData#getIndexInfo(java.lang.String, java.lang.String, java.lang.String, boolean, boolean)
     */
    public ResultSet getIndices(String tableNamePattern, boolean unique, boolean approximate) throws SQLException
    {
        return getMetaData().getIndexInfo(getCatalog(), getSchemaPattern(), tableNamePattern, unique, approximate);
    }
}


text:
import TestBase from '../testbase';
TestBase.init();

import FakeScope from '../../node_modules/gs-tools/src/ng/fake-scope';
import { NavGraphCtrl } from './nav-graph';
import TestDispose from '../../node_modules/gs-tools/src/testing/test-dispose';

describe('asset.NavGraphCtrl', () => {
  let mock$scope;
  let mockDeregister;
  let mockExportNode;
  let mockGlobalNode;
  let mockHelperNode;
  let mockImageNode;
  let mockLabelNode;
  let mockPartialNode;
  let mockProcessNode;
  let mockTemplateNode;
  let mockTextNode;
  let ctrl;

  function createSpyNode(name: string, deregister: Function): any {
    let mock = jasmine.createSpyObj(name, ['addChangeListener']);
    mock.addChangeListener.and.returnValue(deregister);
    return mock;
  }

  beforeEach(() => {
    mock$scope = FakeScope.create();
    spyOn(mock$scope, '$on');

    mockDeregister = jasmine.createSpy('deregister');
    mockExportNode = createSpyNode('ExportNode', mockDeregister);
    mockGlobalNode = createSpyNode('GlobalNode', mockDeregister);
    mockHelperNode = createSpyNode('HelperNode', mockDeregister);
    mockImageNode = createSpyNode('ImageNode', mockDeregister);
    mockLabelNode = createSpyNode('LabelNode', mockDeregister);
    mockPartialNode = createSpyNode('PartialNode', mockDeregister);
    mockProcessNode = createSpyNode('ProcessNode', mockDeregister);
    mockTemplateNode = createSpyNode('TemplateNode', mockDeregister);
    mockTextNode = createSpyNode('TextNode', mockDeregister);

    let mockAssetPipelineService = jasmine.createSpyObj('AssetPipelineService', ['getPipeline']);
    mockAssetPipelineService.getPipeline.and.returnValue({
      exportNode: mockExportNode,
      globalNode: mockGlobalNode,
      helperNode: mockHelperNode,
      imageNode: mockImageNode,
      labelNode: mockLabelNode,
      partialNode: mockPartialNode,
      processNode: mockProcessNode,
      templateNode: mockTemplateNode,
      textNode: mockTextNode,
    });

    ctrl = new NavGraphCtrl(mock$scope, mockAssetPipelineService);
    ctrl.asset = { id: 'assetId' };
    TestDispose.add(ctrl);
  });

  it('should trigger digest when export node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['exportNode_'];
    expect(mockExportNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockExportNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when global node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['globalNode_'];
    expect(mockGlobalNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockGlobalNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when helper node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['helperNode_'];
    expect(mockHelperNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockHelperNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when image node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['imageNode_'];
    expect(mockImageNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockImageNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when label node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['labelNode_'];
    expect(mockLabelNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockLabelNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when partial node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['partialNode_'];
    expect(mockPartialNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockPartialNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when process node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['processNode_'];
    expect(mockProcessNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockProcessNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when template node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['templateNode_'];
    expect(mockTemplateNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockTemplateNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should trigger digest when text node is changed', () => {
    spyOn(mock$scope, '$apply');

    ctrl['textNode_'];
    expect(mockTextNode.addChangeListener).toHaveBeenCalledWith(jasmine.any(Function));

    mockTextNode.addChangeListener.calls.argsFor(0)[0]();
    expect(mock$scope.$apply).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should deregister all the listeners on destroy', () => {
    ctrl['exportNode_'];
    ctrl['globalNode_'];
    ctrl['helperNode_'];
    ctrl['imageNode_'];
    ctrl['labelNode_'];
    ctrl['partialNode_'];
    ctrl['processNode_'];
    ctrl['templateNode_'];
    ctrl['textNode_'];

    expect(mock$scope.$on).toHaveBeenCalledWith('$destroy', jasmine.any(Function));

    mock$scope.$on.calls.argsFor(0)[1]();

    expect(mockDeregister).toHaveBeenCalledWith();
    expect(mockDeregister.calls.count()).toEqual(9);
  });
});


text:
/**
 * Created by hlogeon on 8/9/16.
 *
 * EventsListController takes control over displaying
 * list of events and all events map
 */

import ListController from '../../common/controllers/list.controller.js';
import EventsService from '../services/events.service.js';

class OrganizerListController extends ListController {

    constructor ($scope, $state, $stateParams, $q, $timeout, service, CategoriesService, DateFromChangedEvent, DateToChangedEvent, PlaceFilterChangedEvent, CategoryChangedEvent, MarkersLoadedEvent, UserService, GotLocationEvent) {
        super($scope, $q, service);
        this.state = $state;
        this.timeout = $timeout;
        this.stateParams = $stateParams;
        this.isDraft = $state.current.data.drafts;
        UserService.gettingLocation();
        this.categoriesService = CategoriesService;
        this.categoryChanged = CategoryChangedEvent;
        this.categories = [];
        this.init();
        this.loadCategories();
        this.listenDateTo(DateToChangedEvent);
        this.listenDateFrom(DateFromChangedEvent);
        this.listenCity(PlaceFilterChangedEvent);
        this.listenLocation(GotLocationEvent);
        this.listenCategories(CategoryChangedEvent);
        this.init();
    }

    init() {
        this.events = [];
        this.getService().getRequestService().setPage(0);
        this.hasMorePages = true;
        this.pages = 0;
        this.user = {};
        this.user.lat = null;
        this.user.lng = null;
    }

    /**
     * Load view objects
     */
    loadObjects (pushNew = true) {
        let context = this;
        this.loading = true;

        if(this.state.params.slug) {
            this.getService().getRequestService().setCategory(this.state.params.slug);
        } else {
            this.getService().getRequestService().setCategory(null);
        }
        let endPoint = 'organizer';
        if (this.isDraft) {
            endPoint = 'drafts';
        }
        this.getQ().when(this.getService().gettingEvents(endPoint)).then(function (events) {
            context.loading = false;
            context.hasMorePages = context.getService().getRequestService().hasNextPage();
            if(pushNew) {
                events.forEach((event) => {context.events.push(event)});
            } else {
                context.events = events;
            }
        });
    }

    listenDateFrom (dateFrom) {
        dateFrom.subscribe(this.scope, (evt, params) => {
            this.getService().getRequestService().setPage(0);
            this.getService().getRequestService().setDateFrom(params);
            this.loadObjects(false);
        })
    }

    listenDateTo (dateTo) {
        dateTo.subscribe(this.scope, (evt, params) => {
            this.getService().getRequestService().setPage(0);
            this.getService().getRequestService().setDateTo(params);
            this.loadObjects(false);
        });
    }

    listenCity (city) {
        city.subscribe(this.scope, (evt, params) => {
            this.getService().getRequestService().setPage(0);
            this.getService().getRequestService().setLocation(params.place.geometry.location.lat(), params.place.geometry.location.lng());
            this.lat = params.place.geometry.location.lat();
            this.lng = params.place.geometry.location.lng();
            this.loadObjects(false);
        });
    }

    listenCategories (categoriesEvent) {
        let context = this;
        categoriesEvent.subscribe(this.scope, (evt, params) => {
            this.getService().getRequestService().setPage(0);
            if (!params) {
                this.state.params.slug = null;
                this.loadObjects(false);
                context.state.transitionTo('venvast.events');
            } else {
                this.state.params.slug = params.slug;
                this.loadObjects(false);
                context.state.transitionTo('venvast.events.category', {slug: params.slug});
            }
        });
    }

    listenLocation (gotLocationEvent) {
        gotLocationEvent.subscribe(this.scope, (evt, params) => {
            this.user.lat = params.lat;
            this.user.lng = params.lng;
            this.lat = params.lat;
            this.lng = params.lng;
            this.loadObjects(false);
        });
    }

    loadCategories () {
        let context = this;
        this.getQ().when(this.categoriesService.gettingCategories()).then(function (categories) {
            context.categories = categories;
        });
    }

}
export default OrganizerListController;


text:
#include "list_ptr_to_long.h"

typedef NodePtr StackNodePtr; // define StackNodePtr

extern void push( NodePtr *top, long input ); // the prototype of push
extern long pop( NodePtr *top ); // the prototype of pop

#endif


text:
package org.artifactory.webapp.wicket.page.browse.treebrowser.tabs.build.actionable;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.markup.html.panel.Panel;
import org.artifactory.api.security.AuthorizationService;
import org.artifactory.build.BuildRun;
import org.artifactory.common.wicket.component.modal.ModalHandler;
import org.artifactory.webapp.actionable.ActionableItemBase;
import org.artifactory.webapp.wicket.page.browse.treebrowser.tabs.build.action.GoToBuildAction;
import org.artifactory.webapp.wicket.page.browse.treebrowser.tabs.build.action.ShowInCiServerAction;
import org.artifactory.webapp.wicket.page.browse.treebrowser.tabs.build.action.ViewBuildJsonAction;
import org.artifactory.webapp.wicket.util.ItemCssClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Artifact associated build actionable item
 *
 * @author Noam Y. Tenne
 */
public class BuildTabActionableItem extends ActionableItemBase {

    @SuppressWarnings("UnusedDeclaration")
    private static final Logger log = LoggerFactory.getLogger(BuildTabActionableItem.class);

    private String moduleId;
    private BuildRun buildRun;
    private ViewBuildJsonAction viewJsonAction;

    /**
     * Main constructor
     *
     * @param textContentViewer Modal handler for displaying the build XML
     * @param buildRun          Basic build info object to handle
     * @param moduleId          ID of module association to specify
     */
    public BuildTabActionableItem(ModalHandler textContentViewer, BuildRun buildRun, String moduleId) {
        this.buildRun = buildRun;
        this.moduleId = moduleId;

        getActions().add(new GoToBuildAction(buildRun, moduleId));
        viewJsonAction = new
                ViewBuildJsonAction(textContentViewer, buildRun);
        getActions().add(viewJsonAction);
        String ciServerUrl = buildRun.getCiUrl();
        if (StringUtils.isNotBlank(ciServerUrl)) {
            getActions().add(new ShowInCiServerAction(ciServerUrl));
        }
    }

    @Override
    public Panel newItemDetailsPanel(String id) {
        return null;
    }

    @Override
    public String getDisplayName() {
        return buildRun.getName();
    }

    @Override
    public String getCssClass() {
        return ItemCssClass.doc.getCssClass();
    }

    @Override
    public void filterActions(AuthorizationService authService) {
        if (!authService.canDeployToLocalRepository()) {
            viewJsonAction.setEnabled(false);
        }
    }

    /**
     * Returns the ID of the module to specify association with
     *
     * @return Module ID association to specify
     */
    public String getModuleId() {
        return moduleId;
    }
}


text:
package org.jboss.test.gravia.itests;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.Dictionary;
import java.util.Hashtable;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.osgi.StartLevelAware;
import org.jboss.gravia.Constants;
import org.jboss.gravia.itests.support.ArchiveBuilder;
import org.jboss.gravia.resource.ManifestBuilder;
import org.jboss.gravia.runtime.ModuleContext;
import org.jboss.gravia.runtime.Runtime;
import org.jboss.gravia.runtime.RuntimeLocator;
import org.jboss.gravia.runtime.RuntimeType;
import org.jboss.gravia.runtime.ServiceRegistration;
import org.jboss.gravia.utils.IOUtils;
import org.jboss.osgi.metadata.OSGiManifestBuilder;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * Test URLStreamHandler integration
 *
 * @author Thomas.Diesler@jboss.com
 * @since 16-May-2014
 */
@RunWith(Arquillian.class)
public class URLStreamHandlerTest {

    @Deployment
    @StartLevelAware(autostart = true)
    public static Archive<?> deployment() {
        final ArchiveBuilder archive = new ArchiveBuilder("url-handler-test");
        archive.addClasses(URLStreamHandlerTest.class);
        archive.setManifest(new Asset() {
            @Override
            public InputStream openStream() {
                if (ArchiveBuilder.getTargetContainer() == RuntimeType.KARAF) {
                    OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
                    builder.addBundleManifestVersion(2);
                    builder.addBundleSymbolicName(archive.getName());
                    builder.addBundleVersion("1.0.0");
                    builder.addImportPackages(RuntimeLocator.class, IOUtils.class);
                    return builder.openStream();
                } else {
                    ManifestBuilder builder = new ManifestBuilder();
                    builder.addIdentityCapability(archive.getName(), "1.0.0");
                    return builder.openStream();
                }
            }
        });
        return archive.getArchive();
    }

    @Test
    public void testURLHandlerService() throws Exception {

        try {
            new URL("foo://hi");
            Assert.fail("No handler registered. Should throw a MalformedURLException.");
        } catch (MalformedURLException mue) {
            // expected
        }

        Runtime runtime = RuntimeLocator.getRequiredRuntime();
        ModuleContext syscontext = runtime.getModuleContext();

        Dictionary<String, Object> props = new Hashtable<>();
        props.put(Constants.URL_HANDLER_PROTOCOL, "foo");
        ServiceRegistration<URLStreamHandler> sreg = syscontext.registerService(URLStreamHandler.class, new MyHandler(), props);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copyStream(new URL("foo://somehost").openStream(), baos);
            Assert.assertEquals("somehost", new String(baos.toByteArray()));
        } finally {
            sreg.unregister();
        }

        try {
            new URL("foo://hi").openConnection();
            Assert.fail("No handler registered any more.");
        } catch (IOException ex) {
            // expected
        }
    }

    private static class MyHandler extends URLStreamHandler {

        @Override
        public URLConnection openConnection(final URL url) throws IOException {
            return new URLConnection(url) {

                @Override
                public void connect() throws IOException {
                }

                @Override
                public InputStream getInputStream() throws IOException {
                    return new ByteArrayInputStream(url.getHost().getBytes());
                }
            };
        }
    }
}


text:
#include <jni.h>
#include "dcetest.h"
#include <stdio.h>

static jstring o;
static int refWasSet = 0;

JNIEXPORT void JNICALL
Java_org_apache_harmony_test_func_jit_HLO_dce_deadnative_DeadNativeTest_nativeMethodSet
  (JNIEnv * env, jobject par, jstring obj)
{
    char * ch;
    o = obj;
    ch = (*env)->GetStringUTFChars(env, obj, NULL);
    //printf("### Set: object = %p, value = %s\n", obj ,ch);
    return;
}

JNIEXPORT void JNICALL
Java_org_apache_harmony_test_func_jit_HLO_dce_deadnative_DeadNativeTest_nativeMethodFakeSet
  (JNIEnv * env, jobject par, jstring obj)
{
    //printf("Fake Set: Just doing nothing\n");
    return;
}

JNIEXPORT void JNICALL
Java_org_apache_harmony_test_func_jit_HLO_dce_deadnative_DeadNativeTest_nativeMethodSetAndStore
  (JNIEnv * env, jobject par, jstring obj)
{
    char * ch;

    if(refWasSet)
        Java_org_apache_harmony_test_func_jit_HLO_dce_deadnative_DeadNativeTest_nativeDeleteRef(env, par);

    o = (jstring) (*env)->NewGlobalRef(env, obj);
    refWasSet = 1;
    ch = (*env)->GetStringUTFChars(env, o, NULL);
    //printf("### SetAndStore: object = %p, value = %s\n", o, ch);
    return;
}

JNIEXPORT jstring JNICALL
Java_org_apache_harmony_test_func_jit_HLO_dce_deadnative_DeadNativeTest_nativeMethodGet
  (JNIEnv * env, jobject par)
{
    char * ch;
    ch = (*env)->GetStringUTFChars(env, o, NULL);
    //printf("### Get: object = %p, value = %s\n", o, ch);
    return o;
}

JNIEXPORT void JNICALL
Java_org_apache_harmony_test_func_jit_HLO_dce_deadnative_DeadNativeTest_nativeDeleteRef
  (JNIEnv * env, jobject par)
{
    //printf("Delete: object = %p\n", o);
    if(o == NULL || !refWasSet) return;
    (*env)->DeleteGlobalRef(env, o);
    refWasSet = 0;
    o= NULL;
    return;
}


text:
[![Build Status](https://travis-ci.org/nearlyfreeapps/appx.svg?branch=master)](https://travis-ci.org/nearlyfreeapps/appx)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'appx'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install appx

## Usage

```ruby
require 'appx'

appx = Appx::File('path/to/file.appx')

puts appx.manifest.identity_name
puts appx.manifest.version
```

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/nearlyfreeapps/appx.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
package uk.co.blackpepper.bowman.test.it.model;

import java.net.URI;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;

import uk.co.blackpepper.bowman.annotation.LinkedResource;
import uk.co.blackpepper.bowman.annotation.RemoteResource;
import uk.co.blackpepper.bowman.annotation.ResourceId;

@RemoteResource("/optional-links-entities-query")
public class OptionalLinksQueryEntity {

	private URI id;

	private String name;

	private SimpleEntity optionalLinkItem;

	private List<SimpleEntity> optionalLinkCollection;

	@ResourceId
	@JsonIgnore
	public URI getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@LinkedResource(optionalLink = true)
	public SimpleEntity getOptionalLinkItem() {
		return optionalLinkItem;
	}

	public void setOptionalLinkItem(SimpleEntity optionalLinkItem) {
		this.optionalLinkItem = optionalLinkItem;
	}

	@LinkedResource(optionalLink = true)
	public List<SimpleEntity> getOptionalLinkCollection() {
		return optionalLinkCollection;
	}

	public void setOptionalLinkCollection(List<SimpleEntity> optionalLinkCollection) {
		this.optionalLinkCollection = optionalLinkCollection;
	}
}


text:
import * as vscode from 'vscode';
import type * as Proto from '../protocol';
import { ITypeScriptServiceClient } from '../typescriptService';
import API from '../utils/api';
import { coalesce } from '../utils/arrays';
import { conditionalRegistration, requireMinVersion } from '../utils/dependentRegistration';
import { DocumentSelector } from '../utils/documentSelector';
import * as typeConverters from '../utils/typeConverters';

class TypeScriptFoldingProvider implements vscode.FoldingRangeProvider {
	public static readonly minVersion = API.v280;

	public constructor(
		private readonly client: ITypeScriptServiceClient
	) { }

	async provideFoldingRanges(
		document: vscode.TextDocument,
		_context: vscode.FoldingContext,
		token: vscode.CancellationToken
	): Promise<vscode.FoldingRange[] | undefined> {
		const file = this.client.toOpenedFilePath(document);
		if (!file) {
			return;
		}

		const args: Proto.FileRequestArgs = { file };
		const response = await this.client.execute('getOutliningSpans', args, token);
		if (response.type !== 'response' || !response.body) {
			return;
		}

		return coalesce(response.body.map(span => this.convertOutliningSpan(span, document)));
	}

	private convertOutliningSpan(
		span: Proto.OutliningSpan,
		document: vscode.TextDocument
	): vscode.FoldingRange | undefined {
		const range = typeConverters.Range.fromTextSpan(span.textSpan);
		const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);

		// Workaround for #49904
		if (span.kind === 'comment') {
			const line = document.lineAt(range.start.line).text;
			if (line.match(/\/\/\s*#endregion/gi)) {
				return undefined;
			}
		}

		const start = range.start.line;
		const end = this.adjustFoldingEnd(range, document);
		return new vscode.FoldingRange(start, end, kind);
	}

	private static readonly foldEndPairCharacters = ['}', ']', ')', '`'];

	private adjustFoldingEnd(range: vscode.Range, document: vscode.TextDocument) {
		// workaround for #47240
		if (range.end.character > 0) {
			const foldEndCharacter = document.getText(new vscode.Range(range.end.translate(0, -1), range.end));
			if (TypeScriptFoldingProvider.foldEndPairCharacters.includes(foldEndCharacter)) {
				return Math.max(range.end.line - 1, range.start.line);
			}
		}

		return range.end.line;
	}

	private static getFoldingRangeKind(span: Proto.OutliningSpan): vscode.FoldingRangeKind | undefined {
		switch (span.kind) {
			case 'comment': return vscode.FoldingRangeKind.Comment;
			case 'region': return vscode.FoldingRangeKind.Region;
			case 'imports': return vscode.FoldingRangeKind.Imports;
			case 'code':
			default: return undefined;
		}
	}
}

export function register(
	selector: DocumentSelector,
	client: ITypeScriptServiceClient,
): vscode.Disposable {
	return conditionalRegistration([
		requireMinVersion(client, TypeScriptFoldingProvider.minVersion),
	], () => {
		return vscode.languages.registerFoldingRangeProvider(selector.syntax,
			new TypeScriptFoldingProvider(client));
	});
}