text:
package desmoj.core.report;

import desmoj.core.simulator.TimeSpan;
import desmoj.core.statistic.StatisticObject;

public class HistogramReporter extends desmoj.core.report.Reporter {

	// ****** attributes ******

	/**
	 * The column headings of the histogram part of this HistogramReporter.
	 * Entries should contain in the elements in the same order as the
	 * histEntries[].
	 */
	private String[] _histColumns;

	/**
	 * The data entries of the histogram part of this HistogramReporter. The
	 * first (leftmost) dimension of this array is representing the number of
	 * cells the interval of the histogram is devided into (incl. under- and
	 * overflow). The second dimension of this array is representing each column
	 * entry of the specified cell. So the second dimension entries should
	 * contain the data elements in the same order as defined in the
	 * histColumns[] array.
	 */
	private String[][] _histEntries;

	/**
	 * The number of columns of the histogram part (table) of this
	 * HistogramReporter.
	 */
	private int _histNumColumns;

	/**
	 * The number of cells the interval of the given Histogram is devided into.
	 */
	private int _noOfCells;

	// ****** methods ******

	/**
	 * Constructor for a new HistogramReporter. Note that although any
	 * Reportable is accepted you should make sure that only subtypes of
	 * Histogram are passed to this constructor. Otherwise the number of column
	 * titles and their individual headings will differ from the actual content
	 * collected by this reporter.
	 *
	 * @param informationSource
	 *            desmoj.core.simulator.Reportable : The Histogram to report about.
	 */
	public HistogramReporter(desmoj.core.simulator.Reportable informationSource) {
		super(informationSource); // make a Reporter (source =
		// informationSource)

		// the Histogram we report about (source = informationSource)
		desmoj.core.statistic.Histogram hist 	= (desmoj.core.statistic.Histogram) source;

		groupID = 1411; // see Reporter for more information about groupID

		numColumns = 8;
		columns = new String[numColumns];
		columns[0] = "Title";
		columns[1] = "(Re)set";
		columns[2] = "Obs";
		columns[3] = "Mean";
		columns[4] = "Std.Dev";
		columns[5] = "Min";
		columns[6] = "Max";
		columns[7] = "Unit";
		groupHeading = "Histograms";

		entries = new String[numColumns];

		// *** histogram part ***

		_histNumColumns = 7;
		_noOfCells = hist.getCells();

		_histColumns = new String[_histNumColumns];
		_histColumns[0] = "Cell";
		_histColumns[1] = "Cell Range";
		_histColumns[2] = "n";
		_histColumns[3] = "%";
		_histColumns[4] = "Cum. %";
		_histColumns[5] = "|";
		_histColumns[6] = "Graph";

		_histEntries = new String[_noOfCells + 3][_histNumColumns];
	}

	/**
	 * Returns an array of Strings each containing the data for the
	 * corresponding column in array columns[]. Implement this
	 * method in a way, that an array of the same length as the columntitles is
	 * produced containing the data at the point of time this method is called
	 * by someone else to produce up-to-date information.
	 *
	 * @return java.lang.String[] : Array containing the data for reporting
	 */
	public String[] getEntries() {
		if (source instanceof desmoj.core.statistic.Histogram) {
			// the Histogram we report about (source = informationSource)
			desmoj.core.statistic.Histogram hist 	= (desmoj.core.statistic.Histogram) source;
			boolean _showTimeSpansInReport     = hist.getShowTimeSpansInReport();
			desmoj.core.statistic.Tally tl 			= (desmoj.core.statistic.Tally) source;
			desmoj.core.statistic.TallyRunning tlr = null;
			if (tl instanceof desmoj.core.statistic.TallyRunning) {
				tlr = (desmoj.core.statistic.TallyRunning) tl;
			}

			// Title
			entries[0] = hist.getName();
			// (Re)set
			entries[1] = hist.resetAt().toString();
			// Obs
			entries[2] = Long.toString(hist.getObservations());

			// Mean
			// no observations made, so Mean can not be calculated
			if (tl.getObservations() == 0) {
				entries[3] = "Insufficient data";
			} else // return mean value
			{
				entries[3] = this.format(_showTimeSpansInReport, tl.getMean());
				if (tlr != null)
					entries[3] += " (last "
							+ tlr.getSampleSizeN()
							+ " obs: "
							+ this.format(_showTimeSpansInReport, tlr.getMeanLastN())
							+ ")";
			}

			// Std.Dev
			// not enough observations are made, so Std.Dev can not be
			// calculated
			if (tl.getObservations() < 2) {
				entries[4] = "Insufficient data";
			} else // return standard deviation
			{
				entries[4] = this.format(_showTimeSpansInReport, tl.getStdDev());
				if (tlr != null)
					entries[4] += " (last "
							+ tlr.getSampleSizeN()
							+ " obs: "
							+ this.format(_showTimeSpansInReport, tlr.getStdDevLastN())
							+ ")";
			}

			// Min
			if (tl.getObservations() == 0) {
				entries[5] = "Insufficient data";
			} else {
				entries[5] = this.format(_showTimeSpansInReport, tl.getMinimum());
				if (tlr != null)
					entries[5] += " (last "
							+ tlr.getSampleSizeN()
							+ " obs: "
							+ this.format(_showTimeSpansInReport, tlr.getMinimumLastN())
							+ ")";
			}

			// Max
			if (tl.getObservations() == 0) {
				entries[6] = "Insufficient data";
			} else {
				entries[6] = this.format(_showTimeSpansInReport, tl.getMaximum());
				if (tlr != null)
					entries[6] += " (last "
							+ tlr.getSampleSizeN()
							+ " obs: "
							+ this.format(_showTimeSpansInReport, tlr.getMaximumLastN())
							+ ")";
			}

			//cm 21.11.12  Extension for viewing unit
            entries[7] = tl.getUnitText();

		} else {
			for (int i = 0; i < numColumns; i++) {
				entries[i] = "Invalid source!";
			} // end for
		} // end else

		return entries;
	}

	/**
	 * Returns an array of Strings each containing the title for the
	 * corresponding column of the histogram part (table).
	 *
	 * @return java.lang.String[] : Array containing column titles of the
	 *         histogram part (table).
	 */
	public String[] getHistColumnTitles() {
		return _histColumns.clone();
	}

	/**
	 * Returns a two-dimensional array of Strings containing the data for the
	 * histogram part of this HistogramReporter. Implement this method in a way,
	 * that the data is collected at the point of time this method is called by
	 * someone else to produce up-to-date information.
	 *
	 * @return java.lang.String[][] : Array containing the data for reporting
	 *         about the histogram part of this HistogramReporter.
	 */
	public String[][] getHistEntries() {
		// the Histogram we report about (source = informationSource)
		desmoj.core.statistic.Histogram hist = (desmoj.core.statistic.Histogram) source;
		boolean _showTimeSpansInReport     = hist.getShowTimeSpansInReport();

		// get hold of the accumulated percentage
		double cumPerc = 0.0;

		// flag if all remaining cells are empty
		boolean tailIsEmpty = false;

		for (int j = 0; j < _noOfCells + 2; j++) // loop through all cells
		{
			if (source instanceof desmoj.core.statistic.Histogram) {
				// Cell
				_histEntries[j][0] = Integer.toString(j);

				// Lower Limit
				String a = this.format(_showTimeSpansInReport, hist.getLowerLimit(j));
				String b = this.format(_showTimeSpansInReport, Double.POSITIVE_INFINITY);
				if(j+1 < _noOfCells+2) b = this.format(_showTimeSpansInReport, hist.getLowerLimit(j+1));
				if(j == 0) 	_histEntries[j][1] = "("+a+", "+b+")";
				else 		_histEntries[j][1] = "["+a+", "+b+")";
				//_histEntries[j][1] = Double.toString(hist.getLowerLimit(j));

				// n
				_histEntries[j][2] = Long
						.toString(hist.getObservationsInCell(j));

				// % rounded percentage

				// calculate the percentage with 4 digits after the decimal
				// point
				double perc = StatisticObject.round(100.0 * hist
						.getObservationsInCell(j) / hist
						.getObservations());

				cumPerc += perc; // update the accumulated percentage
				// to display the perc. round it to 2 digits after the decimal
				// point
				perc = StatisticObject.round(perc);

				_histEntries[j][3] = Double.toString(perc);

				// Cum. %

				// round the accumulated percentage
				double rdCumPerc = StatisticObject.round(cumPerc);

				_histEntries[j][4] = Double.toString(rdCumPerc);

				// check if the accumulated percentage has reached 100%
				// AND it is not the last cell
				if (rdCumPerc > 99.98 && j < (_noOfCells + 1)) {
					// flag if cells so far are empty
					boolean yetEmpty = true;
					// check if all the remaining cells are empty
					for (int k = j; k < _noOfCells + 2; k++) // loop thru
					// remaining cells
					{
						yetEmpty = (yetEmpty && (hist.getObservationsInCell(k) == 0));
					}

					tailIsEmpty = yetEmpty;
				}

				// |
				_histEntries[j][5] = "|";

				// Graph number of asterix's

				// if all remaining cells are empty
				if (tailIsEmpty) {
					_histEntries[j][6] = "the remaining cells are all empty";
					_noOfCells = j; // set the no. of cells to the actual value
					break; // the for-loop for all cells
				}

				// calculate the number of asterix's (one asterix per 2 percent)
				int ast = (int) (perc / 2.0);

				String lineOfAsterix = ""; // make an empty String

				// if percentage between zero and 2 percent
				if (hist.getObservationsInCell(j) > 0) {
					lineOfAsterix = "*"; // start with one asterix
				}

				for (int k = 0; k < ast; k++) // fill the String with
				// asterix's
				{
					lineOfAsterix = lineOfAsterix + "*";
				}

				_histEntries[j][6] = lineOfAsterix;
			} else {
				for (int i = 0; i < _histNumColumns; i++) {
					_histEntries[j][i] = "Invalid source!";
				} // end for
			} // end else
		} // end for

		return _histEntries;
	}

	/**
	 * Returns the number of columns of the histogram part (table) of this
	 * HistogramReporter.
	 *
	 * @return int : The number of columns of the histogram part (table) of this
	 *         HistogramReporter
	 */
	public int getHistNumColumns() {
		return _histNumColumns;
	}

	/**
	 * Returns the number of cells the interval of the given Histogram is
	 * devided into.
	 *
	 * @return int : The number of cells the interval of the given Histogram is
	 *         devided into.
	 */
	public int getNoOfCells() {
		return _noOfCells;
	}

