text:
<?php

// Comment mail notify
function comment_mail_notify($comment_id) {
  $comment = get_comment($comment_id);
  $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
  $spam_confirmed = $comment->comment_approved;

  $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
  $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
  $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";

  if (($parent_id != '') && ($spam_confirmed != 'spam')) {
    $to = trim(get_comment($parent_id)->comment_author_email);
    $subject = '你在 [' . get_option("blogname") . '] 的留言有了新回复';
    $message = '

' . trim(get_comment($parent_id)->comment_author) . ', 你好!

您曾在《' . get_the_title($comment->comment_post_ID) . '》的留言为:
'
                                            . trim(get_comment($parent_id)->comment_content) . '

' . trim($comment->comment_author) . ' 给你的回复是:
'
                           . trim($comment->comment_content) . '

你可以点击此链接 查看完整内容

欢迎再次来访' . get_option('blogname') . '

(此邮件为系统自动发送,请勿直接回复.)

';

    wp_mail( $to, $subject, $message, $headers );
  }
}
add_action('comment_post', 'comment_mail_notify');

// Meridian coment part
function meridian_comment($comment, $args, $depth) {
  $GLOBALS['comment'] = $comment;
  global $commentcount;
  if(!$commentcount) {
    $page = ( !empty($in_comment_loop) ) ? get_query_var('cpage')-1 : get_page_of_comment( $comment->comment_ID, $args )-1;
    $cpp = get_option('comments_per_page');
    $commentcount = $cpp * $page;
  }
  if(!$comment->comment_parent){
  ?>
    <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
      <div id="comment-<?php comment_ID(); ?>" class="comment-body">

<?php echo get_avatar( $comment, $size = '40'); ?>

          <?php printf(__('%s'), get_comment_author_link()) ?> /
          <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth'], 'reply_text' => __('reply')))) ?>
          <?php echo time_since(abs(strtotime($comment->comment_date_gmt . "GMT")), true);?>

<?php comment_text() ?>

  <?php }else{?>
    <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
      <div id="comment-<?php comment_ID(); ?>" class="comment-body comment-children-body">

<?php echo get_avatar( $comment, $size = '30'); ?>

          <?php $parent_id = $comment->comment_parent; $comment_parent = get_comment($parent_id); printf(__('%s'), get_comment_author_link()) ?> /
          <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth'], 'reply_text' => __('reply')))) ?>
          <?php echo time_since(abs(strtotime($comment->comment_date_gmt . "GMT")), true);?>

          <a href="<?php echo "#comment-".$parent_id;?>" title="<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $comment_parent->comment_content)), 0, 100,"..."); ?>">@<?php echo $comment_parent->comment_author;?>:
          <?php echo get_comment_text(); ?>

  <?php }
}

