text:
#include "tensorflow/lite/tools/accuracy/ilsvrc/imagenet_model_evaluator.h"

#include <dirent.h>

#include <fstream>
#include <iomanip>
#include <mutex>  // NOLINT(build/c++11)
#include <string>
#include <thread>  // NOLINT(build/c++11)
#include <vector>

#include "absl/memory/memory.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/c/c_api_internal.h"
#include "tensorflow/lite/tools/command_line_flags.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_config.pb.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_stages.pb.h"
#include "tensorflow/lite/tools/evaluation/stages/image_classification_stage.h"
#include "tensorflow/lite/tools/evaluation/utils.h"

namespace {

using tflite::evaluation::TfliteInferenceParams;

constexpr char kNumImagesFlag[] = "num_images";
constexpr char kModelOutputLabelsFlag[] = "model_output_labels";
constexpr char kGroundTruthImagesPathFlag[] = "ground_truth_images_path";
constexpr char kGroundTruthLabelsFlag[] = "ground_truth_labels";
constexpr char kBlacklistFilePathFlag[] = "blacklist_file_path";
constexpr char kModelFileFlag[] = "model_file";
constexpr char kInterpreterThreadsFlag[] = "num_interpreter_threads";
constexpr char kDelegateFlag[] = "delegate";
constexpr char kNnapiDelegate[] = "nnapi";
constexpr char kGpuDelegate[] = "gpu";

template <typename T>
std::vector<T> GetFirstN(const std::vector<T>& v, int n) {
  if (n >= v.size()) return v;
  std::vector<T> result(v.begin(), v.begin() + n);
  return result;
}

template <typename T>
std::vector<std::vector<T>> Split(const std::vector<T>& v, int n) {
  if (n <= 0) {
    return std::vector<std::vector<T>>();
  }
  std::vector<std::vector<T>> vecs(n);
  int input_index = 0;
  int vec_index = 0;
  while (input_index < v.size()) {
    vecs[vec_index].push_back(v[input_index]);
    vec_index = (vec_index + 1) % n;
    input_index++;
  }
  return vecs;
}

// File pattern for imagenet files.
const char* const kImagenetFilePattern = "*.[jJ][pP][eE][gG]";

}  // namespace

namespace tensorflow {
namespace metrics {

class CompositeObserver : public ImagenetModelEvaluator::Observer {
 public:
  explicit CompositeObserver(const std::vector<Observer*>& observers)
      : observers_(observers) {}

  void OnEvaluationStart(const std::unordered_map<uint64_t, int>&
                             shard_id_image_count_map) override {
    std::lock_guard<std::mutex> lock(mu_);
    for (auto observer : observers_) {
      observer->OnEvaluationStart(shard_id_image_count_map);
    }
  }

  void OnSingleImageEvaluationComplete(
      uint64_t shard_id,
      const tflite::evaluation::TopkAccuracyEvalMetrics& metrics,
      const std::string& image) override {
    std::lock_guard<std::mutex> lock(mu_);
    for (auto observer : observers_) {
      observer->OnSingleImageEvaluationComplete(shard_id, metrics, image);
    }
  }

 private:
  const std::vector<ImagenetModelEvaluator::Observer*>& observers_;
  std::mutex mu_;
};

/*static*/ TfLiteStatus ImagenetModelEvaluator::Create(
    int argc, char* argv[], int num_threads,
    std::unique_ptr<ImagenetModelEvaluator>* model_evaluator) {
  Params params;
  params.number_of_images = 100;
  std::vector<tflite::Flag> flag_list = {
      tflite::Flag::CreateFlag(kNumImagesFlag, &params.number_of_images,
                               "Number of examples to evaluate, pass 0 for all "
                               "examples. Default: 100"),
      tflite::Flag::CreateFlag(
          kModelOutputLabelsFlag, &params.model_output_labels_path,

          "Path to labels that correspond to output of model."
          " E.g. in case of mobilenet, this is the path to label "
          "file where each label is in the same order as the output"
          " of the model."),
      tflite::Flag::CreateFlag(
          kGroundTruthImagesPathFlag, &params.ground_truth_images_path,

          "Path to ground truth images. These will be evaluated in "
          "alphabetical order of filename"),
      tflite::Flag::CreateFlag(
          kGroundTruthLabelsFlag, &params.ground_truth_labels_path,
          "Path to ground truth labels, corresponding to alphabetical ordering "
          "of ground truth images."),
      tflite::Flag::CreateFlag(
          kBlacklistFilePathFlag, &params.blacklist_file_path,
          "Path to blacklist file (optional) where each line is a single "
          "integer that is "
          "equal to index number of blacklisted image."),
      tflite::Flag::CreateFlag(kModelFileFlag, &params.model_file_path,
                               "Path to test tflite model file."),
      tflite::Flag::CreateFlag(
          kInterpreterThreadsFlag, &params.num_interpreter_threads,
          "Number of interpreter threads to use for inference."),
      tflite::Flag::CreateFlag(kDelegateFlag, &params.delegate,
                               "Delegate to use for inference, if available. "
                               "Must be one of {'nnapi', 'gpu'}"),
  };
  tflite::Flags::Parse(&argc, const_cast<const char**>(argv), flag_list);

  if (params.number_of_images < 0) {
    LOG(ERROR) << "Invalid: num_examples";
    return kTfLiteError;
  }

  *model_evaluator =
      absl::make_unique<ImagenetModelEvaluator>(params, num_threads);
  return kTfLiteOk;
}

struct ImageLabel {
  std::string image;
  std::string label;
};

TfLiteStatus EvaluateModelForShard(const uint64_t shard_id,
                                   const std::vector<ImageLabel>& image_labels,
                                   const std::vector<std::string>& model_labels,
                                   const ImagenetModelEvaluator::Params& params,
                                   ImagenetModelEvaluator::Observer* observer,
                                   int num_ranks) {
  tflite::evaluation::EvaluationStageConfig eval_config;
  eval_config.set_name("image_classification");
  auto* classification_params = eval_config.mutable_specification()
                                    ->mutable_image_classification_params();
  auto* inference_params = classification_params->mutable_inference_params();
  inference_params->set_model_file_path(params.model_file_path);
  inference_params->set_num_threads(params.num_interpreter_threads);
  if (params.delegate == kNnapiDelegate) {
    inference_params->set_delegate(TfliteInferenceParams::NNAPI);
  } else if (params.delegate == kGpuDelegate) {
    inference_params->set_delegate(TfliteInferenceParams::GPU);
  }
  classification_params->mutable_topk_accuracy_eval_params()->set_k(num_ranks);

  tflite::evaluation::ImageClassificationStage eval(eval_config);
  eval.SetAllLabels(model_labels);
  TF_LITE_ENSURE_STATUS(eval.Init());

  for (const auto& image_label : image_labels) {
    eval.SetInputs(image_label.image, image_label.label);

    TF_LITE_ENSURE_STATUS(eval.Run());
    observer->OnSingleImageEvaluationComplete(
        shard_id,
        eval.LatestMetrics()
            .process_metrics()
            .image_classification_metrics()
            .topk_accuracy_metrics(),
        image_label.image);
  }
  return kTfLiteOk;
}

// TODO(b/130823599): Move to tools/evaluation/utils.
TfLiteStatus FilterBlackListedImages(const std::string& blacklist_file_path,
                                     std::vector<ImageLabel>* image_labels) {
  if (!blacklist_file_path.empty()) {
    std::vector<std::string> lines;
    if (!tflite::evaluation::ReadFileLines(blacklist_file_path, &lines)) {
      LOG(ERROR) << "Could not read: " << blacklist_file_path;
      return kTfLiteError;
    }
    std::vector<int> blacklist_ids;
    blacklist_ids.reserve(lines.size());
    // Populate blacklist_ids with indices of images.
    std::transform(lines.begin(), lines.end(),
                   std::back_inserter(blacklist_ids),
                   [](const std::string& val) { return std::stoi(val) - 1; });

    std::vector<ImageLabel> filtered_images;
    std::sort(blacklist_ids.begin(), blacklist_ids.end());
    const size_t size_post_filtering =
        image_labels->size() - blacklist_ids.size();
    filtered_images.reserve(size_post_filtering);
    int blacklist_index = 0;
    for (int image_index = 0; image_index < image_labels->size();
         image_index++) {
      if (blacklist_index < blacklist_ids.size() &&
          blacklist_ids[blacklist_index] == image_index) {
        blacklist_index++;
        continue;
      }
      filtered_images.push_back((*image_labels)[image_index]);
    }

    if (filtered_images.size() != size_post_filtering) {
      LOG(ERROR) << "Invalid number of filtered images";
      return kTfLiteError;
    }
    *image_labels = filtered_images;
  }
  return kTfLiteOk;
}

TfLiteStatus ImagenetModelEvaluator::EvaluateModel() const {
  const std::string data_path = tflite::evaluation::StripTrailingSlashes(
                                    params_.ground_truth_images_path) +
                                "/";
  std::vector<std::string> image_files;
  TF_LITE_ENSURE_STATUS(
      tflite::evaluation::GetSortedFileNames(data_path, &image_files));
  std::vector<string> ground_truth_image_labels;
  if (!tflite::evaluation::ReadFileLines(params_.ground_truth_labels_path,
                                         &ground_truth_image_labels))
    return kTfLiteError;
  if (image_files.size() != ground_truth_image_labels.size()) {
    LOG(ERROR) << "Images and ground truth labels don't match";
    return kTfLiteError;
  }

  std::vector<ImageLabel> image_labels;
  image_labels.reserve(image_files.size());
  for (int i = 0; i < image_files.size(); i++) {
    image_labels.push_back({image_files[i], ground_truth_image_labels[i]});
  }

  // Filter any blacklisted images.
  if (FilterBlackListedImages(params_.blacklist_file_path, &image_labels) !=
      kTfLiteOk) {
    LOG(ERROR) << "Could not filter by blacklist";
    return kTfLiteError;
  }

  if (params_.number_of_images > 0) {
    image_labels = GetFirstN(image_labels, params_.number_of_images);
  }

  std::vector<string> model_labels;
  if (!tflite::evaluation::ReadFileLines(params_.model_output_labels_path,
                                         &model_labels)) {
    LOG(ERROR) << "Could not read: " << params_.model_output_labels_path;
    return kTfLiteError;
  }
  if (model_labels.size() != 1001) {
    LOG(ERROR) << "Invalid number of labels: " << model_labels.size();
    return kTfLiteError;
  }

  auto img_labels = Split(image_labels, num_threads_);

  CompositeObserver observer(observers_);

  std::vector<std::thread> thread_pool;
  bool all_okay = true;
  std::unordered_map<uint64_t, int> shard_id_image_count_map;
  thread_pool.reserve(num_threads_);
  for (int i = 0; i < num_threads_; i++) {
    const auto& image_label = img_labels[i];
    const uint64_t shard_id = i + 1;
    shard_id_image_count_map[shard_id] = image_label.size();
    auto func = [shard_id, &image_label, &model_labels, this, &observer,
                 &all_okay]() {
      if (EvaluateModelForShard(shard_id, image_label, model_labels, params_,
                                &observer, params_.num_ranks) != kTfLiteOk) {
        all_okay = all_okay && false;
      }
    };
    thread_pool.push_back(std::thread(func));
  }

  observer.OnEvaluationStart(shard_id_image_count_map);
  for (auto& thread : thread_pool) {
    thread.join();
  }

  return kTfLiteOk;
}

}  // namespace metrics
}  // namespace tensorflow