	/**
	 * Returns the number of observations made by the Histogram object. This
	 * method call is passed on to the Histogram object.
	 *
	 * @return long : The number of observations made by the Histogram object.
	 */
	public long getObservations() {

		return source.getObservations(); // that's all
	}

	/*@TODO: Comment */
	public boolean isContinuingReporter() {
		return true;
	}

	private String format(boolean showTimeSpans, double value){
		String out = Double.toString(value);
		if(showTimeSpans && value < 0.0) 					out += " (Invalid)";
		else if(showTimeSpans && value >= Long.MAX_VALUE) 	out += " (Invalid)";
		else if(showTimeSpans) 								out = new TimeSpan(value).toString();
		return out;
	}
} // end class HistogramReporter


text:
<?php
/* Server MySQL data functions
******************/

function _checkStatus( $sro, $zip ) {

	$_server = get_option( 'tekserve_repair_status_server_setting' );
	$_login = get_option( 'tekserve_repair_status_server_login_setting' );
	$_pass = get_option( 'tekserve_repair_status_server_password_setting' );
	$_db = get_option( 'tekserve_repair_status_server_db_setting' );
	$_query = "SELECT * FROM status WHERE SROnumber='" . $sro . "' AND ZIP='" . $zip . "' LIMIT 1";
	$status_array = array();

	$mysqli = new mysqli( $_server, $_login, $_pass, $_db );

	if ($mysqli->connect_error) {

		$status_array['error'] = 'Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
		return $status_array['error'];

	}// end if ($mysqli->connect_error)

	if ( $result = $mysqli->query( $_query ) ) {

		$status_array = $result->fetch_assoc();
		$result->close();
		$mysqli->close();
		return $status_array;

	}// end if ($result = $mysqli->query( $_query ))

} // end function _checkStatus( $sronum, $zipcode )

function returnRepairStatus( $sro, $zip ) {

	$status = _checkStatus( $sro, $zip );
	$json = json_encode( $status );
	if( $status == null || $json == null ) {

		return false;

	}
	else {

		return $json;

	}// end if( $status == null || $json == null )

} // end function returnRepairStatus( $sro, $zip )

redpajama_set_name: RedPajamaGithub


text:
package nl.my888.resume.repository.people;

/**
 * Created by ejl on 31/05/15.
 */
public enum Nationality {

    DUTCH
}


text:
NSString* const kTDReplicatorDatabaseName = @"_replicator";

@interface TDReplicatorManager ()
- (BOOL) validateRevision: (TD_Revision*)newRev context: (id<TD_ValidationContext>)context;
- (void) processAllDocs;
@end

@implementation TDReplicatorManager

- (id) initWithDatabaseManager: (TD_DatabaseManager*)dbManager {
    self = [super init];
    if (self) {
        _dbManager = dbManager;
        _replicatorDB = [dbManager databaseNamed: kTDReplicatorDatabaseName];
        if (!_replicatorDB) {
            return nil;
        }
        Assert(_replicatorDB);
        _thread = [NSThread currentThread];
    }
    return self;
}

- (void)dealloc {
    [self stop];
}

- (void) start {
    [_replicatorDB defineValidation: @"TDReplicatorManager" asBlock:
         ^BOOL(TD_Revision *newRevision, id<TD_ValidationContext> context) {
             return [self validateRevision: newRevision context: context];
         }];
    [self processAllDocs];
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(dbChanged:)
                                                 name: TD_DatabaseChangeNotification
                                               object: _replicatorDB];
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(someDbDeleted:)
                                                 name: TD_DatabaseWillBeDeletedNotification
                                               object: nil];
#if TARGET_OS_IPHONE
    // Register for foreground/background transition notifications, on iOS:
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appForegrounding:)
                                                 name: UIApplicationWillEnterForegroundNotification
                                               object: nil];
#endif

}

- (void) stop {
    LogTo(TD_Server, @"STOP %@", self);
    [_replicatorDB defineValidation: @"TDReplicatorManager" asBlock: nil];
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    _replicatorsByDocID = nil;
}

- (NSString*) docIDForReplicator: (TDReplicator*)repl {
    return [[_replicatorsByDocID allKeysForObject: repl] lastObject];
}

#pragma mark - CRUD:

// Validation function for the _replicator database:
- (BOOL) validateRevision: (TD_Revision*)newRev context: (id<TD_ValidationContext>)context {
    // Ignore the change if it's one I'm making myself, or if it's a deletion:
    if (_updateInProgress || newRev.deleted)
        return YES;

    // First make sure the basic properties are valid:
    NSDictionary* newProperties = newRev.properties;
    LogTo(Sync, @"ReplicatorManager: Validating %@: %@", newRev, newProperties);
    if ([_dbManager validateReplicatorProperties: newProperties] >= 300) {
        context.errorMessage = @"Invalid replication parameters";
        return NO;
    }

    // Only certain keys can be changed or removed:
    NSSet* deletableProperties = [NSSet setWithObjects: @"_replication_state", nil];
    NSSet* mutableProperties = [NSSet setWithObjects: @"filter", @"query_params",
                                                      @"heartbeat", @"feed", @"reset", nil];
    NSSet* partialMutableProperties = [NSSet setWithObjects:@"target", @"source", nil];
    return [context enumerateChanges: ^BOOL(NSString *key, id oldValue, id newValue) {
        if (![context currentRevision])
            return ![key hasPrefix: @"_"];

        // allow change of 'headers' and 'auth' in target and source
        if ([partialMutableProperties containsObject:key]) {
            NSDictionary *old = $castIf(NSDictionary, oldValue);
            NSDictionary *nuu = $castIf(NSDictionary, newValue);
            if ([oldValue isKindOfClass:[NSString class]]) {
                old = @{@"url": oldValue};
            }
            if ([newValue isKindOfClass:[NSString class]]) {
                nuu = @{@"url": newValue};
            }
            NSMutableSet* changedKeys = [NSMutableSet set];
            for (NSString *subKey in old.allKeys) {
                if (!$equal(old[subKey], nuu[subKey])) {
                    [changedKeys addObject:subKey];
                }
            }
            for (NSString *subKey in nuu.allKeys) {
                if (!old[subKey]) {
                    [changedKeys addObject:subKey];
                }
            }
            NSSet* mutableSubProperties = [NSSet setWithObjects:@"headers", @"auth", nil];
            [changedKeys minusSet:mutableSubProperties];
            return [changedKeys count] == 0;
        }

        return [mutableProperties containsObject: key] ||
                (newValue == nil && [deletableProperties containsObject: key]);
    }];
}

// PUT a change to a replication document, retrying if there are conflicts:
- (TDStatus) updateDoc: (TD_Revision*)currentRev
        withProperties: (NSDictionary*)updates
{
    LogTo(Sync, @"ReplicatorManager: Updating %@ with %@", currentRev, updates);
    Assert(currentRev.revID);
    TDStatus status;
    do {
        // Create an updated revision by merging in the updates:
        NSDictionary* currentProperties = currentRev.properties;
        NSMutableDictionary* updatedProperties = [currentProperties mutableCopy];
        [updatedProperties addEntriesFromDictionary: updates];
        [updatedProperties removeObjectForKey: @"reset"];   // reset is one-shot, so take it out now

        if ($equal(updatedProperties, currentProperties)) {
            status = kTDStatusOK;     // this is a no-op change
            break;
        }
        TD_Revision* updatedRev = [TD_Revision revisionWithProperties: updatedProperties];

        // Attempt to PUT the updated revision:
        _updateInProgress = YES;
        @try {
            [_replicatorDB putRevision: updatedRev prevRevisionID: currentRev.revID
                         allowConflict: NO status: &status];
        } @finally {
            _updateInProgress = NO;
        }

        if (status == kTDStatusConflict) {
            // Conflict -- doc has been updated, get the latest revision & try again:
            TDStatus status2;
            currentRev = [_replicatorDB getDocumentWithID: currentRev.docID
                                               revisionID: nil options: 0
                                                   status: &status2];
            if (!currentRev)
                status = status2;
        }
    } while (status == kTDStatusConflict);

    if (TDStatusIsError(status))
        Warn(@"TDReplicatorManager: Error %d updating _replicator doc %@", status, currentRev);
    return status;
}

- (void) updateDoc: (TD_Revision*)rev forReplicator: (TDReplicator*)repl {
    NSString* state;
    if (repl.running)
        state = @"triggered";
    else if (repl.error)
        state = @"error";
    else
        state = @"completed";

    NSMutableDictionary* update = $mdict({@"_replication_id", repl.sessionID});
    if (!$equal(state, rev[@"_replication_state"])) {
        update[@"_replication_state"] = state;
        update[@"_replication_state_time"] = @(time(NULL));
    }
    [self updateDoc: rev withProperties: update];
}

// A replication document has been created, so create the matching TDReplicator:
- (void) processInsertion: (TD_Revision*)rev {
    if (_replicatorsByDocID[rev.docID])
        return;
    LogTo(Sync, @"ReplicatorManager: %@ was created", rev);
    NSDictionary* properties = rev.properties;
    TDReplicator* repl = [_dbManager replicatorWithProperties: properties status: NULL];
    if (!repl) {
        Warn(@"TDReplicatorManager: Can't create replicator for %@", properties);
        return;
    }
    NSString* replicationID = properties[@"_replication_id"] ?: TDCreateUUID();
    repl.sessionID = replicationID;

    if (!_replicatorsByDocID)
        _replicatorsByDocID = [[NSMutableDictionary alloc] init];
    _replicatorsByDocID[rev.docID] = repl;

    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(replicatorChanged:)
                                                 name: nil
                                               object: repl];

    [repl start];
    [self updateDoc: rev forReplicator: repl];
}

// A replication document has been changed:
- (void) processUpdate: (TD_Revision*)rev {
    if (!rev[@"_replication_state"]) {
        // Client deleted the _replication_state property; restart the replicator:
        LogTo(Sync, @"ReplicatorManager: Restarting replicator for %@", rev);
        TDReplicator* repl = _replicatorsByDocID[rev.docID];
        if (repl) {
            [repl.db stopAndForgetReplicator: repl];
            [_replicatorsByDocID removeObjectForKey: rev.docID];
        }
        [self processInsertion: rev];
    }
}

