text:
package opennlp.scalabha.cluster

import org.apache.commons.logging.LogFactory
import org.apache.log4j.Logger
import org.apache.log4j.Level

import opennlp.scalabha.util.CollectionUtil._

/**
 * A class for computing clusters for a set of points using k-means (specifically, Lloyd's algorithm).
 *
 * @param points	the set of points to be clustered
 * @param distance  the DistanceFunction to use to compute distance between pairs of points
 * @param maxChangeInDispersion each iteration of the algorithm produces a dispersion value, which is the squared sum distance from each centroid to the points it is responsible for. The minChangeInDispersion is a value that tells the algorithm to stop when change from one iteration to the next is less than this value.
 * @param maxIterations the maximum number of iterations to run k-means for
 */
class Kmeans(
  points: IndexedSeq[Point],
  distance: DistanceFunction,
  minChangeInDispersion: Double = 0.0001,
  maxIterations: Int = 100) {

  private val LOG = LogFactory.getLog(Kmeans.getClass)

  private[this] val numDimensions = points.head.numDimensions
  private[this] val origin = Point(IndexedSeq.fill(numDimensions)(0.0))

  // Actually, this should be "truly" random, but it is seeded with 13 to
  // ensure consistency for homework. See the commented out line for a seed
  // based on the current time.
  private[this] val random = new util.Random(13)
  //private[this] val random = new util.Random(compat.Platform.currentTime)

  /**
   * Run the k-means algorithm on this set of points for some given k.
   *
   * @param k The number of clusters to produce.
   * @param restarts The number of times to run k-means from different random starting points.
   * @return A pair, the first element of which is the dispersion for the best set of centroids found, and the second element of which is that set of centroids.
   */
  def run(k: Int, restarts: Int = 25): (Double, IndexedSeq[Point]) = {
    val runResults = (1 to restarts).map { _ =>
      moveCentroids(chooseRandomCentroids(k))
    }

    val (bestDispersion, bestCentroids) = runResults.minBy(_._1)

    LOG.debug("Dispersion: " + bestDispersion)
    LOG.debug("Centroids: ")
    if (LOG.isDebugEnabled)
      bestCentroids.foreach(println)

    (bestDispersion, bestCentroids)
  }

  /**
   * Run the k-means algorithm starting from the given set of centroids.
   *
   * @return A pair, the first element of which is the dispersion for the best set of centroids found, and the second element of which is that set of centroids.
   */
  def moveCentroids(centroids: IndexedSeq[Point]): (Double, IndexedSeq[Point]) = {

    // Inner recursive function for computing next centroids
    def inner(centroids: IndexedSeq[Point],
      lastDispersion: Double,
      iteration: Int): (Double, IndexedSeq[Point]) = {

      LOG.debug("Iteration " + iteration)

      val (dispersion, memberships) = computeClusterMemberships(centroids)
      val updatedCentroids = computeCentroids(memberships)

      LOG.debug("Dispersion: " + dispersion)
      LOG.debug("Centroids: ")
      if (LOG.isDebugEnabled)
        updatedCentroids.foreach(println)

      val dispersionChange = lastDispersion - dispersion

      if (iteration > maxIterations || dispersionChange < minChangeInDispersion)
        (lastDispersion, centroids)
      else
        inner(updatedCentroids, dispersion, iteration + 1)
    }

    inner(centroids, Double.PositiveInfinity, 1)
  }

  /**
   *  Given a sequence of centroids, compute the cluster memberships for each point.
   *
   *  @param centroids A set of points representing centroids.
   *  @return A pair, the first element of which is the dispersion given these centroids, and the second of which is the list of centroid indices for each of the points being clustered (based on the nearest centroid to each).
   */
  def computeClusterMemberships(centroids: IndexedSeq[Point]) = {
    val (squaredDistances, memberships) = points.map { point =>
      val distances = centroids.map(distance(_, point))
      val shortestDistance = distances.min
      val closestCentroid = distances.indexWhere(shortestDistance==)
      (shortestDistance * shortestDistance, closestCentroid)
    }.unzip
    (squaredDistances.sum, memberships)
  }

  /**
   *  Given memberships for each point, compute the centroid for each cluster.
   */
  private[this] def computeCentroids(memberships: IndexedSeq[Int]) = {
    memberships.zip(points)
      .groupByKey
      .mapValues(group => group.reduce(_ ++ _) / group.length.toDouble)
      .toVector
      .sortBy(_._1)
      .map(_._2)
  }

  /**
   * Randomly choose k of the points as initial centroids.
   */
  private[this] def chooseRandomCentroids(k: Int) = {
    random.shuffle(points).take(k)
  }

}


text:
package org.n52.sos.ogc.sensorML.elements;

/**
 * SOS internal representation of SensorML identifier
 *
 * @since 4.0.0
 */
public class SmlIdentifier {

    private String name;

    private String definition;

    private String value;

    /**
     * constructor
     *
     * @param name
     *            Identifier name
     * @param definition
     *            Identifier definition
     * @param value
     *            Identifier value
     */
    public SmlIdentifier(final String name, final String definition, final String value) {
        super();
        this.name = name;
        this.definition = definition;
        this.value = value;
    }

    /**
     * @return the Identifier name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            Identifier name
     */
    public void setName(final String name) {
        this.name = name;
    }

    /**
     * @return the Identifier definition
     */
    public String getDefinition() {
        return definition;
    }

    /**
     * @param definition
     *            Identifier definition
     */
    public void setDefinition(final String definition) {
        this.definition = definition;
    }

    /**
     * @return the Identifier value
     */
    public String getValue() {
        return value;
    }

    /**
     * @param value
     *            Identifier value
     */
    public void setValue(final String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.format("SosSMLIdentifier [name=%s, definition=%s, value=%s]", name, definition, value);
    }

    public boolean isSetName() {
        return name != null && !name.isEmpty();
    }

    public boolean isSetValue() {
        return value != null && !value.isEmpty();
    }

    public boolean isSetDefinition() {
        return definition != null && !definition.isEmpty();
    }
}

redpajama_set_name: RedPajamaGithub


text:
using base::BindLambdaForTesting;
using chrome_browser_sharing::ResponseMessage;
using chrome_browser_sharing::SharingMessage;
using content::SmsFetcher;
using ::testing::_;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::StrictMock;

namespace {

const char kEmptyDeviceName[] = "";
const char kDefaultDeviceName[] = "Default Device";

class MockSmsFetcher : public SmsFetcher {
 public:
  MockSmsFetcher() = default;

  MockSmsFetcher(const MockSmsFetcher&) = delete;
  MockSmsFetcher& operator=(const MockSmsFetcher&) = delete;

  ~MockSmsFetcher() override = default;