text:
package datadog

import (
	"fmt"
)

// Alert represents the data of an alert: a query that can fire and send a
// message to the users.
type Alert struct {
	Id           int    `json:"id,omitempty"`
	Creator      int    `json:"creator,omitempty"`
	Query        string `json:"query,omitempty"`
	Name         string `json:"name,omitempty"`
	Message      string `json:"message,omitempty"`
	Silenced     bool   `json:"silenced,omitempty"`
	NotifyNoData bool   `json:"notify_no_data,omitempty"`
	State        string `json:"state,omitempty"`
}

// reqAlerts receives a slice of all alerts.
type reqAlerts struct {
	Alerts []Alert `json:"alerts,omitempty"`
}

// CreateAlert adds a new alert to the system. This returns a pointer to an
// Alert so you can pass that to UpdateAlert later if needed.
func (self *Client) CreateAlert(alert *Alert) (*Alert, error) {
	var out Alert
	err := self.doJsonRequest("POST", "/v1/alert", alert, &out)
	if err != nil {
		return nil, err
	}
	return &out, nil
}

// UpdateAlert takes an alert that was previously retrieved through some method
// and sends it back to the server.
func (self *Client) UpdateAlert(alert *Alert) error {
	return self.doJsonRequest("PUT", fmt.Sprintf("/v1/alert/%d", alert.Id),
		alert, nil)
}

// GetAlert retrieves an alert by identifier.
func (self *Client) GetAlert(id int) (*Alert, error) {
	var out Alert
	err := self.doJsonRequest("GET", fmt.Sprintf("/v1/alert/%d", id), nil, &out)
	if err != nil {
		return nil, err
	}
	return &out, nil
}

// DeleteAlert removes an alert from the system.
func (self *Client) DeleteAlert(id int) error {
	return self.doJsonRequest("DELETE", fmt.Sprintf("/v1/alert/%d", id),
		nil, nil)
}

// GetAlerts returns a slice of all alerts.
func (self *Client) GetAlerts() ([]Alert, error) {
	var out reqAlerts
	err := self.doJsonRequest("GET", "/v1/alert", nil, &out)
	if err != nil {
		return nil, err
	}
	return out.Alerts, nil
}

// MuteAlerts turns off alerting notifications.
func (self *Client) MuteAlerts() error {
	return self.doJsonRequest("POST", "/v1/mute_alerts", nil, nil)
}

// UnmuteAlerts turns on alerting notifications.
func (self *Client) UnmuteAlerts() error {
	return self.doJsonRequest("POST", "/v1/unmute_alerts", nil, nil)
}

redpajama_set_name: RedPajamaGithub


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.hbb20.countrycodepickerproject.SetCountryFragment">

    <android.support.v7.widget.CardView style="@style/parentCard">

        <ScrollView style="@style/parentScrollView">

            <LinearLayout style="@style/parentLinear">

                <TextView
                    style="@style/fragmentTitle"
                    android:text="Choose and set country" />

                <TextView
                    style="@style/fragmentSubTitle"
                    android:text="Choosing and setting country will update selected country in CCP." />

                <TextView
                    style="@style/sectionText"
                    android:text="How to choose country?" />

                <TextView
                    style="@style/pointText"
                    android:text="\u2022 In order to choose country, click on CCP view." />

                <TextView
                    style="@style/pointText"
                    android:text="\u2022 Then search country by country name or phone code or name code." />

                <TextView
                    style="@style/pointText"
                    android:text="\u2022 Tap on county from list to choose" />

                <TextView
                    style="@style/pointText"
                    android:text="\u2022 Try with this (Tap on ccp view)" />

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="16dp"
                    android:layout_marginLeft="32dp"
                    android:layout_marginRight="16dp"
                    android:background="@color/dullBG"
                    android:padding="8dp">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="Phone number"
                            android:textSize="18sp" />

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center_vertical">

                            <com.hbb20.CountryCodePicker
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                />

                            <EditText
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:enabled="false"
                                android:hint="phone"
                                android:inputType="phone"
                                android:singleLine="true" />
                        </LinearLayout>
                    </LinearLayout>
                </RelativeLayout>

                <TextView style="@style/sectionText"
                    android:text="Set country programmatically
                   "/>

                <TextView
                    style="@style/pointText"
                    android:text="\u2022 Using country name code"
                    android:textStyle="bold"/>
                <TextView
                    style="@style/pointText"
                    android:layout_marginLeft="24dp"
                    android:text="Use setCountryForNameCode() method." />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="32dp"
                    android:layout_marginRight="16dp"
                    android:gravity="center_vertical"
                    android:orientation="horizontal">
                    <EditText
                        android:id="@+id/editText_countryNameCode"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:maxWidth="50dp"
                        android:minWidth="50dp"
                        android:singleLine="true"
                        android:text="US" />
                    <Button
                        android:id="@+id/button_setCountryNameCode"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:maxLines="2"
                        android:text="set country with name code  'US'"
                        />
                </LinearLayout>
                <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                android:text="OR"
                    android:textSize="24sp" />
                <TextView
                    style="@style/pointText"
                    android:text="\u2022 Using phone code"
                    android:textStyle="bold"/>

                <TextView
                    style="@style/pointText"
                    android:layout_marginLeft="24dp"
                    android:text="\u2022 Use setCountryForPhoneCode() method." />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="32dp"
                    android:layout_marginRight="16dp"
                    android:gravity="center_vertical"
                    android:orientation="horizontal">
                    <EditText
                        android:id="@+id/editText_countryCode"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:maxWidth="50dp"
                        android:minWidth="50dp"
                        android:singleLine="true"
                        android:text="672" />
                    <Button
                        android:id="@+id/button_setCountry"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:maxLines="2"
                        android:text="set country with code 672"
                        />
                </LinearLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="16dp"
                    android:layout_marginLeft="32dp"
                    android:layout_marginRight="16dp"
                    android:background="@color/dullBG"
                    android:padding="8dp">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="Phone number"
                            android:textSize="18sp" />

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center_vertical">

                            <com.hbb20.CountryCodePicker
                                android:id="@+id/ccp"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content" />

                            <EditText
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:enabled="false"
                                android:hint="phone"
                                android:inputType="phone"
                                android:singleLine="true" />
                        </LinearLayout>
                    </LinearLayout>
                </RelativeLayout>
                <TextView
                    style="@style/pointText"
                    android:layout_marginLeft="32dp"
                    android:layout_marginRight="16dp"
                    android:text="\u2022 If specified country code does not match in any country, default country will be set in to CCP." />

                <TextView
                    style="@style/sectionText"
                    android:text="How to listen change in selection?" />

                <TextView
                    style="@style/pointText"
                    android:text="\u2022 To get call back when country is changed, you need to add OnCountryChangeListener from code." />

                <TextView
                    style="@style/pointText"
                    android:text="\u2022 To set listener, use ccp.setOnCountryChangeListener(changeListener); function." />

                <Button
                    android:id="@+id/button_next"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Next feature >"/>
            </LinearLayout>
        </ScrollView>
    </android.support.v7.widget.CardView>
</FrameLayout>


text:
<?php
/**
 * [PHPFOX_HEADER]
 */

defined('PHPFOX') or exit('NO DICE!');

Phpfox::getLibClass('phpfox.mail.interface');

/**
 * Email Driver Layer
 * Our email loads a 3rd party email class that usually has support for both sendmail and smtp.
 *
 * Example:
 *
 * Phpfox::getLib('mail')->to('foo@bar.com')
 * 		->subject('Test Subject')
 * 		->message('Test Message')
 * 		->send();
 *
 *
 * @copyright		[PHPFOX_COPYRIGHT]
 * @author			Raymond Benc
 * @package 		Phpfox
 * @version 		$Id: mail.class.php 4578 2012-07-31 13:07:50Z Miguel_Espinoza $
 */
class Phpfox_Mail
{
	/**
	 * Object of the 3rd party library we are using to send the actual image.
	 *
	 * @var object
	 */
	private $_oMail = null;

	/**
	 * STRING or ARRAY of emails or users to send the emai to.
	 *
	 * @var mixed
	 */
	private $_mTo = null;

	/**
	 * ARRAY if loading a phrase or STRING if we are passing a subject.
	 *
	 * @var mixed
	 */
	private $_aSubject = null;

	/**
	 * The name of the person sending the email.
	 *
	 * @var string
	 */
	private $_sFromName = null;

	/**
	 * The email of the person sending the email.
	 *
	 * @var string
	 */
	private $_sFromEmail = null;

	/**
	 * Notification ID to be used to check if a user has privacy settings on receiving an email.
	 *
	 * @var string
	 */
	private $_sNotification = null;

	/**
	 * ARRAY of users to email and their information.
	 *
	 * @var array
	 */
	private $_aUsers = null;

	/**
	 * ARRAY of loading a phrase or STRING of we are passing the message directly.
	 *
	 * @var mixed
	 */
	private $_aMessagePlain = null;

	/**
	 * TRUE to send the message to ourself and FALSE to not.
	 *
	 * @var bool
	 */
	private $_bSendToSelf = false;

	/**
	 * Controlls if we should include the default header in the message. Default is TRUE.
	 *
	 * @var bool
	 */
	private $_bMessageHeader = true;

	/**
	 * ARRAY of loading a phrase or STRING of we are passing the message directly.
	 *
	 * @var mixed
	 */
	private $_aMessage = null;

	/**
	 * Used for global replacements like site_name and site_email
	 * @var String
	 */
	private $_sArray = 'array()';
	/**
	 * Class constructor that loads a specific method of sending emails (sendmail or smtp)
	 *
	 * @param string $sMethod Method to send an email (sendmail or smtp)
	 */
	public function __construct($sMethod = null)
    {
    	$this->_oMail = Phpfox::getLib('mail.driver.phpmailer.' . ($sMethod === null ? Phpfox::getParam('core.method') : $sMethod));
		$this->_sArray = 'array("site_name" => "'.Phpfox::getParam('core.site_title').'","site_email" => "'.Phpfox::getParam('core.email_from_email').'")';
    }

    /**
     * Run a test if we are able to send out an email using the default method being loaded.
     *
     * @param array $aVals ARRAY of values to test.
     * @return object Returns this class.
     */
    public function test($aVals)
    {
    	$this->_oMail->test($aVals);

    	return $this;
    }

    /**
     * Identify who this email will be sent to. Can be an actual email or a user ID or an array of
     * emails or user IDs.
     *
     * @param mixed $mTo ARRAY of emails/users or STRING of email/user
     * @return object Returns this class.
     */
    public function to($mTo)
    {
    	$this->_mTo = $mTo;

    	return $this;
    }