// A replication document has been deleted:
- (void) processDeletion: (TD_Revision*)rev ofReplicator: (TDReplicator*)repl {
    LogTo(Sync, @"ReplicatorManager: %@ was deleted", rev);
    [_replicatorsByDocID removeObjectForKey: rev.docID];
    [repl stop];
}

#pragma mark - NOTIFICATIONS:

- (void) processRevision: (TD_Revision*)rev {
    if (rev.generation == 1)
        [self processInsertion: rev];
    else
        [self processUpdate: rev];
}

// Create TDReplications for all documents at startup:
- (void) processAllDocs {
    if (!_replicatorDB.exists)
        return;
    [_replicatorDB open];
    LogTo(Sync, @"ReplicatorManager scanning existing _replicator docs...");
    TDQueryOptions options = kDefaultTDQueryOptions;
    options.includeDocs = YES;
    NSArray* allDocs = [_replicatorDB getAllDocs: &options][@"rows"];
    for (NSDictionary* row in allDocs) {
        NSDictionary* docProps = row[@"doc"];
        NSString* state = docProps[@"_replication_state"];
        if (state==nil || $equal(state, @"triggered") ||
                    [docProps[@"continuous"] boolValue]) {
            [self processInsertion: [TD_Revision revisionWithProperties: docProps]];
        }
    }
    LogTo(Sync, @"ReplicatorManager done scanning.");
}

- (void) appForegrounding: (NSNotification*)n {
    // Danger: This is called on the main thread!
    MYOnThread(_thread, ^{
        LogTo(Sync, @"App activated -- restarting all replications");
        [self processAllDocs];
    });
}

// Notified that a _replicator database document has been created/updated/deleted:
- (void) dbChanged: (NSNotification*)n {
    if (_updateInProgress)
        return;
    TD_Revision* rev = (n.userInfo)[@"rev"];
    LogTo(SyncVerbose, @"ReplicatorManager: %@ %@", n.name, rev);
    NSString* docID = rev.docID;
    if ([docID hasPrefix: @"_"])
        return;
    if (rev.deleted) {
        TDReplicator* repl = _replicatorsByDocID[docID];
        if (repl)
            [self processDeletion: rev ofReplicator: repl];
    } else {
        if ([_replicatorDB loadRevisionBody: rev options: 0])
            [self processRevision: rev];
        else
            Warn(@"Unable to load body of %@", rev);
    }
}

// Notified that a TDReplicator has changed status or stopped:
- (void) replicatorChanged: (NSNotification*)n {
    TDReplicator* repl = n.object;
    LogTo(SyncVerbose, @"ReplicatorManager: %@ %@", n.name, repl);
    NSString* docID = [self docIDForReplicator: repl];
    if (!docID)
        return;  // If it's not a persistent replicator
    TD_Revision* rev = [_replicatorDB getDocumentWithID: docID revisionID: nil];

    [self updateDoc: rev forReplicator: repl];

    if ($equal(n.name, TDReplicatorStoppedNotification)) {
        // Replicator has stopped:
        [[NSNotificationCenter defaultCenter] removeObserver: self name: nil object: repl];
        [_replicatorsByDocID removeObjectForKey: docID];
    }
}

// Notified that some database is being deleted; delete any associated replication document:
- (void) someDbDeleted: (NSNotification*)n {
    if (!_replicatorDB.exists)
        return;
    TD_Database* db = n.object;
    if ([_dbManager.allOpenDatabases indexOfObjectIdenticalTo: db] == NSNotFound)
        return;
    NSString* dbName = db.name;

    TDQueryOptions options = kDefaultTDQueryOptions;
    options.includeDocs = YES;
    NSArray* allDocs = [_replicatorDB getAllDocs: &options][@"rows"];
    for (NSDictionary* row in allDocs) {
        NSDictionary* docProps = row[@"doc"];
        NSString* source = $castIf(NSString, docProps[@"source"]);
        NSString* target = $castIf(NSString, docProps[@"target"]);
        if ([source isEqualToString: dbName] || [target isEqualToString: dbName]) {
            // Replication doc involves this database -- delete it:
            LogTo(Sync, @"ReplicatorManager deleting replication %@", docProps);
            TD_Revision* delRev = [[TD_Revision alloc] initWithDocID: docProps[@"_id"]
                                                             revID: nil deleted: YES];
            TDStatus status;
            if (![_replicatorDB putRevision: delRev
                             prevRevisionID: docProps[@"_rev"]
                              allowConflict: NO status: &status]) {
                Warn(@"TDReplicatorManager: Couldn't delete replication doc %@", docProps);
            }
        }
    }
}

@end


text:
__author__ = 'Willian'
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())

class Receita(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    nome = models.CharField(max_length=100, blank=True, default='')
    estrelas = models.IntegerField(blank=True, default=1)
    tempo = models.CharField(max_length=100, blank=True, default='')
    rendimento = models.CharField(max_length=100, blank=True, default='')
    ingredientes = models.CharField(max_length=100, blank=True, default='')
    autor = models.CharField(max_length=100, blank=True, default='')
    preparo = models.CharField(max_length=100, blank=True, default='')

    class Meta:
        ordering = ('created',)


text:
//
//   Copyright 2018  SenX S.A.S.
//
//   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 io.warp10.script;

import io.warp10.script.WarpScriptStack.Macro;
import io.warp10.script.functions.SNAPSHOT.Snapshotable;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import org.apache.commons.io.output.ByteArrayOutputStream;

/**
 * Class containing various methods related to macros.
 */
public class MacroHelper {

  private static final class MacroWrapper extends NamedWarpScriptFunction implements WarpScriptStackFunction, Snapshotable {

    private final Macro macro;

    public MacroWrapper(String name, Macro macro) {
      super(name);
      this.macro = macro;
    }

    @Override
    public Object apply(WarpScriptStack stack) throws WarpScriptException {
      stack.exec(this.macro);
      return stack;
    }

    @Override
    public String toString() {
      if (null != getName()) {
        return super.toString();
      } else {
        return this.macro.toString() + " " + WarpScriptLib.EVAL;
      }
    }

    @Override
    public String snapshot() {
      if (macro instanceof Snapshotable) {
        return macro.snapshot();
      } else {
        return this.toString();
      }
    }
  }

  public static WarpScriptStackFunction wrap(String name, String mc2, boolean secure) {

    if (mc2.startsWith("@")) {
      return wrap(name, getResource(mc2.substring(1)), secure);
    }

    MemoryWarpScriptStack stack = new MemoryWarpScriptStack(null, null);
    stack.maxLimits();

    try {
      stack.execMulti(mc2);
    } catch (WarpScriptException wse) {
      throw new RuntimeException(wse);
    }

    Object top = stack.pop();

    if (!(top instanceof Macro)) {
      throw new RuntimeException("WarpScript code did not leave a macro on top of the stack.");
    }

    ((Macro) top).setSecure(secure);

    return new MacroWrapper(name, (Macro) top);
  }

  public static WarpScriptStackFunction wrap(String mc2, boolean secure) {
    return wrap(null, mc2, secure);
  }

  public static WarpScriptStackFunction wrap(String mc2) {
    return wrap(null, mc2, false);
  }

  public static WarpScriptStackFunction wrap(String name, String mc2) {
    return wrap(name, mc2, false);
  }

  public static WarpScriptStackFunction wrap(String name, InputStream in, boolean secure) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];

    try {
      while(true) {
        int len = in.read(buf);

        if (len < 0) {
          break;
        }

        baos.write(buf, 0, len);
      }

      in.close();

      String mc2 = new String(baos.toByteArray(), StandardCharsets.UTF_8);

      return wrap(name, mc2, secure);
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }

  public static WarpScriptStackFunction wrap(InputStream in, boolean secure) {
    return wrap(null, in, secure);
  }

  public static WarpScriptStackFunction wrap(InputStream in) {
    return wrap(null, in, false);
  }

  public static WarpScriptStackFunction wrap(String name, InputStream in) {
    return wrap(name, in, false);
  }

  private static InputStream getResource(String path) {
    InputStream in = MacroHelper.class.getResourceAsStream(path.startsWith("/") ? path : "/" + path);
    if (null == in) {
      throw new RuntimeException("Resource " + path + " was not found.");
    }
    return in;
  }
}


text:
@interface WebViewController ()<UIWebViewDelegate>
//@property (strong, nonatomic) UIWebView *myWebView;
@property (strong, nonatomic) NJKWebViewProgress *progressProxy;
@property (strong, nonatomic) NJKWebViewProgressView *progressView;
@end

@implementation WebViewController

+ (instancetype)webVCWithUrlStr:(NSString *)curUrlStr{
    if (!curUrlStr || curUrlStr.length <= 0) {
        return nil;
    }

    NSString *proName = [NSString stringWithFormat:@"/%@.app/", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]];
    NSURL *curUrl;
    if (![curUrlStr hasPrefix:@"/"] || [curUrlStr rangeOfString:proName].location != NSNotFound) {
        curUrl = [NSURL URLWithString:curUrlStr];
    }else{
        curUrl = [NSURL URLWithString:curUrlStr relativeToURL:[NSURL URLWithString:kNetPath_Code_Base]];
    }

    if (!curUrl) {
        return nil;
    }else{
        return [[self alloc] initWithURL:curUrl];
    }
}

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

}

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"加载中...";

    _progressProxy = [[NJKWebViewProgress alloc] init];
    self.delegate = _progressProxy;
    @weakify(self);
    _progressProxy.progressBlock = ^(float progress) {
        @strongify(self);
        [self.progressView setProgress:progress animated:NO];
    };

    CGFloat progressBarHeight = 2.f;
    CGRect navigaitonBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigaitonBarBounds.size.height - progressBarHeight, navigaitonBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _progressView.progressBarView.backgroundColor = [UIColor colorWithHexString:@"0x3abd79"];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:_progressView];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_progressView removeFromSuperview];
}