  MOCK_METHOD2(Subscribe,
               void(const content::OriginList& origin_list,
                    Subscriber& subscriber));
  MOCK_METHOD3(Subscribe,
               void(const content::OriginList& origin_list,
                    Subscriber& subscriber,
                    content::RenderFrameHost& rfh));
  MOCK_METHOD2(Unsubscribe,
               void(const content::OriginList& origin_list,
                    Subscriber* subscriber));
  MOCK_METHOD0(HasSubscribers, bool());
};

class MockSmsFetchRequestHandler : public SmsFetchRequestHandler {
 public:
  explicit MockSmsFetchRequestHandler(content::SmsFetcher* fetcher)
      : SmsFetchRequestHandler(&device_source_, fetcher) {}
  ~MockSmsFetchRequestHandler() override = default;

  MOCK_METHOD3(AskUserPermission,
               void(const content::OriginList&,
                    const std::string& one_time_code,
                    const std::string& client_name));

  content::BrowserTaskEnvironment& task_environment() {
    return task_environment_;
  }

  MockSmsFetchRequestHandler(const MockSmsFetchRequestHandler&) = delete;
  MockSmsFetchRequestHandler& operator=(const MockSmsFetchRequestHandler&) =
      delete;

 private:
  MockSharingDeviceSource device_source_;
  content::BrowserTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
};

SharingMessage CreateRequest(
    const std::string& origin,
    const std::string& device_name = kDefaultDeviceName) {
  SharingMessage message;
  message.set_sender_device_name(device_name);
  message.mutable_sms_fetch_request()->add_origins(origin);
  return message;
}

SharingMessage CreateRequestWithMultipleOrigins(
    const std::vector<std::string>& origins,
    const std::string& device_name = kDefaultDeviceName) {
  SharingMessage message;
  message.set_sender_device_name(device_name);
  for (const auto& origin : origins)
    message.mutable_sms_fetch_request()->add_origins(origin);
  return message;
}

// A similar action as testing::SaveArg, but it takes the address of the thing.
template <size_t I = 0, typename T>
auto SavePtrToArg(T* out) {
  return [out](auto&&... args) {
    *out = std::addressof(std::get<I>(std::tie(args...)));
  };
}

}  // namespace

TEST(SmsFetchRequestHandlerTest, Basic) {
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  const std::string origin = "https://a.com";
  SharingMessage message = CreateRequest(origin);
  JNIEnv* env = base::android::AttachCurrentThread();
  const std::u16string formatted_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(origin)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_origin =
      base::android::ConvertUTF16ToJavaString(env, formatted_origin);

  base::RunLoop loop;

  SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&subscriber));
  EXPECT_CALL(fetcher, Unsubscribe(_, _));

  handler.OnMessage(
      message,
      BindLambdaForTesting([&loop](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("123", response->sms_fetch_response().one_time_code());
        loop.Quit();
      }));

  subscriber->OnReceive(content::OriginList{url::Origin::Create(GURL(origin))},
                        "123", SmsFetcher::UserConsent::kNotObtained);
  handler.OnConfirm(env, j_origin.obj(), nullptr);
  loop.Run();
}

TEST(SmsFetchRequestHandlerTest, OutOfOrder) {
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  JNIEnv* env = base::android::AttachCurrentThread();
  const std::string origin1 = "https://a.com";
  SharingMessage message1 = CreateRequest(origin1);
  const std::u16string formatted_origin1 =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(origin1)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_origin1 =
      base::android::ConvertUTF16ToJavaString(env, formatted_origin1);

  const std::string origin2 = "https://b.com";
  SharingMessage message2 = CreateRequest(origin2);
  const std::u16string formatted_origin2 =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(origin2)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_origin2 =
      base::android::ConvertUTF16ToJavaString(env, formatted_origin2);

  base::RunLoop loop1;

  SmsFetcher::Subscriber* request1;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&request1));
  EXPECT_CALL(fetcher, Unsubscribe(_, _)).Times(2);

  handler.OnMessage(
      message1,
      BindLambdaForTesting([&loop1](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("1", response->sms_fetch_response().one_time_code());
        loop1.Quit();
      }));

  base::RunLoop loop2;

  SmsFetcher::Subscriber* request2;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&request2));

  handler.OnMessage(
      message2,
      BindLambdaForTesting([&loop2](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("2", response->sms_fetch_response().one_time_code());
        loop2.Quit();
      }));

  request2->OnReceive(content::OriginList{url::Origin::Create(GURL(origin2))},
                      "2", SmsFetcher::UserConsent::kNotObtained);
  handler.OnConfirm(env, j_origin2.obj(), nullptr);
  loop2.Run();

  request1->OnReceive(content::OriginList{url::Origin::Create(GURL(origin1))},
                      "1", SmsFetcher::UserConsent::kNotObtained);
  handler.OnConfirm(env, j_origin1.obj(), nullptr);
  loop1.Run();
}

TEST(SmsFetchRequestHandlerTest, HangingRequestUnsubscribedUponDestruction) {
  StrictMock<MockSmsFetcher> fetcher;

  MockSmsFetchRequestHandler handler(&fetcher);
  SharingMessage message = CreateRequest("https://a.com");
  SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&subscriber));

  // Expects Unsubscribe to be called when SmsFetchRequestHandler goes out of
  // scope.
  EXPECT_CALL(fetcher, Unsubscribe(_, _));

  // Leaves the request deliberately hanging without a response to assert
  // that it gets cleaned up.
  handler.OnMessage(
      message,
      BindLambdaForTesting([&](std::unique_ptr<ResponseMessage> response) {}));
}

TEST(SmsFetchRequestHandlerTest, AskUserPermissionOnReceive) {
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  SharingMessage message = CreateRequest("https://a.com");

  SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&subscriber));
  EXPECT_CALL(fetcher, Unsubscribe);

  handler.OnMessage(message, base::DoNothing());

  EXPECT_CALL(handler, AskUserPermission).Times(0);
  subscriber->OnReceive(
      content::OriginList{url::Origin::Create(GURL("https://a.com"))}, "123",
      SmsFetcher::UserConsent::kNotObtained);

  testing::Mock::VerifyAndClear(&handler);
  EXPECT_CALL(handler, AskUserPermission);
  handler.task_environment().FastForwardBy(base::Seconds(1));
}

TEST(SmsFetchRequestHandlerTest, SendSuccessMessageOnConfirm) {
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  const std::string origin = "https://a.com";
  SharingMessage message = CreateRequest(origin);
  JNIEnv* env = base::android::AttachCurrentThread();
  const std::u16string formatted_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(origin)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_origin =
      base::android::ConvertUTF16ToJavaString(env, formatted_origin);

  base::RunLoop loop;

  SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&subscriber));
  EXPECT_CALL(fetcher, Unsubscribe);

  handler.OnMessage(
      message,
      BindLambdaForTesting([&loop](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("123", response->sms_fetch_response().one_time_code());
        loop.Quit();
      }));

  subscriber->OnReceive(content::OriginList{url::Origin::Create(GURL(origin))},
                        "123", SmsFetcher::UserConsent::kNotObtained);
  handler.OnConfirm(env, j_origin.obj(), nullptr);
  loop.Run();
}