    /**
     * Subject of the email.
     *
     * @param mixed $aSubject ARRAY if loading a phrase or STRING if we are passing a subject.
     * @return object Returns this class.
     */
    public function subject($aSubject)
    {
		$this->_aSubject = $aSubject;

		return $this;
    }

    /**
     * The name of the person sending out the email.
     *
     * @param string $sFromName Persons name.
     * @return object Returns this class.
     */
    public function fromName($sFromName)
    {
    	$this->_sFromName = $sFromName;

    	return $this;
    }

    /**
     * Send a copy to our own email.
     *
     * @param bool $bSendToSelf TRUE will send a copy and FALSE will not.
     * @return object Returns this class.
     */
    public function sendToSelf($bSendToSelf)
    {
    	$this->_bSendToSelf = $bSendToSelf;

    	return $this;
    }

    /**
     * Email of the person sending out this email.
     *
     * @param string $sFromEmail Email.
     * @return object Returns this class.
     */
    public function fromEmail($sFromEmail)
    {
    	$this->_sFromEmail = $sFromEmail;

    	return $this;
    }

    /**
     * Notification param for this specific email to check a users privacy settings.
     *
     * @param string $sNotification Param of the notification.
     * @return object Returns this class.
     */
    public function notification($sNotification)
    {
    	$this->_sNotification = $sNotification;

    	return $this;
    }

    /**
     * Message of the email.
     *
     * @param mixed $aMessage ARRAY of loading a phrase or STRING of we are passing the message directly.
     * @return object Returns this class.
     */
    public function message($aMessage)
    {
		if (is_array($aMessage))
		{
			if (!isset($aMessage[1]['site_name']))
			{
				$aMessage[1]['site_name'] = Phpfox::getParam('core.site_title');
			}
			if (!isset($aMessage[1]['site_url']))
			{
				$aMessage[1]['site_url'] = Phpfox::getLib('url')->getDomain();
			}
		}
		$this->_aMessage = $aMessage;

    	return $this;
    }

    /**
     * Identify if we should load the message header we include by default.
     *
     * @param bool $bMessageHeader Controlls if we should include the default header in the message. Default is TRUE.
     * @return object Returns this class.
     */
    public function messageHeader($bMessageHeader)
    {
    	$this->_bMessageHeader = $bMessageHeader;

    	return $this;
    }

    /**
     * Message of the email (Plain Text).
     *
     * @param mixed $aMessage ARRAY of loading a phrase or STRING of we are passing the message directly.
     * @return object Returns this class.
     */
	public function messagePlain($aMessage)
	{
		$this->_aMessagePlain = $aMessage;

		return $this;
	}

	/**
	 * We load users information in our send() method, however you can also load users by passing
	 * an array of their information with this method.
	 *
	 * @param array $aUser ARRAY of users information.
	 * @return object Returns this class.
	 */
	public function aUser($aUser)
	{
		if (!isset($aUser['user_id']) || !isset($aUser['full_name']) || !isset($aUser['email']))
		{
			// Phpfox_Error::set('aUser incomplete');
		}
		$this->_aUsers[] = ($aUser);

		return $this;
	}

	/**
	 * Email address validator based on http://www.linuxjournal.com/article/9585 and RFC 2821
	 * Uses recursion for arrays
	 *
	 * @param mixed $mEmail array|string
	 * @return boolean true if all valid
	 */
	public function checkEmail($mEmail)
	{
		if (is_array($mEmail))
		{
			foreach($mEmail as $sEmail)
			{
				if (!$this->_checkEmail($sEmail, Phpfox::getParam('core.use_dnscheck')))
				{
					// return here before keep going
					return false;
				}
			}
			return true;
		}
		return $this->_checkEmail($mEmail);
	}

    /**
     * Method to send out the email.
     * Checks:
     * 		(message || to) === null -> return false;
     * 		(sFromName || sFromEmail) === null -> getParam(core.
     * 		(Notification) assumes to is an array of integers, otherwise return false
	 *
	 * @example Phpfox::getLib('mail')->to('user@email.com')->subject('Test Subject')->message('This is a test message')->send();
     * @example Phpfox::getLib('mail')->to(array('user1@email.com', 'user2@email.com', 'user3@email.com')->subject('Test Subject')->message('This is a test message')->send()
     * @return boolean
     */
    public function send($bDoCheck = false)
    {
		if (defined('PHPFOX_SKIP_MAIL'))
		{
			return true;
		}

    	// turn into an array
    	if (!is_array($this->_mTo))
    	{
    		$this->_mTo = array($this->_mTo);
    	}

		// check if the mail(s) are valid
		if ($bDoCheck && $this->checkEmail($this->_mTo) == false)
		{
			return false;
		}

    	if ($this->_aMessage === null || $this->_mTo === null)
    	{
    		return false;
    	}

    	if ($this->_sFromName === null)
		{
			$this->_sFromName = Phpfox::getParam('core.mail_from_name');
		}

		if ($this->_sFromEmail === null)
		{
			$this->_sFromEmail = Phpfox::getParam('core.email_from_email');
		}

		$this->_sFromName = html_entity_decode($this->_sFromName, null, 'UTF-8');

		$sIds = '';
		$sEmails = '';

		if (!empty($this->_aUsers))
		{
			foreach ($this->_aUsers as $aUser)
			{
				if (isset($aUser['user_id']) && !empty($aUser['user_id']))
				{
					$sIds .= (int) $aUser['user_id'] . ',';
				}
			}
		}
		else
		{
			foreach ($this->_mTo as $mTo)
			{
				if (strpos($mTo, '@'))
				{
					$sEmails .= $mTo . ',';
				}
				else
				{
					$sIds .= (int) $mTo . ',';
				}
			}
		}
		$sIds = rtrim($sIds, ',');
		$sEmails = rtrim($sEmails, ',');

		$bIsSent = true;

		if (!empty($sIds))
		{
			if ($this->_sNotification !== null)
			{
				Phpfox::getLib('database')->select('un.user_notification, ')->leftJoin(Phpfox::getT('user_notification'), 'un', "un.user_id = u.user_id AND un.user_notification = '" . Phpfox::getLib('database')->escape($this->_sNotification) . "'");
			}

			(($sPlugin = Phpfox_Plugin::get('mail_send_query')) ? eval($sPlugin) : false);

			if ($this->_aUsers === null)
		    {
				$aUsers = Phpfox::getLib('database')->select('u.user_id, u.email, u.language_id, u.full_name, u.user_group_id')
					->from(Phpfox::getT('user'), 'u')
					->where('u.user_id IN(' . $sIds . ')')
					->execute('getSlaveRows');
			}
			else
			{
				$aUsers = $this->_aUsers;
			}
		    if (!empty($aUsers) && count($aUsers) > 0)
			{
				foreach ($aUsers as $aUser)
				{
					// User is banned, lets not send them any emails
					if (isset($aUser['user_group_id']) && Phpfox::getService('user.group.setting')->getGroupParam($aUser['user_group_id'], 'core.user_is_banned'))
					{
						continue;
					}

					// Lets not send out an email to myself
					if ($this->_bSendToSelf === false && $aUser['user_id'] == Phpfox::getUserId())
					{
						continue;
					}

					$bCanSend = true;
					if ($this->_sNotification !== null && $aUser['user_notification'])
					{
						$bCanSend = false;
					}

					if ($bCanSend === true)
					{
						// load the messages in their language
						$aUser['language_id'] = ($aUser['language_id'] == null || empty($aUser['language_id'])) ?  Phpfox::getParam('core.default_lang_id') : $aUser['language_id'];

						if (is_array($this->_aMessage))
						{
							$sMessage = Phpfox::getPhrase($this->_aMessage[0], isset($this->_aMessage[1]) ? array_merge($aUser, $this->_aMessage[1]) : $aUser, false, null, $aUser['language_id']);
						}
						else
						{
							$sMessage = $this->_aMessage;
						}

						if (is_array($this->_aMessagePlain))
						{
							$sMessagePlain = Phpfox::getPhrase($this->_aMessagePlain[0], isset($this->_aMessagePlain[1]) ? array_merge($aUser, $this->_aMessagePlain[1]) : $aUser, false, null, $aUser['language_id']);
						}
						else
						{
							$sMessagePlain = $this->_aMessagePlain;
						}

						$sMessage = preg_replace('/' . preg_quote(Phpfox::getLib('url')->makeUrl(''), '/') . '/is', str_replace('mobile/', '', Phpfox::getLib('url')->makeUrl('')), $sMessage);
						$sMessagePlain = preg_replace('/' . preg_quote(Phpfox::getLib('url')->makeUrl(''), '/') . '/is', str_replace('mobile/', '', Phpfox::getLib('url')->makeUrl('')), $sMessagePlain);

						if (is_array($this->_aSubject))
						{
							$sSubject = Phpfox::getPhrase($this->_aSubject[0], isset($this->_aSubject[1]) ? array_merge($aUser,$this->_aSubject[1]) : $aUser, false, null, $aUser['language_id']);
						}
						else
						{
							$sSubject = $this->_aSubject;
						}

						$sMessage = preg_replace('/\{setting var=\'(.*)\'\}/ise', "'' . Phpfox::getParam('\\1') . ''", $sMessage);
						$sMessage = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1',{$this->_sArray}, false, null, '".$aUser['language_id']."') . ''", $sMessage);
						$sMessagePlain = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1',{$this->_sArray}, false, null, '".$aUser['language_id']."') . ''", $sMessagePlain);
						$sMessagePlain = preg_replace('/\{setting var=\'(.*)\'\}/ise', "'' . Phpfox::getParam('\\1') . ''", $sMessagePlain);
						$sSubject = preg_replace('/\{setting var=\'(.*)\'\}/ise', "'' . Phpfox::getParam('\\1') . ''", $sSubject);
						$sSubject = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1',{$this->_sArray}, false, null, '".$aUser['language_id']."') . ''", $sSubject);
						// $sSubject = html_entity_decode($sSubject, null, 'UTF-8'); // http://www.phpfox.com/tracker/view/10392/
						$sEmailSig = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1',{$this->_sArray}, false, null, '".$aUser['language_id']."') . ''", Phpfox::getParam('core.mail_signature'));

						// Load plain text template
						$sTextPlain = Phpfox::getLib('template')->assign(array(
									'sName' => $aUser['full_name'],
									'bHtml' => false,
									'sMessage' => $this->_aMessagePlain !== null ? $sMessagePlain : $sMessage,
									'sEmailSig' => $sEmailSig,
									'bMessageHeader' => $this->_bMessageHeader
								)
							)->getLayout('email', true);

						// Load HTML text template
						$sTextHtml = Phpfox::getLib('template')->assign(array(
									'sName' => $aUser['full_name'],
									'bHtml' => true,
									'sMessage' => str_replace("\n", "
", $sMessage),
									'sEmailSig' => str_replace("\n", "
", $sEmailSig),
									'bMessageHeader' => $this->_bMessageHeader
								)
							)->getLayout('email', true);

						if (defined('PHPFOX_DEFAULT_OUT_EMAIL'))
						{
							$aUser['email'] = PHPFOX_DEFAULT_OUT_EMAIL;
						}

						(($sPlugin = Phpfox_Plugin::get('mail_send_call')) ? eval($sPlugin) : false);

						if (empty($aUser['email']))
						{
							continue;
						}

						if (!isset($bSkipMailSend))
						{
							$bIsSent = (defined('PHPFOX_CACHE_MAIL') ? $this->_cache($aUser['email'], $sSubject, $sTextPlain, $sTextHtml, $this->_sFromName, $this->_sFromEmail) : $this->_oMail->send($aUser['email'], $sSubject, $sTextPlain, $sTextHtml, $this->_sFromName, $this->_sFromEmail));
						}
					}
				}
			}
		}

		if (!empty($sEmails))
		{
			$aEmails = explode(',', $sEmails);
			foreach ($aEmails as $sEmail)
			{
				$sEmail = trim($sEmail);

				if (is_array($this->_aMessage))
				{
					$sMessage = Phpfox::getPhrase($this->_aMessage[0], $this->_aMessage[1], false, null, Phpfox::getParam('core.default_lang_id'));
				}
				else
				{
					$sMessage = $this->_aMessage;
				}
				if (is_array($this->_aMessagePlain))
				{
					$sMessagePlain = Phpfox::getPhrase($this->_aMessagePlain[0], $this->_aMessagePlain[1], false, null, Phpfox::getParam('core.default_lang_id'));
				}
				else
				{
					$sMessagePlain  = $this->_aMessagePlain;
				}
				if (is_array($this->_aSubject))
				{
					$sSubject = Phpfox::getPhrase($this->_aSubject[0], $this->_aSubject[1], false, null, Phpfox::getParam('core.default_lang_id'));
				}
				else
				{
					$sSubject = $this->_aSubject;
				}
				$sEmailSig = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1', {$this->_sArray}, false, null, '". Phpfox::getParam('core.default_lang_id')."') . ''", Phpfox::getParam('core.mail_signature'));
				$sMessagePlain = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1', {$this->_sArray}, false, null, '". Phpfox::getParam('core.default_lang_id')."') . ''", $sMessagePlain);
				$sMessage = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1', {$this->_sArray}, false, null, '". Phpfox::getParam('core.default_lang_id')."') . ''", $sMessage);
				$sSubject = preg_replace('/\{phrase var=\'(.*)\'\}/ise', "'' . Phpfox::getPhrase('\\1', {$this->_sArray}, false, null, '". Phpfox::getParam('core.default_lang_id')."') . ''", $sSubject);

				// Load plain text template
				$sTextPlain = Phpfox::getLib('template')->assign(array(
						'bHtml' => false,
						'sMessage' => $this->_aMessagePlain !== null ? $sMessagePlain : $sMessage,
						'sEmailSig' => $sEmailSig,
						'bMessageHeader' => $this->_bMessageHeader
					)
				)->getLayout('email', true);

				// Load HTML text template
				$sTextHtml = Phpfox::getLib('template')->assign(array(
						'bHtml' => true,
						'sMessage' => str_replace("\n", "
", $sMessage),
						'sEmailSig' => str_replace("\n", "
", $sEmailSig),
						'bMessageHeader' => $this->_bMessageHeader
					)
				)->getLayout('email', true);

				if (empty($sEmail))
				{
					continue;
				}

				$bIsSent = (defined('PHPFOX_CACHE_MAIL') ? $this->_cache($sEmail, $sSubject, $sTextPlain, $sTextHtml, $this->_sFromName, $this->_sFromEmail) : $this->_oMail->send($sEmail, $sSubject, $sTextPlain, $sTextHtml, $this->_sFromName, $this->_sFromEmail));
			}
		}
		$this->_aUsers = null;
		return $bIsSent;
    }

    private function _cache($sEmail, $sSubject, $sTexPlain, $sTextHtml, $sFromName, $sFromEmail)
    {
    	Phpfox::getLib('file')->write(PHPFOX_DIR_FILE . 'log' . PHPFOX_DS . 'email_' . md5(str_replace(' ', '_', $this->_aSubject) . PHPFOX_TIME . uniqid()) . '.html', "Email: {$sEmail}
\nSubject: {$sSubject}\n
Text Plan:{$sTexPlain}\n
Text HTML: {$sTextHtml}\n
From Name: {$sFromName}\n
From Email: {$sFromEmail}");

    	return true;
    }

	/**
	 * Checks to validate an email.
	 *
	 * @param string $sEmail email to check
	 * @param boolean $bDoDnsCheck http://php.net/checkdnsrr check for domain name, this could slow down the function so use wisely
	 * @return boolean
	 */
	private function _checkEmail($sEmail, $bDoDnsCheck = false)
	{
		$iAtIndex = strrpos($sEmail, "@");

		if ($iAtIndex === false)
		{ // there is no @ symbol
		   return false;
		}

		$sDomain = substr($sEmail, $iAtIndex+1);
		$sLocal = substr($sEmail, 0, $iAtIndex);

		$iDomainLen = strlen($sDomain);
		$iLocalLen = strlen($sLocal);

		if ( ($iLocalLen < 1) || ($iLocalLen > 64) || ($iDomainLen < 1) || ($iDomainLen > 255))
		{ // either the user or the domain are not within valid values
			return false;
		}

		if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$sLocal)))
		{
		   // character not valid in local part unless
		   // local part is quoted
		   if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$sLocal)))
		   {
			  return false;
		   }
		}