// Ajax comment
add_action('init', 'meridian_ajax_comment');
function meridian_ajax_comment(){
/**
 * WordPress jQuery-Ajax-Comments v1.3 by Willin Kan.
 * URI: http://kan.willin.org/?p=1271
 * for WP3.5+ | modified version URI: http://mufeng.me/wordpress3-5-willin-ajax-comment.html
 */
  if($_POST['action'] == 'meridian_ajax_comment' && 'POST' == $_SERVER['REQUEST_METHOD']){
    global $wpdb;
    nocache_headers();
    $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;

    $post = get_post($comment_post_ID);

    if ( empty($post->comment_status) ) {
      do_action('comment_id_not_found', $comment_post_ID);
      ajax_comment_err(__('Invalid comment status.')); // 將 exit 改為錯誤提示
    }

    // get_post_status() will get the parent status for attachments.
    $status = get_post_status($post);

    $status_obj = get_post_status_object($status);

    if ( !comments_open($comment_post_ID) ) {
      do_action('comment_closed', $comment_post_ID);
      ajax_comment_err(__('评论已关闭!')); // 將 wp_die 改為錯誤提示
    } elseif ( 'trash' == $status ) {
      do_action('comment_on_trash', $comment_post_ID);
      ajax_comment_err(__('Invalid comment status.')); // 將 exit 改為錯誤提示
    } elseif ( !$status_obj->public && !$status_obj->private ) {
      do_action('comment_on_draft', $comment_post_ID);
      ajax_comment_err(__('Invalid comment status.')); // 將 exit 改為錯誤提示
    } elseif ( post_password_required($comment_post_ID) ) {
      do_action('comment_on_password_protected', $comment_post_ID);
      ajax_comment_err(__('Password Protected')); // 將 exit 改為錯誤提示
    } else {
      do_action('pre_comment_on_post', $comment_post_ID);
    }

    $comment_author       = ( isset($_POST['author']) )  ? trim(strip_tags($_POST['author'])) : null;
    $comment_author_email = ( isset($_POST['email']) )   ? trim($_POST['email']) : null;
    $comment_author_url   = ( isset($_POST['url']) )     ? trim($_POST['url']) : null;
    $comment_content      = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null;
    $edit_id              = ( isset($_POST['edit_id']) ) ? $_POST['edit_id'] : null; // 提取 edit_id

    // If the user is logged in
    $user = wp_get_current_user();
    if ( $user->exists() ) {
      if ( empty( $user->display_name ) )
        $user->display_name=$user->user_login;
      $comment_author       = $wpdb->escape($user->display_name);
      $comment_author_email = $wpdb->escape($user->user_email);
      $comment_author_url   = $wpdb->escape($user->user_url);
      if ( current_user_can('unfiltered_html') ) {
        if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {
          kses_remove_filters(); // start with a clean slate
          kses_init_filters(); // set up the filters
        }
      }
    } else {
      if ( get_option('comment_registration') || 'private' == $status )
        ajax_comment_err(__('你必须要登陆之后才可以发表评论.')); // 將 wp_die 改為錯誤提示
    }

    $comment_type = '';

    if ( get_option('require_name_email') && !$user->exists() ) {
      if ( 6 > strlen($comment_author_email) || '' == $comment_author )
        ajax_comment_err( __('请填写昵称和邮箱.') ); // 將 wp_die 改為錯誤提示
      elseif ( !is_email($comment_author_email))
        ajax_comment_err( __('请填写一个有效的邮箱.') ); // 將 wp_die 改為錯誤提示
    }

    if ( '' == $comment_content )
      ajax_comment_err( __('请输入评论.') ); // 將 wp_die 改為錯誤提示

    // 增加: 禁止全英文评论
    $pattern = '/[一-龥]/u';
    if(!preg_match($pattern, $comment_content)) {
      ajax_comment_err(__('You should type some Chinese word (like "你好") in your comment !'));
    }

    // 增加: 檢查重覆評論功能
    $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
    if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' ";
    $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
    if ( $wpdb->get_var($dupe) ) {
      ajax_comment_err(__('您已经发布过一条相同的评论!'));
    }

    // 增加: 檢查評論太快功能
    if ( $lasttime = $wpdb->get_var( $wpdb->prepare("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author) ) ) {
    $time_lastcomment = mysql2date('U', $lasttime, false);
    $time_newcomment  = mysql2date('U', current_time('mysql', 1), false);
    $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
    if ( $flood_die ) {
      ajax_comment_err(__('请过一会再发表评论.'));
      }
    }

    $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;

    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');

    // 增加: 檢查評論是否正被編輯, 更新或新建評論
    if ( $edit_id ){

      // 判断当前用户是否具有编辑该评论权限
      if(current_user_can("edit_comment",$edit_id)){

        // 判断当前用户的邮箱是否与评论邮箱相同
        if($current_user->user_email==$comment_author_email){
          $comment_id = $commentdata['comment_ID'] = $edit_id;
          wp_update_comment( $commentdata );
        }else{
          ajax_comment_err("您不能修改为他人评论!");
        }

      }else{
        ajax_comment_err("您没有权限编辑该评论!");
      }
    } else {
      $comment_id = wp_new_comment( $commentdata );
    }

    $comment = get_comment($comment_id);
    do_action('set_comment_cookies', $comment, $user);

    $comment_depth = 1;   //为评论的 class 属性准备的
    $tmp_c = $comment;
    while($tmp_c->comment_parent != 0){
      $comment_depth++;
      $tmp_c = get_comment($tmp_c->comment_parent);
    }

    //此处非常必要,无此处下面的评论无法输出
    $GLOBALS['comment'] = $comment;

    //以下是評論式樣, 不含 "回覆". 要用你模板的式樣 copy 覆蓋.
    if(!$comment->comment_parent){
    ?>
      <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
        <div id="comment-<?php comment_ID(); ?>" class="comment-body">

<?php echo get_avatar( $comment, $size = '40'); ?>

            <?php printf(__('%s'), get_comment_author_link()) ?> /
            <?php echo time_since(abs(strtotime($comment->comment_date_gmt . "GMT")), true);?>

<?php comment_text() ?>

    <?php }else{?>
       <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
         <div id="comment-<?php comment_ID(); ?>" class="comment-body comment-children-body">

<?php echo get_avatar( $comment, $size = '30'); ?>

             <?php $parent_id = $comment->comment_parent; $comment_parent = get_comment($parent_id); printf(__('%s'), get_comment_author_link()) ?> /
             <?php echo time_since(abs(strtotime($comment->comment_date_gmt . "GMT")), true);?>

             <a href="<?php echo "#comment-".$parent_id;?>" title="<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $comment_parent->comment_content)), 0, 100,"..."); ?>">@<?php echo $comment_parent->comment_author;?>:
             <?php echo get_comment_text(); ?>

    <?php }
    die(); //以上是評論式樣, 不含 "回覆". 要用你模板的式樣 copy 覆蓋.
  }else{return;}
}

/**
 * Ajax comments pagenavi in the theme.
 *
 */
add_action('init', 'meridian_ajax_pagenavi');
function meridian_ajax_pagenavi(){ // pagenavi
  if( isset( $_GET['action'] ) && $_GET['action']== 'meridian_ajax_pagenavi' ){
    global $post,$wp_query, $wp_rewrite;
    $postid = isset($_GET['post']) ? $_GET['post'] : null;
    $pageid = isset($_GET['page']) ? $_GET['page'] : null;
    if(!$postid || !$pageid){
      ajax_comment_err(__('Error post id or comment page id.'));
    }
    // get comments
    $comments = get_comments('post_id='.$postid);

    $post = get_post($postid);

    if(!$comments){
      ajax_comment_err(__('Error! can\'t find the comments'));
    }

    if( 'desc' != get_option('comment_order') ){
      $comments = array_reverse($comments);
    }

    // set as singular (is_single || is_page || is_attachment)
    $wp_query->is_singular = true;

    // base url of page links
    $baseLink = '';
    if ($wp_rewrite->using_permalinks()) {
      $baseLink = '&base=' . user_trailingslashit(get_permalink($postid) . 'comment-page-%#%', 'commentpaged');
    }

    echo '
';
    wp_list_comments('callback=meridian_comment&type=comment&page=' . $pageid . '&per_page=' . get_option('comments_per_page'), $comments);
    echo '

Leave a reply

';
    paginate_comments_links('prev_text=«&next_text=»&current=' . $pageid);
    echo '

';

    die;
  }else{return;}
}

// 增加: 錯誤提示功能
function ajax_comment_err($a) {
  header('HTTP/1.0 500 Internal Server Error');
  header('Content-Type: text/plain;charset=UTF-8');
  echo $a;
  exit;
}

?>


text:
namespace BB.Caching.Redis
{
    using System;
    using System.Threading.Tasks;

    using BB.Caching.Redis.Lua;

    using StackExchange.Redis;

    /// <summary>
    /// Used to limit the rate at which actions can be performed. This class uses redis to track the current usage and
    /// the throttling limit for a particular action.
    /// </summary>
    public static class RateLimiter
    {
        /// <summary>
        /// The rate limit increment hash.
        /// </summary>
        private static byte[] _rateLimitIncrementHash;

        /// <summary>
        /// SHA hash for the RateLimitIncrement lua script.
        /// </summary>
        private static byte[] RateLimitIncrementHash
        {
            get { return RateLimiter._rateLimitIncrementHash; }
        }

        /// <summary>
        /// Loads the underlying Lua script(s) onto all necessary servers.
        /// </summary>
        public static void ScriptLoad()
        {
            var script = ScriptLoader.Instance["RateLimitIncrement"];
            var connections = SharedCache.Instance.GetAllWriteConnections();

            foreach (var connection in connections)
            {
                foreach (var endpoint in connection.GetEndPoints())
                {
                    RateLimiter._rateLimitIncrementHash = connection.GetServer(endpoint).ScriptLoad(script);
                }
            }
        }

        /// <summary>
        /// Increments the rate limiter at the key specified by <param name="increment"/> unless the increment goes
        /// over the <param name="throttle"/>, in which case it returns the amount it's gone over as a negative value.
        /// </summary>
        /// <param name="key">The key where the rate limiter exists.</param>
        /// <param name="spanSize">The full span of time being rate limited.</param>
        /// <param name="bucketSize">The period of time that each bucket should track.</param>
        /// <param name="throttle">The total throttling size.</param>
        /// <param name="increment">How much to increment by.</param>
        /// <returns>The amount remaining, or a negative value for how much the request would have gone over.</returns>
        public static RedisResult Increment(
            string key,
            TimeSpan spanSize,
            TimeSpan bucketSize,
            long throttle,
            int increment = 1)
        {
            RedisKey[] keyArgs = { key };
            RedisValue[] valueArgs =
                {
                    DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond, (long)spanSize.TotalMilliseconds,
                    (long)bucketSize.TotalMilliseconds, increment, throttle
            };

            RedisResult result = SharedCache.Instance.GetWriteConnection(key)
                .GetDatabase(SharedCache.Instance.Db)
                .ScriptEvaluate(RateLimiter.RateLimitIncrementHash, keyArgs, valueArgs);

            return result;
        }

        /// <summary>
        /// Increments the rate limiter at the key specified by <param name="increment"/> unless the increment goes
        /// over the <param name="throttle"/>, in which case it returns the amount it's gone over as a negative value.
        /// </summary>
        /// <param name="key">The key where the rate limiter exists.</param>
        /// <param name="spanSize">The full span of time being rate limited.</param>
        /// <param name="bucketSize">The period of time that each bucket should track.</param>
        /// <param name="throttle">The total throttling size.</param>
        /// <param name="increment">How much to increment by.</param>
        /// <returns>The amount remaining, or a negative value for how much the request would have gone over.</returns>
        public static async Task<RedisResult> IncrementAsync(
            string key,
            TimeSpan spanSize,
            TimeSpan bucketSize,
            long throttle,
            int increment = 1)
        {
            RedisKey[] keyArgs = { key };
            RedisValue[] valueArgs =
                {
                    DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond, (long)spanSize.TotalMilliseconds,
                    (long)bucketSize.TotalMilliseconds, increment, throttle
            };

            RedisResult result = await SharedCache.Instance.GetWriteConnection(key)
                .GetDatabase(SharedCache.Instance.Db)
                .ScriptEvaluateAsync(RateLimiter.RateLimitIncrementHash, keyArgs, valueArgs);

            return result;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace DvsaMotTestTest\Data;

use DvsaCommon\HttpRestJson\Client;
use DvsaMotTest\Data\TesterInProgressTestNumberResource;

class TesterInProgressTestIdResourceTest extends \Dvsa\Mot\Frontend\Test\TestCase
{
    /** @var TesterInProgressTestNumberResource */
    private $resource;

    public function setUp()
    {
        $client = \DvsaCommonTest\TestUtils\XMock::of(Client::class);

        // get should be called only once and  cached
        $client->expects($this->once())->method('get')->will($this->returnValue(['data' => [(int) (100 * rand())]]));

        $this->resource = new TesterInProgressTestNumberResource($client);
    }

    public function testGet()
    {
        $personId = 42;
        $this->resource->get($personId);
    }
}


text:
package tiedot

func NewUnit(c *Context) *Unit {
	return &Unit{
		context: c,
	}
}

type Unit struct {
	context *Context
	// Mapper  *Mapper
}

func (self *Unit) Begin() error {
	return self.context.Open()
}

func (self *Unit) Commit() error {
	return self.context.Close()
}

// TODO: Remove
// Thist is the generic data mapping using reflection. Currently the data mapping logic is in the repository.
// Must be decided if it will stay there, and this generic code to be removed.
// type Mapper struct {
// }

// func (m *Mapper) Map(obj interface{}, arr []map[string]interface{}) {
// 	for _, item := range arr {
// 		fillObject(obj, item)
// 	}
// }

// func fillObject(o interface{}, m map[string]interface{}) error {
// 	for k, v := range m {
// 		err := setField(o, k, v)
// 		if err != nil {
// 			return err
// 		}
// 	}
// 	return nil
// }

// func setField(obj interface{}, name string, value interface{}) error {
// 	structValue := reflect.ValueOf(obj).Elem()
// 	structFieldValue := structValue.FieldByName(name)

// 	if !structFieldValue.IsValid() {
// 		return fmt.Errorf("No such field: %s in obj", name)
// 	}

// 	if !structFieldValue.CanSet() {
// 		return fmt.Errorf("Cannot set %s field value", name)
// 	}

// 	structFieldType := structFieldValue.Type()
// 	val := reflect.ValueOf(value)
// 	if structFieldType != val.Type() {
// 		return errors.New("Provided value type didn't match obj field type")
// 	}

// 	structFieldValue.Set(val)
// 	return nil
// }


text:
package com.baremetalstudios.minicam.simulator;

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

public class SimpleAperture implements Aperture {
    private final int num;
    private final List<Double> modifiers;
    private final ApertureType type;

    public SimpleAperture(ApertureType type, int num, List<Double> modifiers) {
        this.type = type;
        this.num = num;
        this.modifiers = modifiers;
    }

    @Override
    public int getId() {
        return num;
    }

    @Override
    public ApertureType getType() {
        return type;
    }

    @Override
    public String toString() {
        return toString(null);
    }

    public String toString(PlotterMode mode) {
        return type.name().toLowerCase() + extraText() + " " + num + " (" + join(modifiers, ",") + ")";
    }

    protected String extraText() {
        return "";
    }

    private static<T> String join(Iterable<T> iterable, String delimiter) {
        final Iterator<T> iterator = iterable.iterator();
        final T first = iterator.next();
        if (!iterator.hasNext()) {
            return (first == null) ? "null" : first.toString();
        }

        // two or more elements
        final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
        if (first != null) {
            buf.append(first);
        }

        while (iterator.hasNext()) {
            buf.append(delimiter);
            final T obj = iterator.next();
            if (obj != null) {
                buf.append(obj);
            }
        }

        return buf.toString();
    }
}


text:
module Core
  class ExternalPost
    class ScheduledAnalysisService
      class << self
        THROTTLE = 400

        def run!
          ##
          # let's sanitize languages
          grouped_analyses = scheduled_analyses.group_by(&:lang)
          sanitized_analyses = grouped_analyses.keys.inject({}) do |memo, lang|
            if Sentiment140Api::ALLOWED_LANGUAGES.include?(lang)
              memo[lang] = grouped_analyses[lang]
            else
              memo["auto"] ||= []
              memo["auto"].concat grouped_analyses[lang]
            end
            memo
          end
          sanitized_analyses.each do |language, analyses|
            new(language: language, analyses: analyses).run!
          end
        end

        def scheduled_analyses
          Brain::ScheduledAnalysis.latest
                                  .with_status(:new)
                                  .limit(THROTTLE)
        end
      end

      def initialize(language:, analyses:)
        puts "analysing #{analyses.count} posts in #{language}"
        @language = language
        @analyses = analyses
      end

      def run!
        # @external_posts = @analyses.map(&:subject)
        classification = post_to_sentiment_140
        Sentiment140Response.new(
          classification.response.body
        ).external_posts_response.each do |response|
          parse_external_post_response(response)
        end
      end

      private

      def parse_external_post_response(response)
        ##
        # may be better outside?
        analysis = Brain::ScheduledAnalysis.find response["id"]
        external_post = analysis.subject
        analysis.update!(status: :done)
        Brain::ExternalAnalysis.create!(
          subject_id: external_post.id,
          subject_type: "Core::ExternalPost",
          provider: :sentiment140,
          response: sanitize_post_response(response)
        )
        if response["polarity"] == 4 # AKA P+
          external_post.update!(status: :will_repost)
        end
      end

      def sanitize_post_response(response)
        response.slice("polarity", "meta")
      end

      def post_to_sentiment_140
        sentiment140_api = Sentiment140Api.new
        data = @analyses.map do |analysis|
          {
            id: analysis.id.to_s,
            text: get_text_for(analysis),
            query: get_query_for(analysis)
          }
        end
        sentiment140_api.classify_analyses(
          data: data,
          language: @language
        )
      end

      def get_text_for(analysis)
        analysis.subject.raw_hash["text"]
      end

      def get_query_for(analysis)
        Core::Account::SearchtermService.new(
          analysis.subject.external_provider.account
        ).rules_joined
      end
    end
  end
end


text:
package ruby

import (
	"github.com/nuclio/nuclio/pkg/functionconfig"
	"github.com/nuclio/nuclio/pkg/processor/build/runtime"

	"github.com/nuclio/errors"
	"github.com/nuclio/logger"
)

type factory struct{}

func (f *factory) Create(logger logger.Logger,
	containerBuilderKind string,
	stagingDir string,
	functionConfig *functionconfig.Config) (runtime.Runtime, error) {

	abstractRuntime, err := runtime.NewAbstractRuntime(logger, containerBuilderKind, stagingDir, functionConfig)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create abstract runtime")
	}

	return &ruby{
		AbstractRuntime: abstractRuntime,
	}, nil
}

func init() {
	runtime.RuntimeRegistrySingleton.Register("ruby", &factory{})
}


text:
package com.intellij.openapi.actionSystem.impl;

import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.ex.DataConstantsEx;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.plaf.beg.BegMenuItemUI;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashSet;
import java.util.Set;

public class ActionMenuItem extends JMenuItem {
  private static final Icon ourCheckedIcon = IconLoader.getIcon("/actions/check.png");
  private static final Icon ourUncheckedIcon = new EmptyIcon(18, 18);

  private final AnAction myAction;
  private final Presentation myPresentation;
  private final String myPlace;
  private final DataContext myContext;
  private final AnActionEvent myEvent;
  private MenuItemSynchronizer myMenuItemSynchronizer;
  private boolean myEnableMnemonics;

  public ActionMenuItem(AnAction action, Presentation presentation, String place, DataContext context, final boolean enableMnemonics, boolean prepareNow) {
    myAction = action;
    myPresentation = presentation;
    myPlace = place;
    myContext = context;
    myEnableMnemonics = enableMnemonics;
    myEvent = new AnActionEvent(null, context, place, myPresentation, ActionManager.getInstance(), 0);
    addActionListener(new ActionTransmitter());
    setBorderPainted(false);

    if (prepareNow) {
      init();
    } else {
      setText("loading...");
    }
  }

  public void prepare() {
    init();
    installSynchronizer();
  }

  /**
   * We have to make this method public to allow BegMenuItemUI to invoke it.
   */
  public void fireActionPerformed(ActionEvent event) {
    super.fireActionPerformed(event);
  }

  public void addNotify() {
    super.addNotify();
    installSynchronizer();
    init();
  }

  public void removeNotify() {
    uninstallSynchronizer();
    super.removeNotify();
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    //g.setColor(getBackground());
    //g.fillRect(0, 0, getWidth(), getHeight());
  }

  @Override
  protected void paintChildren(Graphics g) {
    super.paintChildren(g);
  }

  @Override
  protected void paintBorder(Graphics g) {
    super.paintBorder(g);
  }

  @Override
  public void paint(Graphics g) {
    super.paint(g);
  }

  private void installSynchronizer() {
    if (myMenuItemSynchronizer == null) {
      myMenuItemSynchronizer = new MenuItemSynchronizer();
    }
  }

  private void uninstallSynchronizer() {
    if (myMenuItemSynchronizer != null) {
      Disposer.dispose(myMenuItemSynchronizer);
      myMenuItemSynchronizer = null;
    }
  }

  private void init() {
    setVisible(myPresentation.isVisible());
    setEnabled(myPresentation.isEnabled());
    setMnemonic(myEnableMnemonics ? myPresentation.getMnemonic() : 0);
    setText(myPresentation.getText());
    final int mnemonicIndex = myEnableMnemonics ? myPresentation.getDisplayedMnemonicIndex() : -1;

    if (getText() != null && mnemonicIndex >= 0 && mnemonicIndex < getText().length()) {
      setDisplayedMnemonicIndex(mnemonicIndex);
    }

    updateIcon();
    String id = ActionManager.getInstance().getId(myAction);
    if (id != null) {
      Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(id);
      setAcceleratorFromShortcuts(shortcuts);
    }
    else {
      final ShortcutSet shortcutSet = myAction.getShortcutSet();
      if (shortcutSet != null) {
        setAcceleratorFromShortcuts(shortcutSet.getShortcuts());
      }
    }
  }

  private void setAcceleratorFromShortcuts(final Shortcut[] shortcuts) {
    for (Shortcut shortcut : shortcuts) {
      if (shortcut instanceof KeyboardShortcut) {
        setAccelerator(((KeyboardShortcut)shortcut).getFirstKeyStroke());
        break;
      }
    }
  }

  public void updateUI() {
    if (UIUtil.isStandardMenuLAF()) {
      super.updateUI();
    }
    else {
      setUI(BegMenuItemUI.createUI(this));
    }
  }

  /**
   * Updates long description of action at the status bar.
   */
  public void menuSelectionChanged(boolean isIncluded) {
    super.menuSelectionChanged(isIncluded);
    ActionMenu.showDescriptionInStatusBar(isIncluded, this, myPresentation.getDescription());
  }

  public String getFirstShortcutText() {
    return KeymapUtil.getFirstKeyboardShortcutText(myAction);
  }

  private final class ActionTransmitter implements ActionListener {
    /**
     * @param component component
     * @return whether the component in Swing tree or not. This method is more
     *         weak then {@link Component#isShowing() }
     */
    private boolean isInTree(final Component component) {
      if (component instanceof Window) {
        return component.isShowing();
      }
      else {
        Window windowAncestor = SwingUtilities.getWindowAncestor(component);
        return windowAncestor != null && windowAncestor.isShowing();
      }
    }

    public void actionPerformed(final ActionEvent e) {
      AnActionEvent event = new AnActionEvent(
        new MouseEvent(ActionMenuItem.this, MouseEvent.MOUSE_PRESSED, 0, e.getModifiers(), getWidth() / 2, getHeight() / 2, 1, false),
        myContext, myPlace, myPresentation, ActionManager.getInstance(), e.getModifiers());
      if (ActionUtil.lastUpdateAndCheckDumb(myAction, event, false)) {
        ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
        actionManager.fireBeforeActionPerformed(myAction, myContext, event);
        Component component = ((Component)event.getDataContext().getData(DataConstantsEx.CONTEXT_COMPONENT));
        if (component != null && !isInTree(component)) {
          return;
        }
        myAction.actionPerformed(event);
        actionManager.queueActionPerformedEvent(myAction, myContext, event);
      }
    }
  }

  private void updateIcon() {
    if (myAction instanceof Toggleable && myPresentation.getIcon() == null) {
      myAction.update(myEvent);
      if (Boolean.TRUE.equals(myEvent.getPresentation().getClientProperty(Toggleable.SELECTED_PROPERTY))) {
        setIcon(ourCheckedIcon);
        setDisabledIcon(IconLoader.getDisabledIcon(ourCheckedIcon));
      }
      else {
        setIcon(ourUncheckedIcon);
        setDisabledIcon(IconLoader.getDisabledIcon(ourUncheckedIcon));
      }
    }
    else {
      if (!SystemInfo.isMac || UISettings.getInstance().SHOW_ICONS_IN_MENUS) {
        Icon icon = myPresentation.getIcon();
        setIcon(icon);
        if (myPresentation.getDisabledIcon() != null) {
          setDisabledIcon(myPresentation.getDisabledIcon());
        }
        else {
          setDisabledIcon(IconLoader.getDisabledIcon(icon));
        }
      }
    }
  }

  private final class MenuItemSynchronizer implements PropertyChangeListener, Disposable {
    @NonNls private static final String SELECTED = "selected";

    private final Set<String> mySynchronized = new HashSet<String>();

    private MenuItemSynchronizer() {
      myPresentation.addPropertyChangeListener(this);
    }

    public void dispose() {
      myPresentation.removePropertyChangeListener(this);
    }

    public void propertyChange(PropertyChangeEvent e) {
      boolean queueForDispose = getParent() == null;

      String name = e.getPropertyName();
      if (mySynchronized.contains(name)) return;

      mySynchronized.add(name);

      try {
        if (Presentation.PROP_VISIBLE.equals(name)) {
          final boolean visible = myPresentation.isVisible();
          if (!visible && SystemInfo.isMacSystemMenu && myPlace == ActionPlaces.MAIN_MENU) {
            setEnabled(false);
          }
          else {
            setVisible(visible);
          }
        }
        else if (Presentation.PROP_ENABLED.equals(name)) {
          setEnabled(myPresentation.isEnabled());
          updateIcon();
        }
        else if (Presentation.PROP_MNEMONIC_KEY.equals(name)) {
          setMnemonic(myPresentation.getMnemonic());
        }
        else if (Presentation.PROP_MNEMONIC_INDEX.equals(name)) {
          setDisplayedMnemonicIndex(myPresentation.getDisplayedMnemonicIndex());
        }
        else if (Presentation.PROP_TEXT.equals(name)) {
          setText(myPresentation.getText());
        }
        else if (Presentation.PROP_ICON.equals(name) || Presentation.PROP_DISABLED_ICON.equals(name)) {
          updateIcon();
        }
        else if (SELECTED.equals(name)) {
          updateIcon();
        }
      }
      finally {
        mySynchronized.remove(name);
        if (queueForDispose) {
          // later since we cannot remove property listeners inside event processing
          //noinspection SSBasedInspection
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              if (getParent() == null) {
                uninstallSynchronizer();
              }
            }
          });
        }
      }
    }

  }
}


text:
package com.microsoft.azure.management.policy.v2018_05_01.implementation;

import com.microsoft.azure.management.policy.v2018_05_01.PolicyType;
import java.util.List;
import com.microsoft.azure.management.policy.v2018_05_01.PolicyDefinitionReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.ProxyResource;

/**
 * The policy set definition.
 */
@JsonFlatten
public class PolicySetDefinitionInner extends ProxyResource {
    /**
     * The type of policy definition. Possible values are NotSpecified,
     * BuiltIn, and Custom. Possible values include: 'NotSpecified', 'BuiltIn',
     * 'Custom'.
     */
    @JsonProperty(value = "properties.policyType")
    private PolicyType policyType;

    /**
     * The display name of the policy set definition.
     */
    @JsonProperty(value = "properties.displayName")
    private String displayName;

    /**
     * The policy set definition description.
     */
    @JsonProperty(value = "properties.description")
    private String description;

    /**
     * The policy set definition metadata.
     */
    @JsonProperty(value = "properties.metadata")
    private Object metadata;

    /**
     * The policy set definition parameters that can be used in policy
     * definition references.
     */
    @JsonProperty(value = "properties.parameters")
    private Object parameters;

    /**
     * An array of policy definition references.
     */
    @JsonProperty(value = "properties.policyDefinitions", required = true)
    private List<PolicyDefinitionReference> policyDefinitions;

    /**
     * Get the type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Possible values include: 'NotSpecified', 'BuiltIn', 'Custom'.
     *
     * @return the policyType value
     */
    public PolicyType policyType() {
        return this.policyType;
    }

    /**
     * Set the type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. Possible values include: 'NotSpecified', 'BuiltIn', 'Custom'.
     *
     * @param policyType the policyType value to set
     * @return the PolicySetDefinitionInner object itself.
     */
    public PolicySetDefinitionInner withPolicyType(PolicyType policyType) {
        this.policyType = policyType;
        return this;
    }

    /**
     * Get the display name of the policy set definition.
     *
     * @return the displayName value
     */
    public String displayName() {
        return this.displayName;
    }

    /**
     * Set the display name of the policy set definition.
     *
     * @param displayName the displayName value to set
     * @return the PolicySetDefinitionInner object itself.
     */
    public PolicySetDefinitionInner withDisplayName(String displayName) {
        this.displayName = displayName;
        return this;
    }

    /**
     * Get the policy set definition description.
     *
     * @return the description value
     */
    public String description() {
        return this.description;
    }

    /**
     * Set the policy set definition description.
     *
     * @param description the description value to set
     * @return the PolicySetDefinitionInner object itself.
     */
    public PolicySetDefinitionInner withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * Get the policy set definition metadata.
     *
     * @return the metadata value
     */
    public Object metadata() {
        return this.metadata;
    }

    /**
     * Set the policy set definition metadata.
     *
     * @param metadata the metadata value to set
     * @return the PolicySetDefinitionInner object itself.
     */
    public PolicySetDefinitionInner withMetadata(Object metadata) {
        this.metadata = metadata;
        return this;
    }

    /**
     * Get the policy set definition parameters that can be used in policy definition references.
     *
     * @return the parameters value
     */
    public Object parameters() {
        return this.parameters;
    }

    /**
     * Set the policy set definition parameters that can be used in policy definition references.
     *
     * @param parameters the parameters value to set
     * @return the PolicySetDefinitionInner object itself.
     */
    public PolicySetDefinitionInner withParameters(Object parameters) {
        this.parameters = parameters;
        return this;
    }

    /**
     * Get an array of policy definition references.
     *
     * @return the policyDefinitions value
     */
    public List<PolicyDefinitionReference> policyDefinitions() {
        return this.policyDefinitions;
    }

    /**
     * Set an array of policy definition references.
     *
     * @param policyDefinitions the policyDefinitions value to set
     * @return the PolicySetDefinitionInner object itself.
     */
    public PolicySetDefinitionInner withPolicyDefinitions(List<PolicyDefinitionReference> policyDefinitions) {
        this.policyDefinitions = policyDefinitions;
        return this;
    }

}


text:
<?php

use yii\db\Migration;
use app\models\Special;
use app\models\Subweapon;
use app\models\WeaponType;
use app\models\DeathReasonType;

class m151009_073533_weapons extends Migration
{
    public function safeUp()
    {
        $this->insert('weapon', [
            'type_id' => WeaponType::findOne(['key' => 'charger'])->id,
            'key' => 'liter3k_scope_custom',
            'name' => 'Custom E-liter 3K Scope',
            'subweapon_id' => Subweapon::findOne(['key' => 'jumpbeacon'])->id,
            'special_id' => Special::findOne(['key' => 'daioika'])->id,
        ]);

        $this->insert('weapon', [
            'type_id' => WeaponType::findOne(['key' => 'shooter'])->id,
            'key' => 'longblaster_custom',
            'name' => 'Custom Range Blaster',
            'subweapon_id' => Subweapon::findOne(['key' => 'splashbomb'])->id,
            'special_id' => Special::findOne(['key' => 'daioika'])->id,
        ]);

        $mainWeapon = DeathReasonType::findOne(['key' => 'main'])->id;
        $this->batchInsert('death_reason', ['type_id', 'key', 'name'], [
            [ $mainWeapon, 'liter3k_scope_custom', 'Custom E-liter 3K Scope' ],
            [ $mainWeapon, 'longblaster_custom', 'Custom Range Blaster' ],
        ]);
    }

    public function safeDown()
    {
        $this->delete(
            'death_reason',
            ['in', 'key', [ 'liter3k_scope_custom', 'longblaster_custom' ]]
        );
        $this->delete(
            'weapon',
            ['in', 'key', [ 'liter3k_scope_custom', 'longblaster_custom' ]]
        );
    }
}


text:
layout: page
title: Henry Ramirez's 74th Birthday
date: 2016-05-24
author: Gregory Hinton
tags: weekly links, java
status: published
summary: Praesent auctor lectus in volutpat gravida. Maecenas.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 12/09/2017
  endDate: 12/10/2017
  ctyhocn: CARGAHX
  groupCode: HR7B
published: true
---
Curabitur mattis posuere elit ac elementum. Maecenas tincidunt urna eu odio egestas, vel pulvinar ante facilisis. Nam ut sapien vestibulum, commodo arcu et, pellentesque est. Suspendisse felis augue, tincidunt nec ornare non, lacinia id nulla. Morbi fringilla turpis magna, ut congue enim viverra id. Pellentesque eu lectus vel massa tempus mattis eget a mauris. Vivamus nulla urna, pharetra a urna vitae, vehicula gravida purus. Ut a nisl consectetur, ornare risus in, pulvinar odio. Vestibulum pellentesque vulputate enim, vel viverra metus sollicitudin eget. Fusce hendrerit tortor id ligula congue feugiat. Etiam condimentum rutrum arcu. Praesent id ante volutpat, sodales augue ac, volutpat diam. Morbi placerat magna magna. Cras vehicula interdum quam et venenatis. Donec efficitur arcu a tellus ornare lacinia.

* Sed volutpat nibh eu turpis vestibulum, eu accumsan diam suscipit
* Cras at metus ac dui facilisis fringilla
* Aliquam in sem eu lorem dictum posuere eu id mauris.

Fusce porta mollis vulputate. Nunc sodales diam pulvinar leo rutrum, a facilisis ipsum bibendum. Aliquam nibh diam, viverra eget elit vel, venenatis commodo augue. Suspendisse quis magna arcu. Sed nec quam nec massa fermentum auctor. Donec hendrerit viverra mi vitae dignissim. Vestibulum vitae nunc non ex pulvinar euismod. Suspendisse gravida nisl urna, at dapibus justo finibus ac. Nunc at tristique turpis.
In sit amet eros et lacus blandit rutrum. Nam pretium tincidunt magna at tincidunt. Nunc laoreet mauris at nisi feugiat consectetur. Integer in diam semper, ornare nibh in, bibendum magna. Suspendisse ut orci malesuada, commodo magna nec, tempus elit. Vestibulum pharetra accumsan ultrices. Phasellus mauris neque, tincidunt sed mollis sit amet, varius id nulla. Fusce rutrum nisl diam. Nunc mauris sem, commodo a massa quis, lobortis tristique ligula. Nam congue posuere ex. Mauris fermentum justo eget mi gravida, et tempor leo feugiat.


text:
package com.amazonaws.services.accessanalyzer.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * Starts a scan of the policies applied to the specified resource.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartResourceScanRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ARN
     * of the analyzer to use to scan the policies applied to the specified resource.
     *

     */
    private String analyzerArn;
    /**
     *

     * The ARN of the resource to scan.
     *

     */
    private String resourceArn;
    /**
     *

     * The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the owning
     * account is the account in which the resource was created.
     *

     */
    private String resourceOwnerAccount;

    /**
     *

     * The ARN
     * of the analyzer to use to scan the policies applied to the specified resource.
     *

     *
     * @param analyzerArn
     *        The ARN of the analyzer to use to scan the policies applied to the specified resource.
     */

    public void setAnalyzerArn(String analyzerArn) {
        this.analyzerArn = analyzerArn;
    }

    /**
     *

     * The ARN
     * of the analyzer to use to scan the policies applied to the specified resource.
     *

     *
     * @return The ARN of the analyzer to use to scan the policies applied to the specified resource.
     */

    public String getAnalyzerArn() {
        return this.analyzerArn;
    }

    /**
     *

     * The ARN
     * of the analyzer to use to scan the policies applied to the specified resource.
     *

     *
     * @param analyzerArn
     *        The ARN of the analyzer to use to scan the policies applied to the specified resource.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartResourceScanRequest withAnalyzerArn(String analyzerArn) {
        setAnalyzerArn(analyzerArn);
        return this;
    }

    /**
     *

     * The ARN of the resource to scan.
     *

     *
     * @param resourceArn
     *        The ARN of the resource to scan.
     */

    public void setResourceArn(String resourceArn) {
        this.resourceArn = resourceArn;
    }

    /**
     *

     * The ARN of the resource to scan.
     *

     *
     * @return The ARN of the resource to scan.
     */

    public String getResourceArn() {
        return this.resourceArn;
    }

    /**
     *

     * The ARN of the resource to scan.
     *

     *
     * @param resourceArn
     *        The ARN of the resource to scan.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartResourceScanRequest withResourceArn(String resourceArn) {
        setResourceArn(resourceArn);
        return this;
    }

    /**
     *

     * The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the owning
     * account is the account in which the resource was created.
     *

     *
     * @param resourceOwnerAccount
     *        The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the
     *        owning account is the account in which the resource was created.
     */

    public void setResourceOwnerAccount(String resourceOwnerAccount) {
        this.resourceOwnerAccount = resourceOwnerAccount;
    }

    /**
     *

     * The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the owning
     * account is the account in which the resource was created.
     *

     *
     * @return The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the
     *         owning account is the account in which the resource was created.
     */

    public String getResourceOwnerAccount() {
        return this.resourceOwnerAccount;
    }

    /**
     *

     * The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the owning
     * account is the account in which the resource was created.
     *

     *
     * @param resourceOwnerAccount
     *        The Amazon Web Services account ID that owns the resource. For most Amazon Web Services resources, the
     *        owning account is the account in which the resource was created.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartResourceScanRequest withResourceOwnerAccount(String resourceOwnerAccount) {
        setResourceOwnerAccount(resourceOwnerAccount);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAnalyzerArn() != null)
            sb.append("AnalyzerArn: ").append(getAnalyzerArn()).append(",");
        if (getResourceArn() != null)
            sb.append("ResourceArn: ").append(getResourceArn()).append(",");
        if (getResourceOwnerAccount() != null)
            sb.append("ResourceOwnerAccount: ").append(getResourceOwnerAccount());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StartResourceScanRequest == false)
            return false;
        StartResourceScanRequest other = (StartResourceScanRequest) obj;
        if (other.getAnalyzerArn() == null ^ this.getAnalyzerArn() == null)
            return false;
        if (other.getAnalyzerArn() != null && other.getAnalyzerArn().equals(this.getAnalyzerArn()) == false)
            return false;
        if (other.getResourceArn() == null ^ this.getResourceArn() == null)
            return false;
        if (other.getResourceArn() != null && other.getResourceArn().equals(this.getResourceArn()) == false)
            return false;
        if (other.getResourceOwnerAccount() == null ^ this.getResourceOwnerAccount() == null)
            return false;
        if (other.getResourceOwnerAccount() != null && other.getResourceOwnerAccount().equals(this.getResourceOwnerAccount()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAnalyzerArn() == null) ? 0 : getAnalyzerArn().hashCode());
        hashCode = prime * hashCode + ((getResourceArn() == null) ? 0 : getResourceArn().hashCode());
        hashCode = prime * hashCode + ((getResourceOwnerAccount() == null) ? 0 : getResourceOwnerAccount().hashCode());
        return hashCode;
    }

    @Override
    public StartResourceScanRequest clone() {
        return (StartResourceScanRequest) super.clone();
    }

}


text: Map of Bits i Revenge of Bits z finałów Confidence CTF 2016


text:
<?php

namespace QbiPlugins\Triggers;

class UpdateKnownPlayers
{
    public function init(\Qbi\PluginManager $pluginManager)
    {
        $pluginManager->addTrigger(
            'UpdateKnownPlayers',
            ['joined the game', 'left the game'],
            function(\Qbi\Parser\Line $line) use ($pluginManager) {
                $json = $pluginManager->getFile()->getContent('storage/known_players.json');
                $players = json_decode($json, true);

                if (!$players) {
                    $players = [];
                }

                if ($line->isPlayerJoining()) {
                    if (!array_key_exists($line->getPlayerName(), $players)) {
                        $players[$line->getPlayerName()]['timePlayed'] = 0;
                        $players[$line->getPlayerName()]['startPlaying'] = time();
                    } else {
                        $players[$line->getPlayerName()]['startPlaying'] = time();
                    }
                } elseif ($line->isPlayerLeaving()) {
                    $duration = time() - $players[$line->getPlayerName()]['startPlaying'];
                    $players[$line->getPlayerName()]['timePlayed'] += $duration;
                    unset($players[$line->getPlayerName()]['startPlaying']);
                }

                $json = json_encode($players);
                $pluginManager->getFile()->putContent('storage/known_players.json', $json);
            }
        );
    }
}


text:
package javax.print.attribute.standard;

import javax.print.attribute.Attribute;
import javax.print.attribute.DocAttribute;
import javax.print.attribute.EnumSyntax;
import javax.print.attribute.PrintJobAttribute;
import javax.print.attribute.PrintRequestAttribute;

/**
 * The Chromaticity printing attribute specifies if print data
 * should be printed in monochrome or color.
 *

 * The attribute interacts with the document to be printed. If the document
 * to be printed is a monochrome document it will be printed monochrome
 * regardless of the value of this attribute category. However if it is a
 * color document supplying the attribute value MONOCHROME
 * will prepare the document to be printed in monochrome instead of color.
 *

 *

 * This printing attribute has nothing to do with the capabilities of the
 * printer device. To check if a specific printer service supports printing
 * in color you have to use the attribute
 * {@link javax.print.attribute.standard.ColorSupported}
 *

 *

 * IPP Compatibility: Chromaticity is not an IPP 1.1 attribute.
 *

 *
 * @author Michael Koch (konqueror@gmx.de)
 */
public final class Chromaticity extends EnumSyntax
  implements DocAttribute, PrintRequestAttribute, PrintJobAttribute
{
  private static final long serialVersionUID = 4660543931355214012L;

  /** Specifies monochrome printing. */
  public static final Chromaticity MONOCHROME = new Chromaticity(0);

  /** Specifies color printing. */
  public static final Chromaticity COLOR = new Chromaticity(1);

  private static final String[] stringTable = { "monochrome", "color" };
  private static final Chromaticity[] enumValueTable = { MONOCHROME, COLOR };

  /**
   * Creates a Chromaticity object.
   *
   * @param value the enum value
   */
  protected Chromaticity(int value)
  {
    super(value);
  }

  /**
   * Returns category of this class.
   *
   * @return The class Chromaticity itself.
   */
  public Class< ? extends Attribute> getCategory()
  {
    return Chromaticity.class;
  }

  /**
   * Returns the name of this attribute.
   *
   * @return The name "chromaticity".
   */
  public String getName()
  {
    return "chromaticity";
  }

  /**
   * Returns a table with the enumeration values represented as strings
   * for this object.
   *
   * @return The enumeration values as strings.
   */
  protected String[] getStringTable()
  {
    return stringTable;
  }

  /**
   * Returns a table with the enumeration values for this object.
   *
   * @return The enumeration values.
   */
  protected EnumSyntax[] getEnumValueTable()
  {
    return enumValueTable;
  }

}


text:
#
# Copyright (c) 2006-2010 National ICT Australia (NICTA), Australia
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#
# = eventlib.rb
#
# == Description
#
# This Ruby file contains various common Event declarations, which the EC will
# load before the user's experiment file
#

#
# This provide some default Event definition that the user may use in his
# experiment, without having to worry about how to define them.
# To start one of the event monitoring defined here, the user need to associate
# at least one block of tasks to it, using the onEvent() OEDL call.
# See the OEDL documentation for more info and a tutorial
#

defEvent(:ALL_UP_AND_INSTALLED) do |event|
  node_status = allGroups.state("status/@value")
  app_status = allGroups.state("apps/app/status/@value")
  if allEqual(node_status, "UP") && allEqual(app_status, "INSTALLED.OK")
    event.fire
  end
end

defEvent(:ALL_UP) do |event|
  node_status = allGroups.state("status/@value")
  event.fire if allEqual(node_status, "UP")
end

defEvent(:ALL_INTERFACE_UP) do |event|
  iface_status = allGroups.state("net/*/*/current/@status")
  #info "TDEBUG - #{if_status.join(" ")}"
  event.fire if allEqual(iface_status, "CONFIGURED.OK")
end

defEvent(:EXPERIMENT_DONE) do |event|
  exp_status = Experiment.state("status/text()")
  event.fire if allEqual(exp_status, "DONE")
end

onEvent(:EXPERIMENT_DONE, true) do |event|
  Experiment.close
end

defEvent(:INTERRUPT, 1) do |event|
  exp_status = Experiment.state("status/text()")
  event.fire if allEqual(exp_status, "INTERRUPTED")
end

onEvent(:INTERRUPT) do |event|
  MObject.info(:INTERRUPT, "\n\nUser issued an Interruption. Stopping the experiment now! Please wait...\n")
  Experiment.done
end

defEvent(:NO_USER_DEFINED_EVENTS) do |event|
  if Experiment.running? && !Experiment.disconnection_allowed?
    if Event.empty?(:ignore => [:EXPERIMENT_DONE, :NO_USER_DEFINED_EVENTS])
      event.fire
    end
  end
end

onEvent(:NO_USER_DEFINED_EVENTS) do |event|
  warn " "
  warn "Warning!!! Your experiment has no user-defined events!"
  warn "It is likely that nothing will happen from now one..."
  warn "Press CTRL-C only ONCE to stop your experiment.\n"
  # An alternative... not sure what is the best here, for now use the above
  # warn "Closing down your experiment now..."
  # Experiment.done
end


text:
namespace remoting {

class ChromotingSession;
class RendererProxy;

// This is a class for interpreting a raw touch input into actions like moving
// the viewport and injecting mouse clicks.
class GestureInterpreter {
 public:
  enum GestureState { GESTURE_BEGAN, GESTURE_CHANGED, GESTURE_ENDED };

  enum InputMode {
    UNDEFINED_INPUT_MODE,
    DIRECT_INPUT_MODE,
    TRACKPAD_INPUT_MODE
  };

  GestureInterpreter();

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

  ~GestureInterpreter();

  // Sets the context for the interpreter. Both arguments are nullable. If both
  // are nullptr then methods below will have no effect.
  void SetContext(RendererProxy* renderer, ChromotingSession* input_stub);

  // Must be called right after the renderer is ready.
  void SetInputMode(InputMode mode);

  // Returns the current input mode.
  InputMode GetInputMode() const;

  // Coordinates of the OpenGL view surface will be used.

  // Called during a two-finger pinching gesture. This can happen in conjunction
  // with Pan().
  void Zoom(float pivot_x, float pivot_y, float scale, GestureState state);

  // Called whenever the user did a pan gesture. It can be one-finger pan, no
  // matter dragging in on or not, or two-finger pan in conjunction with zoom.
  // Two-finger pan without zoom is consider a scroll gesture.
  void Pan(float translation_x, float translation_y);

  // Called when the user did a one-finger tap.
  void Tap(float x, float y);

  void TwoFingerTap(float x, float y);

  void ThreeFingerTap(float x, float y);

  // Caller is expected to call both Pan() and Drag() when dragging is in
  // progress.
  void Drag(float x, float y, GestureState state);

  // Called when the user has just done a one-finger pan (no dragging or
  // zooming) and the pan gesture still has some final velocity.
  void OneFingerFling(float velocity_x, float velocity_y);

  // Called during a two-finger scroll (panning without zooming) gesture.
  void Scroll(float x, float y, float dx, float dy);

  // Called when the user has just done a scroll gesture and the scroll gesture
  // still has some final velocity.
  void ScrollWithVelocity(float velocity_x, float velocity_y);

  // Called to process one animation frame.
  void ProcessAnimations();

  void OnSurfaceSizeChanged(int width, int height);
  void OnDesktopSizeChanged(int width, int height);
  void OnSafeInsetsChanged(int left, int top, int right, int bottom);

  base::WeakPtr<GestureInterpreter> GetWeakPtr();

 private:
  void PanWithoutAbortAnimations(float translation_x, float translation_y);

  void ScrollWithoutAbortAnimations(float dx, float dy);

  void AbortAnimations();

  // Injects the mouse click event and shows the touch feedback.
  void InjectMouseClick(float touch_x,
                        float touch_y,
                        protocol::MouseEvent_MouseButton button);

  void InjectCursorPosition(float x, float y);

  void SetGestureInProgress(TouchInputStrategy::Gesture gesture,
                            bool is_in_progress);

  // Starts the given feedback at (cursor_x, cursor_y) if the feedback radius
  // is non-zero.
  void StartInputFeedback(float cursor_x,
                          float cursor_y,
                          TouchInputStrategy::TouchFeedbackType feedback_type);

  InputMode input_mode_ = UNDEFINED_INPUT_MODE;
  std::unique_ptr<TouchInputStrategy> input_strategy_;
  DesktopViewport viewport_;
  raw_ptr<RendererProxy> renderer_ = nullptr;
  raw_ptr<ChromotingSession> input_stub_ = nullptr;
  TouchInputStrategy::Gesture gesture_in_progress_;

  FlingAnimation pan_animation_;
  FlingAnimation scroll_animation_;

  base::WeakPtrFactory<GestureInterpreter> weak_factory_{this};
};

}  // namespace remoting
#endif  // REMOTING_CLIENT_GESTURE_INTERPRETER_H_


text:
#if !defined( OVR_TextFade_Component_h )
#define OVR_TextFade_Component_h

#include "VRMenuComponent.h"
#include "Fader.h"

namespace OVR {

//==============================================================
// OvrTextFade_Component
class OvrTextFade_Component : public VRMenuComponent
{
public:
	static double const FADE_DELAY;
	static float const  FADE_DURATION;

	OvrTextFade_Component( Vector3f const & iconBaseOffset, Vector3f const & iconFadeOffset );

	virtual eMsgStatus      OnEvent_Impl( App * app, VrFrame const & vrFrame, OvrVRMenuMgr & menuMgr,
										  VRMenuObject * self, VRMenuEvent const & event );

	eMsgStatus Frame( App * app, VrFrame const & vrFrame, OvrVRMenuMgr & menuMgr, VRMenuObject * self, VRMenuEvent const & event );

	eMsgStatus FocusGained( App * app, VrFrame const & vrFrame, OvrVRMenuMgr & menuMgr, VRMenuObject * self, VRMenuEvent const & event );

	eMsgStatus FocusLost( App * app, VrFrame const & vrFrame, OvrVRMenuMgr & menuMgr, VRMenuObject * self, VRMenuEvent const & event );

	static Vector3f CalcIconFadeOffset( char const * text, BitmapFont const & font, Vector3f const & axis, float const iconWidth );

private:
	SineFader   TextAlphaFader;
	double      StartFadeInTime;    // when focus is gained, this is set to the time when the fade in should begin
	double      StartFadeOutTime;   // when focus is lost, this is set to the time when the fade out should begin
	SineFader   IconOffsetFader;
	Vector3f    IconBaseOffset;     // base offset for text
	Vector3f    IconFadeOffset;     // text offset when fully faded
};

} // namespace OVR

#endif // OVR_TextFade_Component_h


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:padding="15dp"
              android:background="#8000"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <TextView
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:textColor="#fff"
        android:textSize="20sp"
        android:text="生活建议"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_comfort"
        android:layout_margin="15dp"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_wash"
        android:layout_margin="15dp"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_sport"
        android:layout_margin="15dp"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <title>Hello World | Will</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
Quick">
<meta property="og:type" content="article">
<meta property="og:title" content="Hello World">
<meta property="og:url" content="http://yoursite.com/2016/04/28/hello-world/index.html">
<meta property="og:site_name" content="Will">
<meta property="og:description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
Quick">
<meta property="og:updated_time" content="2016-04-28T04:29:25.783Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hello World">
<meta name="twitter:description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
Quick">

    <link rel="alternative" href="/atom.xml" title="Will" type="application/atom+xml">

    <link rel="icon" href="/favicon.png">

  <link rel="stylesheet" href="/css/style.css">

		<hgroup>

Will

		</hgroup>

Menu

Tags

Über

主页

所有文章

随笔

相册

								github

								mail

								rss

女Ren╮善 变,男Ren╮善 辩。

Will

			<hgroup>

Will

			</hgroup>

主页

所有文章

随笔

相册

						github

						mail

						rss

  	<time datetime="2016-04-28T04:29:25.779Z" itemprop="datePublished">2016-04-28</time>

      <input type="hidden" class="isFancy" />

      Hello World

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1

$ hexo new "My New Post"

More info: Writing

Run server

1

$ hexo server

More info: Server

Generate static files

1

$ hexo generate

More info: Generating

Deploy to remote sites

1

$ hexo deploy

More info: Deployment

      <

          部署Hexo到github

		Share to:

    		© 2016 Will

      		Hexo  Theme Yilia by Litten

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">


text:
\hypertarget{dir_681990c33591da9376b1ea104e96a61b}{}\section{include/mips/instructions/format\+\_\+\+V\+II Directory Reference}
\label{dir_681990c33591da9376b1ea104e96a61b}\index{include/mips/instructions/format\+\_\+\+V\+I\+I Directory Reference@{include/mips/instructions/format\+\_\+\+V\+I\+I Directory Reference}}
\subsection*{Files}
\begin{DoxyCompactItemize}
\item
file \hyperlink{load_8hpp}{load.\+hpp}
\item
file \hyperlink{store_8hpp}{store.\+hpp}
\end{DoxyCompactItemize}


text:
using System;
using System.Diagnostics;
using System.Linq;

namespace Kf.Numaris.Api.Common
{
    [DebuggerDisplay("{Name} ({Id})")]
    public sealed class Identifier
    {
        public static Identifier For<TSupportedType>(Type type = null)
        {
            if(type == null)
                return new Identifier(typeof(TSupportedType));

            if (type.GetInterfaces().Contains(typeof(TSupportedType)))
                return new Identifier(type);

            throw new UnsupportedInterfaceException(supportedInterfaces: typeof(TSupportedType));
        }

        public string Id { get; }
        public string Name { get; }

        internal Identifier(Type type) : this(
            id: type.FullName,
            name: type.Name)
        { }

        internal Identifier(string id, string name)
        {
            Id = id;
            Name = name;
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            if (ReferenceEquals(this, obj))
                return true;

            if (!(obj is Identifier other))
                return false;

            return other.GetHashCode() == GetHashCode();
        }

        public override int GetHashCode()
        {
            var hash = 13;
            hash = (hash * 7) + Id.GetHashCode();
            hash = (hash * 7) + Name.GetHashCode();

            return hash;
        }

        public override string ToString()
            => $"{Name} ({Id})";
    }
}


text:
'use strict';

angular.module('myApp.skills', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/skills', {
    templateUrl: 'skills/skills.html',
    controller: 'SkillsCtrl',
    animation: 'page-fadein'
  });
}])