TEST(SmsFetchRequestHandlerTest, SendFailureMessageOnDismiss) {
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  const std::string origin = "https://a.com";
  SharingMessage message = CreateRequest(origin);
  JNIEnv* env = base::android::AttachCurrentThread();
  const std::u16string formatted_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(origin)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_origin =
      base::android::ConvertUTF16ToJavaString(env, formatted_origin);

  base::RunLoop loop;

  SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&subscriber));
  EXPECT_CALL(fetcher, Unsubscribe);

  handler.OnMessage(
      message,
      BindLambdaForTesting([&loop](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ(content::SmsFetchFailureType::kPromptCancelled,
                  static_cast<content::SmsFetchFailureType>(
                      response->sms_fetch_response().failure_type()));
        loop.Quit();
      }));

  subscriber->OnReceive(content::OriginList{url::Origin::Create(GURL(origin))},
                        "123", SmsFetcher::UserConsent::kNotObtained);
  handler.OnDismiss(env, j_origin.obj(), nullptr);
  loop.Run();
}

TEST(SmsFetchRequestHandlerTest, EmbeddedFrameConfirm) {
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  const std::string top_origin = "https://top.com";
  const std::string embedded_origin = "https://embedded.com";
  std::vector<std::string> origins{embedded_origin, top_origin};
  SharingMessage message = CreateRequestWithMultipleOrigins(origins);
  JNIEnv* env = base::android::AttachCurrentThread();
  const std::u16string formatted_top_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(top_origin)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_top_origin =
      base::android::ConvertUTF16ToJavaString(env, formatted_top_origin);

  const std::u16string formatted_embedded_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(embedded_origin)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_embedded_origin =
      base::android::ConvertUTF16ToJavaString(env, formatted_embedded_origin);

  base::RunLoop loop;

  SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&subscriber));
  EXPECT_CALL(fetcher, Unsubscribe(_, _));

  handler.OnMessage(
      message,
      BindLambdaForTesting([&](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("123", response->sms_fetch_response().one_time_code());
        const auto& origin_strings = response->sms_fetch_response().origins();
        EXPECT_EQ(embedded_origin, origin_strings[0]);
        EXPECT_EQ(top_origin, origin_strings[1]);
        loop.Quit();
      }));

  content::OriginList origin_list;
  origin_list.push_back(url::Origin::Create(GURL(embedded_origin)));
  origin_list.push_back(url::Origin::Create(GURL(top_origin)));
  subscriber->OnReceive(origin_list, "123",
                        SmsFetcher::UserConsent::kNotObtained);
  handler.OnConfirm(env, j_top_origin.obj(), j_embedded_origin.obj());
  loop.Run();
}

TEST(SmsFetchRequestHandlerTest, EmbeddedFrameDismiss) {
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  const std::string top_origin = "https://top.com";
  const std::string embedded_origin = "https://embedded.com";
  std::vector<std::string> origins{embedded_origin, top_origin};
  SharingMessage message = CreateRequestWithMultipleOrigins(origins);
  JNIEnv* env = base::android::AttachCurrentThread();
  const std::u16string formatted_top_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(top_origin)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_top_origin =
      base::android::ConvertUTF16ToJavaString(env, formatted_top_origin);

  const std::u16string formatted_embedded_origin =
      url_formatter::FormatOriginForSecurityDisplay(
          url::Origin::Create(GURL(embedded_origin)),
          url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS);
  base::android::ScopedJavaLocalRef<jstring> j_embedded_origin =
      base::android::ConvertUTF16ToJavaString(env, formatted_embedded_origin);

  base::RunLoop loop;

  SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SavePtrToArg<1>(&subscriber));
  EXPECT_CALL(fetcher, Unsubscribe(_, _));

  handler.OnMessage(
      message,
      BindLambdaForTesting([&](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ(content::SmsFetchFailureType::kPromptCancelled,
                  static_cast<content::SmsFetchFailureType>(
                      response->sms_fetch_response().failure_type()));
        loop.Quit();
      }));

  content::OriginList origin_list;
  origin_list.push_back(url::Origin::Create(GURL(embedded_origin)));
  origin_list.push_back(url::Origin::Create(GURL(top_origin)));
  subscriber->OnReceive(origin_list, "123",
                        SmsFetcher::UserConsent::kNotObtained);
  handler.OnDismiss(env, j_top_origin.obj(), j_embedded_origin.obj());
  loop.Run();
}

TEST(SmsFetchRequestHandlerTest, DefaultDeviceName) {
  base::HistogramTester histogram_tester;
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  const std::string origin = "https://a.com";
  SharingMessage message = CreateRequest(origin, kDefaultDeviceName);

  EXPECT_CALL(fetcher, Subscribe(_, _));
  EXPECT_CALL(fetcher, Unsubscribe(_, _));

  handler.OnMessage(message, base::DoNothing());
  EXPECT_EQ(handler.requests_.size(), 1u);

  histogram_tester.ExpectBucketCount("Sharing.SmsFetcherClientNameIsEmpty", 0,
                                     1);
  histogram_tester.ExpectTotalCount("Sharing.SmsFetcherClientNameIsEmpty", 1);
}

TEST(SmsFetchRequestHandlerTest, EmptyDeviceName) {
  base::HistogramTester histogram_tester;
  StrictMock<MockSmsFetcher> fetcher;
  MockSmsFetchRequestHandler handler(&fetcher);
  const std::string origin = "https://a.com";
  SharingMessage message = CreateRequest(origin, kEmptyDeviceName);
  handler.OnMessage(message, base::DoNothing());
  EXPECT_TRUE(handler.requests_.empty());

  histogram_tester.ExpectBucketCount("Sharing.SmsFetcherClientNameIsEmpty", 1,
                                     1);
  histogram_tester.ExpectTotalCount("Sharing.SmsFetcherClientNameIsEmpty", 1);
}


text:
"""
Test 8
"""
import csv
import time
import math
import numpy as np
from sklearn.svm import LinearSVC
from sklearn.model_selection import cross_val_score
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.externals import joblib
from preprocessing import (SentimentExtractor,
                           TempExtractor,
                           WindExtractor,
                           tokenize,
                           stopwords_list)

print("Reading CSV...")
csvfile = open('data/train.csv', newline='')
datareader = csv.DictReader(csvfile)
data = list(datareader)

classes = [
    'k1',
    'k2',
    'k3',
    'k4',
    'k5',
    'k6',
    'k7',
    'k8',
    'k9',
    'k10',
    'k11',
    'k12',
    'k13',
    'k14',
    'k15',
    #'s1',
    's2',
    's3',
    's4',
    's5',
    'w1',
    'w2',
    #'w3',
    'w4',
]

def filter_tweets(data):
    return [row['tweet'] for row in data]

def filter_class(data, className):
    y = []
    for row in data:
        value = float(row[className])
        y.append(math.ceil(value))

    return y

x_train = filter_tweets(data)

sentiment_extractor = SentimentExtractor()
temp_extractor = TempExtractor()
wind_extractor = WindExtractor()