#pragma mark UIWebViewDelegate 覆盖

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    BOOL shouldStart = ![self canAndGoOutWithLinkStr:request.URL.absoluteString];

    if (shouldStart && [self.delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
        shouldStart = [self.delegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }

    return shouldStart;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateToolbarItems];

    if ([self.delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
        [self.delegate webView:webView didFailLoadWithError:error];
    }

    if (error) {
        [self handleError:error];
    }
}
#pragma mark VC
- (BOOL)canAndGoOutWithLinkStr:(NSString *)linkStr{
    BOOL canGoOut = NO;
    UIViewController *vc = [BaseViewController analyseVCFromLinkStr:linkStr];
    if (vc) {
        canGoOut = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    return canGoOut;
}

#pragma mark Error
- (void)handleError:(NSError *)error{
    NSString *urlString = error.userInfo[NSURLErrorFailingURLStringErrorKey];

    if (([error.domain isEqualToString:@"WebKitErrorDomain"] && 101 == error.code) ||
        ([error.domain isEqualToString:NSURLErrorDomain] && (NSURLErrorBadURL == error.code || NSURLErrorUnsupportedURL == error.code))) {
        kTipAlert(@"网址无效:\n%@", urlString);
    }else if ([error.domain isEqualToString:NSURLErrorDomain] && (NSURLErrorTimedOut == error.code ||
                                                                  NSURLErrorCannotFindHost == error.code ||
                                                                  NSURLErrorCannotConnectToHost == error.code ||
                                                                  NSURLErrorNetworkConnectionLost == error.code ||
                                                                  NSURLErrorDNSLookupFailed == error.code ||
                                                                  NSURLErrorNotConnectedToInternet == error.code)) {
        kTipAlert(@"网络连接异常:\n%@", urlString);
    }else if ([error.domain isEqualToString:@"WebKitErrorDomain"] && 102 == error.code){
        NSURL *url = [NSURL URLWithString:urlString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }else{
            kTipAlert(@"无法打开连接:\n%@", urlString);
        }
    }else if (error.code == -999){
        //加载中断
    }else{
        kTipAlert(@"%@\n%@", urlString, [error.userInfo objectForKey:@"NSLocalizedDescription"]? [error.userInfo objectForKey:@"NSLocalizedDescription"]: error.description);
    }
}

@end


text: Simple app login


text:
var TestController = require("montage-testing/test-controller").TestController;

exports.Test = TestController.specialize({
    constructor: {
        value: function flow() {
            this.super();
        }
    }
});


text:
(function(win) {

    let _EListener = win.EventListener = function() {

    }

    _EListener.prototype.init = function() {
        new Error("this class ")
    }

})(window);


text:
//*********** IMPORTS *****************//
var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    cssBase64 = require('gulp-css-base64'),
    gutil = require('gulp-util'),
    rename = require("gulp-rename"),
    map = require("map-stream"),
    uglify = require('gulp-uglify'),
    watch = require('gulp-watch'),
    gulpIgnore = require('gulp-ignore'),
    gulpCopy = require('gulp-copy'),
    autoprefixer = require('gulp-autoprefixer'),
    sourcemaps = require('gulp-sourcemaps'),
    add = require('gulp-add'),
    open = require('gulp-open'),
    del = require('del'),
    webpack = require("webpack"),
    WebpackDevServer = require("webpack-dev-server"),
    webpackConfig = require("./webpack.config.js"),
    stream = require('webpack-stream');

var env = process.env.NODE_ENV || 'development',
    gConfig = require("./config/gulpConfig_" + env);

global.errorMessage = '';

//build datestamp for cache busting
var getStamp = function() {
    var stampDate = new Date();
    var stampYear = stampDate.getFullYear().toString();
    var stampMonth = ('0' + (stampDate.getMonth() + 1)).slice(-2);
    var stampDay = ('0' + stampDate.getDate()).slice(-2);
    var stampSeconds = stampDate.getSeconds().toString();
    var stampFullDate = stampYear + stampMonth + stampDay + stampSeconds;
    return stampFullDate;
};

var filePaths = {
    src: 'public/src',
    nodeModules: 'node_modules/',
    js: ['scripts/**/*.js', '!scripts/libs/**/*.js'],
    libs: ['public/src/js/lib/**/*.js'],
    libsTarget: 'public/js/lib/',
    styles: ['styles/**/*.css'],
    views: "public/src/views/layouts/index.html",
    viewsTarget: "public/dist/",
    images: "public/src/images/**/**",
    imagesTarget: "public/dist/images/",
    fonts: "public/src/fonts/**/**",
    fontsTarget: "public/dist/fonts/",
    extras: ['crossdomain.xml', 'humans.txt', 'manifest.appcache', 'robots.txt', 'favicon.ico']
};

var sassConfig = [{
    watch: 'public/scss/**/*.scss',
    paths: ['public/src/scss/app-main.scss', 'public/src/scss/webfonts/**.scss'],
    output: 'public/css/',
    name: 'app-main.css',
    excludedFiles: 'public/src/css/webfonts/**.scss',
    compileOptions: {
        'style': 'expanded', // expanded compressed
        'unixNewlines': true,
        'cacheLocation': './.sass_cache',
        'sourcemap': true
    }
}];

gulp.task('clean', function() {
    return del([filePaths.nodeModules]);
});

gulp.task("copysource", function() {
    gulp.src(filePaths.images)
        .pipe(gulp.dest(filePaths.imagesTarget));
    gulp.src(filePaths.fonts)
        .pipe(gulp.dest(filePaths.fontsTarget));
})

gulp.task('sass', function() {
    return sass(sassConfig[0].paths[0], sassConfig[0].compileOptions)
        .on('error', sass.logError)
        .pipe(sourcemaps.write())
        .pipe(cssBase64({
            baseDir: "./public",
            maxWeightResource: 1000000
        }))
        .pipe(gulp.dest(sassConfig[0].output))
});

/*****Webpack task configuartion*****/

var path = {
    HTML: 'src/index.html',
    ALL: ['public/src/js/**/*.jsx', 'public/src/js/**/*.js'],
    MINIFIED_OUT: 'build.min.js',
    DEST_SRC: 'dist/src',
    DEST_BUILD: 'public/dist/js',
    DEST: 'dist'
};
gulp.task('webpack', [], function() {
    return gulp.src(path.ALL) // gulp looks for all source files under specified path
        .pipe(sourcemaps.init()) // creates a source map which would be very helpful for debugging by maintaining the actual source code structure
        .pipe(stream(webpackConfig)) // blend in the webpack config into the source files
        .pipe(uglify()) // minifies the code for better compression
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.DEST_BUILD));
});

gulp.task("webpack-dev-server", function(callback) {
    // modify some webpack config options
    var myConfig = Object.create(webpackConfig);
    myConfig.devtool = "eval";
    myConfig.debug = true;
    // Start a webpack-dev-server
    new WebpackDevServer(webpack(myConfig), {
        publicPath: "/" + myConfig.output.publicPath,
        stats: {
            colors: true
        }
    }).listen(8080, "localhost", function(err) {
        if (err) throw new gutil.PluginError("webpack-dev-server", err);
        gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html");
    });
});

gulp.task("build", ["copysource", "sass"]);
gulp.task("default", ["copysource", "sass"]);


text:
<!doctype html>
<title>Referrer Policy: iframes with javascript url reuse referrer policy</title>

<meta name="referrer" content="unsafe-url">


text:
package com.limemobile.app.blog.activity;

import java.io.File;
import java.io.IOException;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.limemobile.app.blog.R;
import com.limemobile.app.blog.activity.fragment.TabSelfInfoFragment;
import com.limemobile.app.blog.activity.fragment.TweetListFragment;
import com.limemobile.app.blog.activity.theme.Theme;
import com.limemobile.app.blog.constant.ITransKey;
import com.limemobile.app.blog.weibo.TencentWeibo;
import com.limemobile.app.blog.weibo.tencent.api.ILoadListener;
import com.limemobile.app.blog.weibo.tencent.api.IResultListener;
import com.limemobile.app.blog.weibo.tencent.api.friends.AddBlackListTask;
import com.limemobile.app.blog.weibo.tencent.api.friends.AddTask;
import com.limemobile.app.blog.weibo.tencent.api.friends.DelTask;
import com.limemobile.app.blog.weibo.tencent.api.user.OtherInfoTask;
import com.limemobile.app.blog.weibo.tencent.entity.Entity;
import com.limemobile.app.blog.weibo.tencent.entity.TObject;
import com.limemobile.app.blog.weibo.tencent.entity.user.Info;
import com.limemobile.app.blog.widget.LinkView;
import com.limemobile.app.utils.NetUtils;
import com.limemobile.app.utils.StringUtils;
import com.limemobile.app.utils.ToastUtils;
import com.limemobile.app.utils.UserTask;

import edu.mit.mobile.android.imagecache.ImageCache.OnImageLoadListener;

public class UserInfoActivity extends ThemeActivity implements OnClickListener {

    private ViewGroup mainContainer;
    private View titleBar;
    private TextView title;
    private ImageView back;
    private ImageView home;
    private View headContainer;
    private ImageView head;
    private View vipContainer;
    private TextView vip;
    private TextView nick;
    private TextView name;
    private ImageView sex;
    private View descriptionContainer;
    private TextView description;
    private View addressContainer;
    private TextView address;
    private View followContainer;
    private TextView follow;
    private View fansContainer;
    private TextView fans;
    private View tweetContainer;
    private TextView tweet;
    private View favoriteContainer;
    private TextView favorite;
    private TextView level;
    private TextView action;
    private ImageView constellation;
    private TextView refresh;
    private TextView atHe;
    private TextView privateLetter;
    private TextView add2BlackList;

    private Info userInfo;
    private String openId;
    private String userName;
    private long imageID = 0;

    private OnImageLoadListener headLoadListener;

