text:
package org.apache.cassandra.db.commitlog;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.Checksum;

import com.google.common.collect.Ordering;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.db.*;
import org.apache.cassandra.io.util.FastByteArrayInputStream;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.utils.*;

import org.cliffc.high_scale_lib.NonBlockingHashSet;

public class CommitLogReplayer
{
    private static final Logger logger = LoggerFactory.getLogger(CommitLogReplayer.class);
    private static final int MAX_OUTSTANDING_REPLAY_COUNT = 1024;

    private final Set<Keyspace> keyspacesRecovered;
    private final List<Future<?>> futures;
    private final Map<UUID, AtomicInteger> invalidMutations;
    private final AtomicInteger replayedCount;
    private final Map<UUID, ReplayPosition> cfPositions;
    private final ReplayPosition globalPosition;
    private final Checksum checksum;
    private byte[] buffer;

    public CommitLogReplayer()
    {
        this.keyspacesRecovered = new NonBlockingHashSet<Keyspace>();
        this.futures = new ArrayList<Future<?>>();
        this.buffer = new byte[4096];
        this.invalidMutations = new HashMap<UUID, AtomicInteger>();
        // count the number of replayed mutation. We don't really care about atomicity, but we need it to be a reference.
        this.replayedCount = new AtomicInteger();
        this.checksum = new PureJavaCrc32();

        // compute per-CF and global replay positions
        cfPositions = new HashMap<UUID, ReplayPosition>();
        Ordering<ReplayPosition> replayPositionOrdering = Ordering.from(ReplayPosition.comparator);
        Map<UUID,Pair<ReplayPosition,Long>> truncationPositions = SystemKeyspace.getTruncationRecords();
        for (ColumnFamilyStore cfs : ColumnFamilyStore.all())
        {
            // it's important to call RP.gRP per-cf, before aggregating all the positions w/ the Ordering.min call
            // below: gRP will return NONE if there are no flushed sstables, which is important to have in the
            // list (otherwise we'll just start replay from the first flush position that we do have, which is not correct).
            ReplayPosition rp = ReplayPosition.getReplayPosition(cfs.getSSTables());

            // but, if we've truncted the cf in question, then we need to need to start replay after the truncation
            Pair<ReplayPosition, Long> truncateRecord = truncationPositions.get(cfs.metadata.cfId);
            ReplayPosition truncatedAt = truncateRecord == null ? null : truncateRecord.left;
            if (truncatedAt != null)
                rp = replayPositionOrdering.max(Arrays.asList(rp, truncatedAt));

            cfPositions.put(cfs.metadata.cfId, rp);
        }
        globalPosition = replayPositionOrdering.min(cfPositions.values());
        logger.debug("Global replay position is {} from columnfamilies {}", globalPosition, FBUtilities.toString(cfPositions));
    }

    public void recover(File[] clogs) throws IOException
    {
        for (final File file : clogs)
            recover(file);
    }

    public int blockForWrites()
    {
        for (Map.Entry<UUID, AtomicInteger> entry : invalidMutations.entrySet())
            logger.info(String.format("Skipped %d mutations from unknown (probably removed) CF with id %s", entry.getValue().intValue(), entry.getKey()));

        // wait for all the writes to finish on the mutation stage
        FBUtilities.waitOnFutures(futures);
        logger.debug("Finished waiting on mutations from recovery");

        // flush replayed keyspaces
        futures.clear();
        for (Keyspace keyspace : keyspacesRecovered)
            futures.addAll(keyspace.flush());
        FBUtilities.waitOnFutures(futures);
        return replayedCount.get();
    }

    public void recover(File file) throws IOException
    {
        logger.info("Replaying {}", file.getPath());
        CommitLogDescriptor desc = CommitLogDescriptor.fromFileName(file.getName());
        final long segment = desc.id;
        int version = desc.getMessagingVersion();
        RandomAccessReader reader = RandomAccessReader.open(new File(file.getAbsolutePath()));
        try
        {
            assert reader.length() <= Integer.MAX_VALUE;
            int replayPosition;
            if (globalPosition.segment < segment)
            {
                replayPosition = 0;
            }
            else if (globalPosition.segment == segment)
            {
                replayPosition = globalPosition.position;
            }
            else
            {
                logger.debug("skipping replay of fully-flushed {}", file);
                return;
            }

            if (logger.isDebugEnabled())
                logger.debug("Replaying {} starting at {}", file, replayPosition);
            reader.seek(replayPosition);

            /* read the logs populate RowMutation and apply */
            while (!reader.isEOF())
            {
                if (logger.isDebugEnabled())
                    logger.debug("Reading mutation at {}", reader.getFilePointer());

                long claimedCRC32;
                int serializedSize;
                try
                {
                    // any of the reads may hit EOF
                    serializedSize = reader.readInt();
                    if (serializedSize == CommitLog.END_OF_SEGMENT_MARKER)
                    {
                        logger.debug("Encountered end of segment marker at {}", reader.getFilePointer());
                        break;
                    }

                    // RowMutation must be at LEAST 10 bytes:
                    // 3 each for a non-empty Keyspace and Key (including the
                    // 2-byte length from writeUTF/writeWithShortLength) and 4 bytes for column count.
                    // This prevents CRC by being fooled by special-case garbage in the file; see CASSANDRA-2128
                    if (serializedSize < 10)
                        break;

                    long claimedSizeChecksum = reader.readLong();
                    checksum.reset();
                    if (version < CommitLogDescriptor.VERSION_20)
                        checksum.update(serializedSize);
                    else
                        FBUtilities.updateChecksumInt(checksum, serializedSize);

                    if (checksum.getValue() != claimedSizeChecksum)
                        break; // entry wasn't synced correctly/fully. that's
                               // ok.

                    if (serializedSize > buffer.length)
                        buffer = new byte[(int) (1.2 * serializedSize)];
                    reader.readFully(buffer, 0, serializedSize);
                    claimedCRC32 = reader.readLong();
                }
                catch (EOFException eof)
                {
                    break; // last CL entry didn't get completely written. that's ok.
                }

                checksum.update(buffer, 0, serializedSize);
                if (claimedCRC32 != checksum.getValue())
                {
                    // this entry must not have been fsynced. probably the rest is bad too,
                    // but just in case there is no harm in trying them (since we still read on an entry boundary)
                    continue;
                }

                /* deserialize the commit log entry */
                FastByteArrayInputStream bufIn = new FastByteArrayInputStream(buffer, 0, serializedSize);
                RowMutation rm;
                try
                {
                    // assuming version here. We've gone to lengths to make sure what gets written to the CL is in
                    // the current version. so do make sure the CL is drained prior to upgrading a node.
                    rm = RowMutation.serializer.deserialize(new DataInputStream(bufIn), version, ColumnSerializer.Flag.LOCAL);
                }
                catch (UnknownColumnFamilyException ex)
                {
                    if (ex.cfId == null)
                        continue;
                    AtomicInteger i = invalidMutations.get(ex.cfId);
                    if (i == null)
                    {
                        i = new AtomicInteger(1);
                        invalidMutations.put(ex.cfId, i);
                    }
                    else
                        i.incrementAndGet();
                    continue;
                }

                if (logger.isDebugEnabled())
                    logger.debug(String.format("replaying mutation for %s.%s: %s", rm.getKeyspaceName(), ByteBufferUtil.bytesToHex(rm.key()), "{" + StringUtils.join(rm.getColumnFamilies().iterator(), ", ")
                            + "}"));

                final long entryLocation = reader.getFilePointer();
                final RowMutation frm = rm;
                Runnable runnable = new WrappedRunnable()
                {
                    public void runMayThrow() throws IOException
                    {
                        if (Schema.instance.getKSMetaData(frm.getKeyspaceName()) == null)
                            return;
                        if (pointInTimeExceeded(frm))
                            return;

                        final Keyspace keyspace = Keyspace.open(frm.getKeyspaceName());

                        // Rebuild the row mutation, omitting column families that
                        // a) have already been flushed,
                        // b) are part of a cf that was dropped. Keep in mind that the cf.name() is suspect. do every thing based on the cfid instead.
                        RowMutation newRm = null;
                        for (ColumnFamily columnFamily : frm.getColumnFamilies())
                        {
                            if (Schema.instance.getCF(columnFamily.id()) == null)
                                // null means the cf has been dropped
                                continue;

                            ReplayPosition rp = cfPositions.get(columnFamily.id());

                            // replay if current segment is newer than last flushed one or,
                            // if it is the last known segment, if we are after the replay position
                            if (segment > rp.segment || (segment == rp.segment && entryLocation > rp.position))
                            {
                                if (newRm == null)
                                    newRm = new RowMutation(frm.getKeyspaceName(), frm.key());
                                newRm.add(columnFamily);
                                replayedCount.incrementAndGet();
                            }
                        }
                        if (newRm != null)
                        {
                            assert !newRm.isEmpty();
                            Keyspace.open(newRm.getKeyspaceName()).apply(newRm, false);
                            keyspacesRecovered.add(keyspace);
                        }
                    }
                };
                futures.add(StageManager.getStage(Stage.MUTATION).submit(runnable));
                if (futures.size() > MAX_OUTSTANDING_REPLAY_COUNT)
                {
                    FBUtilities.waitOnFutures(futures);
                    futures.clear();
                }
            }
        }
        finally
        {
            FileUtils.closeQuietly(reader);
            logger.info("Finished reading {}", file);
        }
    }

    protected boolean pointInTimeExceeded(RowMutation frm)
    {
        long restoreTarget = CommitLog.instance.archiver.restorePointInTime;

        for (ColumnFamily families : frm.getColumnFamilies())
        {
            if (CommitLog.instance.archiver.precision.toMillis(families.maxTimestamp()) > restoreTarget)
                return true;
        }
        return false;
    }
}


text:
import * as actionTypes from '../constants/actionTypes';

export function connectToServer() {
  return {
    type: actionTypes.CONNECT_TO_SERVER
  };
}

export function startGame(settings) {
  return {
    type: actionTypes.START_GAME,
    payload: settings
  };
}

export function quitGame() {
  return {
    type: actionTypes.QUIT_GAME
  };
}

export function loadAssets(assets) {
  return {
    type: actionTypes.LOAD_ASSETS,
    assets
  };
}

export function completeAssetLoading() {
  return {
    type: actionTypes.COMPLETE_ASSET_LOADING
  };
}

redpajama_set_name: RedPajamaGithub


text:
from . import ActiveTableRecord

class PracticeActiveTableRecord(ActiveTableRecord):

    def __init__(self):
        super(PracticeActiveTableRecord, self).__init__()


text:
package edu.gemini.spModel.core

import scalaz._
import Scalaz._
import org.scalacheck.Prop._
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
import AlmostEqual.AlmostEqualOps

object DeclinationSpec extends Specification with ScalaCheck with Arbitraries with Helpers {

  "Declination Conversions" should {

    "support Angles" !
      forAll { (dec: Declination) =>
        Declination.fromAngle(dec.toAngle).get == dec
      }

    "declination of 90 is allowed" ! {
      val deg90 = Angle.fromDegrees(90)
      val dec90 = Declination.fromAngle(deg90).get
      dec90.toAngle == deg90
      dec90.toDegrees == 90.0
      dec90.offset(Angle.zero)._1.toAngle == deg90
    }

  }