		// check for dots according to RFC 2822 3.2.4
		if ($sLocal[0] == '.' || $sLocal[$iLocalLen-1] == '.' || preg_match('/\\.\\./', $sLocal))
		{
		   // local starts or ends with a dot or has 2 consecutive dots
		   return false;
		}
		// validate domain
		if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $sDomain) || (preg_match('/\\.\\./', $sDomain)))
		{
		   // Domain has 2 consecutive dots or invalid characters
		   return false;
		}
		elseif ($bDoDnsCheck == true && function_exists('checkdnsrr')
			&& !(checkdnsrr($sDomain,"MX") || checkdnsrr($sDomain, "A")))
		{
		   // domain not found in DNS
		   return false;
		}

		return true;
	}
}

?>


text:
using System;

namespace Greenery.MessageQueueMiddleware.Extensions
{
    /// <summary>
    /// 事件描述扩展方法类
    /// </summary>
    public static class DescriptionExtensions
    {
        /// <summary>
        /// 事件描述/订阅描述分隔符
        /// </summary>
        internal const string Separator = ".";
        /// <summary>
        /// 比较两个描述
        /// </summary>
        /// <param name="descriptionsA">A描述</param>
        /// <param name="descriptionsB">B描述</param>
        /// <returns>是否等同</returns>
        public static bool EqualsTo(this string[] descriptionsA, string[] descriptionsB)
        {
            return descriptionsA.Join() == descriptionsB.Join();
        }
        /// <summary>
        /// 比较两个事件描述
        /// </summary>
        /// <param name="descriptionsA">A事件描述</param>
        /// <param name="descriptionsStrB">B事件描述</param>
        /// <returns>是否等同</returns>
        public static bool EqualsTo(this string[] descriptionsA, string descriptionsStrB)
        {
            return descriptionsA.Join() == descriptionsStrB;
        }
        /// <summary>
        /// 确定此事件描述实例的开头是否与指定的事件描述匹配。
        /// </summary>
        /// <param name="descriptionsA">A事件描述</param>
        /// <param name="descriptionsB">B事件描述</param>
        /// <returns>如果B事件描述与A事件描述的开头匹配,则为 true;否则为 false。</returns>
        public static bool StartsWith(this string descriptionsA, string[] descriptionsB)
        {
            return descriptionsA.StartsWith(descriptionsB.Join());
        }
        /// <summary>
        /// 确定此事件描述实例的开头是否与指定的事件描述匹配。
        /// </summary>
        /// <param name="descriptionsA">A事件描述</param>
        /// <param name="descriptionsStrB">B事件描述</param>
        /// <returns>如果B事件描述与事件描述的开头匹配,则为 true;否则为 false。</returns>
        public static bool StartsWith(this string[] descriptionsA, string descriptionsStrB)
        {
            return descriptionsA.Join().StartsWith(descriptionsStrB);
        }
        /// <summary>
        ///获取事件描述的字符串
        /// </summary>
        /// <param name="descriptions">事件描述</param>
        /// <returns>返回事件描述的字符串</returns>
        public static string Join(this string[] descriptions)
        {
            return string.Join(Separator, descriptions);
        }
        /// <summary>
        /// 获取事件描述的第一项作为事件的分组
        /// </summary>
        /// <param name="descriptions">事件描述</param>
        /// <returns>返回事件分组</returns>
        public static string GetGroup(this string[] descriptions)
        {
            if (descriptions.Length < 1)
                throw new IndexOutOfRangeException("描述信息不全!");
            return descriptions[0];
        }
    }
}


text:
import pefile
import peutils

from datetime import datetime

class Plugin:

	__NAME__ = 'pe'

	def __init__(self, args):

		self.args = args

	def analyze(self, afile):
		'''Analyze the Windows portable executable format.

		ref: https://en.wikipedia.org/wiki/Portable_Executable

		Args:
			afile (FileAnalysis): Mandrake file analysis object.

		Returns:
			None
		'''
		if afile.mime_type == 'application/x-dosexec':
			try:
				pe = pefile.PE(afile.path)
			except:
				afile.errors = afile.errors + ['pe plugin: unsupported filetype']
				output = 'None'
				afile.plugin_output[self.__NAME__] = output
				return

			# Collect interesting flags from the binary
			# Allows >32 bit values for ASLR
			afile.high_entropy_aslr = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA
			afile.uses_aslr = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
			afile.force_integrity = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY
			# DEP
			afile.uses_dep = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NX_COMPAT
			afile.force_no_isolation = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NO_ISOLATION
			afile.uses_seh = not pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NO_SEH
			afile.no_bind = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_NO_BIND
			afile.app_container = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_APPCONTAINER
			afile.wdm_driver = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_WDM_DRIVER
			afile.uses_cfg = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_GUARD_CF
			afile.terminal_server_aware = pe.OPTIONAL_HEADER.IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE

			# Determine whether the pe file is likely to be packed
			afile.is_probably_packed = peutils.is_probably_packed(pe)

			# Attach pe parser warnings
			afile.warnings = pe.get_warnings()

			# This method determines whether or not the binary is a dll
			afile.is_dll = pe.is_dll()
			afile.is_exe = pe.is_exe()
			afile.is_driver = pe.is_driver()

			# Does the checksum check out?
			afile.verify_checksum = pe.verify_checksum()

			# Determine the compile date of a binary
			compile_date = datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp)
			afile.compile_date = compile_date

			# Compute / retrieve the imphash
			afile.imphash = pe.get_imphash()

			# Parse out the import table from within the pe file
			imports = {}
			if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
				afile.has_import_table = True
				for entry in pe.DIRECTORY_ENTRY_IMPORT:
					imports[entry.dll] = []
					for imp in entry.imports:
						imports[entry.dll].append(imp.name)

				afile.imports = imports

			# Parse out the export table listed within the pe file
			exports = []
			if hasattr(pe, 'DIRECTORY_ENTRY_EXPORT'):
				afile.has_export_table = True
				for entry in pe.DIRECTORY_ENTRY_EXPORT.symbols:
					exports.append(entry.name)

				afile.exports = exports

			pe.close()