    private UserTask<Object, Void, Boolean> refreshTask;
    private UserTask<Object, Void, Boolean> addTask;
    private UserTask<Object, Void, Boolean> delTask;
    private UserTask<Object, Void, Boolean> blacklistTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent != null) {
            userName = intent.getStringExtra(ITransKey.KEY);
            openId = intent.getStringExtra(ITransKey.KEY1);
        }
        if (TextUtils.isEmpty(openId) && TextUtils.isEmpty(userName)) {
            finish();
            return;
        }
        if (TextUtils.isEmpty(userName))
            userName = "";
        if (TextUtils.isEmpty(openId))
            openId = "";
        setContentView(R.layout.activity_userinfo);
        initViews();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (headLoadListener != null) {
            MyApplication.imageCache.unregisterOnImageLoadListener(headLoadListener);
            headLoadListener = null;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (isFinishing()) {
            final UserTask<Object, Void, Boolean> task = refreshTask;
            if (task != null && task.getStatus() != UserTask.Status.FINISHED) {
                task.cancel(true);
                refreshTask = null;
            }

            final UserTask<Object, Void, Boolean> task2 = addTask;
            if (task2 != null && task2.getStatus() != UserTask.Status.FINISHED) {
                task2.cancel(true);
                addTask = null;
            }

            final UserTask<Object, Void, Boolean> task3 = delTask;
            if (task3 != null && task3.getStatus() != UserTask.Status.FINISHED) {
                task3.cancel(true);
                delTask = null;
            }

            final UserTask<Object, Void, Boolean> task4 = blacklistTask;
            if (task4 != null && task4.getStatus() != UserTask.Status.FINISHED) {
                task4.cancel(true);
                blacklistTask = null;
            }
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        updateViews();
        super.onResume();
    }

    private void refresh() {
    	if (NetUtils.getType(this) == NetUtils.NO_NET) {
    		ToastUtils.show(this, R.string.msg_nonetwork, Toast.LENGTH_SHORT);
    		return;
    	}
        final UserTask<Object, Void, Boolean> task = refreshTask;
        if (task != null && task.getStatus() != UserTask.Status.FINISHED) {
            return;
        }
        refreshTask = new OtherInfoTask(mainContainer, loadListener, resultListener).execute(userName, openId);
    }

    @Override
    public void themeChanged() {
        titleBar.setBackgroundResource(R.drawable.title_bar_bg);

        Resources res = Theme.getInstance().getContext(this).getResources();

        title.setText(res.getString(R.string.title_other_user_info));
        title.setTextColor(res.getColor(R.color.tab_text_color));
        float titleTextSize = res.getDimension(R.dimen.title_text_size)
                / res.getDisplayMetrics().density;
        title.setTextSize(titleTextSize);

        back.setImageDrawable(res.getDrawable(R.drawable.title_back));
        home.setImageDrawable(res.getDrawable(R.drawable.title_home));

        headContainer.setBackgroundDrawable(res.getDrawable(R.drawable.portrait_bg));

        vipContainer.setBackgroundDrawable(res.getDrawable(R.drawable.circle_list_top));
        descriptionContainer.setBackgroundDrawable(res.getDrawable(R.drawable.circle_list_bottom));
        addressContainer.setBackgroundDrawable(res.getDrawable(R.drawable.circle_list_middle));

        followContainer.setBackgroundDrawable(res.getDrawable(R.drawable.bg_panel_above_left));
        fansContainer.setBackgroundDrawable(res.getDrawable(R.drawable.bg_panel_above_right));
        favoriteContainer.setBackgroundDrawable(res.getDrawable(R.drawable.bg_panel_below_left));
        tweetContainer.setBackgroundDrawable(res.getDrawable(R.drawable.bg_panel_below_right));

        refresh.setBackgroundDrawable(res.getDrawable(R.drawable.toolbar_bg_left));
        refresh.setCompoundDrawablesWithIntrinsicBounds(null,
                res.getDrawable(R.drawable.toolbar_refresh_icon), null, null);
        atHe.setBackgroundDrawable(res.getDrawable(R.drawable.toolbar_bg_middle));
        atHe.setCompoundDrawablesWithIntrinsicBounds(null,
                res.getDrawable(R.drawable.toolbar_at_icon), null, null);
        privateLetter.setBackgroundDrawable(res.getDrawable(R.drawable.toolbar_bg_middle));
        privateLetter.setCompoundDrawablesWithIntrinsicBounds(null,
                res.getDrawable(R.drawable.toolbar_letter_icon), null, null);
        add2BlackList.setBackgroundDrawable(res.getDrawable(R.drawable.toolbar_bg_right));
        add2BlackList.setCompoundDrawablesWithIntrinsicBounds(null,
                res.getDrawable(R.drawable.toolbar_blacklist_icon), null, null);
    }

    @Override
    public void initViews() {
        mainContainer = (ViewGroup) findViewById(R.id.sub_container);
        titleBar = findViewById(R.id.main_titlebar);
        title = (TextView) findViewById(R.id.title);
        back = (ImageView) findViewById(R.id.back);
        home = (ImageView) findViewById(R.id.home);
        back.setOnClickListener(this);
        home.setOnClickListener(this);

        headContainer = findViewById(R.id.user_info_head_container);
        head = (ImageView) findViewById(R.id.user_info_head);
        vipContainer = findViewById(R.id.user_info_vip_container);
        vip = (TextView) findViewById(R.id.user_info_vip);
        descriptionContainer = findViewById(R.id.user_info_description_container);
        description = (TextView) findViewById(R.id.user_info_description);
        nick = (TextView) findViewById(R.id.user_info_nick);
        name = (TextView) findViewById(R.id.user_info_name);
        sex = (ImageView) findViewById(R.id.user_info_sex);
        addressContainer = findViewById(R.id.user_info_address_container);
        address = (TextView) findViewById(R.id.user_info_address);
        followContainer = findViewById(R.id.user_info_follow_container);
        followContainer.setOnClickListener(this);
        follow = (TextView) findViewById(R.id.user_info_follow);
        fansContainer = findViewById(R.id.user_info_fans_container);
        fansContainer.setOnClickListener(this);
        fans = (TextView) findViewById(R.id.user_info_fans);
        tweetContainer = findViewById(R.id.user_info_tweet_container);
        tweetContainer.setOnClickListener(this);
        tweet = (TextView) findViewById(R.id.user_info_tweet);
        favoriteContainer = findViewById(R.id.user_info_favorite_container);
        favoriteContainer.setOnClickListener(this);
        favorite = (TextView) findViewById(R.id.user_info_favorite);
        level = (TextView) findViewById(R.id.user_info_level);
        action = (TextView) findViewById(R.id.item_action);
        action.setOnClickListener(this);
        constellation = (ImageView) findViewById(R.id.user_info_constellation);

        refresh = (TextView) findViewById(R.id.toolbar_refresh);
        refresh.setOnClickListener(this);
        atHe = (TextView) findViewById(R.id.toolbar_at);
        atHe.setOnClickListener(this);
        privateLetter = (TextView) findViewById(R.id.toolbar_privateletter);
        privateLetter.setOnClickListener(this);
        add2BlackList = (TextView) findViewById(R.id.toolbar_blacklist);
        add2BlackList.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.home:
                Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                intent.putExtra(ITransKey.KEY, 0);
                startActivity(intent);
                break;
            case R.id.toolbar_at:
                break;
            case R.id.toolbar_privateletter:
                break;
            case R.id.toolbar_blacklist:
            	if (NetUtils.getType(this) == NetUtils.NO_NET) {
            		ToastUtils.show(this, R.string.msg_nonetwork, Toast.LENGTH_SHORT);
            		return;
            	}
                final UserTask<Object, Void, Boolean> task = blacklistTask;
                if (task != null && task.getStatus() != UserTask.Status.FINISHED) {
                    return;
                }
            	blacklistTask = new AddBlackListTask(mainContainer, loadListener, new IResultListener() {

                    @Override
                    public void onSuccess(Entity<TObject> data) {
                        mainContainer.post(new Runnable() {

                            @Override
                            public void run() {
                                ToastUtils.show(mainContainer.getContext(),
                                        R.string.ok_to_add_to_blacklist, Toast.LENGTH_SHORT);
                            }

                        });
                    }

                    @Override
                    public void onFail(Entity<TObject> data) {
                        mainContainer.post(new Runnable() {

                            @Override
                            public void run() {
                                ToastUtils.show(mainContainer.getContext(),
                                        R.string.fail_to_add_to_blacklist, Toast.LENGTH_SHORT);
                            }

                        });
                    }

                }).execute(userName, openId);
                break;
            case R.id.toolbar_refresh:
            case R.id.refresh:
                refresh();
                break;
            case R.id.item_action:
            	if (NetUtils.getType(this) == NetUtils.NO_NET) {
            		ToastUtils.show(this, R.string.msg_nonetwork, Toast.LENGTH_SHORT);
            		return;
            	}
                if (userInfo != null) {
                    if (userInfo.ismyidol > 0) {
                        final UserTask<Object, Void, Boolean> task1 = delTask;
                        if (task1 != null && task1.getStatus() != UserTask.Status.FINISHED) {
                            return;
                        }
                    	delTask = new DelTask(mainContainer, loadListener, new IResultListener() {

                            @Override
                            public void onSuccess(Entity<TObject> data) {
                                mainContainer.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        userInfo.ismyidol = 0;
                                        updateViews();
                                        ToastUtils.show(mainContainer.getContext(),
                                                R.string.del_attention_ok, Toast.LENGTH_SHORT);
                                    }

                                });
                            }

                            @Override
                            public void onFail(Entity<TObject> data) {
                                mainContainer.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        ToastUtils.show(mainContainer.getContext(),
                                                R.string.del_attention_failed, Toast.LENGTH_SHORT);
                                    }

                                });
                            }

                        }).execute(userInfo.name, "");
                    } else {
                        final UserTask<Object, Void, Boolean> task1 = addTask;
                        if (task1 != null && task1.getStatus() != UserTask.Status.FINISHED) {
                            return;
                        }
                    	addTask = new AddTask(mainContainer, loadListener, new IResultListener() {

                            @Override
                            public void onSuccess(Entity<TObject> data) {
                                mainContainer.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        userInfo.ismyidol = 1;
                                        updateViews();
                                        ToastUtils.show(mainContainer.getContext(),
                                                R.string.add_attention_ok, Toast.LENGTH_SHORT);
                                    }

                                });
                            }

                            @Override
                            public void onFail(Entity<TObject> data) {
                                mainContainer.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        ToastUtils.show(mainContainer.getContext(),
                                                R.string.add_attention_failed, Toast.LENGTH_SHORT);
                                    }

                                });
                            }

                        }).execute(userInfo.name, "");
                    }
                }
                break;
            case R.id.user_info_follow_container:
                if (userInfo != null) {
                    intent = new Intent(this, UsersListActivity.class);
                    intent.putExtra(ITransKey.KEY, userInfo.name);
                    intent.putExtra(ITransKey.KEY1, userInfo.openid);
                    intent.putExtra(ITransKey.KEY2,
                            UsersListActivity.UserListType.IdolList.getNumericType());
                    intent.putExtra(ITransKey.KEY3, userInfo.sex);
                    startActivity(intent);
                }
                break;
            case R.id.user_info_fans_container:
                if (userInfo != null) {
                    intent = new Intent(this, UsersListActivity.class);
                    intent.putExtra(ITransKey.KEY, userInfo.name);
                    intent.putExtra(ITransKey.KEY1, userInfo.openid);
                    intent.putExtra(ITransKey.KEY2,
                            UsersListActivity.UserListType.FansList.getNumericType());
                    intent.putExtra(ITransKey.KEY3, userInfo.sex);
                    startActivity(intent);
                }
                break;
            case R.id.user_info_tweet_container:
                if (userInfo != null) {
                    String titleText = getString(R.string.he_tweet_label);
                    if (userInfo.sex == 2)
                        titleText = getString(R.string.she_tweet_label);
                    intent = new Intent(this, TweetListActivity.class);
                    Bundle extras = new Bundle();
                    extras.putInt(ITransKey.KEY, TweetListFragment.TweetType.UserTweet.getNumericType());
                    extras.putString(ITransKey.KEY1, userInfo.name);
                    extras.putString(ITransKey.KEY2, userInfo.openid);
                    intent.putExtras(extras);
                    intent.putExtra(ITransKey.KEY5, titleText);
                    startActivity(intent);
                }
                break;
            case R.id.user_info_favorite_container:
                if (userInfo != null) {
                    String titleText = getString(R.string.he_favorites_label);
                    if (userInfo.sex == 2)
                        titleText = getString(R.string.she_favorites_label);
                    intent = new Intent(this, TweetListActivity.class);
                    Bundle extras = new Bundle();
                    extras.putInt(ITransKey.KEY, TweetListFragment.TweetType.UserFavoriteTweet.getNumericType());
                    extras.putString(ITransKey.KEY1, userInfo.name);
                    extras.putString(ITransKey.KEY2, userInfo.openid);
                    intent.putExtras(extras);
                    intent.putExtra(ITransKey.KEY5, titleText);
                    startActivity(intent);
                }
                break;
        }
    }

    private void updateViews() {
        if (userInfo != null) {
            Resources res = Theme.getInstance().getContext(this).getResources();
            if (!TextUtils.isEmpty(userInfo.name))
                ((LinkView)name).setLinkText("@" + userInfo.name);
            if (!TextUtils.isEmpty(userInfo.nick))
                nick.setText(userInfo.nick);

            if (!TextUtils.isEmpty(userInfo.location))
                address.setText(userInfo.location);

            follow.setText(StringUtils.friendly_long(this, userInfo.idolnum));
            fans.setText(StringUtils.friendly_long(this, userInfo.fansnum));
            tweet.setText(StringUtils.friendly_long(this, userInfo.tweetnum));
            level.setText(res.getString(R.string.user_info_level) + Long.toString(userInfo.level));
            favorite.setText(StringUtils.friendly_long(this, userInfo.favnum));

            if (userInfo.birth_year > 0)
                constellation.setImageResource(TabSelfInfoFragment
                        .correspondConstellation(userInfo));
            else
                constellation.setVisibility(View.GONE);

            if (!TextUtils.isEmpty(userInfo.introduction))
                description.setText(userInfo.introduction);
            else
                description.setText(R.string.nothing_left);

            if (userInfo.isvip == 1) {
                vipContainer.setVisibility(View.VISIBLE);
                vip.setText(userInfo.verifyinfo);
                addressContainer.setBackgroundDrawable(res
                        .getDrawable(R.drawable.circle_list_middle));
            } else {
                vipContainer.setVisibility(View.GONE);
                addressContainer.setBackgroundDrawable(res.getDrawable(R.drawable.circle_list_top));
            }

            if (userInfo.ismyidol > 0) {
                action.setBackgroundDrawable(res.getDrawable(R.drawable.btn_orange));
                action.setText(res.getString(R.string.user_delattention));
            } else {
                action.setBackgroundDrawable(res.getDrawable(R.drawable.btn_green));
                if (userInfo.sex == 0)
                    action.setText(res.getString(R.string.attention));
                else if (userInfo.sex == 2)
                    action.setText(res.getString(R.string.attend_to_her));
                else
                    action.setText(res.getString(R.string.attend_to_him));
            }

            // 用户性别,1-男,2-女,0-未填写,
            if (userInfo.sex == 0)
                sex.setVisibility(View.INVISIBLE);
            else
                sex.setImageResource(userInfo.sex == 1 ? R.drawable.icon_male
                        : R.drawable.icon_female);

            if (!TextUtils.isEmpty(userInfo.head)) {
                imageID = MyApplication.imageCache.getNewID();
                if (headLoadListener == null) {
                    headLoadListener = new OnImageLoadListener() {

                        @Override
                        public void onImageLoaded(long id, Uri imageUri, Drawable image) {
                            Uri uri = null;
                            if (userInfo.head.startsWith("http")) {
                                uri = Uri.parse(userInfo.head + TencentWeibo.HEAD_LARGE_SIZE);
                            }
                            else {
                                File file = new File(userInfo.head);
                                uri = Uri.fromFile(file);
                            }
                            if (userInfo != null && id == imageID
                                    && imageUri.toString().equals(uri.toString()) && image != null) {
                                head.setImageDrawable(image);
                            }
                        }

                    };
                    MyApplication.imageCache.registerOnImageLoadListener(headLoadListener);
                }
                // attempt to bypass all the loading machinery to get the image
                // loaded as quickly
                // as possible
                Drawable d = null;
                try {
                    Uri uri = null;
                    if (userInfo.head.startsWith("http")) {
                        uri = Uri.parse(userInfo.head + TencentWeibo.HEAD_LARGE_SIZE);
                    }
                    else {
                        File file = new File(userInfo.head);
                        uri = Uri.fromFile(file);
                    }
                    d = MyApplication.imageCache.loadImage(imageID, uri, 0, 0);
                } catch (final IOException e) {
                    e.printStackTrace();
                }
                if (d != null) {
                    head.setImageDrawable(d);
                } else
                    head.setImageResource(R.drawable.portrait_default);
            }
        } else {
            refresh();
        }
    }

    private ILoadListener loadListener = new ILoadListener() {

        @Override
        public void onStart(TextView v) {
            if (v != null)
                v.setText(R.string.progress_loading_text);
        }

        @Override
        public void onEnd() {
        }

    };

    private IResultListener resultListener = new IResultListener() {

        @Override
        public void onSuccess(Entity<TObject> data) {
            if (data != null) {
                if (data.data instanceof Info) {
                    userInfo = (Info) data.data;

                    mainContainer.post(new Runnable() {

                        @Override
                        public void run() {
                            updateViews();
                            ToastUtils.show(head.getContext(), R.string.load_userinfo_success,
                                    Toast.LENGTH_SHORT);
                        }

                    });
                }
            }
        }

        @Override
        public void onFail(Entity<TObject> data) {
            mainContainer.post(new Runnable() {

                @Override
                public void run() {
                    ToastUtils.show(head.getContext(), R.string.load_userinfo_failed,
                            Toast.LENGTH_SHORT);
                }

            });
        }

    };
}