for className in classes:
    y_train = filter_class(data, className)
    print("--------------------------> Training " + className)
    start_time = time.time()

    vectorizer = CountVectorizer(
        min_df=10,
        max_df=0.5,
        ngram_range=(1, 3),
        max_features=10000,
        lowercase=True,
        stop_words=stopwords_list,
        tokenizer=tokenize
    )

    svm = LinearSVC(C=0.3, max_iter=300, loss='hinge')
    pipeline = Pipeline([
        ('union', FeatureUnion([
            ('sentiment', sentiment_extractor),
            ('temp', temp_extractor),
            ('wind', wind_extractor),
            ('vect', vectorizer),
        ])),
        ('cls', svm),
    ])

    y_train = filter_class(data, className)
    accuracy = cross_val_score(pipeline, x_train, y_train, scoring='accuracy')
    print('=== Accuracy ===')
    print(np.mean(accuracy))
    print('Time elapsed:')
    pipeline.fit(x_train, y_train)
    print(time.time() - start_time)
    # save model
    joblib.dump(pipeline, 'models/{}.pkl'.format(className))


text:
using System;

namespace Cars
{
    class StartUp
    {
        public static void Main()
        {
            ICar seat = new Seat("Leon", "Grey");
            ICar tesla = new Tesla("Model 3", "Red", 2);

            Console.WriteLine(seat.ToString());
            Console.WriteLine(tesla.ToString());
        }
    }
}


text:
from django import template
from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
from django.utils.translation import get_language_from_path

register = template.Library()

@register.filter
def clean_url(url):
    parsed = urlsplit(url)
    try:
        parts = parsed.path.split('/')
    except:
        return url
    lang = get_language_from_path(parsed.path)
    if len(parts) > 1 and parts[1] == lang:
        del parts[1]
    return urlunsplit((
        parsed.scheme, parsed.netloc, '/'.join(parts), parsed.query,
        parsed.fragment))


text:
/**
 * @file wbxml_charset.h
 * @ingroup wbxml_charset
 *
 * @author Aymerick Jehanne <aymerick@jehanne.org>
 * @date 04/03/24
 *
 * @brief Charset Functions
 */

#ifndef WBXML_CHARSET_H
#define WBXML_CHARSET_H

#include "wbxml.h"
#include "wbxml_buffers.h"

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/** @addtogroup wbxml_charset
 *  @{
 */

/**
 * @brief Get a Charset MIBEnum given a Charset Name
 * @param name     [in]  Charset Name to search
 * @param mib_enum [out] MIBEnum if found
 * @return Return TRUE if Charset found, FALSE otherwise
 */
WBXML_DECLARE(WB_BOOL) wbxml_charset_get_mib(const WB_TINY       *name,
                                             WBXMLCharsetMIBEnum *mib_enum);

/**
 * @brief Get a Charset Name given a Charset MIBEnum
 * @param mib_enum [in]  MIBEnum to search
 * @param name     [out] Charset Name if found
 * @return Return TRUE if Charset found, FALSE otherwise
 */
WBXML_DECLARE(WB_BOOL) wbxml_charset_get_name(WBXMLCharsetMIBEnum   mib_enum,
                                              const WB_TINY       **name);

/**
 * Charset Convertion function
 *
 * Input is a normal pointer to buffer to convert.
 *
 * Result is a WBXML Buffer. If 'in_charset' and 'out_charset' are
 * identical, and are even ASCII or UTF-8, this will be a static
 * buffer pointing to input buffer.
 *
 * The 'io_bytes' parameter is decremented each time a byte is correctly
 * converted from 'in_buf', so that it reflects the number of bytes that
 * have been converted from 'in_buf'.
 *
 * @param in_buf      Buffer to convert
 * @param io_bytes    Number of bytes in buffer
 * @param in_charset  Original charset
 * @param out_buf     Resulting converted Buffer
 * @param out_charset Destination charset
 */
WBXML_DECLARE(WBXMLError) wbxml_charset_conv(const WB_TINY        *in_buf,
                                             WB_ULONG             *io_bytes,
                                             WBXMLCharsetMIBEnum   in_charset,
                                             WBXMLBuffer         **out_buf,
                                             WBXMLCharsetMIBEnum   out_charset);

/**
 * Charset Convertion function, for unknown length strings
 *
 * This is a wrapper around wbxml_charset_conv(), but to convert
 * a buffer that have an unknown length. This function first try to find
 * the buffer length, by finding its charset specific termination code
 * (eg: '\0', '\0\0'), then it calls the wbxml_charset_conv() function.
 *
 * Set the maximum possible length of input buffer into 'io_bytes'. A check
 * is done if length found is higher than input 'io_bytes' value.
 *
 * WARNING : 'io_bytes' is then set to the real length of input buffer (this is
 * a different behaviour than with wbxml_charset_conv()).
 *
 * @param in_buf      Buffer to convert
 * @param io_bytes    Number of bytes in buffer
 * @param in_charset  Original charset
 * @param out_buf     Resulting converted Buffer
 * @param out_charset Destination charset
 */
WBXML_DECLARE(WBXMLError) wbxml_charset_conv_term(const WB_TINY        *in_buf,
                                                  WB_ULONG             *io_bytes,
                                                  WBXMLCharsetMIBEnum   in_charset,
                                                  WBXMLBuffer         **out_buf,
                                                  WBXMLCharsetMIBEnum   out_charset);

/** @} */

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* WBXML_CHARSET_H */


text:
using RecruitsLauncher.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Resources;
using System.Windows.Forms;

namespace RecruitsLauncher
{
    public partial class MainForm : Form
    {
        public enum Languages
        {
            English,
            German
        };

        private enum ErrorType
        {
            ER_NOCONNECTION,
            ER_WRONG_ACCOUNT_INFO,
            ER_NO_OWN_GAME,
            ER_CORRUPT,
            ER_NOINSTALL,
            ER_NONE
        };

        private enum LauncherState
        {
            LS_SIGNIN,
            LS_UPDATING,
            LS_REPAIRING,
            LS_ONLINE,
            LS_OFFLINE
        };

        public static readonly string MANIFEST_URL = "http://YOURURL.com/fileManifest.txt";
        public static readonly string VERSION_URL = "http://YOURURL.com/downloads/versionInfo.txt";
        public static readonly string AUTHORIZE_URL = "http://YOURURL.com/downloads/installerAuth.php";
        public static readonly string[] DOWNLOAD_URLS = { "http://YOURURL.com/downloads/download.php", "http://localhost:247/YOURURL/download/download.php" }; //Array of Mirror URL's
        public static string DOWNLOAD_URL = ""; //Active Mirror URL
        public static readonly string[] VERIFY_IGNORE_DIRECTORIES = { "/Config/", "/Logs/", "/Localization/", "/UserCode/" }; //Ignore These Directories
        public static readonly string[] VERIFY_IGNORE_FILES = { "InstallInfo.xml" }; //Ignore this File