.controller('SkillsCtrl', ['$scope', 'myService', function($scope, myService) {

	$scope.pageClass = 'page-skills';

	myService.set();

	$scope.skills = [
		{
			name: "InDesign",
			level: 95,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{
			name: "Photoshop",
			level: 90,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{
			name: "Illustrator",
			level: 75,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{
			name: "Java",
			level: 75,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{
			name: "Javascript",
			level: 70,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{
			name: "JQuery",
			level: 70,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{
			name: "HTML/CSS",
			level: 65,
			description: [
			"this is an example", "this is another example"]
		},
		{

			name: "Python",
			level: 60,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{

			name: "PHP",
			level: 50,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{

			name: "AngularJS",
			level: 25,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		},
		{

			name: "D3",
			level: 15,
			view_description: false,
			description: [
			"this is an example", "this is another example"]
		}

	];

	$scope.toggleDescription  = function(skill) {
			if (skill.has_description) {
	      	  return skill.view_description = !skill.view_description;
	      	}
	      	else {
	      		return false;
	      	}

	    };

	$scope.skillLevelString  = function(skill) {
	        return {
	        	"width": skill.level.toString().concat("%")
	        };

	    };

	$scope.interests = [
		{
			name: "Music",
			level: 95,
			view_description: false,
			has_description: true,
			description: [{
				"Perhaps my listening habits interest you": "http://lastfm.com/ctong1124",
				"This is where I keep my playlists": "https://play.spotify.com/user/12121749949"
			}]
		},
		{
			name: "Food",
			level: 90,
			view_description: false,
			has_description: false,
			description: [{
				"this is an example": "link",
				"this is another example": "link2"
			}]
		},
		{
			name: "Tornados",
			level: 85,
			view_description: false,
			has_description: false,
			description: [{
				"this is an example": "link",
				"this is another example": "link2"
			}]
		}

	];
}]);


text:
Batch image resize script

This script reads images out of a source directory and resizes to two sizes:

1. 1600x1600 (large)
2. 120x120 (small/thumbnail)

If a destination is not provided, the resized images are stored in
`resized` which is created in the source directory.

The new images are renamed as well: img0001.jpg, img0002.jpg.

**Warning**: The script is very raw and serves only a specific use case. It
can of course be optimized by adding further options and checks.
Back up images if you do use it.

## Requirements

- Bash shell
- [ImageMagic](http://www.imagemagick.org/script/index.php)

## Running the script

```

sh resize.sh --source /dir/images

```


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>WarcLucene</groupId>
  <artifactId>WarcLucene</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>org.apache.lucene</groupId>
  		<artifactId>lucene-core</artifactId>
  		<version>5.5.0</version>
  	</dependency>
  	<dependency>
		<groupId>org.apache.lucene</groupId>
		<artifactId>lucene-analyzers-common</artifactId>
		<version>5.5.0</version>
	</dependency>
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	</dependency>
	  	<dependency>
  		<groupId>org.apache.solr</groupId>
  		<artifactId>solr-core</artifactId>
  		<version>5.5.0</version>
  	</dependency>
  	  	<dependency>
  		<groupId>org.apache.solr</groupId>
  		<artifactId>solr-solrj</artifactId>
  		<version>5.5.0</version>
  	</dependency>
  </dependencies>
</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using zuoraTools.ZuoraConnections;

namespace zuoraTools.BusinessLogic
{
    class QueryZuora
    {
        public static void Process(Config conf)
        {
            Dictionary<int, string> columnLegend = new Dictionary<int, string>();

            IZConnection zConn = ZConnectionFactory.Make(conf);

            List<string> selectFields = new List<string>();
            Match m = Regex.Match(conf.ZqueryString, @"(?i)select \* (?i)from");

            if (m.Success)
            {
                throw new Exception("star not implemented");
            }
            else
            {

                m = Regex.Match(conf.ZqueryString, @"\b([a-zA-z0-9*]+)\b");

                while (m.Success && m.Value.ToLower() != "from")
                {
                    if (m.Value.ToLower() != "select")
                    {
                        selectFields.Add(m.Value);
                    }
                    m = m.NextMatch();
                }
            }

            string outputHeader = String.Join(",", selectFields);

            Boolean writeToFile = !conf.DryRun && !String.IsNullOrEmpty(conf.OutputFile);

            System.IO.StreamWriter outputFile = null;

            //Console.WriteLine("zquery:" + conf.zqueryString);
            zObject[] zList = zConn.Query(conf.ZqueryString);

            //Console.WriteLine("zlist count:" + zList.Count().ToString());
            //Console.WriteLine(Regex.Replace(JsonConvert.SerializeObject(zList), @",", "\n"));

            if (zList.Count() == 1 && zList[0] == null)
            {
                Console.WriteLine("No records returned from query.");
            }
            else
            {
                if (writeToFile)
                {
                    outputFile = new System.IO.StreamWriter(conf.OutputFile);
                    outputFile.WriteLine(outputHeader);
                }
                else
                {
                    Console.WriteLine(outputHeader);
                }

                foreach (zObject zOb in zList)
                {
                    if (writeToFile)
                    {
                        outputFile.WriteLine(ZObjectHelper.ToCsvRecord(zOb, selectFields.ToArray()));
                        outputFile.Flush();
                    }
                    else
                    {
                        Console.WriteLine(ZObjectHelper.ToCsvRecord(zOb, selectFields.ToArray()));
                    }
                }
            }

        }
    }
}


text:
package com.qualogy.qafe.core.framework.business;

/**
 * Exception thrown when due to a technical reason in Qafe or a
 * mapping file an action cannot be processed.
 * @author Marc van der Wurff
 *
 */
public class UnableToManageException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 1432412937874810646L;

	private UnableToManageException() {
	}

	public UnableToManageException(String message) {
		super(message);
	}

	public UnableToManageException(Throwable cause) {
		super(cause);
	}

	public UnableToManageException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
import datetime

from django import test

from trader.core.models import User

class UserModelTest(test.TestCase):
    def setUp(self):
        self.today = datetime.date.today()
        self.u = User.objects.create(username='u', tax_id='1', date_of_birth=self.today)

    def test_user_tax_id_type(self):
        """User should have Tax ID field as string."""
        self.assertIsInstance(self.u.tax_id, str)

    def test_user_tax_id_value(self):
        """User tax ID value must match."""
        self.assertEqual(self.u.tax_id, '1')

    def test_user_dob_type(self):
        """User date of birth should be a date."""
        self.assertIsInstance(self.u.date_of_birth, datetime.date)

    def test_user_dob_value(self):
        """User DOB should match."""
        self.assertEqual(self.u.date_of_birth, self.today)

    def test_str_method(self):
        """__str__() method should display username."""
        self.assertIn('u', str(self.u))


text:
@extends('app')

@section('content')
<div class="container">

    @include('common.errors')

    {!! Form::model($element, ['route' => ['elements.update', $element->id], 'method' => 'patch']) !!}

        @include('elements.fields')

    {!! Form::close() !!}
</div>
@endsection


text:
package com.amazonaws.services.identitymanagement.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.identitymanagement.AmazonIdentityManagement#createInstanceProfile(CreateInstanceProfileRequest) CreateInstanceProfile operation}.
 *

 * Creates a new instance profile. For information about instance
 * profiles, go to
 *  About Instance Profiles
 * .
 *

 *

 * For information about the number of instance profiles you can create,
 * see
 *  Limitations on IAM Entities
 * in the Using IAM guide.
 *

 *
 * @see com.amazonaws.services.identitymanagement.AmazonIdentityManagement#createInstanceProfile(CreateInstanceProfileRequest)
 */
public class CreateInstanceProfileRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     * The name of the instance profile to create.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     */
    private String instanceProfileName;

    /**
     * The path to the instance profile. For more information about paths,
     * see IAM
     * Identifiers in the Using IAM guide.
This parameter is
     * optional. If it is not included, it defaults to a slash (/).
     *

     * Constraints:

     * Length: 1 - 512

     * Pattern: (\u002F)|(\u002F[\u0021-\u007F]+\u002F)

     */
    private String path;

    /**
     * The name of the instance profile to create.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     *
     * @return The name of the instance profile to create.
     */
    public String getInstanceProfileName() {
        return instanceProfileName;
    }

    /**
     * The name of the instance profile to create.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     *
     * @param instanceProfileName The name of the instance profile to create.
     */
    public void setInstanceProfileName(String instanceProfileName) {
        this.instanceProfileName = instanceProfileName;
    }

    /**
     * The name of the instance profile to create.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 128

     * Pattern: [\w+=,.@-]+

     *
     * @param instanceProfileName The name of the instance profile to create.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateInstanceProfileRequest withInstanceProfileName(String instanceProfileName) {
        this.instanceProfileName = instanceProfileName;
        return this;
    }

    /**
     * The path to the instance profile. For more information about paths,
     * see IAM
     * Identifiers in the Using IAM guide.
This parameter is
     * optional. If it is not included, it defaults to a slash (/).
     *

     * Constraints:

     * Length: 1 - 512

     * Pattern: (\u002F)|(\u002F[\u0021-\u007F]+\u002F)

     *
     * @return The path to the instance profile. For more information about paths,
     *         see IAM
     *         Identifiers in the Using IAM guide.
This parameter is
     *         optional. If it is not included, it defaults to a slash (/).
     */
    public String getPath() {
        return path;
    }

    /**
     * The path to the instance profile. For more information about paths,
     * see IAM
     * Identifiers in the Using IAM guide.
This parameter is
     * optional. If it is not included, it defaults to a slash (/).
     *

     * Constraints:

     * Length: 1 - 512

     * Pattern: (\u002F)|(\u002F[\u0021-\u007F]+\u002F)

     *
     * @param path The path to the instance profile. For more information about paths,
     *         see IAM
     *         Identifiers in the Using IAM guide.
This parameter is
     *         optional. If it is not included, it defaults to a slash (/).
     */
    public void setPath(String path) {
        this.path = path;
    }

    /**
     * The path to the instance profile. For more information about paths,
     * see IAM
     * Identifiers in the Using IAM guide.
This parameter is
     * optional. If it is not included, it defaults to a slash (/).
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 512

     * Pattern: (\u002F)|(\u002F[\u0021-\u007F]+\u002F)

     *
     * @param path The path to the instance profile. For more information about paths,
     *         see IAM
     *         Identifiers in the Using IAM guide.
This parameter is
     *         optional. If it is not included, it defaults to a slash (/).
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateInstanceProfileRequest withPath(String path) {
        this.path = path;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInstanceProfileName() != null) sb.append("InstanceProfileName: " + getInstanceProfileName() + ",");
        if (getPath() != null) sb.append("Path: " + getPath() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInstanceProfileName() == null) ? 0 : getInstanceProfileName().hashCode());
        hashCode = prime * hashCode + ((getPath() == null) ? 0 : getPath().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof CreateInstanceProfileRequest == false) return false;
        CreateInstanceProfileRequest other = (CreateInstanceProfileRequest)obj;

        if (other.getInstanceProfileName() == null ^ this.getInstanceProfileName() == null) return false;
        if (other.getInstanceProfileName() != null && other.getInstanceProfileName().equals(this.getInstanceProfileName()) == false) return false;
        if (other.getPath() == null ^ this.getPath() == null) return false;
        if (other.getPath() != null && other.getPath().equals(this.getPath()) == false) return false;
        return true;
    }

    @Override
    public CreateInstanceProfileRequest clone() {

            return (CreateInstanceProfileRequest) super.clone();
    }

}


text:
package model

import (
	"context"

	"github.com/golang/protobuf/proto"

	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/crossconnect"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/networkservice"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/registry"
	"github.com/networkservicemesh/networkservicemesh/pkg/tools/spanhelper"
	"github.com/networkservicemesh/networkservicemesh/sdk/monitor/connectionmonitor"
)

// ClientConnectionState describes state of ClientConnection
type ClientConnectionState int8

const (
	// ClientConnectionReady means connection is in state 'ready'
	ClientConnectionReady ClientConnectionState = 0

	// ClientConnectionRequesting means connection - is trying to be established for first time.
	ClientConnectionRequesting ClientConnectionState = 1

	// ClientConnectionBroken means connection failed requesting
	ClientConnectionBroken ClientConnectionState = 2

	// ClientConnectionHealingBegin means connection - is trying to be updated or to be healed.
	ClientConnectionHealingBegin ClientConnectionState = 3

	// ClientConnectionHealing means connection - is in progress of being updated or to be healed.
	ClientConnectionHealing ClientConnectionState = 4

	// ClientConnectionClosing means connection is started closing process
	ClientConnectionClosing ClientConnectionState = 5
)

// ClientConnection struct in model that describes cross connect between NetworkServiceClient and NetworkServiceEndpoint
type ClientConnection struct {
	ConnectionID            string
	Request                 *networkservice.NetworkServiceRequest
	Xcon                    *crossconnect.CrossConnect
	RemoteNsm               *registry.NetworkServiceManager
	Endpoint                *registry.NSERegistration
	ForwarderRegisteredName string
	ConnectionState         ClientConnectionState
	ForwarderState          ForwarderState
	Span                    spanhelper.SpanHelper
	Monitor                 connectionmonitor.MonitorServer
}

// GetID returns id of clientConnection
func (cc *ClientConnection) GetID() string {
	if cc == nil {
		return ""
	}
	return cc.ConnectionID
}

// GetNetworkService returns name of networkService of clientConnection
func (cc *ClientConnection) GetNetworkService() string {
	if cc == nil {
		return ""
	}
	return cc.Endpoint.GetNetworkService().GetName()
}

// GetConnectionSource returns source part of connection
func (cc *ClientConnection) GetConnectionSource() *connection.Connection {
	if cc.Xcon == nil {
		return nil
	}
	return cc.Xcon.GetSource()
}

// GetConnectionDestination returns destination part of connection
func (cc *ClientConnection) GetConnectionDestination() *connection.Connection {
	return cc.Xcon.GetDestination()
}

// Clone return pointer to copy of ClientConnection
func (cc *ClientConnection) clone() cloneable {
	if cc == nil {
		return nil
	}

	var xcon *crossconnect.CrossConnect
	if cc.Xcon != nil {
		xcon = proto.Clone(cc.Xcon).(*crossconnect.CrossConnect)
	}

	var remoteNsm *registry.NetworkServiceManager
	if cc.RemoteNsm != nil {
		remoteNsm = proto.Clone(cc.RemoteNsm).(*registry.NetworkServiceManager)
	}

	var endpoint *registry.NSERegistration
	if cc.Endpoint != nil {
		endpoint = proto.Clone(cc.Endpoint).(*registry.NSERegistration)
	}

	var request *networkservice.NetworkServiceRequest
	if cc.Request != nil {
		request = cc.Request.Clone()
	}

	return &ClientConnection{
		ConnectionID:            cc.ConnectionID,
		Xcon:                    xcon,
		RemoteNsm:               remoteNsm,
		Endpoint:                endpoint,
		ForwarderRegisteredName: cc.ForwarderRegisteredName,
		Request:                 request,
		ConnectionState:         cc.ConnectionState,
		ForwarderState:          cc.ForwarderState,
		Span:                    cc.Span,
		Monitor:                 cc.Monitor,
	}
}

type clientConnectionDomain struct {
	baseDomain
}

func newClientConnectionDomain() clientConnectionDomain {
	return clientConnectionDomain{
		baseDomain: newBase(),
	}
}

func (d *clientConnectionDomain) AddClientConnection(ctx context.Context, cc *ClientConnection) {
	d.store(ctx, cc.ConnectionID, cc)
}

func (d *clientConnectionDomain) GetClientConnection(id string) *ClientConnection {
	v, _ := d.load(id)
	if v != nil {
		return v.(*ClientConnection)
	}
	return nil
}

func (d *clientConnectionDomain) GetAllClientConnections() []*ClientConnection {
	var rv []*ClientConnection
	d.kvRange(func(_ string, value interface{}) bool {
		rv = append(rv, value.(*ClientConnection))
		return true
	})
	return rv
}

func (d *clientConnectionDomain) DeleteClientConnection(ctx context.Context, connectionID string) {
	d.delete(ctx, connectionID)
}

func (d *clientConnectionDomain) UpdateClientConnection(ctx context.Context, cc *ClientConnection) {
	d.store(ctx, cc.ConnectionID, cc)
}

func (d *clientConnectionDomain) ApplyClientConnectionChanges(ctx context.Context, id string, f func(*ClientConnection)) *ClientConnection {
	upd := d.applyChanges(ctx, id, func(v interface{}) { f(v.(*ClientConnection)) })
	if upd != nil {
		return upd.(*ClientConnection)
	}
	return nil
}

func (d *clientConnectionDomain) SetClientConnectionModificationHandler(h *ModificationHandler) func() {
	return d.addHandler(h)
}


text:
package com.intellij.history.core.storage;

import com.intellij.history.core.InMemoryStorage;
import com.intellij.history.core.LocalVcsTestCase;
import org.junit.Test;

public class StoredContentTest extends LocalVcsTestCase {
  @Test
  public void testEqualityAndHash() {
    assertTrue(new StoredContent(null, 1).equals(new StoredContent(null, 1)));

    assertFalse(new StoredContent(null, 1).equals(null));
    assertFalse(new StoredContent(null, 1).equals(new StoredContent(null, 2)));

    assertTrue(new StoredContent(null, 1).hashCode() == new StoredContent(null, 1).hashCode());
    assertTrue(new StoredContent(null, 1).hashCode() != new StoredContent(null, 2).hashCode());
  }

  @Test
  public void testUnavailableIfExceptionOccurs() {
    Storage goodStorage = new InMemoryStorage() {
      @Override
      protected byte[] loadContentData(final int id) throws BrokenStorageException {
        return new byte[0];
      }
    };

    Storage brokenStorage = new InMemoryStorage() {
      @Override
      protected byte[] loadContentData(int id) throws BrokenStorageException {
        throw new BrokenStorageException();
      }
    };

    assertTrue(new StoredContent(goodStorage, 0).isAvailable());
    assertFalse(new StoredContent(brokenStorage, 0).isAvailable());
  }
}


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.enricogiurin.sushibar</groupId>
    <artifactId>sushi-bar-BE</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>11</java.version>
    </properties>
    <!-- there is a dependency management section in the parent pon
    that's why some of the dependencies have no version -->

    <scm>
        <connection>scm:git:https://github.com/egch/sushi-bar-BE.git</connection>
        <developerConnection>scm:git:https://github.com/egch/sushi-bar-BE.git</developerConnection>
        <url>scm:git:https://github.com/egch/sushi-bar-BE</url>
    </scm>

    <dependencies>
        <!-- spring boot dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- spring boot dependencies - test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- spring (not boot) dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
        </dependency>

        <!-- Other dependencies -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.3</version>
        </dependency>

        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!-- test dependencies -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.12.1</version>
            <scope>test</scope>
        </dependency>
        <!-- fake smpt server for email -->
        <!-- do not bump up greenmail, tests are failing -->
        <dependency>
            <groupId>com.icegreen</groupId>
            <artifactId>greenmail</artifactId>
            <version>1.5.5</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php

namespace Urodoz\Bundle\CacheBundle\Tests\Event\Mocks;

use Urodoz\Bundle\CacheBundle\Event\CacheHitEvent;
use Urodoz\Bundle\CacheBundle\Event\MissedCacheHitEvent;

/**
 * Class event listener for testing purposes
 *
 * @author Albert Lacarta <urodoz@gmail.com>
 */
class CacheHitEventListener
{

    /**
     * @var array
     */
    private $events=array();

    /**
     * Adds the event to a collection of events
     *
     * @param CacheHitEvent $event
     */
    public function onCacheHitDispatched(CacheHitEvent $event)
    {
        $this->events[] = $event;
    }

    /**
     * Adds the event to a collection of events
     *
     * @param MissedCacheHitEvent $event
     */
    public function onCacheMissHitDispatched(MissedCacheHitEvent $event)
    {
        $this->events[] = $event;
    }

    /**
     * Clear the events array
     */
    public function clear()
    {
        $this->events = array();
    }

    /**
     * Return all events stored on the listener
     *
     * @return array
     */
    public function getEvents()
    {
        return $this->events;
    }

}


text:
BEGIN_INANITY

bigsize_t InputStream::Skip(bigsize_t size)
{
	BEGIN_TRY();

	char buffer[0x1000];
	bigsize_t skipped = 0;
	while(size)
	{
		size_t read = Read(buffer, (size_t)std::min<bigsize_t>(size, sizeof(buffer)));
		if(!read)
			break;
		size -= read;
		skipped += read;
	}
	return skipped;

	END_TRY("Can't skip data in input stream");
}

ptr<File> InputStream::Read(size_t size)
{
	BEGIN_TRY();

	// read data
	ptr<File> file = NEW(MemoryFile(size));
	size_t read = Read(file->GetData(), size);

	// if read less data than requested, slice the file
	if(read < size)
		file = file->Slice(0, read);

	return file;

	END_TRY("Can't read data as file from input stream");
}

bool InputStream::IsAtEnd() const
{
	return false;
}

END_INANITY


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Previous/Next example</title>

'Previous/Next' example

  <button id="prev">Previous</button>
  <button id="next">Next</button>

  Page:  /

  <canvas id="the-canvas" style="border: 1px solid black; direction: ltr;"></canvas>


text: <title>Simple template</title>