text:
require 'hashie'
require 'hive/extensions/hashie_validate_enum'

module Hive
  module Activities
    module Music
      class TrackShareActivity < Hashie::Trash
        include Hashie::Extensions::IgnoreUndeclared
        include Hashie::Extensions::Coercion

        coerce_key :track, Track
        coerce_key :album, Album
        coerce_key :artist, Artist

        property :track, required: true
        property :album
        property :artist
        property :sharedTo, required: true, transform_with: Hashie::Validate.enum(%w(FACEBOOK GOOGLE_PLUS TWITTER BLOGGER TUMBLR))
      end
    end
  end
end


text:
layout: post
title: AutoCAD selection sets in IronRuby
---

Using selection set filters in the AutoCAD .Net api has always been less than enjoyable.
Take, for example, this bit of code from the [online .Net Developer's Guide](ttp://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html)

```csharp
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod(\"FilterSelectionSet\")]
public static void FilterSelectionSet()
{
  // Get the current document editor
  Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

  // Create a TypedValue array to define the filter criteria
  TypedValue[] acTypValAr = new TypedValue[1];
  acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, \"CIRCLE\"), 0);

  // Assign the filter criteria to a SelectionFilter object
  SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

  // Request for objects to be selected in the drawing area
  PromptSelectionResult acSSPrompt;
  acSSPrompt = acDocEd.GetSelection(acSelFtr);

  // If the prompt status is OK, objects were selected
  if (acSSPrompt.Status == PromptStatus.OK)\
  {
    SelectionSet acSSet = acSSPrompt.Value;
    Application.ShowAlertDialog(\"Number of objects selected: \" + acSSet.Count.ToString());
  }
  else
  {
    Application.ShowAlertDialog(\"Number of objects selected: 0\");
  }
}
```

The thing that bothers me the most is having to build that ugly TypedValue array

```csharp
TypedValue[] acTypValAr = new TypedValue[1];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, \"CIRCLE\"), 0);
```
Being an old LISP hacker,  I know most of the DxfCodes (8 for layer, 0 for type, 62 for color, etc) or I can find them easily.  But why am I forced to remember those codes at all?  If I know that I want to filter on type or layer or color, why do I have to either know the appropriate code or cast the enum member to an int.  And why do I have to keep up with the index  (ie, that 0 just after \"CIRCLE\"),  )?
Why can't I just do something like

```ruby
filter = SsFilter.new
filter.Layer = "my_layer"
filter.Type = "Circle"
```

Well now I can.  I have extended my [acadhelper](http://github.com/davidbl/acadhelper) to include a new class called SsFilter

```ruby
class SsFilter
  attr_accessor :data
  def initialize
    @data = {}
    @elements = {:Type => 0, :Text => 1, :BlockName => 2, :LineType => 6, :TextStyle => 7, :Layer => 8,
                 :StartPoint => 10, :CenterPoint => 10, :EndPoint => 11, :Elevation => 38, :Thickness => 39,
                 :TextHeight => 40, :TextWidth => 41, :Rotation => 50, :Oblique => 51, :Color => 62}
    @keys = @elements.keys
  end
  def filter
    typed_value = Ads::TypedValue[]
    new_filter = System::Array.of(typed_value).new(@data.size)
    i = 0
    if @data.size > 0
      @data.each_pair do  |key,value|
        new_filter.set_value(Ads::TypedValue.new( @elements[key], value), i)
        i+=1
      end
    end
    Aei::SelectionFilter.new(new_filter)
  end

  def method_missing(method_name, *args)
    if method_name.to_s.match(/(\\w+)=/) && @keys.include?($1.to_sym)
      @data[$1.to_sym] = args[0]\
    elsif @keys.include?(method_name)
      return @data[method_name]
    else
      super(method_name, *args)
    end
  end
end
```

This new class uses a bit of method_missing magic to create a very friendly and readable way of creating a selection set filter.

The C# code above can now, using other methods from my acadhelper gem,  be written as

```ruby
require 'rubygems'
require 'acadhelper'
include AcadHelper

def filter_selection_set
  filter = SsFilter.new
  filter.Type = "Circle"
  ss = select_on_screen filter
  result = "Number of objects selected: "
  result += ss ?  ss.count.to_s : "0"
  alert result
end
```

And I did have to make a minor change to the select_on_screen method to support the new filter class
and still allow for hand-built filter arrays

```ruby
def select_on_screen( filter_data=[])
  begin
    if filter_data.is_a?(SsFilter) #new test
      filter = filter_data.filter
    else
      filter = build_selection_filter filter_data
    end

    ssPrompt = ed.GetSelection( filter)
    if ssPrompt.Status == Aei::PromptStatus.OK
      return ssPrompt.Value
    else
      nil
    end
    rescue Exception => e
      puts_ex e
    end
end
```

The new class has been added to the gem on [github](http://github.com/davidbl/acadhelper) but
it  does not yet support logical grouping or relational tests.  Those are coming soon


text:
package JSON::PP::Boolean;

use strict;
require overload;
local $^W;
overload::unimport('overload', qw(0+ ++ -- fallback));
overload::import('overload',
    "0+"     => sub { ${$_[0]} },
    "++"     => sub { $_[0] = ${$_[0]} + 1 },
    "--"     => sub { $_[0] = ${$_[0]} - 1 },
    fallback => 1,
);

$JSON::PP::Boolean::VERSION = '4.12';

1;

__END__

=head1 NAME

JSON::PP::Boolean - dummy module providing JSON::PP::Boolean

=head1 SYNOPSIS

 # do not "use" yourself

=head1 DESCRIPTION

This module exists only to provide overload resolution for Storable and similar modules. See
L<JSON::PP> for more info about this class.

=head1 AUTHOR

This idea is from L<JSON::XS::Boolean> written by Marc Lehmann <schmorp[at]schmorp.de>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut


text:
package org.apache.hyracks.algebricks.core.algebra.operators.logical;

import java.util.List;

import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.metadata.IDataSource;

public abstract class AbstractDataSourceOperator extends AbstractScanOperator {
    protected IDataSource<?> dataSource;

    public AbstractDataSourceOperator(List<LogicalVariable> variables, IDataSource<?> dataSource) {
        super(variables);
        this.dataSource = dataSource;
    }

    public IDataSource<?> getDataSource() {
        return dataSource;
    }
}


text:
         <p>
         Paragraph

Textual unit or block; a textual paragraph.


text:
Color picker build with Swift 2, iOS 9, Xcode 7.

## Overview
The color picker view controller created with swift. It can be used to pick color from palette either as Hex string or UIColor.  Just add source file within any swift project, add view controller within storyboard, add collection view, set necessary properrty and constrains, and invoke as a popup. Once color picked it returns selected color value within delegate method.

![ScreenShot iPhone5](../master/Screenshots/main-1t.png)
![ScreenShot iPhone5](../master/Screenshots/main-2t.png)

## Features:
+ Can be invoked by UIButton.
+ Can be invoked by navigation bar button.
+ You can Add more colors to palette via Colors.plist file.
+ Buid with Swift 2, iOS 9, Xcode 7 only, No other dependency.

## Platform
+ Swift 2
+ iOS 9
+ Xcode 7

##Supported Device
iPhone 4s, 5, 5s, 5c, 6, 6 Plus, 6s, 6s Plus, all iPad having iOS 9.

## How To Setup Color Picker Within Your Project

###### 1 - Copy ``ColorPickerViewController.swift`` and ``Colors.plist`` into your project.

###### 2 - Setup ColorPickerViewController within a Storyboard.
+ **Add View Controller within Storyboard**
+ set Class ``ColorPickerViewController``
+ set Storyboard ID ``sbColorPicker``
+ within 'Attribute Inspector' set Similated metrics >> Size``Freeform``
+ Within 'Size inspector' set Width ``273``, Height ``431``
+
+ **Add Collection View within view controller**
+ set collection view background color white.
+ set collection view cell identfier ``ColorCell``
+ uncheck ``Shows Horizonral Indicator``
+ uncheck ``Shows Vertical Indicator``
+ set Cell Size, Width ``24`` Height ``24``
+ set Minimum Spacing, For Cells ``1``, For Lines ``1``
+ set View  X ``8``, Y ``8``, Width ``257``, Height ``415``
+
+ **Set collection view contraints**
+ Leading Space ``8``, Trailing Space ``8``, Top Space ``8``, Bottom Space ``8``
+
+ **Set collection view outlet within ``ColorPickerViewController.swift``**
+ i.e. connect collection view with ``@IBOutlet var colorCollectionView : UICollectionView!``

###### 3 - Now you can use color picker from any view controller.
Please refer 'How To Use' section for more details.

## How To Update Color Palette
- Open ``Colors.plist`` file,
- add/update color hex value.
- e.g. ``<string>002133</string>``

## How To Use
You can use color picker from any view controller.

**Set delegate to class**

 class ViewController: UIViewController, UIPopoverPresentationControllerDelegate, ColorPickerDelegate { .. }

**Add popover delegate function**

// MARK: Popover delegate functions
// Override iPhone behavior that presents a popover as fullscreen.
// i.e. now it shows same popover box within on iPhone & iPad
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
  // show popover box for iPhone and iPad both
  return UIModalPresentationStyle.None
}

**Add color picker delegate function.** This function will be called after color picked, you can add custom code to handle the selected color. i.e you can assign selected color to class variable or change background color of any element etc.

// MARK: Color picker delegate functions
// called by color picker after color selected.
func colorPickerDidColorSelected(#selectedUIColor: UIColor, selectedHexColor: String) {

  // update color value within class variable
  self.selectedColor = selectedUIColor
  self.selectedColorHex = selectedHexColor

  // set preview background to selected color
  self.colorPreview.backgroundColor = selectedUIColor
}

**Add utility function to show color picker from UI Button.**

// MARK: - Utility functions
// show color picker from UIButton
private func showColorPicker(){

    // initialise color picker view controller
    let colorPickerVc = storyboard?.instantiateViewControllerWithIdentifier("sbColorPicker") as! ColorPickerViewController

    // set modal presentation style
    colorPickerVc.modalPresentationStyle = .Popover

    // set max. size
    colorPickerVc.preferredContentSize = CGSizeMake(265, 400)

    // set color picker deleagate to current view controller
    // must write delegate method to handle selected color
    colorPickerVc.colorPickerDelegate = self

    // show popover
    if let popoverController = colorPickerVc.popoverPresentationController {

        // set source view
        popoverController.sourceView = self.view

        // show popover form button
        popoverController.sourceRect = self.changeColorButton.frame

        // show popover arrow at feasible direction
        popoverController.permittedArrowDirections = UIPopoverArrowDirection.Any

        // set popover delegate self
        popoverController.delegate = self
    }

    //show color popover
    presentViewController(colorPickerVc, animated: true, completion: nil)
}

**Set Outlet and Action for UI Button** and call self.showColorPicker() from it.

// outlet - change color button
@IBOutlet var changeColorButton: UIButton!

// action - called when change color button clicked
@IBAction func changeColorButtonClicked(sender: UIButton) {
  self.showColorPicker()
}

## Screenshots

**iPhone 4S**

![ScreenShot iPhone4s](../master/Screenshots/iphone4s-1t.png)
![ScreenShot iPhone4S](../master/Screenshots/iphone4s-2t.png)

**iPhone 5**

![ScreenShot iPhone5](../master/Screenshots/main-1t.png)
![ScreenShot iPhone5](../master/Screenshots/main-2t.png)

**iPhone 6**

![ScreenShot iPhone6](../master/Screenshots/iphone6-1t.png)
![ScreenShot iPhone6](../master/Screenshots/iphone6-2t.png)

**iPad**

![ScreenShot iPhone6](../master/Screenshots/ipad-1t.png)
![ScreenShot iPhone6](../master/Screenshots/ipad-2t.png)

## License
SwiftColorPicker is available under the MIT license. See the LICENSE file for more info.

## Legacy Version
Xcode 6, iOS 8.4 based source code moved to ``Source-Xcode6`` folder. Please note that Xcode 6 based source code are deprecated and not upto date. I will suggest to use latest Xcode 7 based source from``SwiftColorPicker`` folder at root.


text:
import React from 'react';
import SettingsPage from '../components/pages/SettingsPage';

export default function SettingsPageContainer() {
  return (
    <SettingsPage />
  );
}


text:
$(function() {
  $('#other-providers').tooltip();
});


text:
package com.itweeti.isse.popmovies.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.youtube.player.YouTubeApiServiceUtil;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.itweeti.isse.popmovies.R;
import com.itweeti.isse.popmovies.models.Trailer;
import com.itweeti.isse.popmovies.utils.Config;
import com.itweeti.isse.popmovies.utils.Utils;
import com.itweeti.isse.popmovies.views.adapters.TrailerRecyclerViewAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A fragment representing a list of Items.
 *

 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class TrailerFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    private List<Trailer> movieTrailersList;
    private RecyclerView recyclerView;

    private TrailerRecyclerViewAdapter trailerListAdapter;

    // constant value of package & class name of YouTube app
    public static final String YOUTUBE_PACKAGE_NAME = "com.google.android.youtube";
    public static final String YOUTUBE_CLASS_NAME = "com.google.android.youtube.WatchActivity";

    private String movieId;

    private static final String LOG_TAG = "Trailer Fragment";
    private int flagDataType;
    private Intent intent;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public TrailerFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static TrailerFragment newInstance(int columnCount) {
        TrailerFragment fragment = new TrailerFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        intent = getActivity().getIntent();

        if (intent != null) {
            movieId = intent.getStringExtra("movieId");
            flagDataType = intent.getIntExtra("flagData", 0);
        }

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
            //get movieId from MovieDetailActivity
            movieId = getArguments().getString("movieId");
            movieTrailersList = getArguments().getParcelableArrayList("trailer_list");

        }

        if (savedInstanceState != null) {
            movieId = savedInstanceState.getString("movieId");
            Log.v("savedInstanceState", "movieid = " + movieId);
        }

        //Check for any issues
        final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(getActivity());

        if (result != YouTubeInitializationResult.SUCCESS) {
            //If there are any issues we can show an error dialog.
            result.getErrorDialog(getActivity(), 0).show();
        }

        if (flagDataType == 0) {
            //call trailers from API
            requestMovieTrailer(movieId);
        } else {
            Log.v("xxxxxxxx", "trailers not getting from internet");
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trailer_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }

            recyclerView.setAdapter(new TrailerRecyclerViewAdapter(movieTrailersList, mListener));
        }

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {

                Trailer trailer = movieTrailersList.get(position);
                String url = trailer.getTrailerUrl();
                Toast.makeText(getContext(), trailer.getTrailerUrl() + " is selected!", Toast.LENGTH_SHORT).show();
                launchYoutube(Config.DEVELOPER_KEY, url);
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        return view;
    }

    private void getLocalData() {
        movieTrailersList = new ArrayList<>();
        List<Trailer> trailers = intent.getParcelableArrayListExtra("trailers");

        movieTrailersList = trailers;
        for (Trailer t : movieTrailersList) {
            System.out.println("TRAILER_URL===========> local" + t.getTrailerNumber());
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(Trailer trailer);
    }

    /**
     * Launch Youtube to watch  URL
     */
    private void launchYoutube(String api_key, String video_id) {

        Intent intent = YouTubeStandalonePlayer.createVideoIntent(getActivity(), api_key, video_id);
        startActivity(intent);

    }

    private void requestMovieTrailer(String movieId) {

        movieTrailersList = new ArrayList<>();

        final String BASE_PATH = "http://api.themoviedb.org/3/movie/";
        final String api_key = "?api_key=6d369d4e0676612d2d046b7f3e8424bd";
        String id = movieId;
        final String vid = "/videos";
        String trailer_url = BASE_PATH + id + vid + api_key;

        Log.d(LOG_TAG, "TRAILER URL----------> " + trailer_url);

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(getActivity());

        // Formulate the request and handle the response.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, trailer_url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Do something with the response
                        System.out.println(response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray results = jsonObject.getJSONArray("results");

                            for (int i = 0; i < results.length(); i++) {

                                JSONObject obj = results.getJSONObject(i);
                                String trailer_key = obj.getString("key");
                                //String youtube_trailer = "https://www.youtube.com/watch?v=" + trailer_key;
                                String youtube_trailer = trailer_key;
                                String trailer_num = "Trailer " + (i + 1);

                                System.out.println("TRAILER NUMBER --------->" + trailer_num);
                                System.out.println("TRAILER URL --------->" + youtube_trailer);

                                Trailer trailer = new Trailer(trailer_num, youtube_trailer);

                                //save trailers in a list
                                movieTrailersList.add(trailer);

                            }

                            if (movieTrailersList != null) {
                                for (Trailer trailer : movieTrailersList
                                        ) {
                                    System.out.println("TRAILER NUMBER-----------> " + trailer.getTrailerNumber());
                                }

                                recyclerView.getAdapter().notifyDataSetChanged();

                            } else {
                                System.out.println(R.string.no_trailers);
                            }

                            trailerListAdapter.setItemList(movieTrailersList);
                            trailerListAdapter.notifyDataSetChanged();
                            Log.d("Trailer list size: ", String.valueOf(movieTrailersList.size()));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //other catches
                        if (error instanceof NoConnectionError) {
                            //show dialog no net connection
                            Utils.showSuccessDialog(getContext(), R.string.no_connection, R.string.net).show();
                        }
                    }
                });

        // Add the request to the RequestQueue.
        queue.add(stringRequest);

        trailerListAdapter = new TrailerRecyclerViewAdapter(movieTrailersList, mListener);
    }

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildAdapterPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

}