        public String m_localInstallDir;
        public String m_localVersionNumber;
        public String m_remoteVersionNumber;

        public String m_currentUsername;
        public String m_currentPassword;

        private FileDownloader m_downloader;
        private System.Drawing.Point m_dragOffset;
        private ErrorType m_errorType;
        private LauncherState m_launcherState;
        private System.Windows.Forms.Timer m_retryTimer = new System.Windows.Forms.Timer();
        private int m_retryCount = 0;
        private OptionsForm m_optionsForm;
        private ResourceManager LocRM = new ResourceManager("RecruitsLauncher.Resources.Localization.WinFormStrings", typeof(MainForm).Assembly);
        private System.Drawing.Text.PrivateFontCollection pfc;

        public MainForm()
        {
            AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            try
            {
                m_downloader = new FileDownloader(this);
                InitializeComponent();
                ClientSize = new System.Drawing.Size(800, 600);
                LoadCustomFont();
                Icon = Properties.Resources.recruitsicon;
                m_optionsForm = new OptionsForm(this);
                InitializeLauncher();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message, "ERROR!");
                Close();
            }
        }

        private void InitializeLauncher()
        {
            ShowSignIn();

            CheckNetwork();
            m_localVersionNumber = GetLocalVersionNumber();
            GetRemoteVersionNumber();
        }

        private void LoadCustomFont()
        {

            byte[] myFont = Properties.Resources.CPMono_v07_Bold;
            using (var ms = new MemoryStream(myFont))
            {
                pfc = new System.Drawing.Text.PrivateFontCollection();

                byte[] buffer = new byte[ms.Length];
                ms.Read(buffer, 0, (int)ms.Length);

                System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(buffer, System.Runtime.InteropServices.GCHandleType.Pinned);

                checked
                {
                    pfc.AddMemoryFont(handle.AddrOfPinnedObject(), (int)ms.Length);

                    WebsiteLink.Font = new System.Drawing.Font(pfc.Families[0], WebsiteLink.Font.Size, System.Drawing.FontStyle.Bold);
                    ForumsLink.Font = new System.Drawing.Font(pfc.Families[0], ForumsLink.Font.Size, System.Drawing.FontStyle.Bold);
                    OptionsLink.Font = new System.Drawing.Font(pfc.Families[0], OptionsLink.Font.Size, System.Drawing.FontStyle.Bold);
                    eulaLink.Font = new System.Drawing.Font(pfc.Families[0], eulaLink.Font.Size, System.Drawing.FontStyle.Bold);
                    registerLink.Font = new System.Drawing.Font(pfc.Families[0], registerLink.Font.Size, System.Drawing.FontStyle.Bold);
                    forgotPassLink.Font = new System.Drawing.Font(pfc.Families[0], forgotPassLink.Font.Size, System.Drawing.FontStyle.Bold);

                    infoLBL.Font = new System.Drawing.Font(pfc.Families[0], infoLBL.Font.Size, System.Drawing.FontStyle.Bold);
                    passLBL.Font = new System.Drawing.Font(pfc.Families[0], passLBL.Font.Size, System.Drawing.FontStyle.Bold);
                    middleLBL.Font = new System.Drawing.Font(pfc.Families[0], middleLBL.Font.Size, System.Drawing.FontStyle.Bold);

                    actionBtn.Font = new System.Drawing.Font(pfc.Families[0], actionBtn.Font.Size, System.Drawing.FontStyle.Bold);
                    downloadBtn.Font = new System.Drawing.Font(pfc.Families[0], downloadBtn.Font.Size, System.Drawing.FontStyle.Bold);
                }

            }
        }

        public void ChangeLanguage(string languageCode)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(languageCode);
            ComponentResourceManager resources = new ComponentResourceManager(typeof(MainForm));
            resources.ApplyResources(this, "$this");

            UpdateLanguage(resources);