  "Declination Offsetting" should {

    "have identity" !
      forAll { (dec: Declination) =>
        dec.offset(Angle.zero)._1 ~= dec
      }

    "set the carry bit properly" !
      forAll { (dec: Declination, a: Angle) =>
        dec.offset(a)._2 == Declination.fromAngle(dec.toAngle + a).isEmpty
      }

  }

 "Declination Formatting/Parsing Roundtrips" should {

    "Support Degrees" !
      forAll { (dec: Declination) =>
        val s = dec.formatDegrees.init // drop the °
        Angle.parseDegrees(s).fold(_ => false, _ ~= dec.toAngle)
      }

    "Support Sexigesimal" !
      forAll { (dec: Declination) =>
        val s = dec.formatSexigesimal
        Angle.parseSexigesimal(s).fold(_ => false, _ ~= dec.toAngle)
      }

  }

  "Declination Serialization" should {

    "Support Java Binary" !
      forAll { (dec: Declination) =>
        canSerialize(dec)
      }

  }

}


text:
<?php

defined('IN_IA') or exit('Access Denied');

load()->model('wxapp');
load()->model('welcome');

$dos = array('display', 'home', 'get_daily_visittrend');
$do = in_array($do, $dos) ? $do : 'display';
$_W['page']['title'] = '小程序 - 管理';

$version_id = intval($_GPC['version_id']);
$wxapp_info = wxapp_fetch($_W['uniacid']);
if (!empty($version_id)) {
	$version_info = wxapp_version($version_id);
}

if ($do == 'display') {
	$wxapp_version_list = wxapp_version_all($_W['uniacid']);
	template('wxapp/version-display');
}

if ($do == 'home') {
	if ($version_info['design_method'] == WXAPP_TEMPLATE) {
		$version_site_info = wxapp_site_info($version_info['multiid']);
	}
	$role = permission_account_user_role($_W['uid'], $wxapp_info['uniacid']);

	$notices = welcome_notices_get();
	template('wxapp/version-home');
}

if ($do == 'get_daily_visittrend') {
	wxapp_update_daily_visittrend();
		$yesterday = date('Ymd', strtotime('-1 days'));
	$yesterday_stat = pdo_get('wxapp_general_analysis', array('uniacid' => $_W['uniacid'], 'type' => '2', 'ref_date' => $yesterday));
	if (empty($yesterday_stat)) {
		$yesterday_stat = array('session_cnt' => 0, 'visit_pv' => 0, 'visit_uv' => 0, 'visit_uv_new' => 0);
	}
	iajax(0, array('yesterday' => $yesterday_stat), '');
}


text:
using System;
using System.Collections.Generic;
using SIL.Reporting;

namespace GlyssenEngine.ErrorHandling
{
    public interface IErrorHandler
    {
        void HandleException(Exception e, string context = null, Dictionary<string, string> details = null);
    }

	public static class NonFatalErrorHandler
    {
        public static IErrorHandler Default { get; set; }

        public static void HandleException(Exception e, string message = null, Dictionary<string, string> details = null)
        {
	        Default?.HandleException(e, message, details);
		}

		public static void LogAndHandleException(Exception e, string message, Dictionary<string, string> details = null)
		{
			Logger.WriteError(e);
			HandleException(e, message, details);
		}

		/// <summary>
		/// When reporting an exception to the user, we assume that they will normally (when appropriate) communicate
		/// the problem back to the development team, so we will have all the details to be able to follow up as needed.
		/// We intentionally omit the <paramref name="message"/> when passing the exception along to the default
		/// exception handler because it likely contains details that might not be appropriate to pass along to the
		/// "outside" world (e.g., Analytics).
		/// </summary>
		/// <param name="e">The exception</param>
		/// <param name="message">Additional explanatory information to report</param>
		public static void ReportAndHandleException(Exception e, string message)
        {
			ErrorReport.NotifyUserOfProblem(e, message);
			HandleException(e);
        }
	}
}


text:
![logo](logo/Gen-Spring-Logo.jpg?raw=true)

# generator-spring [![Build Status](https://travis-ci.org/davetownsend/generator-spring.svg?branch=master)](https://travis-ci.org/davetownsend/generator-spring)