text:
require 'rails_helper'

# Specs in this file have access to a helper object that includes
# the ScholarshipsHelper. For example:
#
# describe ScholarshipsHelper do
#   describe "string concat" do
#     it "concats two strings with spaces" do
#       expect(helper.concat_strings("this","that")).to eq("this that")
#     end
#   end
# end
RSpec.describe ScholarshipsHelper, type: :helper do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
require 'json'
require 'curb'

module SeafileApi
  class Connect

    attr_accessor :user_name
    attr_accessor :password
    attr_accessor :host
    attr_accessor :repo
    attr_accessor :token

    def initialize(user_name ,password,host,repo)
      self.user_name  = user_name
      self.password   = password
      self.host       = host
      self.repo       = repo
      self.token      = self.get_token
    end

  end

end
require "seafile-api/file/post_operations"
require "seafile-api/message"
require "seafile-api/group"
require "seafile-api/directory"
require "seafile-api/group/group"
require "seafile-api/group/group_member"
require "seafile-api/group/group_message"
require "seafile-api/account"
require "seafile-api/starred"
require "seafile-api/share"
require "seafile-api/library"
require "seafile-api/library/del_library"
require "seafile-api/library/get_library"
require "seafile-api/library/post_library"
require "seafile-api/shared/share"
require "seafile-api/shared/shared_files"
require "seafile-api/shared/shared_libraries"
require "seafile-api/file/dry_methods"
require "seafile-api/file/file_operations"
require "seafile-api/file/get_operations"
require "seafile-api/file"


text:
package com.bnmi.ourmap.web.actions;

import com.bnmi.ourmap.control.EasyDelegate;
import com.bnmi.ourmap.model.Rol;
import com.bnmi.ourmap.model.User;
import com.bnmi.ourmap.web.Constantes;
import com.inga.utils.SigarUtils;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author Manuel Camilo Cuesta
 */
public class NewUserForm extends ActionForm {

    private User user;
    private String userid;
    private String pwd;
    private String nombre;
    private String lastname;
    private String rol;

    @Override
    public void reset(ActionMapping mapping, HttpServletRequest request) {
    }

    @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();

        HttpSession session = request.getSession();
        EasyDelegate del = (EasyDelegate) session.getAttribute(Constantes.DELEGATE);

        try
        {
            User principal = (User) session.getAttribute(Constantes.USER);
            Rol principalRol = del.getRol(principal.getRol());
            List<Rol> allRoles = del.listRoles();
            List<Rol> showRoles = new ArrayList<Rol>();
            for ( Rol r : allRoles )
            {
                if ( r.getWeight().intValue() <= principalRol.getWeight().intValue() )
                   showRoles.add( r );
            }

            request.setAttribute("roles", showRoles );

        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
        }

        String formSubmited = SigarUtils.validarCadena( request.getParameter("formSubmited"));
        if ( formSubmited == null )
        {
            errors.add( "formSubmited", new ActionMessage("formSubmited"));
            return errors;
        }

        userid = SigarUtils.validarCadena( request.getParameter("userid"));
        pwd    = SigarUtils.validarCadena( request.getParameter("pwd") );
        nombre = SigarUtils.validarCadena( request.getParameter("nombre") );
        lastname = SigarUtils.validarCadena( request.getParameter("lastname"));
        rol = SigarUtils.validarCadena( request.getParameter("rol"));

        try
        {
            del.getUser(userid);
            errors.add("error", new ActionMessage("user.exists"));
            request.setAttribute("error-message", "User already exists: " + userid );
            return errors;
        }
        catch ( Exception rex )
        {
        }

        user = new User();
        user.setId(userid);
        user.setPwd(pwd);
        user.setNombre( nombre );
        user.setLastname( lastname );
        user.setRol( rol );

        return errors;

    }

    /**
     * @return the user
     */
    public User getUser() {
        return user;
    }

    /**
     * @param user the user to set
     */
    public void setUser(User user) {
        this.user = user;
    }

    /**
     * @return the userid
     */
    public String getUserid() {
        return userid;
    }

    /**
     * @param userid the userid to set
     */
    public void setUserid(String userid) {
        this.userid = userid;
    }

    /**
     * @return the pwd
     */
    public String getPwd() {
        return pwd;
    }

    /**
     * @param pwd the pwd to set
     */
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    /**
     * @return the nombre
     */
    public String getNombre() {
        return nombre;
    }

    /**
     * @param nombre the nombre to set
     */
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    /**
     * @return the lastname
     */
    public String getLastname() {
        return lastname;
    }

    /**
     * @param lastname the lastname to set
     */
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

}


text:
Imports MySql.Data.MySqlClient

Public Class frmListOfStudentsAdmission

#Region "Database"

    Public Sub GatStudentsAdmittedOnCurrentTermYear()
        Dim dtaTable As New DataTable

        dtaTable = GetStudentsAdmissionByTermYear(ConnectionString, "GatStudentsAdmittedOnCurrentTermYear", 4, CurrentTerm, CurrentSchoolYear)
        Me.dvgList.DataSource = dtaTable
        ArrangeDatagridView(Me.dvgList)

    End Sub

    Public Sub GatStudentsAdmittedAll()
        Dim dtaTable As New DataTable

        dtaTable = GetStudentsAdmissionByTermYear(ConnectionString, "GatStudentsAdmittedAll", 4, CurrentTerm, CurrentSchoolYear)
        Me.dvgList.DataSource = dtaTable
        ArrangeDatagridView(Me.dvgList)

    End Sub

    Public Sub GatStudentsByLastName(ByVal strSearch As String, ByVal strSFor As String)
        Dim dtaTable As New DataTable

        dtaTable = GetDataAndReturnDataSetSearch(ConnectionString, "GatStudentsByLastName", 4, strSearch & "%")
        Me.dvgList.DataSource = dtaTable
        ArrangeDatagridView(Me.dvgList)

    End Sub

#End Region

#Region "Helper"

    Private Sub ArrangeDatagridView(ByVal TheGridView As DataGridView)
        Try
            With TheGridView
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

                .Columns(0).Visible = False
                .Columns(1).Visible = False
                .Columns(2).Visible = False
                .Columns(11).Visible = False
                .Columns(12).Visible = False
                .Columns(13).Visible = False

                .Columns(3).HeaderText = "EDP Number"
                .Columns(4).HeaderText = "Course"
                .Columns(5).HeaderText = "Name"
                .Columns(6).HeaderText = "Civil Status"
                .Columns(7).HeaderText = "Sex"
                .Columns(8).HeaderText = "Date of Birth"
                .Columns(9).HeaderText = "Home Address"
                .Columns(10).HeaderText = "Present Address"

                .Columns(3).Width = "100"
                .Columns(4).Width = "100"
                .Columns(5).Width = "255"
                .Columns(6).Width = "100"
                .Columns(8).Width = "100"
                .Columns(9).Width = "200"
                .Columns(10).Width = "200"

                .Columns(8).DefaultCellStyle.Format = "MMM/dd/yyyy"
                '.Columns(5).DefaultCellStyle.Format = "MMM/dd/yyyy"
                .Columns(8).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                '.Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

                '.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            End With
        Catch ex As Exception

        End Try

    End Sub

#End Region

    Private Sub cmdClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClose.Click
        Me.Close()
    End Sub

    Private Sub frmListOfDepartments_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.ToolStripStatusLabel1.Text = SetWindowHeader(Me, "List of Admissions - " & CurrentTerm & ", " & CurrentSchoolYear)
        'Me.Text = "List of Departments"
        Me.cmdRefresh.PerformClick()

    End Sub

    Private Sub cmdAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddNew.Click
        Dim newfrm As New frmAddEditAdmission

        With newfrm
            .IsAdding = True
            .FormHeading = "Add New Student"
            .ShowDialog()
            If .MustUpdate = True Then
                Me.cmdRefresh.PerformClick()
                Me.txtSearch.Text = .txtLastName.Text & ", " & .txtFirstName.Text
            End If
        End With
    End Sub

    Private Sub cmdRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRefresh.Click
        GatStudentsAdmittedOnCurrentTermYear()
    End Sub

    Private Sub cmdModify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdModify.Click
        Dim newfrm As New frmAddEditAdmission

        With newfrm
            .IsAdding = False
            .FormHeading = "Modify Student"
            .CurrentStudeID = Me.dvgList.CurrentRow.Cells(0).Value
            If IsDBNull(Me.dvgList.CurrentRow.Cells(2).Value) = True Then
                .CurrentCOurseID = -1
            Else
                .CurrentCOurseID = Me.dvgList.CurrentRow.Cells(2).Value
            End If

            .txtEDPNumber.Text = Me.dvgList.CurrentRow.Cells(3).Value.ToString
            .txtLastName.Text = Me.dvgList.CurrentRow.Cells(11).Value.ToString
            .txtFirstName.Text = Me.dvgList.CurrentRow.Cells(12).Value.ToString
            .txtMiddle.Text = Me.dvgList.CurrentRow.Cells(13).Value.ToString
            .cboCivilStatus.Text = Me.dvgList.CurrentRow.Cells(6).Value.ToString
            .cboGender.Text = Me.dvgList.CurrentRow.Cells(7).Value.ToString
            .dtpBirth.Value = Me.dvgList.CurrentRow.Cells(8).Value.ToString
            .txtPAddress.Text = Me.dvgList.CurrentRow.Cells(10).Value.ToString
            .txtHAdress.Text = Me.dvgList.CurrentRow.Cells(9).Value.ToString
            .txtContactPersonName.Text = Me.dvgList.CurrentRow.Cells(15).Value.ToString
            .txtContactPersonNumber.Text = Me.dvgList.CurrentRow.Cells(16).Value.ToString
            .ShowDialog()
            If .MustUpdate = True Then
                Me.cmdRefresh.PerformClick()
                Me.txtSearch.Text = .txtLastName.Text & ", " & .txtFirstName.Text
            End If
        End With
    End Sub

    Private Sub txtSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.Click

    End Sub

    Private Sub txtSearch_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyUp
        Select Case e.KeyCode
            Case Keys.Enter
                GatStudentsByLastName(Me.txtSearch.Text, "Last Name")
        End Select
    End Sub

    Private Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged

        Dim i As Integer = 0

        With Me
            For i = 0 To .dvgList.Rows.Count - 1
                If .dvgList.Rows(i).Cells(5).Value.ToString.StartsWith(txtSearch.Text, StringComparison.InvariantCultureIgnoreCase) Then
                    .dvgList.Rows(i).Selected = True
                    .dvgList.CurrentCell = .dvgList(5, i)
                    .dvgList.FirstDisplayedScrollingRowIndex = .dvgList.CurrentCell.RowIndex
                    Exit Sub
                End If
            Next
        End With

    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Dim newfrm As New frmSearchStudent

        With newfrm
            .Show()
        End With
    End Sub

    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click

    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        GatStudentsAdmittedAll()
    End Sub