            if (m_optionsForm != null)
            {
                resources = new ComponentResourceManager(typeof(OptionsForm));
                resources.ApplyResources(m_optionsForm, m_optionsForm.Name);

                foreach (Control c in m_optionsForm.Controls)
                {
                    resources.ApplyResources(c, c.Name);
                }
            }
        }

        public void UpdateLanguage(ComponentResourceManager resources)
        {
            resources.ApplyResources(WebsiteLink, WebsiteLink.Name);
            resources.ApplyResources(ForumsLink, ForumsLink.Name);
            resources.ApplyResources(OptionsLink, OptionsLink.Name);
            resources.ApplyResources(passLBL, passLBL.Name);
            LoadCustomFont();
        }

        private void UpdateLauncherState(LauncherState newState)
        {
            m_launcherState = newState;

            switch (m_launcherState)
            {
                case LauncherState.LS_SIGNIN:
                    passTF.Show();
                    userTF.Show();
                    passLBL.Show();
                    infoLBL.Show();
                    infoLBL.Text = "E-Mail";
                    registerLink.Show();
                    forgotPassLink.Show();
                    actionBtn.Enabled = true;
                    actionBtn.Text = LocRM.GetString("actionBtnSignIn");
                    pauseBtn.Hide();
                    playBtn.Hide();
                    totalProgressBar.Hide();
                    middleLBL.Hide();
                    break;
                case LauncherState.LS_ONLINE:
                    actionBtn.Enabled = true;
                    infoLBL.Text = LocRM.GetString("updateComplete"); ;
                    pauseBtn.Hide();
                    playBtn.Hide();
                    actionBtn.Text = LocRM.GetString("actionBtnOnline");
                    downloadBtn.Hide();
                    middleLBL.Show();
                    middleLBL.Text = String.Format(LocRM.GetString("updated") + " - V{0}", m_localVersionNumber);
                    break;
                case LauncherState.LS_OFFLINE:
                    passTF.Hide();
                    userTF.Hide();
                    passLBL.Hide();
                    totalProgressBar.Hide();
                    infoLBL.Hide();
                    downloadBtn.Hide();
                    middleLBL.Show();
                    registerLink.Hide();
                    forgotPassLink.Hide();
                    playBtn.Hide();
                    pauseBtn.Hide();
                    actionBtn.Text = LocRM.GetString("actionBtnOffline");
                    actionBtn.Enabled = true;
                    break;
                case LauncherState.LS_UPDATING:
                    pauseBtn.Show();
                    actionBtn.Enabled = false;
                    middleLBL.Hide();
                    downloadBtn.Hide();
                    totalProgressBar.Show();
                    infoLBL.Show();
                    infoLBL.Text = LocRM.GetString("initializingUpdate");
                    break;
            }
        }

        private void ShowSignIn()
        {
            userTF.Text = (String)Settings.Default["rememberedUser"];
            UpdateLauncherState(LauncherState.LS_SIGNIN);
            m_errorType = ErrorType.ER_NONE;
        }

        private void ElevatePrivileges()
        {
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = Application.ExecutablePath;
            proc.Verb = "runas";

            try
            {
                Process.Start(proc);
            }
            catch
            {
                return;
            }

            Application.Exit();  // Quit itself
        }

        public void DownloadComplete()
        {
            UpdateLauncherState(LauncherState.LS_ONLINE);
            totalProgressBar.Hide();
        }

        public void UpdateProgressBar()
        {
            int totalPercent = (int)m_downloader.TotalPercentage();
            if(totalPercent > 100) {totalPercent = 100;}
            if (totalPercent < 0) { totalPercent = 0; }
            totalProgressBar.Value = totalPercent;
            infoLBL.Text = String.Format(LocRM.GetString("downloadingUpdate") + " - {0} / {1} ({2})",
                FileDownloader.FormatSizeBinary(m_downloader.m_totalProgress),
                FileDownloader.FormatSizeBinary(m_downloader.m_totalSize),
                FileDownloader.FormatSizeBinary(m_downloader.m_downloadSpeed*10)+"/s");
        }

        public void DownloadFailed()
        {
            m_downloader.Pause();
            ShowError(ErrorType.ER_NOCONNECTION);
        }

        private void CheckNetwork()
        {
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                ShowError(ErrorType.ER_NOCONNECTION);
            }
        }

        private bool CheckConnection()
        {
            try
            {
                WebClient client = new WebClient();
                Stream stream = client.OpenRead(VERSION_URL);
                stream.Close();
                return true;
            }
            catch
            {
            }
            return false;
        }

        public void ForceRepair()
        {
            m_launcherState = LauncherState.LS_REPAIRING;
            UpdateGame();
        }

        private void ShowError(ErrorType errType)
        {
            m_errorType = errType;

            switch (m_errorType)
            {
                case ErrorType.ER_NOCONNECTION:
                    ConnectionError();
                    break;

                case ErrorType.ER_WRONG_ACCOUNT_INFO:
                    infoLBL.Text = LocRM.GetString("incorrectInfo");
                    infoLBL.ForeColor = System.Drawing.Color.Red;
                    registerLink.Show();
                    passLBL.Show();
                    break;

                case ErrorType.ER_NO_OWN_GAME:
                    infoLBL.Text = LocRM.GetString("noOwn");
                    infoLBL.ForeColor = System.Drawing.Color.Red;
                    registerLink.Hide();
                    passLBL.Hide();
                    break;
            }
        }

        private void ConnectionError()
        {
            UpdateLauncherState(LauncherState.LS_OFFLINE);
            middleLBL.Left = 15;
            middleLBL.Text = LocRM.GetString("retryTXT_p1") + (5 - m_retryCount) + LocRM.GetString("seconds") + "...";
            m_retryCount = 0;
            if (!m_retryTimer.Enabled)
            {
                m_retryTimer.Tick += m_retryTimer_Tick;
                m_retryTimer.Interval = 1000;
                m_retryTimer.Start();
            }
        }

        void m_retryTimer_Tick(object sender, EventArgs e)
        {
            if (m_retryCount > 5)
            {
                if (CheckConnection())
                {
                    middleLBL.Left = 200;
                    m_retryTimer.Stop();
                    ShowSignIn();
                }
                m_retryCount = 0;
            }
            else
            {
                middleLBL.Text = LocRM.GetString("retryTXT_p1") + (5 - m_retryCount) + LocRM.GetString("seconds") + "...";
                m_retryCount++;
            }
        }

        public bool CanUpdateLocalPath()
        {
            if (m_launcherState != LauncherState.LS_REPAIRING && m_launcherState != LauncherState.LS_UPDATING)
            {
                return true;
            }

            return false;
        }

        public void UpdateLocalPath(String newPath)
        {
            m_localInstallDir = newPath;
            if (m_launcherState == LauncherState.LS_ONLINE || m_launcherState == LauncherState.LS_OFFLINE)
            {
                UserLoggedIn();
            }
        }

        private void actionBtn_Click(object sender, EventArgs e)
        {
            switch (m_launcherState)
            {
                case LauncherState.LS_SIGNIN:
                    registerLink.Hide();
                    infoLBL.ForeColor = System.Drawing.Color.Silver;
                    infoLBL.Text = LocRM.GetString("attemptingSignIn");
                    TryLogin(userTF.Text, passTF.Text);
                    break;

                case LauncherState.LS_OFFLINE:
                case LauncherState.LS_ONLINE:
                    LaunchGame();
                    break;
            }
        }

        private void LaunchGame()
        {
            try
            {
                Process.Start(m_localInstallDir + "/Binaries/Win32/Recruits.exe");
                Close();
            }
            catch (Exception ex)
            {
                DialogResult result = MessageBox.Show(ex.Message + "\n\n" + LocRM.GetString("launchError_p1") + "\n\n" + LocRM.GetString("launchError_p2") + "\n\n" + LocRM.GetString("launchError_p3"), "ERROR", MessageBoxButtons.OKCancel);
                if(result == DialogResult.OK)
                {
                    ForceRepair();
                }
            }
        }

        private void TryLogin(String username, String password)
        {
            Settings.Default["rememberedUser"] = username;
            Settings.Default.Save();
            m_currentUsername = username;
            m_currentPassword = password;

            if (username == "" || password == "")
            {
                ShowError(ErrorType.ER_WRONG_ACCOUNT_INFO);
                return;
            }

            username = username.ToLower();

            WebClient client = new WebClient();
            Encryption enc = new Encryption();
            String ParamString = enc.Encrypt3DES(password);
            try
            {
                String ConnString = AUTHORIZE_URL+"?user="+username+"&params="+ParamString;
                String line = client.DownloadString(ConnString);
                if (line == "VALID")
                {
                    UserLoggedIn();
                    return;
                }
                else if (line == "NO GAME")
                {
                    ShowError(ErrorType.ER_NO_OWN_GAME);
                    return;
                }
                else if (line.Contains("INVALID"))
                {
                    ShowError(ErrorType.ER_WRONG_ACCOUNT_INFO);
                    return;
                }
            }
            catch (Exception e)
            {
                #if DEBUG
                    MessageBox.Show("Unable to Connect to Recruits Login Servers: " + e.Message);
                #endif
            }
            ShowError(ErrorType.ER_NOCONNECTION);
        }

        private void UserLoggedIn()
        {
            UpdateLauncherState(LauncherState.LS_OFFLINE);
            actionBtn.Text = LocRM.GetString("actionBtnOffline");
            middleLBL.Text = LocRM.GetString("scanningInstall");
            CheckForInstall();
        }

        private void CheckForInstall()
        {
            try {
                WebClient client = new WebClient();
                Stream stream = client.OpenRead(MANIFEST_URL);

                StreamReader resStream = new StreamReader(stream);

                while (!resStream.EndOfStream)
                {
                    String filePath = resStream.ReadLine();
                    string[] splitFile = filePath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if (splitFile.Length >= 2)
                    {
                        if (!File.Exists(m_localInstallDir + splitFile[0]) || (new FileInfo(m_localInstallDir + splitFile[0]).Length != Int64.Parse(splitFile[1])))
                        {
                            bool bIgnore = false;

                            foreach (string str in VERIFY_IGNORE_DIRECTORIES)
                            {
                                if (splitFile[0].Contains(str))
                                {
                                    bIgnore = true;
                                }
                            }

                            foreach (string str in VERIFY_IGNORE_FILES)
                            {
                                if (splitFile[0].Contains(str))
                                {
                                    bIgnore = true;
                                }
                            }
                            System.Diagnostics.Debug.WriteLine("YAY");
                            if (!bIgnore)
                            {
                                System.Diagnostics.Debug.WriteLine("FAILED");
                                System.Diagnostics.Debug.WriteLine(splitFile[0]);
                                ErrorCheckingInstall();
                                stream.Close();
                                resStream.Dispose();
                                return;
                            }
                        }
                    }
                }
                stream.Close();
                resStream.Dispose();

                SuccessCheckingInstall();
                return;
            }
            catch (Exception e)
            {
                MessageBox.Show("Turd");
                System.Diagnostics.Debug.WriteLine("Tured");
                #if DEBUG
                    MessageBox.Show("Unable to Connect to Recruits Servers for Install Verification: " + e.Message);
                #endif
            }
            ShowError(ErrorType.ER_NOCONNECTION);
            return;
        }

        private void SuccessCheckingInstall()
        {
            if (m_localVersionNumber != m_remoteVersionNumber)
            {
                Int64 downloadSize = GetDownloadSize();
                actionBtn.Text = LocRM.GetString("actionBtnOffline");
                middleLBL.Text = LocRM.GetString("updateAvailable") + String.Format(" - V{0}  |  {1}", m_remoteVersionNumber, FileDownloader.FormatSizeBinary(downloadSize));
                downloadBtn.Show();
            }
            else
            {
                UpdateLauncherState(LauncherState.LS_ONLINE);
                infoLBL.Hide();
            }
        }

        private void ErrorCheckingInstall()
        {
            Int64 downloadSize = GetDownloadSize();
            middleLBL.Text = LocRM.GetString("needDownload") + String.Format(" - V{0}  |  {1}", m_remoteVersionNumber, FileDownloader.FormatSizeBinary(downloadSize));
            downloadBtn.Show();
        }

        private string GetLocalVersionNumber()
        {
            String filePath = "/UDKGame/versionInfo.txt";
            String version = "-1";
            Debug.WriteLine(m_localInstallDir + filePath + " _ " + File.Exists(m_localInstallDir + filePath));
            if (File.Exists(m_localInstallDir + filePath))
            {

                string[] lines = File.ReadAllLines(m_localInstallDir + filePath);
                foreach (string line in lines)
                {
                    if (line.IndexOf(':') != -1)
                    {
                        try
                        {
                            String key = line.Substring(0, line.IndexOf(':'));
                            String value = line.Substring(line.IndexOf(':') + 1);

                            if (key == "VER")
                            {
                                version = value;
                            }
                        }
                        catch (Exception) { }
                    }
                }
            }

            return version;
        }

        private void GetRemoteVersionNumber()
        {
            string version = "-2";
            try
            {
                WebClient client = new WebClient();
                Stream stream = client.OpenRead(VERSION_URL);
                StreamReader resStream = new StreamReader(stream);

                while (!resStream.EndOfStream)
                {
                    String line = resStream.ReadLine();
                    if (line.IndexOf(':') != -1)
                    {
                        try
                        {
                            String key = line.Substring(0, line.IndexOf(':'));
                            String value = line.Substring(line.IndexOf(':') + 1);

                            if (key == "VER")
                            {
                                version = value;
                            }
                        }
                        catch (Exception) { }
                    }
                }
                stream.Close();
                resStream.Dispose();
                m_remoteVersionNumber = version;
                return;
            }
            catch (Exception e)
            {
                #if DEBUG
                    MessageBox.Show("Unable to Connect to Recruits Servers for Version Authentication: " + e.Message);
                #endif
            }

            ShowError(ErrorType.ER_NOCONNECTION);
            m_remoteVersionNumber = "-2";
        }

        private void downloadBtn_Click(object sender, EventArgs e)
        {
            UpdateGame();
        }

        private void UpdateGame()
        {
            bool connection = CheckConnection();

            try
            {
                if (!Directory.Exists(m_localInstallDir))
                {
                    Directory.CreateDirectory(m_localInstallDir);
                }

                using (FileStream fstream = new FileStream(m_localInstallDir+"/rubbish.txt", FileMode.Create))
                using (TextWriter writer = new StreamWriter(fstream))
                {
                    writer.WriteLine("sometext");
                }

                File.Delete(m_localInstallDir + "/rubbish.txt");
            }
            catch (Exception)
            {
                DialogResult result = MessageBox.Show(m_localInstallDir + LocRM.GetString("privError_p1"), "ERROR", MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    ElevatePrivileges();
                }
                return;
            }
            UpdateLauncherState(LauncherState.LS_UPDATING);

            SetDownloadServer();
        }

        private void SetupDownloader()
        {
            m_downloader.m_localDirectory = m_localInstallDir;
            m_downloader.m_files.Clear();
            GetFileList();
        }

        private void SetDownloadServer()
        {
            Int64 lowestTime = Int64.MaxValue;
            foreach (String serverURL in DOWNLOAD_URLS)
            {
                Int64 time = PingServer(serverURL + "?loc=UDKGame/PCTOC.txt");
                if (time < lowestTime)
                {
                    lowestTime = time;
                    DOWNLOAD_URL = serverURL;
                    m_downloader.m_downloadURL = serverURL;
                }
            }

            if (DOWNLOAD_URL != "")
            {
                SetupDownloader();
            }
        }

        private Int64 PingServer(String ServerURL)
        {
            Stopwatch watch = new Stopwatch();
            try
            {
                WebClient client = new WebClient();
                watch.Start();
                Stream stream = client.OpenRead(ServerURL);
                stream.Close();
                watch.Stop();
            } catch {
                return Int64.MaxValue;
            }

            return watch.ElapsedMilliseconds;
        }

        private void GetFileList()
        {
            List<FileDownloader.FileInfo> result = new List<FileDownloader.FileInfo>();
            result.Clear();
            try
            {
                WebClient client = new WebClient();
                Stream stream = client.OpenRead(MANIFEST_URL);
                StreamReader resStream = new StreamReader(stream);

                while (!resStream.EndOfStream)
                {
                    String filePath = resStream.ReadLine();
                    string[] splitFile = filePath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if (splitFile.Length >= 2)
                    {
                        Int64 size = Int64.Parse(splitFile[1]);
                        try
                        {
                            result.Add(new FileDownloader.FileInfo(splitFile[0], splitFile[0].Substring(0, splitFile[0].LastIndexOf('/')), Int64.Parse(splitFile[1]), DateTime.Now));
                        }
                        catch (Exception)
                        {
                            result.Add(new FileDownloader.FileInfo(splitFile[0], splitFile[0].Substring(0, splitFile[0].LastIndexOf('/'))));
                        }
                    }
                    else
                    {
                        result.Add(new FileDownloader.FileInfo(splitFile[0], splitFile[0].Substring(0, splitFile[0].LastIndexOf('/'))));
                    }
                }
                stream.Close();
                resStream.Dispose();
                m_downloader.m_files.AddRange(result);
                m_downloader.Start();
                return;
            }
            catch (Exception) { }
        }

        private Int64 GetDownloadSize()
        {
            Int64 totalSize = 0;

            totalSize = 0;
            try
            {
                WebClient client = new WebClient();
                Stream stream = client.OpenRead(MANIFEST_URL);

                StreamReader resStream = new StreamReader(stream);

                while (!resStream.EndOfStream)
                {
                    String filePath = resStream.ReadLine();
                    string[] splitFile = filePath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if (splitFile.Length >= 2)
                    {
                        if (!File.Exists(m_localInstallDir + splitFile[0]) || (new FileInfo(m_localInstallDir + splitFile[0]).Length != Int64.Parse(splitFile[1])))
                        {
                            bool bIgnore = false;

                            foreach (string str in VERIFY_IGNORE_DIRECTORIES)
                            {
                                if (splitFile[0].Contains(str))
                                {
                                    bIgnore = true;
                                }
                            }

                            foreach (string str in VERIFY_IGNORE_FILES)
                            {
                                if (splitFile[0].Contains(str))
                                {
                                    bIgnore = true;
                                }
                            }

                            if (!bIgnore)
                            {
                                totalSize += Int64.Parse(splitFile[1]);
                            }
                        }
                    }
                }
                stream.Close();
                resStream.Dispose();
                return totalSize;
            }
            catch (Exception e)
            {
                #if DEBUG
                MessageBox.Show(e.Message);
                #endif
            }

            ShowError(ErrorType.ER_NOCONNECTION);
            return totalSize;
        }

        private void PauseBtn_Click(object sender, EventArgs e)
        {
                pauseBtn.Hide();
                playBtn.Show();
                m_downloader.Pause();
        }

        private void playBtn_Click(object sender, EventArgs e)
        {
                pauseBtn.Show();
                playBtn.Hide();
                m_downloader.Resume();
        }

        #region TopBar Stuff

        private void WebsiteLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://recruitsgame.com");

        }

        private void ForumsLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://forums.recruitsgame.com");
        }

        private void OptionsLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            m_optionsForm.ShowDialog();
        }

        private void eulaLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://recruitsgame.com/license");
        }

        private void registerLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://recruitsgame.com/TestSite/register/");
        }

        private void forgotPassLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://recruitsgame.com/TestSite/password-reset/");
        }

        private void movebar_picBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                m_dragOffset = PointToScreen(e.Location);
                var formLocation = FindForm().Location;
                m_dragOffset.X -= formLocation.X;
                m_dragOffset.Y -= formLocation.Y;
            }
        }

        private void movebar_picBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                System.Drawing.Point newLoc = PointToScreen(e.Location);

                newLoc.X -= m_dragOffset.X;
                newLoc.Y -= m_dragOffset.Y;
                FindForm().Location = newLoc;
            }
        }

        private void closeLBL_Click(object sender, EventArgs e)
        {
            m_downloader.Pause();
            Close();
        }

        private void minimizeLBL_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
        }

        System.Drawing.Color offColor = System.Drawing.Color.FromArgb(190, 190, 190);
        System.Drawing.Color hoverColor = System.Drawing.Color.FromArgb(255, 255, 255);

        private void WebsiteLink_MouseEnter(object sender, EventArgs e)
        {
            WebsiteLink.LinkColor = hoverColor;
        }

        private void WebsiteLink_MouseLeave(object sender, EventArgs e)
        {
            WebsiteLink.LinkColor = offColor;
        }

        private void ForumsLink_MouseEnter(object sender, EventArgs e)
        {
            ForumsLink.LinkColor = hoverColor;
        }

        private void ForumsLink_MouseLeave(object sender, EventArgs e)
        {
            ForumsLink.LinkColor = offColor;
        }

        private void OptionsLink_MouseEnter(object sender, EventArgs e)
        {
            OptionsLink.LinkColor = hoverColor;
        }

        private void OptionsLink_MouseLeave(object sender, EventArgs e)
        {
            OptionsLink.LinkColor = offColor;
        }

        private void eulaLink_MouseEnter(object sender, EventArgs e)
        {
            eulaLink.LinkColor = hoverColor;
        }

        private void eulaLink_MouseLeave(object sender, EventArgs e)
        {
            eulaLink.LinkColor = offColor;
        }

        private void registerLink_MouseEnter(object sender, EventArgs e)
        {
            registerLink.LinkColor = hoverColor;
        }

        private void registerLink_MouseLeave(object sender, EventArgs e)
        {
            registerLink.LinkColor = offColor;
        }

        private void forgotPassLink_MouseEnter(object sender, EventArgs e)
        {
            forgotPassLink.LinkColor = hoverColor;
        }

        private void forgotPassLink_MouseLeave(object sender, EventArgs e)
        {
            forgotPassLink.LinkColor = offColor;
        }

        private void minimizeLBL_MouseEnter(object sender, EventArgs e)
        {
            minimizeLBL.ForeColor = hoverColor;
        }

        private void minimizeLBL_MouseLeave(object sender, EventArgs e)
        {
            minimizeLBL.ForeColor = offColor;
        }

        private void closeLBL_MouseEnter(object sender, EventArgs e)
        {
            closeLBL.ForeColor = hoverColor;
        }

        private void closeLBL_MouseLeave(object sender, EventArgs e)
        {
            closeLBL.ForeColor = offColor;
        }

        #endregion

        private void enLangBtn_Click(object sender, EventArgs e)
        {
            ChangeLanguage("en-US");
            m_optionsForm.languageCombo.SelectedIndex = m_optionsForm.languageCombo.Items.IndexOf(Languages.English);
        }

        private void deLangBtn_Click(object sender, EventArgs e)
        {
            ChangeLanguage("de-de");
            m_optionsForm.languageCombo.SelectedIndex = m_optionsForm.languageCombo.Items.IndexOf(Languages.German);
        }
    }
}


text:
package org.usfirst.frc.team1797.robot.commands;

import org.usfirst.frc.team1797.robot.Robot;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class FloorGearDefaultCommand extends Command {

    public FloorGearDefaultCommand() {
    	requires(Robot.floorgear);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	if(Robot.floorgear.blockerIsDone()) {
    		Robot.floorgear.stopBlocker();
    	}

    	if(Robot.floorgear.lifterIsDone()) {
    		Robot.floorgear.stopLifter();
    	}
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
name             "rngd-tools"
maintainer       "Ovais Tariq"
maintainer_email "me@ovaistariq.net"
license          "Apache 2.0"
description      "Installs/Configures rng-tools"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "1.3.0"

%w{ centos fedora amazon redhat debian ubuntu }.each do |os|
  supports os
end