text:
#pragma once

#include "sql.h"

#ifdef _WIN32
	#include <Windows.h>
	#define SLEEP(x) Sleep(x);
#else
	#include "pthread.h"
	#include <unistd.h>
	#define SLEEP(x) usleep(x * 1000);
	typedef unsigned long DWORD;
	typedef unsigned int UINT;
#endif

#ifdef _WIN32
	DWORD WINAPI SQL_Worker(LPVOID param);
#else
	void *SQL_Worker(void *param);
#endif

/**
 * An abstract SQL connection.
 */
class SQL_Connection {

	public:

		/**
		 * SQL's connection unique ID.
		 */
		int id;

		/**
		 * The AMX machine owning this connection.
		 */
		AMX *amx;

		/**
		 * SQL's connection type (MySQL, PostgreSQL, etc.).
		 */
		int type;

		/**
		 * `true` if SQL's worker thread is active, `false` otherwise.
		 */
		bool isActive;

		/**
		 * The queue of pending queries, scheduled for execution.
		 */
		statementsQueue_t pending;

	#ifdef _WIN32

		/**
		 * Win32 thread.
		 */
		HANDLE thread;
	#else

		/**
		 * UNIX thread.
		 */
		pthread_t thread;
	#endif

		/**
		 * Constructor.
		 * @param id
		 */
		SQL_Connection(int id, AMX *amx);