A [Yeoman](http://yeoman.io) generator for scaffolding and bootstrapping [Spring Boot](http://projects.spring.io/spring-boot/) and [Spring Cloud](http://projects.spring.io/spring-cloud/) applications. Provides the same selectable options as [Spring Initializr](http://start.spring.io), but with and interactive CLI interface so your hands can stay where they belong, on the keyboard!

## Getting Started

**Install Yeoman**

```
$ npm install -g yo
```

**Install generator-spring**

```
$ npm install -g generator-spring
```

**Initiate spring-generator!**

```
$ yo spring
```
_The interactive CLI menu will guide the way._

### Extras (Sub-generators)
Creates a REST endpoint

```
$ yo spring:rest
```

Creates a REST endpoint with HATEOAS support *(has dependency on choosing the hateoas starter option)*

```
$ yo spring:hateoas
```

Creates an initial Thymeleaf view *(has dependency on choosing the Thyemleaf starter option)*

```
$ yo spring:route
```

## TODO
- Add the new Spring Cloud libs supported with Spring Boot 1.5.x
- Add support for createing a serverless (AWS) project with Spring Cloud Function.
- Add React support. This will essentially scaffold an opinionated react SPA (webpack/es6/material-ui) as the front end.

## License

[MIT License](http://en.wikipedia.org/wiki/MIT_License)


text:
class Property
{
	Color reflectance;
	Color ambient;
	double specular, mirror;
	std::string name;
public:
	Property(void) : reflectance(), specular(0.0), mirror(0.0) {};
	Property(char *n, Color &a, Color &r, double s, double m) : name(n), ambient(a), reflectance(r), specular(s), mirror(m) {};

	Color getAmbient() { return ambient; };
	Color getReflectance() { return reflectance; };
	double getSpecular() { return specular; };
	double getMirror() { return mirror; };
	std::string getName() { return name; };
};


text:
/*
 * verifier.hpp
 *
 *  Created on: Nov 16, 2019
 *      Author: GC
 */

#ifndef SRC_LIBRARY_OS_VERIFIER_HPP_
#define SRC_LIBRARY_OS_VERIFIER_HPP_

#include <string>
#include "../base/base.h"

namespace license {
namespace os {
FUNCTION_RETURN verify_signature(const std::string& stringToVerify, const std::string& signatureB64);
}
} /* namespace license */

#endif /* SRC_LIBRARY_OS_VERIFIER_HPP_ */


text:
package com.huassit.imenu.android.biz;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Handler;

import com.huassit.imenu.android.http.BaseInvoker;
import com.huassit.imenu.android.model.API;
import com.huassit.imenu.android.parser.BaseParser;
import com.huassit.imenu.android.parser.MenuAndStoreParser;

public class GetMenuDetailResp extends BaseInvoker{

	private String menuId;
	private MenuAndStoreParser menuAndStoreParser;
	public GetMenuDetailResp(Activity ctx, Handler handler,String menuId) {
		super(ctx, handler);
		this.menuId =menuId;
		menuAndStoreParser =new MenuAndStoreParser();
	}

	@Override
	public List<NameValuePair> getParameters() {
		List<NameValuePair> nvp =new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("route", API.GET_MENU_DETAIL));
		nvp.add(new BasicNameValuePair("token", ""));
		nvp.add(new BasicNameValuePair("jsonText", makeJsonText()));
		return nvp;
	}

	private String makeJsonText() {
		JSONObject json =new JSONObject();
		try {
			json.put("menu_id", menuId);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	@Override
	public String getRequestUrl() {
		return API.server;
	}

	@Override
	public HTTP_METHOD getRequestMethod() {
		return HTTP_METHOD.METHOD_POST;
	}

	@Override
	protected void handleResponse(String response) {
		try {
			Map<String,Object> menuAndStore =menuAndStoreParser.doParse(response);
			if(menuAndStoreParser.getResponseCode()==BaseParser.SUCCESS && menuAndStore!=null){
				sendMessage(ON_SUCCESS, menuAndStore);
			}else{
				sendMessage(ON_FAILURE, null);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}


text:
set(files
    channel.go
    component.go
    convert.go
    convert_test.go
    datatype.go
    doc.go
    format.go
    sampling.go
    stream.pb.go
    stream.proto
)
set(dirs
    fmts
)


text:
EMSDK_VERSION=1.38.47_v1

# Can check CHROME_VERSION with
# docker run karma-chrome-tests /usr/bin/google-chrome-stable --version
CHROME_VERSION=72.0.3626.121_v1

publish_emsdk_base:
	docker build --no-cache -t emsdk-base ./emsdk-base/
	docker tag emsdk-base gcr.io/skia-public/emsdk-base:${EMSDK_VERSION}
	docker push gcr.io/skia-public/emsdk-base:${EMSDK_VERSION}
	docker tag emsdk-base gcr.io/skia-public/emsdk-base:prod
	docker push gcr.io/skia-public/emsdk-base:prod

publish_karma_chrome_tests:
	docker build --no-cache -t karma-chrome-tests ./karma-chrome-tests/
	docker tag karma-chrome-tests gcr.io/skia-public/karma-chrome-tests:${CHROME_VERSION}
	docker push gcr.io/skia-public/karma-chrome-tests:${CHROME_VERSION}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta description content="A tic-tac-toe game.">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
  <link href='https://fonts.googleapis.com/css?family=Poiret+One' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" type="text/css" href="stylesheet.css"/>

  <title>Tic-Tac-Toe!</title>
  This application requires JavaScript to function. Please enable scripts in your browser.

TicTacToe!

Player One: Choose your mark!

      <button id="xSelect" type="button" class="btn"></button>
      <button id="oSelect" type="button" class="btn"></button>

Players

Is the other player a friend or the AI?

        <button id="twoPlayer" type="button" class="btn"></button>
        <button id="singlePlayer" type="button" class="btn"></button>

      Game Over!

    </div


text:
layout: post
title: "July Meeting Summary"
date: 2013-07-15 10:00
author: john
comments: false
categories: Philadelphia Microsoft Virtual Academy presentation materials Windows Azure
---

* Active Directory SDK team member and former Senior Programing writer for the Windows PowerShell team, [June Blender](https://twitter.com/juneb_get_help) gave a presentation on *The Hidden Charms of Windows PowerShell 3.0* via
Lync. You can get a copy of [her presentation here](http://cdn.powershell.org/wp/wp-content/uploads/2013/07/PhillyPosh_2013-07-11_June_Blender.pptx) and see a [recording of the Lync meeting](https://www.youtube.com/watchv=rY-kkuTwWUs) on our [YouTube channel](https://www.youtube.com/channel/UCAc_ow5FIJtRpvew__9Iqzg)
<iframe width="420" height="315" src="//www.youtube.com/embed/rY-kkuTwWUs" frameborder="0" allowfullscreen></iframe>

* Microsoft Technology Evangelist [Yung Chou](http://blogs.technet.com/b/yungchou/) gave demonstration on how to use the [PowerShell Azure cmdlets](http://msdn.microsoft.com/en-us/library/windowsazure/jj152841.aspx) to automate data center deployments

* You can try doing the same and test server 2012 R2 out with a free [1-month trial of Windows Azure](http://aka.ms/200)

## General Announcements

* [The Microsoft Virtual Academy](http://www.microsoftvirtualacademy.com) is hosting 2 separate day long PowerShell learning sessions that will be taught by the lead Architect of PowerShell [Jeffery Snover ](http://powershell.org/wp/wp-admin/@jsnover)and [PowerShell.org](http://powershell.org/wp/wp-admin/PowerShell.org) board member [Jason Helmick.](http://powershell.org/wp/wp-admin/@theJasonHelmick) Links to the sessions are as follows:
  - [Getting Started with PowerShell 3.0 : 7/18/2013 9AM-5PM PDT](http://www.microsoftvirtualacademy.com/liveevents/PowerShell-JumpStart)
  - [Advanced Tools & Scripting with PowerShell 3.0: 8/1/2013 9AM-5PM PDT](http://www.microsoftvirtualacademy.com/liveevents/Adv-PowerShell-Jump-Start)

* The [PowerScript Podcast](http://powerscripting.wordpress.com/2013/07/08/we-want-your-powershell-show-ideas/) is looking for show ideas.

* In the wake of the 2013 scripting games there are many entries in the [Great
Debates](http://powershell.org/wp/category/great-debates/) series, in which the [PowerShell.org](PowerShell.org) community discusses the differing techniques that the community used during the games.

* Speaking of the scripting games, the winners were on the [PowerScritping
Podcast](http://powerscripting.wordpress.com/2013/07/10/up-next-winners-from-the-2013-scripting-games/) this week.

*  [Mike Robbins](http://mikefrobbins.com/), the winner of the advanced category, will be presenting for us in September!

* Mike also runs the virtual [Mississippi PowerShell User Group](http://mspsug.com/) and makes his meetings available to everyone.

*  Last months speaker, [Rohn Edwards](http://rohnspowershellblog.wordpress.com/), has recently [blogged](http://rohnspowershellblog.wordpress.com/tag/powershellaccesscontrol/) about how to use some of the functions
included in his [PowerShellAccessControl Module](http://gallery.technet.microsoft.com/scriptcenter/PowerShellAccessControl-d3be7b83).

* Check out [Chocolatey](http://chocolatey.org/) which is a Machine Package Manager, somewhat like apt-get, but built with Windows and PowerShell in mind.


text:
package Raytracing

import (
	objects "de/vorlesung/projekt/raytracer/SceneObjects"
)

//a light implementation
type Light struct {
	position *objects.Vector
	color    *objects.Vector
}

//creates a new instance of a light
func NewLight(position, color *objects.Vector) *Light {
	light := new(Light)
	light.SetPosition(position)
	light.SetColor(color)
	return light
}

//returns the position
func (this *Light) Position() *objects.Vector { return this.position }

//returns the color
func (this *Light) Color() *objects.Vector { return this.color }

//sets the position
func (this *Light) SetPosition(position *objects.Vector) { this.position = position }

//sets the color
func (this *Light) SetColor(color *objects.Vector) { this.color = color }


text:
package io.gatling.recorder.scenario.template

import io.gatling.BaseSpec
import io.gatling.recorder.scenario.{ RequestBodyParams, RequestElement }

class RequestTemplateSpec extends BaseSpec {

  val url = "http://gatling.io/path1/file1"
  val simulationClass = "Simulation Class"

  def mockRequestBody(paramName: String, paramValue: String) = RequestBodyParams(List((paramName, paramValue)))
  def mockRequestElement(paramName: String, paramValue: String) =
    RequestElement(url, "post", Map(), Some(mockRequestBody(paramName, paramValue)), None, 200, Nil)

  "request template" should "not wrap with joinStrings strings shorter than 65535 characters" in {
    val mockedRequest1 = mockRequestElement("name", "short")
    val res1 = RequestTemplate.render(simulationClass, mockedRequest1, new ExtractedUris(Seq(mockedRequest1)))
    res1 should include(".formParam(\"name\", \"short\")")

    val mockedRequest2 = mockRequestElement("name", "1" * 65534)
    val res2 = RequestTemplate.render(simulationClass, mockedRequest2, new ExtractedUris(Seq(mockedRequest2)))
    res2 should not include "Seq"
    res2 should not include ".mkString"
  }

  it should "wrap with joinStrings strings with not less than 65535 characters" in {
    val mockedRequest = mockRequestElement("name", "a" * 65535)
    val res = RequestTemplate.render(simulationClass, mockedRequest, new ExtractedUris(Seq(mockedRequest)))
    res should include("Seq(\"" + "a" * 65534 + "\", \"a\").mkString")
  }
}


text:
@interface ProductDetailVC : UIViewController
- (IBAction)SkuClick;

@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: Arsan Irianto
 * Date: 08/01/2016
 * Time: 22:14
 */
session_start();
include_once("../../config/connect.php");
include_once("../../library/functions.php");

?>
    <link href="../../plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />

    <link href="../../font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
    <link href="../../font-awesome/css/fonts.googleapis.css" rel="stylesheet" type="text/css" />

    <link href="../../font-awesome/css/ionicons.min.css" rel="stylesheet" type="text/css" />

    <link href="../../plugins/datepicker/datepicker3.css" rel="stylesheet" type="text/css" />
    <link href="../../plugins/datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css" />

    <link href="../../dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />

    <link href="../../dist/css/skins/skin-red.min.css" rel="stylesheet" type="text/css" />

<form id="form1" name="form1" method="get" enctype="multipart/form-data" action="../modules/act_excel_logsheet.php">
    <input type="hidden" name="modules" value="logsheet" >

Data Logsheet

                                Excel

                            <?php echo combonamabln(1, 12, "cbo_month", "-Month-","form-control input-sm");?>

                            <?php echo combothn(date("Y")-2, date("Y"), "cbo_year", "-Year-","form-control input-sm");?>

</form>

<?php
include_once("../footer.php");
?>


text:
/*global $, app*/
"use strict";

var _ = require('underscore');
var HumanView = require('human-view');
var templates = require('../templates');

module.exports = HumanView.extend({
    template: templates.includes.call,
    classBindings: {
        state: ''
    },
    events: {
        'click .answer': 'handleAnswerClick',
        'click .ignore': 'handleIgnoreClick',
        'click .cancel': 'handleCancelClick',
        'click .end': 'handleEndClick',
        'click .mute': 'handleMuteClick'
    },
    render: function () {
        this.renderAndBind();
        // register bindings for sub model
        this.registerBindings(this.model.contact, {
            textBindings: {
                displayName: '.callerName'
            },
            srcBindings: {
                avatar: '.callerAvatar'
            }
        });
        this.$buttons = this.$('button');
        this.listenToAndRun(this.model, 'change:state', this.handleCallStateChange);

        return this;
    },
    handleAnswerClick: function (e) {
        e.preventDefault();
        var self = this;
        self.model.state = 'active';
        app.navigate('/chat/' + self.model.contact.jid);
        self.model.contact.onCall = true;
        self.model.jingleSession.accept();
        return false;
    },
    handleIgnoreClick: function (e) {
        e.preventDefault();
        this.model.jingleSession.end({
            condition: 'decline'
        });
        return false;
    },
    handleCancelClick: function (e) {
        e.preventDefault();
        this.model.jingleSession.end({
            condition: 'cancel'
        });
        return false;
    },
    handleEndClick: function (e) {
        e.preventDefault();
        this.model.jingleSession.end({
            condition: 'success'
        });
        return false;
    },
    handleMuteClick: function (e) {
        return false;
    },
    // we want to make sure we show the appropriate buttons
    // when in various stages of the call
    handleCallStateChange: function (model, callState) {
        var state = callState || this.model.state;
        // hide all
        this.$buttons.hide();

        var map = {
            incoming: '.ignore, .answer',
            outgoing: '.cancel',
            accepted: '.end, .mute',
            terminated: '',
            ringing: '.cancel',
            mute: '.end, .unmute',
            unmute: '.end, .mute'
            //hold: '',
            //resumed: ''
        };

        console.log('map[state]', map[state]);

        this.$(map[state]).show();
    }
});


text:
<title>FTP Download</title>
<meta name="order" content="7" />

Downloads

A number of downloads are available for each species:

Genomic	Raw FASTA genome file

Masked Genomic	Genome FASTA with repeat regions hard-masked

Soft-masked Genomic	Genome FASTA with repeat regions soft-masked

Annotations (GFF3)	GFF3 file containing all annotations

Annotations (GTF)	GTF file containing only the canonical gene set

Proteins	FASTA protein file

mRNA Transcripts	FASTA of the spliced full-length transcripts

CDS Transcripts	FASTA of the spliced CDS-portion of the protein coding transcripts

Orthologs	TSV of the orthologues in other species

Paralogs	TSV of the paralogues in other species

Data for previous releases can be found on the WormBase ParaSite FTP server.

When using data from WormBase ParaSite, please cite both this resource and the original paper for the genome.  Full details are available in our Data Usage and Citations guide.

  [[SCRIPT::EnsEMBL::Web::Document::HTML::FTPtable]]


text:
@interface NSView (AMViewAnimation)
- (IBAction)fadeOut:sender;
- (IBAction)fadeIn:sender;
- (void)animateToFrame:(NSRect)rect;
- (void)fadeToFrame:(NSRect)rect; // animates to supplied frame; fades in if view is hidden; fades out if view is visible

+ (void)setDefaultDuration:(NSTimeInterval)duration;
+ (void)setDefaultBlockingMode:(NSAnimationBlockingMode)mode;
+ (void)setDefaultAnimationCurve:(NSAnimationCurve)curve;
@end


text:
/*
 * Notifier lists
 *
 * Copyright IBM, Corp. 2010
 *
 * Authors:


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo.service;

import db.exception.NegocioException;
import db.exception.PersistenciaException;
import java.util.List;
import modelo.domain.Alocação;

/**
 *
 * @author Cliente
 */
public interface IManterAlocação {
    public Integer cadastrar(Alocação curriculo) throws PersistenciaException, NegocioException;
    public void atualizar(Alocação curriculo) throws PersistenciaException, NegocioException;
    public void excluir(Alocação curriculo) throws PersistenciaException, NegocioException;
    public List<Alocação> listarTodos() throws PersistenciaException, NegocioException;
}


text:
(function($){

	var count=0;
	$.fn.scrollfade=function(option){
		if(typeof(option)=='object'||typeof(option)=='undefined'){
      var args=(typeof(option)=='object'?[option]:[]);
			return this.each(function(){
			  return methods.init.apply(this,args);
			});
		}else if(typeof option=='string'&&typeof methods[option]=='function'){
      var args=Array.prototype.slice.call(arguments,1);
			return this.each(function(){
				return methods[option].apply(this,args);
				$.error('Element is not a scrollfade plugin');
			});
		}else $.error('Requested scrollfade method not found.');
	};

	var methods={
	// V A R S
		init:function(settings){
	    var self=this;
	    this.settings=$.extend({
		    'arrow-color':'black',
		    'click-scroll':100,
		    'time-fade-in':100,
		    'time-fade-out':200,
		    'delay-fader':1000,
		    'animate-multiplier':0
  		},settings);
	    this.index=count++;
	    this.scrollbar=false;
	    this.resizing=false;
	    this.manual=false;
	    this.timerFader=null;
	    this.timerResize=null;
	    this.timerNoise=null;
	    this.noise=false;
	    this.innerHeight=0;
	    this.thumbHeight=0;
	    this.thumbTop=0;
	    this.ignore=false;
	    this.mouseScrollbar=false;
	// C O N T E N T
			this.$content=$('
').css({padding:$(this).css('padding')}).html($(this).html());
	    this.$inner=$('
').html(this.$content);
	    this.$scroll=$('
').html(this.$inner).scroll(function(){$(self).scrollfade('position');$(self).scrollfade('fader');});
			// T H U M B
	    this.$thumb=$('
').mousedown(function(e){
    		$(window).unbind('mousemove.scroll'+self.index).unbind('mouseup.mouseup'+self.index).unbind('selectstart.scroll'+self.index);
	    	if(self.ignore)return;
	    	var start=e.pageY;
	    	var scrollTop=self.$scroll.scrollTop();
	    	var top={
	    		scrollbar:((self.thumbTop/100)*self.$track.height()),
	    		page:(self.$scroll.scrollTop())
	    	}
	    	var avaiable={
	    		scrollbar:self.$track.height()-self.$thumb.height(),
	    		page:self.innerHeight-self.$outer.height()
	    	}
	    	self.manual=true;
	    	var ratio=avaiable.page/avaiable.scrollbar;
	    	$(window).attr('unselectable','on').css('user-select','none').bind('selectstart.scroll'+self.index,function(e){return false;});
	    	$(window).bind('mousemove.scroll'+self.index,function(e){
	    		var difference=e.pageY-start;
	    		difference=difference*ratio;
	    		if(difference<0){
	    			if(top.page<1)return;
	    			if(top.page<difference*-1)difference=top.page*-1;
	    		}else{
	    			if(top.page+avaiable.page>=self.innerHeight)return;
	    			if(top.page+difference>self.innerHeight)difference=self.innerHeight-avaiable.page;
	    		}
	    		self.$scroll.scrollTop(scrollTop+difference);
	    	});
	    	$(window).bind('mouseup.mouseup'+self.index,function(e){
	    		$(window).unbind('mousemove.scroll'+self.index).unbind('mouseup.mouseup'+self.index).unbind('selectstart.scroll'+self.index);
		    	$(self).scrollfade('position');
		    	self.manual=false;
	    	});
	    });
			// A R R O W S
	    this.$up=$('
').click(function(){
	    	if(self.ignore)return;
	    	var top=self.$scroll.scrollTop();
	    	if(top<1)return;
	    	var amount=(top<self.settings['click-scroll']?top:self.settings['click-scroll']);
	    	var time=(+self.settings['animate-multiplier'])*amount;
	    	self.$scroll.animate({scrollTop:'-='+amount},time);
	    });
	    this.$down=$('
').click(function(){
	    	if(self.ignore)return;
	    	var total=self.innerHeight;
	    	var bottom=self.$scroll.scrollTop()+self.$outer.height();
	    	if(bottom>=total)return;
	    	var amount=((bottom+self.settings['click-scroll']>total)?(total-bottom):self.settings['click-scroll']);
	    	var time=(+self.settings['animate-multiplier'])*amount;
	    	self.$scroll.animate({scrollTop:'+='+amount},time);
	    });
			// T R A C K   I N N E R   O U T E R
	    this.$track=$('
').append(this.$thumb);
	    this.$scrollbar=$('
').append(this.$up,this.$track,this.$down).mouseenter(function(e){self.mouseScrollbar=true;}).mouseleave(function(){self.mouseScrollbar=false;});
	    this.$outer=$('
').append(this.$scroll,this.$scrollbar);
	    if($(this).css('position').toLowerCase()!='absolute')$(this).css('position','relative');
	    $(this).css({overflow:'hidden'}).html(this.$outer);
	// E V E N T S
	    $(this).mousemove(function(e){
	    	$(this).scrollfade('fader',e.pageX+'x'+e.pageY);
	    });
	    $(window).bind('resize.win'+self.index,function(){
	    	var key=$(window).width()+'x'+$(window).height();
	    	if(self.key==$(window).width()+'x'+$(window).height())return;
	    	self.$inner.width(self.$scroll.width()/2);
      	self.resizing=true;
	    	$(self).scrollfade('fader',key);
	      clearTimeout(self.timerResize);
	      self.timerResize=setTimeout(function(){
	      	self.resizing=false;
	      },+self.settings['delay-fader']);
	    });
	    self.$inner.width(self.$scroll.width()/2);
	    $(this).scrollfade('fader');
		},
		html:function(html){
	    this.$content.html(html);
    	$(this).scrollfade('fader');
		},
		append:function(html){
	    this.$content.append(html);
    	$(this).scrollfade('fader');
		},
		prepend:function(html){
	    this.$content.prepend(html);
    	$(this).scrollfade('fader');
		},
// P O S I T I O N
		position:function(){
    	var additional=parseInt(this.$inner.children().children().first().css('margin-top'))+parseInt(this.$inner.children().children().last().css('margin-bottom'));
    	this.innerHeight=this.$inner.height()+additional;
    	if(this.innerHeight<=$(this).height()){
    		this.ignore=true;
    		if(this.scrollbar||this.resizing)this.$scrollbar.fadeOut(+this.settings['time-fade-out']);
    		return;
    	}
    	this.ignore=false;
      this.thumbHeight=Math.round(($(this).height()/this.innerHeight)*10000)/100;
      this.thumbTop=Math.round((this.$scroll.scrollTop()/this.innerHeight)*10000)/100;
      this.$thumb.css({height:this.thumbHeight+'%',top:this.thumbTop+'%'});
		},
		fader:function(key){
			var self=this;
			if(self.noise)return;
			self.noise=true;
			this.timerNoise=setTimeout(function(){
				self.noise=false;
			},50);
	    $(this).scrollfade('position');
			if(this.ignore||this.mouseScrollbar||(key&&self.key==key))return;
			self.key=key;
      clearTimeout(self.timerFader);
			if(!self.scrollbar){
				self.scrollbar=true;
	      self.$scrollbar.fadeIn(+self.settings['time-fade-in']);
			}
      self.timerFader=setTimeout(function(){
      	if(self.mouseScrollbar||self.manual)return false;
				self.scrollbar=false;
        self.$scrollbar.fadeOut(+self.settings['time-fade-out']);
      },+self.settings['delay-fader']);
		}
	};

}(jQuery));


text:
package org.apache.archiva.rest.services;

import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.rest.api.services.MergeRepositoriesService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Olivier Lamy
 */
public class MergeRepositoriesServiceTest
    extends AbstractArchivaRestTest
{

    private static final String TEST_REPOSITORY = "test-repository";
    private static final String TEST_REPOSITORY_STAGE = TEST_REPOSITORY + "-stage";

    private Path repo = getAppserverBase().resolve("data/repositories").resolve( "test-repository" );

    private Path repoStage = getAppserverBase().resolve("data/repositories").resolve( "test-repository-stage" );

    private int maxChecks = 10;
    private int checkWaitMs = 500;

    @Test
    public void getMergeConflictedArtifacts()
        throws Exception
    {
        MergeRepositoriesService service = getMergeRepositoriesService( authorizationHeader );

        waitForScanToComplete( TEST_REPOSITORY );
        waitForScanToComplete( TEST_REPOSITORY_STAGE );

        int checks = maxChecks;
        Throwable ex = null;
        while(checks-->0) {
            try {
                log.info("Test Try " + checks);
                List<Artifact> artifactMetadatas = service.getMergeConflictedArtifacts( TEST_REPOSITORY_STAGE,
                        TEST_REPOSITORY );
                log.info("conflicts: {}", artifactMetadatas);

                assertThat(artifactMetadatas).isNotNull().isNotEmpty().hasSize(8);
                return;
            } catch (Throwable e) {
                ex = e;
            }
            Thread.currentThread().sleep(checkWaitMs);
        }
        if (ex!=null && ex instanceof AssertionError) {
            throw (AssertionError)ex;
        } else {
            throw new Exception(ex);
        }

    }

    @Test
    public void merge()
        throws Exception
    {
        String mergedArtifactPath =
            "org/apache/felix/org.apache.felix.bundlerepository/1.6.4/org.apache.felix.bundlerepository-1.6.4.jar";
        String mergedArtifactPomPath =
            "org/apache/felix/org.apache.felix.bundlerepository/1.6.4/org.apache.felix.bundlerepository-1.6.4.pom";

        assertTrue( Files.exists(repoStage.resolve(mergedArtifactPath)) );
        assertTrue( Files.exists(repoStage.resolve(mergedArtifactPomPath)) );

        waitForScanToComplete( TEST_REPOSITORY );
        waitForScanToComplete( TEST_REPOSITORY_STAGE );

        MergeRepositoriesService service = getMergeRepositoriesService( authorizationHeader );

        int checks = maxChecks;
        Throwable ex = null;
        while(checks-->0) {
            try {
                log.info("Test Try " + checks);
                service.mergeRepositories(TEST_REPOSITORY_STAGE, TEST_REPOSITORY, true);

                assertTrue(Files.exists(repo.resolve(mergedArtifactPath)));
                assertTrue(Files.exists(repo.resolve(mergedArtifactPomPath)));
                return;
            } catch (Throwable e) {
                log.info("Exception {}, {}", e.getMessage(), e.getClass());
                ex = e;
            }
            Thread.currentThread().sleep(checkWaitMs);
        }
        if (ex!=null && ex instanceof AssertionError) {
            throw (AssertionError)ex;
        } else if (ex!=null) {
            throw new Exception(ex);
        }

    }

    @After
    public void deleteStageRepo()
        throws Exception
    {
        waitForScanToComplete( TEST_REPOSITORY );
        waitForScanToComplete( TEST_REPOSITORY_STAGE );

        deleteTestRepo( TEST_REPOSITORY );

        org.apache.archiva.common.utils.FileUtils.deleteDirectory( repo );
        org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoStage );
    }

    @Before
    public void createStageRepo()
        throws Exception
    {
        // FileUtils.copyDirectory( Paths.get( System.getProperty( "basedir" ), "src/test/repo-with-osgi" ).toFile(), repo.toFile() );

        Path srcRepo = getProjectDirectory().resolve(  "src/test/repo-with-osgi" );
        createStagedNeededRepo( TEST_REPOSITORY, srcRepo , getProjectDirectory().resolve("src/test/repo-with-osgi-stage" ),  true );

    }
}


text:
export default Static;
export type Options = {
    /**
     * Attributions.
     */
    attributions?: string | string[] | ((arg0: import("../PluggableMap.js").FrameState) => string | string[]);
    /**
     * The `crossOrigin` attribute for loaded images.  Note that
     * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
     * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
     */
    crossOrigin?: string;
    /**
     * Extent of the image in map coordinates.
     * This is the [left, bottom, right, top] map coordinates of your image.
     */
    imageExtent?: number[];
    /**
     * Optional function to load an image given a URL.
     */
    imageLoadFunction?: (arg0: ImageWrapper, arg1: string) => void;
    /**
     * Enable image smoothing.
     */
    imageSmoothing?: boolean;
    /**
     * Projection. Default is the view projection.
     */
    projection?: string | import("../proj/Projection.js").default;
    /**
     * Size of the image in pixels. Usually the image size is auto-detected, so this
     * only needs to be set if auto-detection fails for some reason.
     */
    imageSize?: number[];
    /**
     * Image URL.
     */
    url: string;
};
/**
 * @typedef {Object} Options
 * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
 * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
 * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
 * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
 * @property {import("../extent.js").Extent} [imageExtent] Extent of the image in map coordinates.
 * This is the [left, bottom, right, top] map coordinates of your image.
 * @property {import("../Image.js").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.
 * @property {boolean} [imageSmoothing=true] Enable image smoothing.
 * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
 * @property {import("../size.js").Size} [imageSize] Size of the image in pixels. Usually the image size is auto-detected, so this
 * only needs to be set if auto-detection fails for some reason.
 * @property {string} url Image URL.
 */
/**
 * @classdesc
 * A layer source for displaying a single, static image.
 * @api
 */
declare class Static extends ImageSource {
    /**
     * @param {Options} options ImageStatic options.
     */
    constructor(options: Options);
    /**
     * @private
     * @type {string}
     */
    private url_;
    /**
     * @private
     * @type {import("../extent.js").Extent}
     */
    private imageExtent_;
    /**
     * @private
     * @type {import("../Image.js").default}
     */
    private image_;
    /**
     * @private
     * @type {import("../size.js").Size}
     */
    private imageSize_;
    /**
     * Returns the image extent
     * @return {import("../extent.js").Extent} image extent.
     * @api
     */
    getImageExtent(): number[];
    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../Image.js").default} Single image.
     */
    getImageInternal(extent: number[], resolution: number, pixelRatio: number, projection: import("../proj/Projection.js").default): ImageWrapper;
    /**
     * Return the URL used for this image source.
     * @return {string} URL.
     * @api
     */
    getUrl(): string;
}
import ImageWrapper from "../Image.js";
import ImageSource from "./Image.js";
//# sourceMappingURL=ImageStatic.d.ts.map


text:
@interface UIViewController (XFAProperties)

@property (nonatomic,strong) NSMutableArray * xfaProperties;

@end


text:
package de.mxro.maven.tools;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;

import de.mxro.process.Spawn;

/**
 * Utility methods for working with Maven remote repositories.
 *
 * @author Max Rohde
 *
 */
public class MavenRemoteRepository {

    /**
     *

     * Downloads the maven-metadata.xml from a remote repository.
     *
     * @param repositoryUrl
     * @param destFolder
     *
     * @return true if xml file could be downloaded, false otherwise.
     * @throws IOException
     */
    public static boolean downloadRepositoryXml(final String repositoryUrl, final Path destFolder,
            final Dependency dependency) throws IOException {

        if (Files.exists(destFolder.resolve("maven-metadata.xml"))) {
            throw new RuntimeException("maven-metadata.xml file already existed in folder: " + destFolder);
        }

        final String path = repositoryUrl + dependency.groupId().replaceAll("\\.", "/") + "/" + dependency.artifactId()
                + "/maven-metadata.xml";
        final String output = Spawn.sh(destFolder.toFile(), "wget " + path);

        if (output.contains("ERROR 404") || output.contains("Not Found")) {

            return false;
        }

        if (output.contains("ERROR")) {
            System.out.println(output);
            throw new RuntimeException("Error while downloading repository index file from: " + path);
        }

        return true;

    }

    public static void createRepositoryXml(final String repositoryUrl, final Path destFolder, final Dependency dependency)
            throws IOException {
        final Path file = Files.createFile(destFolder.resolve("maven-metadata.xml"));

        String xml = "";
        xml += "<metadata>\n";
        xml += "  <groupId>" + dependency.groupId() + "</groupId>\n";
        xml += "  <artifactId>" + dependency.artifactId() + "</artifactId>\n";
        xml += "  <versioning>\n";
        xml += "    <release>0.0.0</release>\n";
        xml += "    <versions>\n";
        xml += "    </versions>\n";
        xml += "    <lastUpdated>00000</lastUpdated>\n";
        xml += "  </versioning>\n";
        xml += "</metadata>";

        Files.write(file, xml.getBytes("UTF-8"));
    }

    public static void assertVersionInRepositoryXml(final Path destFolder, final String newVersion) throws Exception {

        final Path mavenMetadata = destFolder.resolve("maven-metadata.xml");

        final byte[] mavenMetadataBytes = Files.readAllBytes(mavenMetadata);

        String mavenMetadataString = new String(mavenMetadataBytes, "UTF-8");

        if (!mavenMetadataString.contains(newVersion)) {
            final int versionsEndTagIndex = mavenMetadataString.indexOf("</versions>");
            mavenMetadataString = mavenMetadataString.substring(0, versionsEndTagIndex) + "\n         <version>"
                    + newVersion + "</version>\n" + mavenMetadataString.substring(versionsEndTagIndex);
        }

        final String lastChanged = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

        mavenMetadataString = mavenMetadataString.replaceAll("<lastUpdated>[^<]*</lastUpdated>", "<lastUpdated>"
                + lastChanged + "</lastUpdated>");

        mavenMetadataString = mavenMetadataString.replaceAll("<release>[^<]*</release>", "<release>" + newVersion
                + "</release>");

        Files.write(mavenMetadata, mavenMetadataString.getBytes("UTF-8"));

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yeamy.daily"
    android:installLocation="auto">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="UMENG_APPKEY"
            android:value="5693aae4e0f55a7829000ed0" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".DetailsActivity"
            android:label="@string/title_details"
            android:theme="@style/AppTheme.NoActionBar.NoOver" />
        <activity
            android:name=".AddActivity"
            android:label="@string/title_add"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustResize" />
        <activity
            android:name=".EditActivity"
            android:label="@string/title_edit"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustResize" />
        <activity
            android:name=".AboutActivity"
            android:label="@string/title_about"
            android:theme="@style/AppTheme.NoActionBar" />

        <receiver
            android:name=".MainWidgetProvider"
            android:process=":widget">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/main_widget_info" />
        </receiver>

        <service
            android:name=".MainWidgetService"
            android:exported="false"
            android:permission="android.permission.BIND_REMOTEVIEWS"
            android:process=":widget" />
    </application>

</manifest>


text:
"""A parser for Relay's text format."""
from __future__ import absolute_import

import sys

from collections import deque
from typing import TypeVar, Deque, Tuple, Optional, Union, NamedTuple, List, Callable, Any, Dict

import tvm

from . import module
from .base import Span, SourceName
from . import expr
from . import ty
from . import op

class ParseError(Exception):
    """Exception type for parse errors."""

    def __init__(self, message):
        # type: (str) -> None
        super(ParseError, self).__init__()
        self.message = message

PYTHON_VERSION = sys.version_info.major
try:
    from .grammar.py3.RelayVisitor import RelayVisitor
    from .grammar.py3.RelayParser import RelayParser
    from .grammar.py3.RelayLexer import RelayLexer
except ImportError:
    raise ParseError("Couldn't find ANTLR parser. Try building with USE_ANTLR=ON.")

try:
    from antlr4 import ParserRuleContext, InputStream, CommonTokenStream
    from antlr4.tree.Tree import TerminalNode
except ImportError:
    raise ParseError("Couldn't find ANTLR runtime." +
                     "Try running `pip{version} install antlr4-python{version}-runtime`."
                     .format(version=PYTHON_VERSION))

BINARY_OPS = {
    RelayParser.MUL: op.multiply,
    RelayParser.DIV: op.divide,
    RelayParser.ADD: op.add,
    RelayParser.SUB: op.subtract,
    RelayParser.LT:  op.less,
    RelayParser.GT:  op.greater,
    RelayParser.LE:  op.less_equal,
    RelayParser.GE:  op.greater_equal,
    RelayParser.EQ:  op.equal,
    RelayParser.NE:  op.not_equal,
}

TYPE_PREFIXES = [
    "int",
    "uint",
    "float",
    "bool",
]

T = TypeVar("T")
Scope = Deque[Tuple[str, T]]
Scopes = Deque[Scope[T]]

def lookup(scopes, name):
    # type: (Scopes[T], str) -> Optional[T]
    """Look up `name` in `scopes`."""

    for scope in scopes:
        for key, val in scope:
            if key == name:
                return val
    return None

def spanify(f):
    """A decorator which attaches span information
       to the value returned by calling `f`.

       Intended for use with the below AST visiting
       methods. The idea is that after we do the work
       of constructing the AST we attach Span information.
    """

    def _wrapper(*args, **kwargs):
        # Assumes 0th arg is self and gets source_name from object.
        sn = args[0].source_name
        # Assumes 1st arg is an ANTLR parser context.
        ctx = args[1]
        ast = f(*args, **kwargs)
        line, col = ctx.getSourceInterval()
        sp = Span(sn, line, col)
        ast.set_span(sp)
        return ast
    return _wrapper

# TODO(@jmp): Use https://stackoverflow.com/q/13889941
# to figure out how to get ANTLR4 to be more unhappy about syntax errors
class ParseTreeToRelayIR(RelayVisitor):
    """Parse Relay text format into Relay IR."""

    def __init__(self, source_name):
        # type: (str) -> None
        self.source_name = source_name
        self.module = module.Module({})   # type: module.Module

        # Adding an empty scope allows naked lets without pain.
        self.var_scopes = deque([deque()])          # type: Scopes[expr.Var]
        self.global_var_scope = deque()             # type: Scope[expr.GlobalVar]
        self.type_param_scopes = deque([deque()])   # type: Scopes[ty.TypeVar]
        self.graph_expr = []                        # type: List[expr.Expr]

        super(ParseTreeToRelayIR, self).__init__()

    def enter_var_scope(self):
        # type: () -> None
        """Enter a new Var scope so it can be popped off later."""

        self.var_scopes.appendleft(deque())

    def exit_var_scope(self):
        # type: () -> Scope[expr.Var]
        """Pop off the current Var scope and return it."""

        return self.var_scopes.popleft()

    def mk_var(self, name, type_):
        # type: (str, ty.Type) -> expr.Var
        """Create a new Var and add it to the Var scope."""

        var = expr.Var(name, type_)
        self.var_scopes[0].appendleft((name, var))
        return var

    def mk_global_var(self, name):
        # type: (str) -> expr.GlobalVar
        """Create a new GlobalVar and add it to the GlobalVar scope."""

        var = expr.GlobalVar(name)
        self.global_var_scope.append((name, var))
        return var

    def enter_type_param_scope(self):
        # type: () -> None
        """Enter a new TypeVar scope so it can be popped off later."""

        self.type_param_scopes.appendleft(deque())

    def exit_type_param_scope(self):
        # type: () -> Scope[ty.TypeVar]
        """Pop off the current TypeVar scope and return it."""

        return self.type_param_scopes.popleft()

    def mk_typ(self, name, kind):
        # (str, ty.Kind) -> ty.TypeVar
        """Create a new TypeVar and add it to the TypeVar scope."""

        typ = ty.TypeVar(name, kind)
        self.type_param_scopes[0].appendleft((name, typ))
        return typ

    def visitTerminal(self, node):
        # type: (TerminalNode) -> Union[expr.Expr, int, float]
        """Visit lexer tokens that aren't ignored or visited by other functions."""

        node_type = node.getSymbol().type
        node_text = node.getText()
        name = node_text[1:]

        # variables
        if node_type == RelayLexer.GLOBAL_VAR:
            return lookup(deque([self.global_var_scope]), node_text[1:])
        if node_type == RelayLexer.LOCAL_VAR:
            # Remove the leading '%' and lookup the name.
            var = lookup(self.var_scopes, name)
            if var is None:
                raise ParseError("Couldn't resolve `{}`.".format(name))
            return var
        if node_type == RelayLexer.GRAPH_VAR:
            try:
                return self.graph_expr[int(name)]
            except IndexError:
                raise ParseError("Couldn't resolve `{}`".format(name))

        # data types
        if node_type == RelayLexer.NAT:
            return int(node_text)
        if node_type == RelayLexer.FLOAT:
            return float(node_text[:-1])
        if node_type == RelayLexer.BOOL_LIT:
            if node_text == "True":
                return True
            if node_text == "False":
                return False
            raise ParseError("Unrecognized BOOL_LIT: `{}`".format(node_text))

        raise ParseError("todo: {}".format(node_text))

    def visit_list(self, ctx_list):
        # type: (List[ParserRuleContext]) -> List[Any]
        """"Visit a list of contexts."""

        return [self.visit(ctx) for ctx in ctx_list]

    def getType_(self, ctx):
        # type: (Optional[RelayParser.Type_Context]) -> Optional[ty.Type]
        """Return a (possibly None) Relay type."""

        if ctx is None:
            return None

        return self.visit(ctx)

    def visitProg(self, ctx):
        # type: (RelayParser.ProgContext) -> Union[expr.Expr, module.Module]
        if ctx.defn():
            self.visit_list(ctx.defn())
            return self.module

        if ctx.expr():
            return self.visit(ctx.expr())

        return self.module

    # Exprs
    def visitOpIdent(self, ctx):
        # type: (RelayParser.OpIdentContext) -> op.Op
        return op.get(ctx.CNAME().getText())

    # pass through
    def visitParens(self, ctx):
        # type: (RelayParser.ParensContext) -> expr.Expr
        return self.visit(ctx.expr())

    # pass through
    def visitBody(self, ctx):
        # type: (RelayParser.BodyContext) -> expr.Expr
        return self.visit(ctx.expr())

    def visitScalarFloat(self, ctx):
        # type: (RelayParser.ScalarFloatContext) -> expr.Constant
        return expr.const(self.visit(ctx.FLOAT()))

    def visitScalarInt(self, ctx):
        # type: (RelayParser.ScalarIntContext) -> expr.Constant
        return expr.const(self.visit(ctx.NAT()))

    def visitScalarBool(self, ctx):
        # type: (RelayParser.ScalarBoolContext) -> expr.Constant
        return expr.const(self.visit(ctx.BOOL_LIT()))

    def visitNeg(self, ctx):
        # type: (RelayParser.NegContext) -> Union[expr.Constant, expr.Call]
        val = self.visit(ctx.expr())
        if isinstance(val, expr.Constant) and val.data.asnumpy().ndim == 0:
            # fold Neg in for scalars
            return expr.const(-val.data.asnumpy().item())

        return op.negative(val)

    def visitTuple(self, ctx):
        # type: (RelayParser.TupleContext) -> expr.Tuple
        tup = self.visit_list(ctx.expr())
        return expr.Tuple(tup)

    # Currently doesn't support mutable sequencing.
    def visitLet(self, ctx):
        # type: (RelayParser.SeqContext) -> expr.Let
        """Desugar various sequence constructs to Relay Let nodes."""
        if ctx.MUT() is not None:
            raise ParseError("Mutation is currently unsupported.")

        if ctx.var() is None or ctx.var().ident() is None:
            # anonymous identity
            ident = "_"
            type_ = None
        else:
            local_var = ctx.var().ident().LOCAL_VAR()
            if local_var is None:
                raise ParseError("Only local ids may be used in `let`s.")
            ident = local_var.getText()[1:]
            type_ = self.getType_(ctx.var().type_())

        var = self.mk_var(ident, type_)

        self.enter_var_scope()
        value = self.visit(ctx.expr(0))
        self.exit_var_scope()

        body = self.visit(ctx.expr(1))

        return expr.Let(var, value, body)

    def visitBinOp(self, ctx):
        # type: (RelayParser.BinOpContext) -> expr.Call
        """Desugar binary operators."""
        arg0, arg1 = self.visit_list(ctx.expr())
        relay_op = BINARY_OPS.get(ctx.op.type)

        if relay_op is None:
            raise ParseError("Unimplemented binary op.")

        return relay_op(arg0, arg1)

    @spanify
    def visitVar(self, ctx):
        # type: (RelayParser.VarContext) -> expr.Var
        """Visit a single variable."""
        ident = ctx.ident().LOCAL_VAR()

        if ident is None:
            raise ParseError("Only local ids may be used in vars.")

        type_ = self.getType_(ctx.type_())

        return self.mk_var(ident.getText()[1:], type_)

    def visitVarList(self, ctx):
        # type: (RelayParser.VarListContext) -> List[expr.Var]
        return self.visit_list(ctx.var())

    # TODO: support a larger class of values than just Relay exprs
    def visitAttr(self, ctx):
        # type: (RelayParser.AttrContext) -> Tuple[str, expr.Expr]
        return (ctx.CNAME().getText(), self.visit(ctx.expr()))

    def visitAttrList(self, ctx):
        # type: (RelayParser.AttrListContext) -> Dict[str, expr.Expr]
        return dict(self.visit_list(ctx.attr()))

    def visitArgList(self,
                     ctx    # type: RelayParser.ArgListContext
                    ):
        # type: (...) -> Tuple[Optional[List[expr.Var]], Optional[Dict[str, expr.Expr]]]
        var_list = self.visit(ctx.varList()) if ctx.varList() else None
        attr_list = self.visit(ctx.attrList()) if ctx.attrList() else None

        return (var_list, attr_list)

    def mk_func(self, ctx):
        # type: (Union[RelayParser.FuncContext, RelayParser.DefnContext]) -> expr.Function
        """Construct a function from either a Func or Defn."""

        # Enter var scope early to put params in scope.
        self.enter_var_scope()
        # Capture type params in params.
        self.enter_type_param_scope()
        type_params = ctx.typeParamSeq()

        if type_params is not None:
            type_params = type_params.ident()
            assert type_params
            for ty_param in type_params:
                name = ty_param.getText()
                self.mk_typ(name, ty.Kind.Type)

        var_list, attr_list = self.visit(ctx.argList())
        if var_list is None:
            var_list = []
        ret_type = self.getType_(ctx.type_())

        body = self.visit(ctx.body())
        # NB(@jroesch): you must stay in the type parameter scope until
        # after you exit the body, you can reference the type parameters
        # of your parent scopes.
        type_params = list(self.exit_type_param_scope())
        if type_params:
            _, type_params = zip(*type_params)
        self.exit_var_scope()

        attrs = tvm.make.node("DictAttrs", **attr_list) if attr_list is not None else None
        return expr.Function(var_list, body, ret_type, type_params, attrs)

    @spanify
    def visitFunc(self, ctx):
        # type: (RelayParser.FuncContext) -> expr.Function
        return self.mk_func(ctx)

    # TODO: how to set spans for definitions?
    # @spanify
    def visitDefn(self, ctx):
        # type: (RelayParser.DefnContext) -> None
        ident = ctx.ident().GLOBAL_VAR()
        if ident is None:
            raise ParseError("Only global ids may be used in `def`s.")
        ident_name = ident.getText()[1:]
        ident = self.mk_global_var(ident_name)

        self.module[ident] = self.mk_func(ctx)

    @spanify
    def visitCall(self, ctx):
        # type: (RelayParser.CallContext) -> expr.Call
        visited_exprs = self.visit_list(ctx.expr())

        func = visited_exprs[0]
        args = visited_exprs[1:]

        return expr.Call(func, args, None, None)

    @spanify
    def visitIfElse(self, ctx):
        # type: (RelayParser.IfElseContext) -> expr.If
        """Construct a Relay If node. Creates a new scope for each branch."""
        cond = self.visit(ctx.expr())

        self.enter_var_scope()
        true_branch = self.visit(ctx.body(0))
        self.exit_var_scope()

        self.enter_var_scope()
        false_branch = self.visit(ctx.body(1))
        self.exit_var_scope()

        return expr.If(cond, true_branch, false_branch)

    @spanify
    def visitGraph(self, ctx):
        # type: (RelayParser.GraphContext) -> expr.Expr
        """Visit a graph variable assignment."""
        if ctx.ident().GRAPH_VAR() is None:
            raise ParseError("Expected a graph var, but got `{}`".format(ctx.ident().getText()))
        graph_nid = int(ctx.ident().GRAPH_VAR().getText()[1:])

        self.enter_var_scope()
        value = self.visit(ctx.expr(0))
        self.exit_var_scope()

        if graph_nid != len(self.graph_expr):
            raise ParseError(
                "Expected new graph variable to be `%{}`,".format(len(self.graph_expr)) + \
                "but got `%{}`".format(graph_nid))
        self.graph_expr.append(value)

        kont = self.visit(ctx.expr(1))
        return kont

    # Types

    # pylint: disable=unused-argument
    def visitIncompleteType(self, ctx):
        # type (RelayParser.IncompleteTypeContext) -> None:
        return None

    def visitTypeIdent(self, ctx):
        # type: (RelayParser.TypeIdentContext) -> Union[ty.TensorType, str]
        '''
        Handle type identifier.
        '''
        type_ident = ctx.CNAME().getText()

        # Look through all type prefixes for a match
        for type_prefix in TYPE_PREFIXES:
            if type_ident.startswith(type_prefix):
                return ty.scalar_type(type_ident)

        type_param = lookup(self.type_param_scopes, type_ident)
        if type_param is not None:
            return type_param

        raise ParseError("Unknown builtin type: {}".format(type_ident))

    # def visitCallType(self, ctx):
    #     # type: (RelayParser.CallTypeContext) -> Union[expr.Expr, ty.TensorType]
    #     ident_type = ctx.identType().CNAME().getText()

    #     args = self.visit_list(ctx.type_())

    #     if not args:
    #         raise ParseError("Type-level functions must have arguments!")

    #     func_type = TYPE_FUNCS.get(ident_type)(args)

    #     if func_type is None:
    #         raise ParseError("Unknown type-level function: `{}`".format(ident_type))
    #     else:
    #         return func_type

    def visitParensShape(self, ctx):
        # type: (RelayParser.ParensShapeContext) -> int
        return self.visit(ctx.shape())

    def visitShapeSeq(self, ctx):
        # type: (RelayParser.ShapeSeqContext) -> List[int]
        return self.visit_list(ctx.shape())

    def visitTensorType(self, ctx):
        # type: (RelayParser.TensorTypeContext) -> ty.TensorType
        """Create a simple tensor type. No generics."""

        shape = self.visit(ctx.shapeSeq())
        dtype = self.visit(ctx.type_())

        if not isinstance(dtype, ty.TensorType):
            raise ParseError("Expected dtype to be a Relay base type.")

        dtype = dtype.dtype

        return ty.TensorType(shape, dtype)

    def visitTupleType(self, ctx):
        # type: (RelayParser.TupleTypeContext) -> ty.TupleType
        return ty.TupleType(self.visit_list(ctx.type_()))

    def visitFuncType(self, ctx):
        # type: (RelayParser.FuncTypeContext) -> ty.FuncType
        types = self.visit_list(ctx.type_())

        arg_types = types[:-1]
        ret_type = types[-1]

        return ty.FuncType(arg_types, ret_type, [], None)

def make_parser(data):
    # type: (str) -> RelayParser
    """Construct a RelayParser a given data stream."""
    input_stream = InputStream(data)
    lexer = RelayLexer(input_stream)
    token_stream = CommonTokenStream(lexer)
    return RelayParser(token_stream)

__source_name_counter__ = 0

def fromtext(data, source_name=None):
    # type: (str, str) -> Union[expr.Expr, module.Module]
    """Parse a Relay program."""
    if data == "":
        raise ParseError("Cannot parse the empty string.")

    global __source_name_counter__

    if source_name is None:
        source_name = "source_file{0}".format(__source_name_counter__)

    if isinstance(source_name, str):
        source_name = SourceName(source_name)

    tree = make_parser(data).prog()
    return ParseTreeToRelayIR(source_name).visit(tree)


text:
class Menu < ActiveRecord::Base
  belongs_to :merchant
  has_many :menu_items

  validates_presence_of :name, :merchant
end


text:
package mil.nga.giat.geowave.format.gpx;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import javax.xml.stream.XMLStreamException;

import mil.nga.giat.geowave.adapter.vector.ingest.AbstractSimpleFeatureIngestPlugin;
import mil.nga.giat.geowave.adapter.vector.utils.SimpleFeatureUserDataConfigurationSet;
import mil.nga.giat.geowave.core.geotime.store.dimension.GeometryWrapper;
import mil.nga.giat.geowave.core.geotime.store.dimension.Time;
import mil.nga.giat.geowave.core.index.ByteArrayId;
import mil.nga.giat.geowave.core.ingest.GeoWaveData;
import mil.nga.giat.geowave.core.ingest.IngestPluginBase;
import mil.nga.giat.geowave.core.ingest.hdfs.mapreduce.IngestWithMapper;
import mil.nga.giat.geowave.core.ingest.hdfs.mapreduce.IngestWithReducer;
import mil.nga.giat.geowave.core.store.CloseableIterator;
import mil.nga.giat.geowave.core.store.index.CommonIndexValue;
import mil.nga.giat.geowave.core.store.index.PrimaryIndex;

import org.apache.avro.Schema;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.xml.sax.SAXException;

/**
 * This plugin is used for ingesting any GPX formatted data from a local file
 * system into GeoWave as GeoTools' SimpleFeatures. It supports the default
 * configuration of spatial and spatial-temporal indices and it will support
 * wither directly ingesting GPX data from a local file system to GeoWave or to
 * stage the data in an intermediate format in HDFS and then to ingest it into
 * GeoWave using a map-reduce job. It supports OSM metadata.xml files if the
 * file is directly in the root base directory that is passed in command-line to
 * the ingest framework.
 */
public class GpxIngestPlugin extends
		AbstractSimpleFeatureIngestPlugin<GpxTrack>
{

	private final static Logger LOGGER = Logger.getLogger(GpxIngestPlugin.class);

	private final static String TAG_SEPARATOR = " ||| ";

	private Map<Long, GpxTrack> metadata = null;
	private static final AtomicLong currentFreeTrackId = new AtomicLong(
			0);

	public GpxIngestPlugin() {}

	@Override
	public String[] getFileExtensionFilters() {
		return new String[] {
			"xml",
			"gpx"
		};
	}

	@Override
	public void init(
			final File baseDirectory ) {
		final File f = new File(
				baseDirectory,
				"metadata.xml");
		if (!f.exists()) {
			LOGGER.info("No metadata file found - looked at: " + f.getAbsolutePath());
			LOGGER.info("No metadata will be loaded");
		}
		else {
			try {
				long time = System.currentTimeMillis();
				metadata = GpxUtils.parseOsmMetadata(f);
				time = System.currentTimeMillis() - time;
				final String timespan = String.format(
						"%d min, %d sec",
						TimeUnit.MILLISECONDS.toMinutes(time),
						TimeUnit.MILLISECONDS.toSeconds(time)
								- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)));
				LOGGER.info("Metadata parsed in in " + timespan + " for " + metadata.size() + " tracks");
			}
			catch (final XMLStreamException | FileNotFoundException e) {
				LOGGER.warn(
						"Unable to read OSM metadata file: " + f.getAbsolutePath(),
						e);
			}
		}

	}

	@Override
	public boolean supportsFile(
			final File file ) {
		// if its a gpx extension assume it is supported
		if (file.getName().toLowerCase(
				Locale.ENGLISH).endsWith(
				"gpx")) {
			return true;
		}
		if ("metadata.xml".equals(file.getName())) {
			return false;
		}
		// otherwise take a quick peek at the file to ensure it matches the GPX
		// schema
		try {
			return GpxUtils.validateGpx(file);
		}
		catch (SAXException | IOException e) {
			LOGGER.warn(
					"Unable to read file:" + file.getAbsolutePath(),
					e);
		}
		return false;
	}

	@Override
	protected SimpleFeatureType[] getTypes() {
		return new SimpleFeatureType[] {
			SimpleFeatureUserDataConfigurationSet.configureType(GPXConsumer.pointType),
			SimpleFeatureUserDataConfigurationSet.configureType(GPXConsumer.waypointType),
			SimpleFeatureUserDataConfigurationSet.configureType(GPXConsumer.trackType),
			SimpleFeatureUserDataConfigurationSet.configureType(GPXConsumer.routeType)
		};
	}

	@Override
	public Schema getAvroSchema() {
		return GpxTrack.getClassSchema();
	}

	@Override
	public GpxTrack[] toAvroObjects(
			final File input ) {
		GpxTrack track = null;
		if (metadata != null) {
			try {
				final long id = Long.parseLong(FilenameUtils.removeExtension(input.getName()));
				track = metadata.remove(id);
			}
			catch (final NumberFormatException e) {
				LOGGER.info("OSM metadata found, but track file name is not a numeric ID");
			}
		}
		if (track == null) {
			track = new GpxTrack();
			track.setTrackid(currentFreeTrackId.getAndIncrement());
		}

		try {
			track.setGpxfile(ByteBuffer.wrap(Files.readAllBytes(input.toPath())));
		}
		catch (final IOException e) {
			LOGGER.warn(
					"Unable to read GPX file: " + input.getAbsolutePath(),
					e);
		}

		return new GpxTrack[] {
			track
		};
	}

	@Override
	public boolean isUseReducerPreferred() {
		return false;
	}

	@Override
	public IngestWithMapper<GpxTrack, SimpleFeature> ingestWithMapper() {
		return new IngestGpxTrackFromHdfs(
				this);
	}

	@Override
	public IngestWithReducer<GpxTrack, ?, ?, SimpleFeature> ingestWithReducer() {
		// unsupported right now
		throw new UnsupportedOperationException(
				"GPX tracks cannot be ingested with a reducer");
	}

	@Override
	protected CloseableIterator<GeoWaveData<SimpleFeature>> toGeoWaveDataInternal(
			final GpxTrack gpxTrack,
			final Collection<ByteArrayId> primaryIndexIds,
			final String globalVisibility ) {
		final InputStream in = new ByteArrayInputStream(
				gpxTrack.getGpxfile().array());
		// LOGGER.debug("Processing track [" + gpxTrack.getTimestamp() + "]");
		try {
			return new GPXConsumer(
					in,
					primaryIndexIds,
					gpxTrack.getTrackid() == null ? "" : gpxTrack.getTrackid().toString(),
					getAdditionalData(gpxTrack),
					false, // waypoints, even dups, are unique, due to QGis
							// behavior
					globalVisibility);
		}
		catch (final Exception e) {
			LOGGER.warn(
					"Unable to convert GpxTrack to GeoWaveData",
					e);
			return null;
		}
	}

	@Override
	public PrimaryIndex[] getRequiredIndices() {
		return new PrimaryIndex[] {};
	}

	private Map<String, Map<String, String>> getAdditionalData(
			final GpxTrack gpxTrack ) {
		final Map<String, Map<String, String>> pathDataSet = new HashMap<String, Map<String, String>>();
		final Map<String, String> dataSet = new HashMap<String, String>();
		pathDataSet.put(
				"gpx.trk",
				dataSet);

		if (gpxTrack.getTrackid() != null) {
			dataSet.put(
					"TrackId",
					gpxTrack.getTrackid().toString());
		}
		if (gpxTrack.getUserid() != null) {
			dataSet.put(
					"UserId",
					gpxTrack.getUserid().toString());
		}
		if (gpxTrack.getUser() != null) {
			dataSet.put(
					"User",
					gpxTrack.getUser().toString());
		}
		if (gpxTrack.getDescription() != null) {
			dataSet.put(
					"Description",
					gpxTrack.getDescription().toString());
		}

		if ((gpxTrack.getTags() != null) && (gpxTrack.getTags().size() > 0)) {
			final String tags = org.apache.commons.lang.StringUtils.join(
					gpxTrack.getTags(),
					TAG_SEPARATOR);
			dataSet.put(
					"Tags",
					tags);
		}
		else {
			dataSet.put(
					"Tags",
					null);
		}
		return pathDataSet;
	}

	public static class IngestGpxTrackFromHdfs extends
			AbstractIngestSimpleFeatureWithMapper<GpxTrack>
	{
		public IngestGpxTrackFromHdfs() {
			this(
					new GpxIngestPlugin());
			// this constructor will be used when deserialized
		}

		public IngestGpxTrackFromHdfs(
				final GpxIngestPlugin parentPlugin ) {
			super(
					parentPlugin);
		}
	}

	@Override
	public IngestPluginBase<GpxTrack, SimpleFeature> getIngestWithAvroPlugin() {
		return new IngestGpxTrackFromHdfs(
				this);
	}

	@Override
	public Class<? extends CommonIndexValue>[] getSupportedIndexableTypes() {
		return new Class[] {
			GeometryWrapper.class,
			Time.class
		};
	}

}


text:
package org.sakaiproject.component.app.messageforums.dao.hibernate;

import lombok.extern.slf4j.Slf4j;

import org.sakaiproject.api.app.messageforums.OpenTopic;

@Slf4j
public class OpenTopicImpl extends TopicImpl implements OpenTopic {

    private Boolean locked;
    private Boolean draft;

    public Boolean getLocked() {
        return locked;
    }

    public void setLocked(Boolean locked) {
        this.locked = locked;
    }

    public Boolean getDraft() {
        return draft;
    }

    public void setDraft(Boolean draft) {
        this.draft = draft;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea macrophylla var. platycarpa

### Remarks
null


text:
      View Archive
      |

         Save

      |

       Expand

  Only the previous {{options.tailLines || 5000}} log lines and new log
  messages will be displayed because of the large log size.

  <ellipsis-pulser ng-if="!chromeless" color="dark" size="sm" display="inline" msg="Loading log" class="log-pending-ellipsis"></ellipsis-pulser>
  <ellipsis-pulser ng-if="chromeless" color="light" size="sm" display="inline" msg="Loading log" class="log-pending-ellipsis"></ellipsis-pulser>

Logs are not available.

    {{emptyStateMessage}}

    View Archive

        Follow
        Stop Following

        Go to End

        End of log

    <ellipsis-pulser color="light" size="md" ng-show="loading"></ellipsis-pulser>

      Go to Top

  The maximum web console log size has been reached. Use the command-line interface or
  reload the log to see new messages.

  An error occurred loading the log.
  Reload


text:
package org.jsoup.parser;

import org.jsoup.helper.Validate;
import org.jsoup.nodes.*;

import java.util.Iterator;
import java.util.List;

/**
 * @author Jonathan Hedley
 */
public class XmlTreeBuilder extends TreeBuilder {
    @Override
    protected void initialiseParse(String input, String baseUri, ParseErrorList errors) {
        super.initialiseParse(input, baseUri, errors);
        stack.add(doc); // place the document onto the stack. differs from HtmlTreeBuilder (not on stack)
    }

    @Override
    protected boolean process(Token token) {
        // start tag, end tag, doctype, comment, character, eof
        switch (token.type) {
            case StartTag:
                insert(token.asStartTag());
                break;
            case EndTag:
                popStackToClose(token.asEndTag());
                break;
            case Comment:
                insert(token.asComment());
                break;
            case Character:
                insert(token.asCharacter());
                break;
            case Doctype:
                insert(token.asDoctype());
                break;
            case EOF: // could put some normalisation here if desired
                break;
            default:
                Validate.fail("Unexpected token type: " + token.type);
        }
        return true;
    }

    private void insertNode(Node node) {
        currentElement().appendChild(node);
    }

    Element insert(Token.StartTag startTag) {
        Tag tag = Tag.valueOf(startTag.name());
        // todo: wonder if for xml parsing, should treat all tags as unknown? because it's not html.
        Element el = new Element(tag, baseUri, startTag.attributes, startTag.getPos());
        insertNode(el);
        if (startTag.isSelfClosing()) {
            tokeniser.acknowledgeSelfClosingFlag();
            if (!tag.isKnownTag()) // unknown tag, remember this is self closing for output. see above.
                tag.setSelfClosing();
        } else {
            stack.add(el);
        }
        return el;
    }

    void insert(Token.Comment commentToken) {
        Comment comment = new Comment(commentToken.getData(), baseUri, commentToken.getPos());
        Node insert = comment;
        if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml)
            String data = comment.getData();
            if (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))) {
                String declaration = data.substring(1);
                insert = new XmlDeclaration(declaration, comment.baseUri(), data.startsWith("!"), comment.getOffset());
            }
        }
        insertNode(insert);
    }

    void insert(Token.Character characterToken) {
        Node node = new TextNode(characterToken.getData(), baseUri);
        insertNode(node);
    }

    void insert(Token.Doctype d) {
        DocumentType doctypeNode = new DocumentType(d.getName(), d.getPublicIdentifier(), d.getSystemIdentifier(), baseUri, d.getPos());
        insertNode(doctypeNode);
    }

    /**
     * If the stack contains an element with this tag's name, pop up the stack to remove the first occurrence. If not
     * found, skips.
     *
     * @param endTag
     */
    private void popStackToClose(Token.EndTag endTag) {
        String elName = endTag.name();
        Element firstFound = null;

        Iterator<Element> it = stack.descendingIterator();
        while (it.hasNext()) {
            Element next = it.next();
            if (next.nodeName().equals(elName)) {
                firstFound = next;
                break;
            }
        }
        if (firstFound == null)
            return; // not found, skip

        it = stack.descendingIterator();
        while (it.hasNext()) {
            Element next = it.next();
            if (next == firstFound) {
                it.remove();
                break;
            } else {
                it.remove();
            }
        }
    }

    List<Node> parseFragment(String inputFragment, String baseUri, ParseErrorList errors) {
        initialiseParse(inputFragment, baseUri, errors);
        runParser();
        return doc.childNodes();
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {Tensor, TypedTensor} from './tensor';

interface Properties {
  /**
   * Get the number of elements in the tensor.
   */
  readonly size: number;
}

export interface TypedShapeUtils<T extends Tensor.Type> {
  /**
   * Create a new tensor with the same data buffer and specified dims.
   *
   * @param dims - New dimensions. Size should match the old one.
   */
  reshape(dims: readonly number[]): TypedTensor<T>;
}

// TODO: add more tensor utilities
export interface TypedTensorUtils<T extends Tensor.Type> extends Properties, TypedShapeUtils<T> {}


text: export { default } from './Expertise'


text:
import React from 'react'
import ReactDOM from 'react-dom'
import { Form, Field } from 'src'

class EditUser extends React.Component {

  constructor() {
    super()
    this.state = {}
  }

  componentWillMount() {
    // Simulate network latency
    setTimeout(() => {
      this.setState({
        email: 'example@example.com',
        password: 'abc123'
      })
    }, 500)
  }

  render() {
    return (
      <Form>
        <Field name="email" component="input" value={this.state.email}/>

        <Field name="password" type="password" component="input" value={this.state.password}/>

        <button type="submit">Submit</button>
      </Form>
    )
  }
}

ReactDOM.render(<EditUser />, document.getElementById('root'))


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CompressedStreamReader (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.streaming.compress

Class CompressedStreamReader

java.lang.Object

org.apache.cassandra.streaming.StreamReader

org.apache.cassandra.streaming.compress.CompressedStreamReader

public class CompressedStreamReader
extends StreamReader

StreamReader that reads from streamed compressed SSTable

Field Summary

Fields

Modifier and Type
Field and Description

protected CompressionInfo
compressionInfo

Fields inherited from class org.apache.cassandra.streaming.StreamReader

cfId, desc, estimatedKeys, inputVersion, sections, session

Constructor Summary

Constructors

Constructor and Description

CompressedStreamReader(FileMessageHeader header,
                      StreamSession session)

Method Summary

Methods

Modifier and Type
Method and Description

SSTableWriter
read(java.nio.channels.ReadableByteChannel channel)

protected long
totalSize()

Methods inherited from class org.apache.cassandra.streaming.StreamReader

createWriter, drain, writeRow

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

compressionInfo

protected final CompressionInfo compressionInfo

Constructor Detail

CompressedStreamReader

public CompressedStreamReader(FileMessageHeader header,
                      StreamSession session)

Method Detail

read

public SSTableWriter read(java.nio.channels.ReadableByteChannel channel)
                   throws java.io.IOException

Overrides:

read in class StreamReader

Parameters:

channel - where this reads data from

Returns:

SSTable transferred

Throws:

java.io.IOException - if reading the remote sstable fails. Will throw an RTE if local write fails.

totalSize

protected long totalSize()

Overrides:

totalSize in class StreamReader

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015 The Apache Software Foundation


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ListIP : MonoBehaviour {

	public static string ipAddress="";
	public static string otherIPAddress="";
	public InputField ipField;
	public InputField otherField;

	public GameObject requestPage;
	public GameObject requestMenu;
	public GameObject mainMenu;
	public GameObject loginPage;
	public GameObject title;
	public static GameObject selfIP;

	private bool found = false;

	private int activeLevel=0;
	private GameObject activeLevelObj;
	// Use this for initialization
	void Start () {
		DontDestroyOnLoad(GameObject.Find("PlatformManager_Dev"));
		DontDestroyOnLoad(GameObject.Find("OSCHandler_Developer"));
		DontDestroyOnLoad (gameObject);
//		Application.LoadLevelAdditive ("MainMenu");
//		Application.LoadLevelAdditive ("LoginPage");
//		Application.LoadLevelAdditive ("RequestPage");
//		Application.LoadLevelAdditive ("RequestMenu");
		selfIP = this.gameObject;
		//InvokeRepeating ("FindLevels", 0.1f, 0.1f);
	}

	// Update is called once per frame
	void Update () {

//		if (Input.GetMouseButtonDown (0)) {
//			Application.LoadLevel ("MainMenu");
		//}

	}

	public void SwitchLevel(int activeLevel)
	{
		activeLevelObj.SetActive (false);
		switch (activeLevel) {

		case 1:
			mainMenu.SetActive (true);
			activeLevelObj = mainMenu;
			break;
		case 2:
			loginPage.SetActive (true);
			activeLevelObj = loginPage;
			break;
		case 3:
			requestMenu.SetActive (true);
			activeLevelObj = requestMenu;
			break;
		case 4:
			requestPage.SetActive (true);
			activeLevelObj = requestPage;
			break;
		}

	}

	void FindLevels()
	{
		if (!found) {
			if (requestPage == null)
				requestPage = GameObject.Find ("RequestPage");
			else if (requestMenu == null)
				requestMenu = GameObject.Find ("RequestMenu");
			else if (loginPage == null)
				loginPage = GameObject.Find ("LoginPage");
			else if (mainMenu == null)
				mainMenu = GameObject.Find ("MainMenu");
			else if (title == null)
				title = GameObject.Find ("Title");
			else
				found = true;

		requestPage.SetActive (false);
		loginPage.SetActive (false);
		requestMenu.SetActive (false);
		mainMenu.SetActive (false);
		activeLevelObj = title;
		}
	}

	public void OnEnterApp()
	{
		ipAddress = ipField.text.ToString ();
		otherIPAddress = otherField.text.ToString ();
	//	SwitchLevel (1);
		if (PlatformManager_Dev.platformVersion == 2)
			Application.LoadLevel ("MainMenu");
		else
			Application.LoadLevel ("MainMenu");
	}
}


text: exports.WatchList = require('./watch_list');


text:
"use strict";
module.exports = function(ngModule){
	ngModule.controller('CaseListCtrl', function(CaseService, AppConfig, ModalService, $filter, Loader) {
		var vm  = this;
		vm.searchParams = {};
		var getList = function() {
			var parameterFilter = $filter('parameterFilter');
			var params = parameterFilter.getQueryParams(vm.searchParams, vm.pager);
			Loader.show();
			CaseService.list(params).then(function(data) {
				var result = data.response.data;
        vm.list = result.data;
        vm.pager.total = result.count;
				Loader.hide();
			}, function(error) {
				Loader.hide();
				ModalService.alert(error.response.error);
			});
		};
		_.extend(vm, {
			pager: angular.copy(AppConfig.PAGER),
			pageChanged: function() {
          getList();
      },
			search: function() {
				vm.pager.page = 1;
				getList();
			},
			remove: function(id) {
				ModalService.alert('确定要删除此记录?').then(function() {
          Loader.show();
					CaseService.remove(id).then(function() {
            Loader.hide();
            ModalService.alert('删除成功').then(function(){
							vm.search();
						});
					}, function () {
						ModalService.popupMessage('删除失败');
					});
				});
			},
			view: function(id) {
				console.log(id);
				ModalService.show({
					title: '查看案例',
          okButtonLabel: '添加',
          cancelButtonLabel: "取消",
          cancelCls: 'btn btn-default',
          okCls: 'btn btn-primary',
          html: require('./../templates/popup/case-view.jade'),
          controller: "PopupCaseViewCtrl as vm",
					size: 'lg'
				}, {
					id: id
				});

			}
		});
		vm.search();
	});
};