End Class


text:
package main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/xrash/smetrics"
)

type GuessEpisode struct {
	Season  int
	Episode int
	Name    string
}

/// From a tv episode eg 'Some TV Show - Episode Name.vob' it looks up tmdb, finds the closest episode name, and
/// renames to eg 'Seinfeld S09E03 The Serenity Now.Seinfeld - Serenity.vob.remove if correct'
/// Returns an error if it can't figure anything out.
func tvEpisodeGuess(folder string, file string, paths Paths, config Config) error {
	s := strings.Split(file, "-")

	if len(s) < 2 {
		return errors.New("Unrecognised file naming, expected eg 'Some show - Episode name.vob'")
	}

	showTitleFromFile := strings.TrimSpace(s[0])
	episodeTitleFromFile := strings.TrimSpace(s[1])

	if showTitleFromFile == "" {
		return errors.New("Missing show name before the dash")
	}

	if episodeTitleFromFile == "" {
		return errors.New("Missing episode name after the dash")
	}

	// Search for the id.
	log.Println("Searching for series for title", showTitleFromFile)
	seriesId := tvdbSearchForSeries(showTitleFromFile)
	if seriesId == "" {
		log.Println("Could not find TV show for", showTitleFromFile)
		return errors.New("Series search")
	}

	// Get show details.
	log.Println("Fetching series details for series id", seriesId)
	series, seriesErr := tvdbSeriesDetails(seriesId)
	if seriesErr != nil {
		log.Println("Could not get TV show metadata for", showTitleFromFile)
		return seriesErr
	}

	allEpisodes := make([]GuessEpisode, 0)

	// Find all seasons.
	for _, sparseSeason := range series.Seasons {

		log.Println("Looking up details for season: ", sparseSeason.Season)
		fatSeason, seasonErr := tvdbSeasonDetails(seriesId, sparseSeason.TVDBID, sparseSeason.Season)
		if seasonErr != nil {
			log.Println("Could not get season metadata for", showTitleFromFile)
			return seasonErr
		}

		for _, episode := range fatSeason.Episodes {
			guess := GuessEpisode{
				Season:  episode.SeasonNumber,
				Episode: episode.Episode,
				Name:    episode.Name,
			}
			allEpisodes = append(allEpisodes, guess)
		}

	}

	// Any episodes?
	if len(allEpisodes) == 0 {
		return errors.New("No episodes found")
	}

	// Find the closest.
	closestDistance := 99999
	var closestGuess *GuessEpisode
	for _, ep := range allEpisodes {
		thisDistance := smetrics.WagnerFischer(
			strings.ToLower(ep.Name),
			strings.ToLower(episodeTitleFromFile),
			1, 3, 2)
		log.Println("Comparing", episodeTitleFromFile, "to", ep.Name, "distance =", thisDistance)
		if thisDistance < closestDistance {
			closestDistance = thisDistance
			epCopy := ep // Without this, the memory for 'ep' is overwritten next loop iteration.
			closestGuess = &epCopy
		}
	}

	if closestGuess == nil {
		return errors.New("No guesses found")
	}

	// Rename it and succeed.
	sxex := fmt.Sprintf("S%02dE%02d", closestGuess.Season, closestGuess.Episode)
	newName := series.Name + " " + sxex + " " + closestGuess.Name + "." + file + ".remove if correct"
	os.Rename(filepath.Join(folder, file), filepath.Join(folder, newName))
	log.Println("Guessed a file. You can remove the 'remove if correct' if you're happy with the guess.")
	return nil
}


text:
"""
Testing for the tribe module
"""

##########################################################################
## Imports
##########################################################################

import unittest

##########################################################################
## Module Constants
##########################################################################

TEST_VERSION = "1.3" ## Also the expected version of the package

##########################################################################
## Initialization Tests
##########################################################################

class InitializationTests(unittest.TestCase):

    def test_initialization(self):
        """
        Test that the world is sane and 2+2=4
        """
        self.assertEqual(2+2,4)

    def test_import(self):
        """
        Check ability to import the tribe module
        """
        try:
            import tribe
        except ImportError:
            self.fail("Could not import the tribe module")

    def test_version(self):
        """
        Assert that the version is sane
        """
        import tribe
        self.assertEqual(TEST_VERSION, tribe.__version__)


text:
package chapter03;

import java.io.File;
import java.util.Date;

/**
 * Created by Peng on 2016/1/22.
 * File class test.
 */
public class FileTest {
    public static void main(String[] args) {
        File mFile = new File("image/Cover.jpg");
        System.out.println(mFile.exists());
        System.out.println(mFile.length() + "Bytes.");
        System.out.println(mFile.getAbsolutePath());
//        System.out.println(mFile.getCanonicalPath());
        System.out.println(mFile.isFile());
        System.out.println(mFile.isAbsolute());

        // 使用 Date 类输出时间。
        System.out.println(new Date(mFile.lastModified()));
    }
}


text:
package org.kuali.kpme.core.bo.dao;

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

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.ojb.broker.query.Criteria;
import org.joda.time.LocalDate;
import org.kuali.kpme.core.api.bo.HrBusinessObjectContract;
import org.kuali.kpme.core.lookup.WildcardableAttributeDefinition;
import org.kuali.kpme.core.util.OjbSubQueryUtil;
import org.kuali.kpme.core.util.TKUtils;
import org.kuali.rice.core.api.search.SearchOperator;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.dao.impl.LookupDaoOjb;
import org.kuali.rice.krad.datadictionary.AttributeDefinition;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;

public class KpmeHrBusinessObjectLookupDaoOjbImpl extends LookupDaoOjb {

	private static final String DOES_NOT_CONTAIN_BUSINESS_KEYS_MESSAGE = " does not contain a BUSINESS_KEYS list";
	private static final String TIMESTAMP = "timestamp";
	private static final String BUSINESS_KEYS_VAR_NAME = "BUSINESS_KEYS";
	private static final String EFFECTIVE_DATE = "effectiveDate";
	private static final String NO = "N";
	private static final String HISTORY_PARAM_NAME = "history";