		/**
		 * Destructor.
		 */
		virtual ~SQL_Connection();

		/**
		 * Starts the worker thread of this SQL connection.
		 */
		void startWorker();

		/**
		 * Stops the worker thread of this SQL connection.
		 */
		void stopWorker();

		/**
		 * Establishes a new connection to a SQL server.
		 * @param host
		 * @param user
		 * @param pass
		 * @param db
		 * @param port
		 * @return
		 */
		virtual bool connect(const char *host, const char *user, const char *pass, const char *db, int port) = 0;

		/**
		 * Destroys the connection to the SQL server.
		 */
		virtual void disconnect() = 0;

		/**
		 * Gets latest error ID returned by the server.
		 * @return
		 */
		virtual int getErrorId() = 0;

		/**
		 * Gets latest error message returned by the server.
		 * @return
		 */
		virtual const char *getError() = 0;

		/**
		 * Pings the server and returns its status.
		 * @return
		 */
		virtual int ping() = 0;

		/**
		 * Gets server's statistics.
		 * @return
		 */
		virtual const char *getStat() = 0;

		/**
		 * Gets server's charset.
		 * @return
		 */
		virtual const char *getCharset() = 0;

		/**
		 * Sets server's charset.
		 * @param charset
		 * @return
		 */
		virtual bool setCharset(char *charset) = 0;

		/**
		 * Escapes a string, making it suitable for SQL queries.
		 * @return
		 */
		virtual int escapeString(const char *src, char *&dest) = 0;

		/**
		 * Executes a SQL statement.
		 * @param stmt
		 */
		virtual void executeStatement(SQL_Statement *stmt) = 0;

		/**
		 * Seeks a result set.
		 * @param stmt
		 * @param resultIdx
		 * @return
		 */
		virtual bool seekResult(SQL_Statement *stmt, int resultIdx) = 0;

		/**
		 * Fetches the name of a field.
		 * @param stmt
		 * @param fieldIdx
		 * @param dest
		 * @param len
		 * @return
		 */
		virtual bool fetchField(SQL_Statement *stmt, int fieldIdx, char *&dest, int &len) = 0;

		/**
		 * Seeks a row.
		 * @param stmt
		 * @param rowIdx
		 * @return
		 */
		virtual bool seekRow(SQL_Statement *stmt, int rowIdx) = 0;

		/**
		 * Fetches a field by it's index.
		 * @param stmt
		 * @param fieldIdx
		 * @param dest
		 * @param len
		 * @return
		 */
		virtual bool fetchNum(SQL_Statement *stmt, int fieldIdx, char *&dest, int &len) = 0;

		/**
		 * Fetches a field by it's name.
		 * @param stmt
		 * @param fieldName
		 * @param dest
		 * @param len
		 * @return
		 */
		virtual bool fetchAssoc(SQL_Statement *stmt, char *fieldName, char *&dest, int &len) = 0;
};


text:
package com.geth1b.coding.skills.lc;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;

/**
 * @author geth1b
 */
public class _001_TwoSum_Test {
  private _001_TwoSum solution;

  @Before public void setUp() {
    this.solution = new _001_TwoSum();
  }

  @Test public void twoSum() {
    final int[] A = new int[] {2, 7, 1, 5};
    int[] result = solution.twoSum(A, 9);
    assertNotNull(result);
    assertEquals(2, result.length);
    assertEquals(0, result[0]);
    assertEquals(1, result[1]);
  }

}


text:
package com.gmail.Lecrayen.Platinum.MMO.Commands.Quarry;

import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import com.gmail.Lecrayen.Platinum.API.MainCommand;
import com.gmail.Lecrayen.Platinum.API.Subcommand;
import com.gmail.Lecrayen.Platinum.MMO.MMO;
import com.gmail.Lecrayen.Platinum.MMO.Quarry;
import com.gmail.Lecrayen.Platinum.MMO.Selection;
import com.gmail.Lecrayen.Platinum.MMO.DataLibrary.SelectionManager;

public class QuarryNew implements Subcommand {

	private String description = "Create a new quarry";
	private MainCommand main;
	private String name = "new";
	private String permission = "platinum.quarry.new";
	private boolean playeronly = true;
	private String usage = "/quarry new <name>";

	public QuarryNew(MainCommand maincommand) {
		main = maincommand;
	}

	@Override
	public String getDescription() {
		return description;
	}

	@Override
	public MainCommand getMainCommand() {
		return main;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String getPermission() {
		return permission;
	}

	@Override
	public String getUsage() {
		return usage;
	}

	@Override
	public boolean isPlayerOnly() {
		return playeronly;
	}

	@Override
	public void run(CommandSender sender, String[] args) {
		Player p = (Player) sender;
		Selection sel = SelectionManager.getSelection(p.getUniqueId());
		ItemStack i = p.getInventory().getItemInMainHand();
		if (!sel.isComplete()) {
			p.sendMessage("§4[Error]:§f No selection");
			return;
		}
		if (MMO.quarry_manager.isOverlappingQuarry(sel.getArea())) {
			p.sendMessage("§4[Error]:§f Overlapping quarries");
			return;
		}
		if (!(args.length > 1)) {
			p.sendMessage("§4[Error]:§f Enter a name");
			return;
		}
		if (MMO.quarry_manager.getQuarry(args[1]) != null) {
			p.sendMessage("§4[Error]:§f That name is in use");
			return;
		}
		if (!p.getInventory().getItemInMainHand().getType().isBlock()) {
			p.sendMessage("§4[Error]:§f Hold a block");
			return;
		}
		MMO.quarry_manager.addQuarry(new Quarry(sel.getArea(), args[1], p.getLocation(), i.getType(), i.getData().getData()));
		p.sendMessage("§2[Info]:§f Quarry created");
	}
}