	private static final Logger LOG = Logger.getLogger(KpmeHrBusinessObjectLookupDaoOjbImpl.class);

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Criteria getCollectionCriteriaFromMap(BusinessObject example, Map formProps) {
		Map<String, String> removedProperties = removeAndTransformFormProperties((Class<? extends HrBusinessObjectContract>) example.getClass(), formProps);
		Criteria rootCriteria = super.getCollectionCriteriaFromMap(example, formProps);
		processRootCriteria(rootCriteria, (Class<? extends HrBusinessObjectContract>) example.getClass(), formProps, removedProperties);
		return rootCriteria;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Criteria getCollectionCriteriaFromMapUsingPrimaryKeysOnly(Class businessObjectClass, Map formProps) {
		Map<String, String> removedProperties = removeAndTransformFormProperties(businessObjectClass, formProps);
		Criteria rootCriteria = super.getCollectionCriteriaFromMapUsingPrimaryKeysOnly((Class<? extends HrBusinessObjectContract>) businessObjectClass, formProps);
		processRootCriteria(rootCriteria, (Class<? extends HrBusinessObjectContract>) businessObjectClass, formProps, removedProperties);
		return rootCriteria;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected void transformWildCardableFields(Class<? extends HrBusinessObjectContract> hrBOClass, Map formProps) {
		Iterator propsIter = formProps.keySet().iterator();
        while (propsIter.hasNext()) {
            String propertyName = (String) propsIter.next();
            String propertyValue = (String) formProps.get(propertyName);
            if (StringUtils.isNotBlank(propertyValue)) {
            	// transform this value into an "OR" with the wildcard symbols
            	boolean canContainWildcard = false;
            	if (KRADServiceLocatorWeb.getDataDictionaryService().isAttributeDefined(hrBOClass, propertyName)) {
            		AttributeDefinition attributeDefinition = KRADServiceLocatorWeb.getDataDictionaryService().getAttributeDefinition(hrBOClass.getName(), propertyName);
            		// check if this property is wildcarded
            		if (attributeDefinition instanceof WildcardableAttributeDefinition) {
            			canContainWildcard = ((WildcardableAttributeDefinition) attributeDefinition).getContainsWildcardData();
            		}
            		if (canContainWildcard) {
                		// get the wildcard symbols and attach them with an "OR" seperator i.e. "|"
                		List<String> wildcardStrings = ((WildcardableAttributeDefinition) attributeDefinition).getAllowedWildcardStrings();
                		if(wildcardStrings != null) {
	                		for(String wildcardString : wildcardStrings) {
	                			if( StringUtils.equals("*", wildcardString) || StringUtils.equals("%", wildcardString) ){
	                				wildcardString = "\\" + wildcardString;
	                			}
	                			propertyValue = propertyValue + SearchOperator.OR.op() + wildcardString;
	                		}
	                		formProps.put(propertyName, propertyValue);
                		}
            		}
            	}
            }
        }
	}

	@SuppressWarnings("rawtypes")
	protected Map<String, String> removeAndTransformFormProperties(Class<? extends HrBusinessObjectContract> businessObjectClass, Map formProps) {
		HashMap<String, String> retVal = new HashMap<String, String>();
		// remove the history option field from the form map and add it to the return value map
		retVal.put(HISTORY_PARAM_NAME, (String) formProps.remove(HISTORY_PARAM_NAME));
		// covert any field inputs to be ORed with wild cards if applicable
		transformWildCardableFields(businessObjectClass, formProps);
		return retVal;
	}

	// inject effective dated subqueries into the root criteria if show history is not chosen
	@SuppressWarnings("rawtypes")
	protected void processRootCriteria(Criteria rootCriteria, Class<? extends HrBusinessObjectContract> businessObjectClass, Map formProps, Map<String, String> removedProperties) {
		// inject the efft date and timestamp subqueries if history is not to be shown
		if (StringUtils.equals(removedProperties.get(HISTORY_PARAM_NAME), NO)) {
			injectSubQueries(rootCriteria, businessObjectClass, formProps);
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void injectSubQueries(Criteria root, Class<? extends HrBusinessObjectContract> hrBOClass, Map formProps) {
		// create the effective date filter criteria
		Criteria effectiveDateFilter = new Criteria();
		LocalDate fromEffdt = TKUtils.formatDateString(TKUtils.getFromDateString((String) formProps.get(EFFECTIVE_DATE)));
		LocalDate toEffdt = TKUtils.formatDateString(TKUtils.getToDateString((String) formProps.get(EFFECTIVE_DATE)));
		if (fromEffdt != null) {
			effectiveDateFilter.addGreaterOrEqualThan(EFFECTIVE_DATE, fromEffdt.toDate());
		}
		if (toEffdt != null) {
			effectiveDateFilter.addLessOrEqualThan(EFFECTIVE_DATE,	toEffdt.toDate());
		}
		if (fromEffdt == null && toEffdt == null) {
			effectiveDateFilter.addLessOrEqualThan(EFFECTIVE_DATE, LocalDate.now().toDate());
		}

		List<String> businessKeys = new ArrayList<String>();
		try {
			businessKeys = (List<String>) hrBOClass.getDeclaredField(BUSINESS_KEYS_VAR_NAME).get(hrBOClass);
		}
		catch (NoSuchFieldException e) {
			LOG.warn(hrBOClass.getName() + DOES_NOT_CONTAIN_BUSINESS_KEYS_MESSAGE);
		}
		catch (IllegalAccessException e) {
			LOG.warn(hrBOClass.getName() + DOES_NOT_CONTAIN_BUSINESS_KEYS_MESSAGE);
		}

	    // inject the subqueries
		root.addEqualTo(EFFECTIVE_DATE, OjbSubQueryUtil.getEffectiveDateSubQueryWithFilter(hrBOClass, effectiveDateFilter, businessKeys, false));
		root.addEqualTo(TIMESTAMP, OjbSubQueryUtil.getTimestampSubQuery(hrBOClass, businessKeys, false));
	}

}


text:
#ifndef SVGRectElement_h
#define SVGRectElement_h

#include "core/SVGNames.h"
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedLength.h"
#include "core/svg/SVGGeometryElement.h"

namespace blink {

class SVGRectElement final : public SVGGeometryElement {
    DEFINE_WRAPPERTYPEINFO();
public:
    DECLARE_NODE_FACTORY(SVGRectElement);

    SVGAnimatedLength* x() const { return m_x.get(); }
    SVGAnimatedLength* y() const { return m_y.get(); }
    SVGAnimatedLength* width() const { return m_width.get(); }
    SVGAnimatedLength* height() const { return m_height.get(); }
    SVGAnimatedLength* rx() const { return m_rx.get(); }
    SVGAnimatedLength* ry() const { return m_ry.get(); }

private:
    explicit SVGRectElement(Document&);

    bool isSupportedAttribute(const QualifiedName&);
    virtual void parseAttribute(const QualifiedName&, const AtomicString&) override;
    virtual void svgAttributeChanged(const QualifiedName&) override;

    virtual bool selfHasRelativeLengths() const override;

    virtual RenderObject* createRenderer(RenderStyle*) override;

    RefPtr<SVGAnimatedLength> m_x;
    RefPtr<SVGAnimatedLength> m_y;
    RefPtr<SVGAnimatedLength> m_width;
    RefPtr<SVGAnimatedLength> m_height;
    RefPtr<SVGAnimatedLength> m_rx;
    RefPtr<SVGAnimatedLength> m_ry;
};

} // namespace blink

#endif // SVGRectElement_h


text:
using Http.Shared.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestWebServer
{
	public class Initializer : IRouteInitializer
	{
		public void RegisterRoutes(IRoutingHandler routingHandler)
		{
			routingHandler.MapRoute("Default","~/{controller}/{action}/{id}",
				new {
					Controller = "WebApi",
					Action = "Index",
					Id = RoutingParameter.Optional
				});
		}
	}
}


text:
package com.reason.ide;

import com.intellij.openapi.project.*;
import com.intellij.openapi.vfs.*;
import org.jetbrains.annotations.*;

import java.util.*;

public class ORFileUtils {
    private ORFileUtils() {
    }

    /**
     * Given a `start` directory (or file), searches that directory for `target`, continuing up
     * directories until either `target` is found or the project base path is reached.
     *
     * @param project project to use
     * @param target  file being searched for
     * @param start   starting directory (or file) to begin searching for `target`
     * @return found target file
     */
    public static Optional<VirtualFile> findAncestor(@NotNull Project project, @NotNull String target, @NotNull VirtualFile start) {
        // start must be a directory, should only happen on first iteration
        if (!start.isDirectory()) {
            start = start.getParent();
            // parent is null, done
            if (start == null) {
                return Optional.empty();
            }
        }
        // target found, done
        VirtualFile foundTarget = start.findChild(target);
        if (foundTarget != null) {
            return Optional.of(foundTarget);
        }
        // just checked project root, done
        if (start.getPath().equals(project.getBasePath())) {
            return Optional.empty();
        }
        // parent is null, we're done
        VirtualFile parent = start.getParent();
        if (parent == null) {
            return Optional.empty();
        }
        return findAncestor(project, target, parent);
    }
}


text:
var settings_invites = (function () {

var exports = {};

var meta = {
    loaded: false,
};

exports.reset = function () {
    meta.loaded = false;
};

function failed_listing_invites(xhr) {
    loading.destroy_indicator($('#admin_page_invites_loading_indicator'));
    ui_report.error(i18n.t("Error listing invites"), xhr, $("#organization-status"));
}

function populate_invites(invites_data) {
    if (!meta.loaded) {
        return;
    }
    var invites_table = $("#admin_invites_table").expectOne();

    list_render(invites_table, invites_data.invites, {
        name: "admin_invites_list",
        modifier: function (item) {
            return templates.render("admin_invites_list", { invite: item });
        },
        filter: {
            element: invites_table.closest(".settings-section").find(".search"),
            callback: function (item, value) {
                return item.email.toLowerCase().indexOf(value) >= 0;
            },
        },
    }).init();

    loading.destroy_indicator($('#admin_page_invites_loading_indicator'));
}

exports.set_up = function () {
    meta.loaded = true;

    // create loading indicators
    loading.make_indicator($('#admin_page_invites_loading_indicator'));

    // Populate invites table
    channel.get({
        url: '/json/invites',
        idempotent: true,
        timeout:  10*1000,
        success: exports.on_load_success,
        error: failed_listing_invites,
    });
};

exports.on_load_success = function (invites_data) {
    meta.loaded = true;
    populate_invites(invites_data);

    $(".admin_invites_table").on("click", ".revoke", function (e) {
        e.preventDefault();
        e.stopPropagation();

        var row = $(e.target).closest(".invite_row");
        var email = row.find('.email').text();
        meta.current_revoke_invite_user_modal_row = row;
        meta.invite_id = $(e.currentTarget).attr("data-invite-id");

        $("#revoke_invite_modal .email").text(email);
        $("#revoke_invite_modal #do_revoke_invite_button").attr("data-invite-id", meta.invite_id);
        $("#revoke_invite_modal").modal("show");
    });

    $(".admin_invites_table").on("click", ".resend", function (e) {
        e.preventDefault();
        e.stopPropagation();

        var row = $(e.target).closest(".invite_row");
        var email = row.find('.email').text();
        meta.current_resend_invite_user_modal_row = row;
        meta.invite_id = $(e.currentTarget).attr("data-invite-id");

        $("#resend_invite_modal .email").text(email);
        $("#resend_invite_modal #do_resend_invite_button").attr("data-invite-id", meta.invite_id);
        $("#resend_invite_modal").modal("show");
    });

    $("#do_revoke_invite_button").click(function () {
        var modal_invite_id = $("#revoke_invite_modal #do_revoke_invite_button").attr("data-invite-id");
        var revoke_button = meta.current_revoke_invite_user_modal_row.find("button.revoke");

        if (modal_invite_id !== meta.invite_id) {
            blueslip.error("Invite revoking canceled due to non-matching fields.");
            ui_report.message(i18n.t("Resending encountered an error. Please reload and try again."),
               $("#home-error"), 'alert-error');
        }
        $("#revoke_invite_modal").modal("hide");
        revoke_button.prop("disabled", true).text(i18n.t("Working…"));
        channel.del({
            url: '/json/invites/' + meta.invite_id,
            error: function (xhr) {
                if (xhr.status.toString().charAt(0) === "4") {
                    revoke_button.closest("td").html(
                        $("<p>").addClass("text-error").text(JSON.parse(xhr.responseText).msg)
                    );
                } else {
                    revoke_button.text(i18n.t("Failed!"));
                }
            },
            success: function () {
                meta.current_revoke_invite_user_modal_row.remove();
            },
        });
    });

    $("#do_resend_invite_button").click(function () {
        var modal_invite_id = $("#resend_invite_modal #do_resend_invite_button").attr("data-invite-id");
        var resend_button = meta.current_resend_invite_user_modal_row.find("button.resend");

        if (modal_invite_id !== meta.invite_id) {
            blueslip.error("Invite resending canceled due to non-matching fields.");
            ui_report.message(i18n.t("Resending encountered an error. Please reload and try again."),
               $("#home-error"), 'alert-error');
        }
        $("#resend_invite_modal").modal("hide");
        resend_button.prop("disabled", true).text(i18n.t("Working…"));
        channel.post({
            url: '/json/invites/' + meta.invite_id + "/resend",
            error: function (xhr) {
                if (xhr.status.toString().charAt(0) === "4") {
                    resend_button.closest("td").html(
                        $("<p>").addClass("text-error").text(JSON.parse(xhr.responseText).msg)
                    );
                } else {
                    resend_button.text(i18n.t("Failed!"));
                }
            },
            success: function (data) {
                resend_button.text(i18n.t("Sent!"));
                resend_button.removeClass('resend btn-warning').addClass('sea-green');
                meta.current_resend_invite_user_modal_row.find(".invited_at").text(data.timestamp);
            },
        });
    });
};

return exports;
}());

if (typeof module !== 'undefined') {
    module.exports = settings_invites;
}


text:
package org.elasticsearch.test.rest.yaml.section;

import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentLocation;
import org.elasticsearch.common.xcontent.XContentParser;

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

/**
 * Represents a test section, which is composed of a skip section and multiple executable sections.
 */
public class ClientYamlTestSection implements Comparable<ClientYamlTestSection> {
    public static ClientYamlTestSection parse(XContentParser parser) throws IOException {
        ParserUtils.advanceToFieldName(parser);
        ClientYamlTestSection testSection = new ClientYamlTestSection(parser.getTokenLocation(), parser.currentName());
        try {
            parser.nextToken();
            testSection.setSkipSection(SkipSection.parseIfNext(parser));

            while (parser.currentToken() != XContentParser.Token.END_ARRAY) {
                ParserUtils.advanceToFieldName(parser);
                testSection.addExecutableSection(ExecutableSection.parse(parser));
            }

            parser.nextToken();
            assert parser.currentToken() == XContentParser.Token.END_OBJECT : "malformed section [" + testSection.getName() + "] expected "
                + XContentParser.Token.END_OBJECT  + " but was " + parser.currentToken();
            parser.nextToken();

            return testSection;
        } catch (Exception e) {
            throw new ParsingException(parser.getTokenLocation(), "Error parsing test named [" + testSection.getName() + "]", e);
        }
    }

    private final XContentLocation location;
    private final String name;
    private SkipSection skipSection;
    private final List<ExecutableSection> executableSections;

    public ClientYamlTestSection(XContentLocation location, String name) {
        this.location = location;
        this.name = name;
        this.executableSections = new ArrayList<>();
    }

    public XContentLocation getLocation() {
        return location;
    }

    public String getName() {
        return name;
    }

    public SkipSection getSkipSection() {
        return skipSection;
    }

    public void setSkipSection(SkipSection skipSection) {
        this.skipSection = skipSection;
    }

    public List<ExecutableSection> getExecutableSections() {
        return executableSections;
    }

    public void addExecutableSection(ExecutableSection executableSection) {
        if (executableSection instanceof DoSection) {
            DoSection doSection = (DoSection) executableSection;
            if (false == doSection.getExpectedWarningHeaders().isEmpty()
                    && false == skipSection.getFeatures().contains("warnings")) {
                throw new IllegalArgumentException("Attempted to add a [do] with a [warnings] section without a corresponding [skip] so "
                        + "runners that do not support the [warnings] section can skip the test at line ["
                        + doSection.getLocation().lineNumber + "]");
            }
        }
        this.executableSections.add(executableSection);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ClientYamlTestSection that = (ClientYamlTestSection) o;

        if (name != null ? !name.equals(that.name) : that.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return name != null ? name.hashCode() : 0;
    }

    @Override
    public int compareTo(ClientYamlTestSection o) {
        return name.compareTo(o.getName());
    }
}


text:
package fr.fscf.contacts.client.validation;

import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.validation.client.impl.Validation;
import fr.fscf.contacts.client.i18n.I18N;
import fr.fscf.contacts.client.ui.notification.N10N;
import fr.fscf.contacts.client.ui.view.base.IsBeanEditor;
import fr.fscf.contacts.shared.util.ClientUtils;

import javax.validation.ConstraintViolation;
import javax.validation.groups.Default;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * Validator.
 *
 * @author Denis
 */
public final class Validator {

    private final javax.validation.Validator validator;

    public Validator() {
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * Validates the given {@code beanEditor} corresponding bean.
     *
     * @param beanEditor The bean editor.
     * @param groups     The additional validation group(s) ({@code null} values are ignored).
     *                   Note that {@link Default} group is automatically included.
     * @return {@code true} if the bean is valid, {@code false} otherwise.
     */
    @SuppressWarnings("unchecked")
    public boolean validate(final IsBeanEditor beanEditor, final Class<?>... groups) {

        final SimpleBeanEditorDriver driver = beanEditor.getDriver();
        final Object bean = driver.flush();

        final Set<Class<?>> groupSet = new HashSet<>();
        for (final Class<?> group : groups) {
            if (group != null) {
                groupSet.add(group);
            }
        }
        groupSet.add(Default.class);
        final Set<ConstraintViolation<Object>> violations = validator.validate(bean,
                groupSet.toArray(new Class<?>[groupSet.size()]));

        if (ClientUtils.isNotEmpty(violations)) {
            driver.setConstraintViolations(new ArrayList<>(violations));
            return false;

        } else if (driver.hasErrors()) {
            N10N.errorNotif(I18N.VALIDATION.global_validation_hasError());
            return false;

        } else {
            return true;
        }
    }

}


text:
class Libplist < Formula
  desc "Library for Apple Binary- and XML-Property Lists"
  homepage "http://www.libimobiledevice.org"
  url "http://www.libimobiledevice.org/downloads/libplist-1.12.tar.bz2"
  sha256 "0effdedcb3de128c4930d8c03a3854c74c426c16728b8ab5f0a5b6bdc0b644be"

  bottle do
    cellar :any
    sha1 "abd1c58c509b305549310367feab44bca513d647" => :yosemite
    sha1 "e7bf9fbf14a51449b6b8dd5c2f084ace824f553f" => :mavericks
    sha1 "40172d50d4c836931dbfd38700a9088842c56b6c" => :mountain_lion
  end

  head do
    url "http://git.sukimashita.com/libplist.git"

    depends_on "automake" => :build
    depends_on "autoconf" => :build
    depends_on "libtool" => :build
  end

  option "with-python", "Enable Cython Python bindings"

  depends_on "pkg-config" => :build
  depends_on "libxml2"
  depends_on :python => :optional

  resource "cython" do
    url "http://cython.org/release/Cython-0.21.tar.gz"
    sha256 "0cd5787fb3f1eaf8326b21bdfcb90aabd3eca7c214c5b7b503fbb82da97bbaa0"
  end

  def install
    ENV.deparallelize
    args = %W[
      --disable-dependency-tracking
      --disable-silent-rules
      --prefix=#{prefix}
    ]

    if build.with? "python"
      resource("cython").stage do
        ENV.prepend_create_path "PYTHONPATH", buildpath+"lib/python2.7/site-packages"
        system "python", "setup.py", "build", "install", "--prefix=#{buildpath}",
                 "--single-version-externally-managed", "--record=installed.txt"
      end
      ENV.prepend_path "PATH", "#{buildpath}/bin"
    else
      args << "--without-cython"
    end

    system "./autogen.sh" if build.head?
    system "./configure", *args
    system "make", "install"
  end
end


text:
using System;
using System.Threading.Tasks;
using RabbitMQ.Client;

namespace EasyNetQ.Producer
{
    /// <summary>
    /// Handles basic publish scenarios where publisher confirms and transactions are not required
    ///
    /// Note, this class is designed to be called sequentially from a single thread. It is NOT
    /// thread safe.
    /// </summary>
    public class PublisherBasic : PublisherBase
    {
        public PublisherBasic(IEventBus eventBus) : base(eventBus)
        {
        }

        public override Task PublishAsync(IModel model, Action<IModel> publishAction)
        {
            SetModel(model);
            publishAction(model);
            return TaskHelpers.Completed;
        }
    }
}


text:
//go:generate sh -c "go run github.com/gomatic/renderizer --name=alert --resource=alert --type=Alert --title=Alert --article=an swagger_operations.tmpl > alert_swagger.go"
//go:generate sh -c "go run github.com/gomatic/renderizer --name=alert --resource=alert --type=Alert --title=Alert swagger_definitions.tmpl > alert_swagger.json"

package server

import (
	"time"

	"github.com/skydive-project/skydive/api/types"
	shttp "github.com/skydive-project/skydive/http"
)

// AlertResourceHandler aims to creates and manage a new Alert.
type AlertResourceHandler struct {
	ResourceHandler
}

// AlertAPIHandler aims to exposes the Alert API.
type AlertAPIHandler struct {
	BasicAPIHandler
}

// New creates a new alert
func (a *AlertResourceHandler) New() types.Resource {
	return &types.Alert{
		CreateTime: time.Now().UTC(),
	}
}

// Name returns resource name "alert"
func (a *AlertResourceHandler) Name() string {
	return "alert"
}

// RegisterAlertAPI registers an Alert's API to a designated API Server
func RegisterAlertAPI(apiServer *Server, authBackend shttp.AuthenticationBackend) (*AlertAPIHandler, error) {
	alertAPIHandler := &AlertAPIHandler{
		BasicAPIHandler: BasicAPIHandler{
			ResourceHandler: &AlertResourceHandler{},
			EtcdKeyAPI:      apiServer.EtcdKeyAPI,
		},
	}
	if err := apiServer.RegisterAPIHandler(alertAPIHandler, authBackend); err != nil {
		return nil, err
	}
	return alertAPIHandler, nil
}


text:
namespace chrono {
namespace opengl {

/// @addtogroup opengl_module
/// @{

/// Generic renderable point cloud.
class CH_OPENGL_API ChOpenGLCloud : public ChOpenGLObject {
  public:
    ChOpenGLCloud();
    bool Initialize(const std::vector<glm::vec3>& data, ChOpenGLMaterial mat, ChOpenGLShader* shader);

    virtual void Draw(const glm::mat4& projection, const glm::mat4& view) override;
    virtual void TakeDown() override;

    void Update(const std::vector<glm::vec3>& data);
    void SetPointSize(const float& pointsize);

  private:
    typedef ChOpenGLObject super;

    std::vector<glm::vec3> vertices;
    glm::vec4 color;
    float point_size;
    GLuint color_handle;
    GLuint point_size_handle;
};

/// @} opengl_module

}
}

#endif


text:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Icon from '../icon';
import classNames from 'classnames';

export interface AvatarProps {
  /** Shape of avatar, options:`circle`, `square` */
  shape?: 'circle' | 'square';
  /** Size of avatar, options:`large`, `small`, `default` */
  size?: 'large' | 'small' | 'default';
  /** Src of image avatar */
  src?: string;
  /** Type of the Icon to be used in avatar */
  icon?: string;
  style?: React.CSSProperties;
  prefixCls?: string;
  className?: string;
  children?: any;
}

export interface AvatarState {
  scale: number;
  isImgExist: boolean;
}

export default class Avatar extends React.Component<AvatarProps, AvatarState> {
  static defaultProps = {
    prefixCls: 'ant-avatar',
    shape: 'circle',
    size: 'default',
  };

  private avatarChildren: any;

  constructor(props: AvatarProps) {
    super(props);
    this.state = {
      scale: 1,
      isImgExist: true,
    };
  }

  componentDidMount() {
    this.setScale();
  }

  componentDidUpdate(prevProps: AvatarProps, prevState: AvatarState) {
    if (prevProps.children !== this.props.children
        || (prevState.scale !== this.state.scale && this.state.scale === 1)) {
      this.setScale();
    }
  }

  setScale = () => {
    const childrenNode = this.avatarChildren;
    if (childrenNode) {
      const childrenWidth = childrenNode.offsetWidth;
      const avatarWidth = ReactDOM.findDOMNode(this).getBoundingClientRect().width;
      // add 4px gap for each side to get better performance
      if (avatarWidth - 8 < childrenWidth) {
        this.setState({
          scale: (avatarWidth - 8) / childrenWidth,
        });
      } else {
        this.setState({
          scale: 1,
        });
      }
    }
  }

  handleImgLoadError = () => this.setState({ isImgExist: false });

  render() {
    const {
      prefixCls, shape, size, src, icon, className, ...others,
    } = this.props;

    const sizeCls = classNames({
      [`${prefixCls}-lg`]: size === 'large',
      [`${prefixCls}-sm`]: size === 'small',
    });

    const classString = classNames(prefixCls, className, sizeCls, {
      [`${prefixCls}-${shape}`]: shape,
      [`${prefixCls}-image`]: src,
      [`${prefixCls}-icon`]: icon,
    });

    let children = this.props.children;
    if (src && this.state.isImgExist) {
      children = (
        <img
          src={src}
          onError={this.handleImgLoadError}
        />
      );
    } else if (icon) {
      children = <Icon type={icon} />;
    } else {
      const childrenNode = this.avatarChildren;
      if (childrenNode || this.state.scale !== 1) {
        const childrenStyle: React.CSSProperties = {
          msTransform: `scale(${this.state.scale})`,
          WebkitTransform: `scale(${this.state.scale})`,
          transform: `scale(${this.state.scale})`,
          position: 'absolute',
          display: 'inline-block',
          left: `calc(50% - ${Math.round(childrenNode.offsetWidth / 2)}px)`,
        };
        children = (
          <span
            className={`${prefixCls}-string`}
            ref={span => this.avatarChildren = span}
            style={childrenStyle}
          >
            {children}
          </span>
        );
      } else {
        children = (
          <span
            className={`${prefixCls}-string`}
            ref={span => this.avatarChildren = span}
          >
            {children}
          </span>
        );
      }
    }
    return (
      <span {...others} className={classString}>
        {children}
      </span>
    );
  }
}