text:
package net.morimekta.providence.generator.format.java.utils;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import net.morimekta.providence.descriptor.PDeclaredDescriptor;
import net.morimekta.providence.descriptor.PDescriptor;
import net.morimekta.providence.descriptor.PField;
import net.morimekta.providence.descriptor.PList;
import net.morimekta.providence.descriptor.PMap;
import net.morimekta.providence.descriptor.PPrimitive;
import net.morimekta.providence.descriptor.PService;
import net.morimekta.providence.descriptor.PSet;
import net.morimekta.providence.generator.GeneratorException;
import net.morimekta.providence.reflect.contained.CField;
import net.morimekta.providence.reflect.contained.CProgram;
import net.morimekta.providence.reflect.util.ProgramTypeRegistry;
import net.morimekta.providence.util.ThriftContainer;
import net.morimekta.util.Binary;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import static net.morimekta.providence.generator.format.java.utils.JUtils.camelCase;

/**
 *
 */
public class JHelper {
    public static final String packageSeparator = ".";

    private final ProgramTypeRegistry mRegistry;

    public JHelper(ProgramTypeRegistry registry) {
        mRegistry = registry;
    }

    public ProgramTypeRegistry getRegistry() {
        return mRegistry;
    }

    public String getJavaPackage(PDeclaredDescriptor<?> type) throws GeneratorException {
        String packageContext = type.getProgramName();
        CProgram document = mRegistry.getProgramForName(packageContext);
        return JUtils.getJavaPackage(document);
    }

    public String getJavaPackage(PService type) throws GeneratorException {
        String packageContext = type.getProgramName();
        CProgram document = mRegistry.getProgramForName(packageContext);
        return JUtils.getJavaPackage(document);
    }

    public String getJavaPackage(CProgram document) throws GeneratorException {
        return JUtils.getJavaPackage(document);
    }

    public String getInstanceClassName(CField field) throws GeneratorException {
        switch (field.getType()) {
            case VOID:
                return Void.class.getSimpleName();
            case BOOL:
                return Boolean.class.getSimpleName();
            case BYTE:
                return Byte.class.getSimpleName();
            case I16:
                return Short.class.getSimpleName();
            case I32:
                return Integer.class.getSimpleName();
            case I64:
                return Long.class.getSimpleName();
            case DOUBLE:
                return Double.class.getSimpleName();
            case STRING:
                return String.class.getSimpleName();
            case BINARY:
                return Binary.class.getName();
            case MAP: {
                ThriftContainer ct = JAnnotation.containerType(field);
                switch (ct) {
                    case DEFAULT:
                        return ImmutableMap.class.getName();
                    case SORTED:
                        return ImmutableSortedMap.class.getName();
                    case ORDERED:
                        return LinkedHashMap.class.getName();
                }
            }
            case SET:{
                ThriftContainer ct = JAnnotation.containerType(field);
                switch (ct) {
                    case DEFAULT:
                        return ImmutableSet.class.getName();
                    case SORTED:
                        return ImmutableSortedSet.class.getName();
                    case ORDERED:
                        return LinkedHashSet.class.getName();
                }
            }
            case LIST:
                return ArrayList.class.getName();
            case ENUM:
            case MESSAGE:
                PDeclaredDescriptor<?> dt = (PDeclaredDescriptor<?>) field.getDescriptor();
                return getJavaPackage(dt) + packageSeparator + JUtils.getClassName(dt);
        }
        throw new IllegalArgumentException("Unhandled type group" + field.getType());
    }

    public String getConstantsClassName(CProgram document) {
        return camelCase(document.getProgramName()) + "_Constants";
    }

    public String getHazelcastFactoryClassName(CProgram document) {
        return camelCase(document.getProgramName())  + "_Factory";
    }

    public String getHazelcastOptionalName(JMessage<?> message) {
        return camelCase("__hzOptionalsForClass", message.descriptor().getName());
    }

    public String getValueType(PDescriptor type) throws GeneratorException {
        switch (type.getType()) {
            case VOID:
                return Void.TYPE.getSimpleName();
            case BOOL:
                return Boolean.TYPE.getSimpleName();
            case BYTE:
                return Byte.TYPE.getSimpleName();
            case I16:
                return Short.TYPE.getSimpleName();
            case I32:
                return Integer.TYPE.getSimpleName();
            case I64:
                return Long.TYPE.getSimpleName();
            case DOUBLE:
                return Double.TYPE.getSimpleName();
            case STRING:
                return String.class.getSimpleName();
            case BINARY:
                return Binary.class.getName();
            case MAP:
                PMap<?, ?> mType = (PMap<?, ?>) type;
                return String.format(Locale.US, "%s<%s,%s>",
                                     Map.class.getName(),
                                     getFieldType(mType.keyDescriptor()),
                                     getFieldType(mType.itemDescriptor()));
            case SET:
                PSet<?> sType = (PSet<?>) type;
                return String.format(Locale.US, "%s<%s>",
                                     Set.class.getName(),
                                     getFieldType(sType.itemDescriptor()));
            case LIST:
                PList<?> lType = (PList<?>) type;
                return String.format(Locale.US, "%s<%s>",
                                     List.class.getName(),
                                     getFieldType(lType.itemDescriptor()));
            case ENUM:
            case MESSAGE:
                PDeclaredDescriptor<?> dt = (PDeclaredDescriptor<?>) type;
                return getJavaPackage(dt) + "." + JUtils.getClassName((PDeclaredDescriptor<?>) type);
        }
        throw new IllegalArgumentException("Unhandled type group" + type.getType());
    }

    public String getFieldType(PDescriptor type) throws GeneratorException {
        switch (type.getType()) {
            case BOOL:
                return Boolean.class.getSimpleName();
            case BYTE:
                return Byte.class.getSimpleName();
            case I16:
                return Short.class.getSimpleName();
            case I32:
                return Integer.class.getSimpleName();
            case I64:
                return Long.class.getSimpleName();
            case DOUBLE:
                return Double.class.getSimpleName();
            case STRING:
                return String.class.getSimpleName();
            case BINARY:
                return Binary.class.getName();
            case MAP:
                PMap<?, ?> mType = (PMap<?, ?>) type;
                return String.format(Locale.US, "%s<%s,%s>",
                                     Map.class.getName(),
                                     getFieldType(mType.keyDescriptor()),
                                     getFieldType(mType.itemDescriptor()));
            case SET:
                PSet<?> sType = (PSet<?>) type;
                return String.format(Locale.US, "%s<%s>", Set.class.getName(), getFieldType(sType.itemDescriptor()));
            case LIST:
                PList<?> lType = (PList<?>) type;
                return String.format(Locale.US, "%s<%s>", List.class.getName(), getFieldType(lType.itemDescriptor()));
            case ENUM:
            case MESSAGE:
                PDeclaredDescriptor<?> dt = (PDeclaredDescriptor<?>) type;
                return getJavaPackage(dt) + packageSeparator + JUtils.getClassName(dt);
        }
        throw new IllegalArgumentException("Unhandled field type group " + type.getType());
    }

    public Object getDefaultValue(PField field) {
        if (field.hasDefaultValue()) {
            return field.getDefaultValue();
        }
        return field.getDescriptor().getDefaultValue();
    }

    public String getProviderName(PDescriptor type) throws GeneratorException {
        switch (type.getType()) {
            case ENUM:
            case MESSAGE:
                return String.format(Locale.US, "%s.provider()", getFieldType(type));
            case LIST:
                PList<?> lType = (PList<?>) type;
                return String.format(Locale.US, "%s.provider(%s)",
                                     PList.class.getName(),
                                     getProviderName(lType.itemDescriptor()));
            case SET:
                PSet<?> sType = (PSet<?>) type;
                return String.format(Locale.US, "%s.provider(%s)",
                                     PSet.class.getName(),
                                     getProviderName(sType.itemDescriptor()));
            case MAP:
                PMap<?, ?> mType = (PMap<?, ?>) type;
                return String.format(Locale.US, "%s.provider(%s,%s)",
                                     PMap.class.getName(),
                                     getProviderName(mType.keyDescriptor()),
                                     getProviderName(mType.itemDescriptor()));
            default:
                if (!(type instanceof PPrimitive)) {
                    throw new IllegalArgumentException("Unhandled type group " + type.getType());
                }
                return String.format(Locale.US, "%s.%s.provider()",
                                     PPrimitive.class.getName(),
                                     type.getName().toUpperCase(Locale.US));
        }
    }
}


text:
module KoSpec
  module Matchers
    def error(expected)
      Error.new(expected)
    end

    alias_method :exception, :error

    class Error < Matcher
      class PositiveHandler < Handler
        def matches?
          @matcher.actual.call
        rescue Exception => @actual_error
          @matcher.expected.class === @actual_error &&
          @matcher.expected.message == @actual_error.message
        end

        def message
          "raised #{@actual_error.inspect}"
        end

        def failure_message
          "expected #{@matcher.expected.inspect}, but raised #{@actual_error.inspect}"
        end
      end

      class NegativeHandler < PositiveHandler
        def matches?
          not super
        end

        def message
          "did not raise #{@matcher.expected.inspect}"
        end

        def failure_message
          "expected to not raise #{@actual_error.inspect}"
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
typedef NS_ENUM(NSUInteger, SBProgressBarOptions) {
    SBProgressBarOptionsLeftToRight = 1 << 0,
    SBProgressBarOptionsRightToLeft = 1 << 1,

    SBProgressBarOptionsHorizontal = 1 << 2,
    SBProgressBarOptionsVertical = 1 << 3
};

@class SBProgressBar;

@interface SBProgressBar : UIView

extern SBProgressBarOptions SBProgressBarOptionsFromOrientation(UIInterfaceOrientation orietnation);

@property (nonatomic, assign) CGFloat value;
@property (nonatomic, readonly) CGFloat maxValue;
@property (nonatomic, readonly) CGFloat minValue;

@property (nonatomic, readonly) NSMutableSet *stopValues;

@property (nonatomic, assign) SBProgressBarOptions options;

- (id) initWithMinValue:(CGFloat)minValue maxValue:(CGFloat)maxValue;

//Adds the current @value attribute to @stopValues
- (void) addCurrentValueToStopValues;

- (void) addStopValuesObject:(NSNumber *)value;
- (void) removeStopValuesObject:(NSNumber *)value;

@end


text:
#include "win_etpan.h"

void *mmap (void *__addr, size_t __len, int __prot,
				   int __flags, int __fd, size_t __offset) {
#ifdef _DEBUG
	fprintf( stderr, "mmap inimplemented\n");
#endif
   return MAP_FAILED;
}

int munmap (void *__addr, size_t __len) {
#ifdef _DEBUG
	fprintf( stderr, "mmap inimplemented\n");
#endif
	return -1;
}

int msync (void *__addr, size_t __len, int __flags) {
#ifdef _DEBUG
	fprintf( stderr, "mmap inimplemented\n");
#endif
	return -1;
}


text:
package com.easyooo.framework.sharding;

/**
 * 路由上下文绑定在当前线程变量
 *
 * @author Killer
 */
public final class RoutingContextHolder {

	private static final ThreadLocal<RoutingContext> contextHolder =
			new ThreadLocal<RoutingContext>();

    public static void setRoutingContext(RoutingContext context) {
        contextHolder.set(context);
    }

    public static RoutingContext getRoutingContext() {
        return contextHolder.get();
    }

    public static void clearRoutingContext() {
        contextHolder.remove();
    }
}


text:
% matWrapper.m
%
%	* Created by Yair Movshovitz-Attias on 8/22/13.
%	* yair@cs.cmu.edu (http://www.cs.cmu.edu/~ymovshov/)
%	* Copyright 2013 Carnegie Mellon University. All rights reserved.
% 	* Notes : This class wraps a full (single) matrix so that it can be passed by reference to functions.

classdef matWrapper < handle
   properties
      Data
   end
   methods
      function obj = matWrapper(shape)
         if nargin > 0
            obj.Data = zeros(shape);
         end
      end
   end
end


text:
'use strict';

var path = require ('path');
module.exports = path.resolve (__dirname, '../../app');


text:
package com.dgrlucky.extend.ui.activity;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.dgrlucky.extend.R;
import com.dgrlucky.extend.base.BaseActivity;
import com.dgrlucky.extend.ui.mvp.model.entity.MeizhiList;
import com.dgrlucky.extend.ui.mvp.presenter.MainIPresenter;
import com.dgrlucky.extend.ui.mvp.view.IMainView;
import com.dgrlucky.extend.util.ExitUtil;
import com.library.view.loading.ProgressView;

import javax.inject.Inject;

import butterknife.BindView;
import me.fangx.haorefresh.HaoRecyclerView;
import me.fangx.haorefresh.LoadMoreListener;

public class OneActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        IMainView, LoadMoreListener {

    @BindView(R.id.recycler_list)
    HaoRecyclerView mRecyclerList;
    @BindView(R.id.swipeRefresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @Inject
    MainIPresenter mMainPresenter;
    private long page = 1;

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected View initView(Bundle savedInstanceState) {
        return null;
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void onSaveState(Bundle savedInstanceState) {
        //mMainPresenter.attachView(this);
        //mMainPresenter.setDataLayer(getDataLayer());
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        RecyclerView.LayoutManager manager = new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL);
        mRecyclerList.setLayoutManager(manager);
        mRecyclerList.setLoadMoreListener(this);
        ProgressView footLoading = new ProgressView(this);
        footLoading.setIndicatorId(ProgressView.CubeTransition);
        footLoading.setIndicatorColor(getResources().getColor(R.color.colorPrimary));
        mRecyclerList.setFootLoadingView(footLoading);
        TextView textView = new TextView(this);
        textView.setText("宝宝心里苦...");
        mRecyclerList.setFootEndView(textView);
        //mMainPresenter.dataLoading(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        //mMainPresenter.onRefresh(page);
    }

    @Override
    public void onLoadMore() {
        page++;
        //mMainPresenter.onLoadMore(page);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void dataLoading(MeizhiList meizhis) {

    }

    @Override
    public void showError(String msg, View.OnClickListener onClickListener) {

    }

    @Override
    public void showEmpty(String msg, View.OnClickListener onClickListener, int imageId) {

    }

    @Override
    public void onBackPressed() {
        if (!ExitUtil.isClickAgain()) {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.settings, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
<?php

namespace Drupal\features_ui\Form;

use Drupal\features\FeaturesManagerInterface;
use Drupal\features\FeaturesAssignerInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configures the selected configuration assignment method for this site.
 */
abstract class AssignmentFormBase extends FormBase {

  /**
   * The features manager.
   *
   * @var \Drupal\features\FeaturesManagerInterface
   */
  protected $featuresManager;

  /**
   * The package assigner.
   *
   * @var \Drupal\features\FeaturesAssignerInterface
   */
  protected $assigner;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The current bundle.
   *
   * @var \Drupal\features\FeaturesBundleInterface
   */
  protected $currentBundle;

  /**
   * Constructs a AssignmentBaseForm object.
   *
   * @param \Drupal\features\FeaturesManagerInterface $features_manager
   *   The features manager.
   * @param \Drupal\features\FeaturesAssignerInterface $assigner
   *   The assigner.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(FeaturesManagerInterface $features_manager, FeaturesAssignerInterface $assigner, EntityTypeManagerInterface $entity_type_manager) {
    $this->featuresManager = $features_manager;
    $this->assigner = $assigner;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('features.manager'),
      $container->get('features_assigner'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * Adds configuration types checkboxes.
   */
  protected function setConfigTypeSelect(&$form, $defaults, $type, $bundles_only = FALSE, $description = '') {
    $options = $this->featuresManager->listConfigTypes($bundles_only);

    if (!isset($form['types'])) {
      $form['types'] = array(
        '#type' => 'container',
        '#tree' => TRUE,
      );
    }

    $form['types']['config'] = array(
      '#type' => 'checkboxes',
      '#title' => $this->t('Configuration types'),
      '#description' => !empty($description) ? $description : $this->t('Select types of configuration that should be considered @type types.', array('@type' => $type)),
      '#options' => $options,
      '#default_value' => $defaults,
    );
  }

  /**
   * Adds content entity types checkboxes.
   */
  protected function setContentTypeSelect(&$form, $defaults, $type, $exclude_has_config_bundles = TRUE) {
    $entity_types = $this->entityTypeManager->getDefinitions();

    $has_config_bundle = array();
    foreach ($entity_types as $definition) {
      if ($entity_type_id = $definition->getBundleOf()) {
        $has_config_bundle[] = $entity_type_id;
      }
    }
    $options = array();

    foreach ($entity_types as $entity_type_id => $entity_type) {
      if (!$entity_type instanceof ContentEntityTypeInterface) {
        continue;
      }
      if ($exclude_has_config_bundles && in_array($entity_type_id, $has_config_bundle)) {
        continue;
      }
      $options[$entity_type_id] = $entity_type->getLabel() ?: $entity_type_id;
    }

    // Sort the entity types by label.
    uasort($options, 'strnatcasecmp');

    if (!isset($form['types'])) {
      $form['types'] = array(
        '#type' => 'container',
        '#tree' => TRUE,
      );
    }

    $form['types']['content'] = array(
      '#type' => 'checkboxes',
      '#title' => $this->t('Content entity types'),
      '#description' => $this->t('Select content entity types that should be considered @type types.', array('@type' => $type)),
      '#options' => $options,
      '#default_value' => $defaults,
    );
  }

  /**
   * Adds a "Save settings" submit action.
   */
  protected function setActions(&$form, $method_id = NULL) {
    $assignment_info = $this->assigner->getAssignmentMethods();
    if (isset($method_id) && isset($assignment_info[$method_id])) {
      $method = $assignment_info[$method_id];
      $form['help_text'] = array(
        '#markup' => $method['description'],
        '#prefix' => '
',
        '#suffix' => '
',
        '#weight' => -99,
      );
    }

    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this->t('Save settings'),
    );
    $form['#attributes']['class'][] = 'features-assignment-settings-form';
    $form['#attached'] = array(
      'library' => array(
        'features_ui/drupal.features_ui.admin',
    ));
  }

  /**
   * Redirects back to the Bundle config form.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  protected function setRedirect(FormStateInterface $form_state) {
    $form_state->setRedirect('features.assignment', array('bundle_name' => $this->currentBundle->getMachineName()));
  }

}


text:
Tutorial
========

Basic Use
---------

Ini Handler is designed to be simple and lightweight to use. First off you will
need to import the Ini class and create a new instance::

  from ini_handler.vbini import Ini

  ini_file = Ini()

The Ini class has two keyword arguments, with defaults, in its constructor::

  filename='settings'
  directory=None

The directory kwarg will be set to different values depending on your OS: My Documents
for Windows machines, and the home directory for Linux. To use, you can simply
do the following:

Create and modify settings::

  ini_file['NewSetting'] = 'A new setting'
  ini_file['Bool'] = True
  ini_file['Integer'] = 1993

Get settings::

  ini_file['NewSetting']

The Ini class defines the __iter__ magic methed, so you can very easily iterate
over the settings. For each loop a tuple is returned with the setting key in
index 0 and the value in index 1::

  ini_file['Setting1'] = 'Value 1'
  ini_file['Setting2'] = 'Value 2'
  for setting in ini_file:
    print(setting)

  ('Setting1', 'Value 1')
  ('Setting2', 'Value 2')

Delete settings::

  del ini_file['OldSetting']

Get the number of settings::

  len(ini_file)

To create the .ini file itself all you have to call is::

  ini_file.save()

To read the settings back in call::

  ini_file.load()

Sections
--------

Settings can also be grouped into different sections. This is as simple as creating
or modifying a setting by passing a tuple, list, or set with element one as the
section name and element two as the actual value::

  ini_file['SettingKey'] = ('Section', 'Value')
  ini_file['Another'] = ['Section2', True]
  ini_file['Final'] = {'New Section', 2000}

And that's it! The Ini class behaves exactly as it did without grouping your
settings into different sections. Though if you ever want to get a section for a
particular settings, call::

  ini_file.get_setting_section('SettingKey')

And if you want to set a section::

  ini_file.set_setting_section('SettingKey', 'SectionName')


text:
<component name="ProjectDictionaryState">
  <dictionary name="Wiki">
    <words>
      <w>mixpush</w>
    </words>
  </dictionary>
</component>


text:
package org.arquillian.cube.docker.impl.await;

import java.util.ArrayList;
import java.util.List;
import org.arquillian.cube.docker.impl.client.config.Await;
import org.arquillian.cube.docker.impl.util.Ping;
import org.arquillian.cube.spi.Cube;

public class StaticAwaitStrategy extends SleepingAwaitStrategyBase {

    public static final String TAG = "static";

    private static final int DEFAULT_POLL_ITERATIONS = 10;

    private int pollIterations = DEFAULT_POLL_ITERATIONS;

    private String ip;
    private List<Integer> ports = new ArrayList<Integer>();

    public StaticAwaitStrategy(Cube<?> cube, Await params) {
        super(params.getSleepPollingTime());

        this.ip = params.getIp();
        this.ports.addAll(params.getPorts());

        if (params.getIterations() != null) {
            this.pollIterations = params.getIterations();
        }
    }

    @Override
    public boolean await() {

        for (Integer port : this.ports) {
            if (!Ping.ping(this.ip, port, this.pollIterations, this.getSleepTime(), this.getTimeUnit())) {
                return false;
            }
        }

        return true;
    }

    public String getIp() {
        return ip;
    }

    public List<Integer> getPorts() {
        return ports;
    }

    public int getPollIterations() {
        return pollIterations;
    }
}


text:
cryptophoto-node-demo
=====================

Securing an Express application using the [CryptoPhoto](http://cryptophoto.com/) [API](https://cryptophoto.com/admin/api).


text:
<?php

class Preferences extends XMLModel
{

}


text:
using IdentityServer3.Core.Logging;
using IdentityServer3.Core.Models;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace IdentityServer3.Core.Results
{
    internal class TokenResult : IHttpActionResult
    {
        private readonly static ILog Logger = LogProvider.GetCurrentClassLogger();
        private readonly static JsonMediaTypeFormatter Formatter = new JsonMediaTypeFormatter
        {
            SerializerSettings = { DefaultValueHandling = DefaultValueHandling.Ignore }
        };

        private readonly TokenResponse _response;

        public TokenResult(TokenResponse response)
        {
            _response = response;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute());
        }

        private HttpResponseMessage Execute()
        {
            var dto = new TokenResponseDto
            {
                id_token = _response.IdentityToken,
                access_token = _response.AccessToken,
                refresh_token = _response.RefreshToken,
                expires_in = _response.AccessTokenLifetime,
                token_type = Constants.TokenTypes.Bearer
            };

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ObjectContent<TokenResponseDto>(dto, Formatter)
            };

            Logger.Info("Returning token response.");
            return response;
        }

        internal class TokenResponseDto
        {
            public string id_token { get; set; }
            public string access_token { get; set; }
            public int expires_in { get; set; }
            public string token_type { get; set; }
            public string refresh_token { get; set; }
        }
    }
}


text:
"""logging Formatters"""

__author__    = 'Philip Jenvey <pjenvey@groovie.org>, Stojan Jovic <stojan.jovic@dmsgroup.rs>'
__contact__   = 'pjenvey@groovie.org, stojan.jovic@dmsgroup.rs'
__date__      = '19 August 2007'
__copyright__ = 'Python Software Foundation'

# Modified: 29 January 2009
import cgi
import logging

__all__ = ['XMLLayout']

class XMLLayout(logging.Formatter):
    """Formats log Records as XML according to the `log4j XMLLayout
    <http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/
    XMLLayout.html>_`
    """

    def __init__(self, properties=None):
        logging.Formatter.__init__(self)

        self.properties = properties

    def format(self, record):
        """Format the log record as XMLLayout XML"""
        levelname = record.levelname
        if levelname == 'VERBOSE':
            levelname = 'TRACE'
        elif levelname == 'WARNING':
            levelname = 'WARN'
        elif levelname == 'CRITICAL':
            levelname = 'FATAL'
        event = dict(name=cgi.escape(record.name),
                     threadName=cgi.escape(record.threadName),
                     levelname=cgi.escape(levelname),
                     created=int(record.created * 1000))

        event['message'] = LOG4J_MESSAGE % escape_cdata(record.getMessage())

        # FIXME: Support an NDC somehow
        event['ndc'] = LOG4J_NDC % ''
        #ndc = self.get_ndc(record)
        #if ndc:
        #    event['ndc'] = LOG4J_NDC % escape_cdata(ndc)

        event['throwable'] = ''
        if record.exc_info:
            if not record.exc_text:
                record.exc_text = self.formatException(record.exc_info)
            event['throwable'] = LOG4J_THROWABLE % escape_cdata(record.exc_text)

        location_info = dict(pathname=cgi.escape(record.pathname),
                             lineno=record.lineno,
                             module=cgi.escape(record.module), funcName='')
        if hasattr(record, 'funcName'):
            # >= Python 2.5
            location_info['funcName'] = cgi.escape(record.funcName)
        event['locationInfo'] = LOG4J_LOCATIONINFO % location_info

        if self.properties is not None:
            domain_info = dict(hostname=self.properties.hostname,
                               application=self.properties.application)
            event['domainInfo'] = LOG4J_DOMAININFO % domain_info
        else:
            event['domainInfo'] = ''

        log4j_log_message = LOG4J_EVENT % event
        return log4j_log_message

def escape_cdata(cdata):
    return cdata.replace(']]>', ']]>]]><![CDATA[')

# General logging information
LOG4J_EVENT = """\
<log4j:event logger="%(name)s" timestamp="%(created)i" level="%(levelname)s" thread="%(threadName)s">
%(message)s%(ndc)s%(throwable)s%(locationInfo)s%(domainInfo)s</log4j:event>
"""

# The actual log message
LOG4J_MESSAGE = """\
    <log4j:message><![CDATA[%s]]></log4j:message>
"""

# log4j's 'Nested Diagnostic Context': additional, customizable information
# included with the log record
LOG4J_NDC = """\
    <log4j:ndc><![CDATA[%s]]></log4j:ndc>
"""

# Exception information, if exc_info was included with the record
LOG4J_THROWABLE = """\
    <log4j:throwable><![CDATA[%s]]></log4j:throwable>
"""

# Traceback information
LOG4J_LOCATIONINFO = """\
    <log4j:locationInfo class="%(module)s" method="%(funcName)s" file="%(pathname)s" line="%(lineno)d"/>
"""

# Domain information
LOG4J_DOMAININFO = """\
    <log4j:properties>
        <log4j:data name="hostname" value="%(hostname)s"/>
        <log4j:data name="application" value="%(application)s"/>
    </log4j:properties>
"""


text:
package com.lanyuan.service;

import java.util.List;

import com.lanyuan.entity.ServerInfo;
import com.lanyuan.util.PageView;

public interface ServerInfoService {
	public PageView query(PageView pageView,ServerInfo serverInfo);

	public List<ServerInfo> queryAll(ServerInfo serverInfo);

	public void add(ServerInfo serverInfo);

	public void delete(String id);

	public ServerInfo getById(String id);

	public void modify(ServerInfo serverInfo);
}


text:
AsakusaSatellite::Application.routes.draw do
  post 'device_setting/update'
end


text:
// This script displays an intro message for the setup script
/* eslint-disable no-console */
console.log('===========================');
console.log('=  HCJ Starter Setup  =');
console.log('===========================\n');
console.log('Installing dependencies. Please wait...');


text:
package net.codog.domain;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* @author 王文涵
* @date 2016年10月20日
* <p>Description:permission的实体类 </p>
 */
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Setter
@Getter
public class Permission {
    private Integer permissionId;

    private String permissionName;

    private String permissionUrl;
}


text:
<?php

namespace Hal\Violation\Package;

use Hal\Metric\Metric;
use Hal\Metric\PackageMetric;
use Hal\Violation\Violation;

class StableDependenciesPrinciple implements Violation
{
    /** @var PackageMetric|null */
    private $metric;

    /** @var array */
    private $violatingInstabilities = [];

    public function getName()
    {
        return 'Stable Dependencies Principle';
    }

    public function apply(Metric $metric)
    {
        if (! $metric instanceof PackageMetric) {
            return;
        }
        $instability = $metric->getInstability();
        $violatingInstabilities = array_filter(
            $metric->getDependentInstabilities(),
            function ($otherInstability) use ($instability) {
                return $otherInstability >= $instability;
            }
        );
        if (count($violatingInstabilities) > 0) {
            $this->violatingInstabilities = $violatingInstabilities;
            $this->metric = $metric;
            $metric->get('violations')->add($this);
        }
    }

    public function getLevel()
    {
        return Violation::WARNING;
    }

    public function getDescription()
    {
        $count = count($this->violatingInstabilities);
        $thisInstability = round($this->metric->getInstability(), 3);
        $packages = implode("\n* ", array_map(function ($name, $instability) {
            $name = $name === '\\' ? 'global' : substr($name, 0, -1);
            $instability = round($instability, 3);
            return "$name ($instability)";
        }, array_keys($this->violatingInstabilities), $this->violatingInstabilities));
        return <<<EOT
Packages should depend in the direction of stability.

This package is more stable ({$thisInstability}) than {$count} package(s) that it depends on.
The packages that are more stable are

* {$packages}
EOT;
    }
}


text:
SET_DEFAULT_DEBUG_CHANNEL(POLL);

int poll(struct pollfd *pollSet, int pollCount, int pollTimeout)
{
    struct timeval tv;
    struct timeval *tvp;
    fd_set readFDs, writeFDs, exceptFDs;
    fd_set *readp, *writep, *exceptp;
    struct pollfd *pollEnd, *p;
    int selected;
    int result;
    int maxFD;

    if (!pollSet) {
        pollEnd = NULL;
        readp = NULL;
        writep = NULL;
        exceptp = NULL;
        maxFD = 0;
    }
    else {
        pollEnd = pollSet + pollCount;
        readp = &readFDs;
        writep = &writeFDs;
        exceptp = &exceptFDs;

        FD_ZERO(readp);
        FD_ZERO(writep);
        FD_ZERO(exceptp);

        // Find the biggest fd in the poll set
        maxFD = 0;
        for (p = pollSet; p < pollEnd; p++) {
            if (p->fd > maxFD) maxFD = p->fd;
        }

        if (maxFD >= FD_SETSIZE) {
            // At least one fd is too big
            errno = EINVAL;
            return -1;
        }

        // Transcribe flags from the poll set to the fd sets
        for (p = pollSet; p < pollEnd; p++) {
            if (p->fd < 0) {
                // Negative fd checks nothing and always reports zero
            } else {
                if (p->events & POLLIN)  FD_SET(p->fd, readp);
                if (p->events & POLLOUT) FD_SET(p->fd, writep);
                if (p->events != 0)      FD_SET(p->fd, exceptp);
                // POLLERR is never set coming in; poll() always reports errors.
                // But don't report if we're not listening to anything at all.
            }
        }
    }

    // poll timeout is in milliseconds. Convert to struct timeval.
    // poll timeout == -1 : wait forever : select timeout of NULL
    // poll timeout == 0  : return immediately : select timeout of zero
    if (pollTimeout >= 0) {
        tv.tv_sec = pollTimeout / 1000;
        tv.tv_usec = (pollTimeout % 1000) * 1000;
        tvp = &tv;
    } else {
        tvp = NULL;
    }

    selected = select(maxFD+1, readp, writep, exceptp, tvp);

    if (selected < 0) {
        // Error during select
        result = -1;
    }
    else if (selected > 0) {
        // Select found something
        // Transcribe result from fd sets to poll set.
        // Also count the number of selected fds. poll returns the
        // number of ready fds; select returns the number of bits set.
        int polled = 0;
        for (p = pollSet; p < pollEnd; p++) {
            p->revents = 0;
            if (p->fd > -1) {
                // Check p->events before setting p->revents. If we
                // have multiple pollfds with the same fd, we want to
                // set the appropriate revents value for each pollfd.
                if (FD_ISSET(p->fd, readp) && (p->events & POLLIN))
                    p->revents |= POLLIN;
                if (FD_ISSET(p->fd, writep) && (p->events & POLLOUT))
                    p->revents |= POLLOUT;
                if (FD_ISSET(p->fd, exceptp) && (p->events != 0))
                    p->revents |= POLLERR;
                if (p->revents) polled++;
            }
        }
        result = polled;
    }
    else {
        // selected == 0, select timed out before anything happened
        // Clear all result bits and return zero.
        for (p = pollSet; p < pollEnd; p++) {
            p->revents = 0;
        }
        result = 0;
    }

    return result;
}


text:
package org.lwjgl.vulkan;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.system.*;

import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;

/**
 * This extension adds the ability to change the rate at which fragments are shaded. Rather than the usual single fragment invocation for each pixel covered by a primitive, multiple pixels can be shaded by a single fragment shader invocation.
 *
 *
Up to three methods are available to the application to change the fragment shading rate:

 *
 *

 *
Pipeline Fragment Shading Rate, which allows the specification of a rate per-draw.

 *
Primitive Fragment Shading Rate, which allows the specification of a rate per primitive, specified during shading.

 *
Attachment Fragment Shading Rate, which allows the specification of a rate per-region of the framebuffer, specified in a specialized image attachment.

 *

 *
 *
Additionally, these rates can all be specified and combined in order to adjust the overall detail in the image at each point.

 *
 *
This functionality can be used to focus shading efforts where higher levels of detail are needed in some parts of a scene compared to others. This can be particularly useful in high resolution rendering, or for XR contexts.

 *
 *
This extension also adds support for the {@code SPV_KHR_fragment_shading_rate} extension which enables setting the primitive fragment shading rate, and allows querying the final shading rate from a fragment shader.

 *
 *
VK_KHR_fragment_shading_rate

 *
 *

 *
Name String

 *
{@code VK_KHR_fragment_shading_rate}

 *
Extension Type

 *
Device extension

 *
Registered Extension Number

 *
227

 *
Revision

 *
2

 *
Extension and Version Dependencies

 *

 *
Requires support for Vulkan 1.0

 *
Requires {@link KHRCreateRenderpass2 VK_KHR_create_renderpass2} to be enabled for any device-level functionality

 *
Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality

 *

 *
Contact

 *

 *
Tobias Hector tobski

 *

 *
Extension Proposal

 *
VK_KHR_fragment_shading_rate

 *

 *
 *
Other Extension Metadata

 *
 *

 *
Last Modified Date

 *
2021-09-30

 *
Interactions and External Dependencies

 *

 *
This extension requires {@code SPV_KHR_fragment_shading_rate}.

 *
This extension provides API support for {@code GL_EXT_fragment_shading_rate}

 *

 *
Contributors

 *

 *
Tobias Hector, AMD

 *
Guennadi Riguer, AMD

 *
Matthaeus Chajdas, AMD

 *
Pat Brown, Nvidia

 *
Matthew Netsch, Qualcomm

 *
Slawomir Grajewski, Intel

 *
Jan-Harald Fredriksen, Arm

 *
Jeff Bolz, Nvidia

 *
Arseny Kapoulkine, Roblox

 *
Contributors to the VK_NV_shading_rate_image specification

 *
Contributors to the VK_EXT_fragment_density_map specification

 *

 *

 */
public class KHRFragmentShadingRate {

    /** The extension specification version. */
    public static final int VK_KHR_FRAGMENT_SHADING_RATE_SPEC_VERSION = 2;

    /** The extension name. */
    public static final String VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME = "VK_KHR_fragment_shading_rate";

    /** Extends {@code VkImageLayout}. */
    public static final int VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR = 1000164003;

    /** Extends {@code VkDynamicState}. */
    public static final int VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR = 1000226000;

    /**
     * Extends {@code VkStructureType}.
     *
     *
Enum values:

     *
     *

     *
{@link #VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR}

     *
{@link #VK_STRUCTURE_TYPE_PIPELINE_FRAGMENT_SHADING_RATE_STATE_CREATE_INFO_KHR STRUCTURE_TYPE_PIPELINE_FRAGMENT_SHADING_RATE_STATE_CREATE_INFO_KHR}

     *
{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_PROPERTIES_KHR STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_PROPERTIES_KHR}

     *
{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR}

     *
{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_KHR STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_KHR}

     *

     */
    public static final int
        VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR            = 1000226000,
        VK_STRUCTURE_TYPE_PIPELINE_FRAGMENT_SHADING_RATE_STATE_CREATE_INFO_KHR = 1000226001,
        VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_PROPERTIES_KHR = 1000226002,
        VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR   = 1000226003,
        VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_KHR            = 1000226004;

    /** Extends {@code VkAccessFlagBits}. */
    public static final int VK_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR = 0x800000;

    /** Extends {@code VkImageUsageFlagBits}. */
    public static final int VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = 0x100;

    /** Extends {@code VkPipelineStageFlagBits}. */
    public static final int VK_PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = 0x400000;

    /** Extends {@code VkFormatFeatureFlagBits}. */
    public static final int VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = 0x40000000;

    /** Extends {@code VkFormatFeatureFlagBits2}. */
    public static final long VK_FORMAT_FEATURE_2_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = 0x40000000L;

    /**
     * VkFragmentShadingRateCombinerOpKHR - Control how fragment shading rates are combined
     *
     *
Description

     *
     *

     *
{@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR} specifies a combiner operation of combine(Axy,Bxy) = Axy.

     *
{@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR} specifies a combiner operation of combine(Axy,Bxy) = Bxy.

     *
{@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MIN_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_MIN_KHR} specifies a combiner operation of combine(Axy,Bxy) = min(Axy,Bxy).

     *
{@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR} specifies a combiner operation of combine(Axy,Bxy) = max(Axy,Bxy).

     *
{@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MUL_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_MUL_KHR} specifies a combiner operation of combine(Axy,Bxy) = Axy*Bxy.

     *

     *
     *
where combine(Axy,Bxy) is the combine operation, and Axy and Bxy are the inputs to the operation.

     *
     *
If {@code fragmentShadingRateStrictMultiplyCombiner} is {@link VK10#VK_FALSE FALSE}, using {@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MUL_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_MUL_KHR} with values of 1 for both A and B in the same dimension results in the value 2 being produced for that dimension. See the definition of {@code fragmentShadingRateStrictMultiplyCombiner} for more information.

     *
     *
These operations are performed in a component-wise fashion.

     *
     *
See Also

     *
     *
{@link VkPipelineFragmentShadingRateEnumStateCreateInfoNV}, {@link VkPipelineFragmentShadingRateStateCreateInfoKHR}, {@link NVFragmentShadingRateEnums#vkCmdSetFragmentShadingRateEnumNV CmdSetFragmentShadingRateEnumNV}, {@link #vkCmdSetFragmentShadingRateKHR CmdSetFragmentShadingRateKHR}

     */
    public static final int
        VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR    = 0,
        VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR = 1,
        VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MIN_KHR     = 2,
        VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_KHR     = 3,
        VK_FRAGMENT_SHADING_RATE_COMBINER_OP_MUL_KHR     = 4;

    protected KHRFragmentShadingRate() {
        throw new UnsupportedOperationException();
    }

    // --- [ vkGetPhysicalDeviceFragmentShadingRatesKHR ] ---

    /**
     * Unsafe version of: {@link #vkGetPhysicalDeviceFragmentShadingRatesKHR GetPhysicalDeviceFragmentShadingRatesKHR}
     *
     * @param pFragmentShadingRateCount a pointer to an integer related to the number of fragment shading rates available or queried, as described below.
     */
    public static int nvkGetPhysicalDeviceFragmentShadingRatesKHR(VkPhysicalDevice physicalDevice, long pFragmentShadingRateCount, long pFragmentShadingRates) {
        long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceFragmentShadingRatesKHR;
        if (CHECKS) {
            check(__functionAddress);
        }
        return callPPPI(physicalDevice.address(), pFragmentShadingRateCount, pFragmentShadingRates, __functionAddress);
    }

    /**
     * Get available shading rates for a physical device.
     *
     *
C Specification

     *
     *
To query available shading rates, call:

     *
     *

     * VkResult vkGetPhysicalDeviceFragmentShadingRatesKHR(
     *     VkPhysicalDevice                            physicalDevice,
     *     uint32_t*                                   pFragmentShadingRateCount,
     *     VkPhysicalDeviceFragmentShadingRateKHR*     pFragmentShadingRates);

     *
     *
Description

     *
     *
If {@code pFragmentShadingRates} is {@code NULL}, then the number of fragment shading rates available is returned in {@code pFragmentShadingRateCount}. Otherwise, {@code pFragmentShadingRateCount} must point to a variable set by the user to the number of elements in the {@code pFragmentShadingRates} array, and on return the variable is overwritten with the number of structures actually written to {@code pFragmentShadingRates}. If {@code pFragmentShadingRateCount} is less than the number of fragment shading rates available, at most {@code pFragmentShadingRateCount} structures will be written, and {@link VK10#VK_INCOMPLETE INCOMPLETE} will be returned instead of {@link VK10#VK_SUCCESS SUCCESS}, to indicate that not all the available fragment shading rates were returned.

     *
     *
The returned array of fragment shading rates must be ordered from largest {@code fragmentSize.width} value to smallest, and each set of fragment shading rates with the same {@code fragmentSize.width} value must be ordered from largest {@code fragmentSize.height} to smallest. Any two entries in the array must not have the same {@code fragmentSize} values.

     *
     *
For any entry in the array, the following rules also apply:

     *
     *

     *
The value of {@code fragmentSize.width} must be less than or equal to {@code maxFragmentSize.width}.

     *
The value of {@code fragmentSize.width} must be greater than or equal to 1.

     *
The value of {@code fragmentSize.width} must be a power-of-two.

     *
The value of {@code fragmentSize.height} must be less than or equal to {@code maxFragmentSize.height}.

     *
The value of {@code fragmentSize.height} must be greater than or equal to 1.

     *
The value of {@code fragmentSize.height} must be a power-of-two.

     *
The highest sample count in {@code sampleCounts} must be less than or equal to {@code maxFragmentShadingRateRasterizationSamples}.

     *
The product of {@code fragmentSize.width}, {@code fragmentSize.height}, and the highest sample count in {@code sampleCounts} must be less than or equal to {@code maxFragmentShadingRateCoverageSamples}.

     *

     *
     *
Implementations must support at least the following shading rates:

     *
     *

     *

{@code sampleCounts}	{@code fragmentSize}

     *

     *
{@link VK10#VK_SAMPLE_COUNT_1_BIT SAMPLE_COUNT_1_BIT} | {@link VK10#VK_SAMPLE_COUNT_4_BIT SAMPLE_COUNT_4_BIT}	{2,2}

     *
{@link VK10#VK_SAMPLE_COUNT_1_BIT SAMPLE_COUNT_1_BIT} | {@link VK10#VK_SAMPLE_COUNT_4_BIT SAMPLE_COUNT_4_BIT}	{2,1}

     *
~0	{1,1}

     *

     *

     *
     *
If {@code framebufferColorSampleCounts}, includes {@link VK10#VK_SAMPLE_COUNT_2_BIT SAMPLE_COUNT_2_BIT}, the required rates must also include {@link VK10#VK_SAMPLE_COUNT_2_BIT SAMPLE_COUNT_2_BIT}.

     *
     *

Note

     *
     *
Including the {1,1} fragment size is done for completeness; it has no actual effect on the support of rendering without setting the fragment size. All sample counts and render pass transforms are supported for this rate.

     *

     *
     *
The returned set of fragment shading rates must be returned in the native (rotated) coordinate system. For rasterization using render pass {@code transform} not equal to {@link KHRSurface#VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR SURFACE_TRANSFORM_IDENTITY_BIT_KHR}, the application must transform the returned fragment shading rates into the current (unrotated) coordinate system to get the supported rates for that transform.

     *
     *

Note

     *
     *
For example, consider an implementation returning support for 4x2, but not 2x4 in the set of supported fragment shading rates. This means that for transforms {@link KHRSurface#VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR SURFACE_TRANSFORM_ROTATE_90_BIT_KHR} and {@link KHRSurface#VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR SURFACE_TRANSFORM_ROTATE_270_BIT_KHR}, 2x4 is a supported rate, but 4x2 is an unsupported rate.

     *

     *
     *
Valid Usage (Implicit)

     *
     *

     *
{@code physicalDevice} must be a valid {@code VkPhysicalDevice} handle

     *
{@code pFragmentShadingRateCount} must be a valid pointer to a {@code uint32_t} value

     *
If the value referenced by {@code pFragmentShadingRateCount} is not 0, and {@code pFragmentShadingRates} is not {@code NULL}, {@code pFragmentShadingRates} must be a valid pointer to an array of {@code pFragmentShadingRateCount} {@link VkPhysicalDeviceFragmentShadingRateKHR} structures

     *

     *
     *
Return Codes

     *
     *

     *
On success, this command returns

     *

     *
{@link VK10#VK_SUCCESS SUCCESS}

     *
{@link VK10#VK_INCOMPLETE INCOMPLETE}

     *

     *
On failure, this command returns

     *

     *
{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}

     *

     *

     *
     *
See Also

     *
     *
{@link VkPhysicalDeviceFragmentShadingRateKHR}

     *
     * @param physicalDevice            the handle to the physical device whose properties will be queried.
     * @param pFragmentShadingRateCount a pointer to an integer related to the number of fragment shading rates available or queried, as described below.
     * @param pFragmentShadingRates     either {@code NULL} or a pointer to an array of {@link VkPhysicalDeviceFragmentShadingRateKHR} structures.
     */
    @NativeType("VkResult")
    public static int vkGetPhysicalDeviceFragmentShadingRatesKHR(VkPhysicalDevice physicalDevice, @NativeType("uint32_t *") IntBuffer pFragmentShadingRateCount, @Nullable @NativeType("VkPhysicalDeviceFragmentShadingRateKHR *") VkPhysicalDeviceFragmentShadingRateKHR.Buffer pFragmentShadingRates) {
        if (CHECKS) {
            check(pFragmentShadingRateCount, 1);
            checkSafe(pFragmentShadingRates, pFragmentShadingRateCount.get(pFragmentShadingRateCount.position()));
        }
        return nvkGetPhysicalDeviceFragmentShadingRatesKHR(physicalDevice, memAddress(pFragmentShadingRateCount), memAddressSafe(pFragmentShadingRates));
    }

    // --- [ vkCmdSetFragmentShadingRateKHR ] ---

    /** Unsafe version of: {@link #vkCmdSetFragmentShadingRateKHR CmdSetFragmentShadingRateKHR} */
    public static void nvkCmdSetFragmentShadingRateKHR(VkCommandBuffer commandBuffer, long pFragmentSize, long combinerOps) {
        long __functionAddress = commandBuffer.getCapabilities().vkCmdSetFragmentShadingRateKHR;
        if (CHECKS) {
            check(__functionAddress);
        }
        callPPPV(commandBuffer.address(), pFragmentSize, combinerOps, __functionAddress);
    }

    /**
     * Set pipeline fragment shading rate and combiner operation dynamically for a command buffer.
     *
     *
C Specification

     *
     *
To dynamically set the pipeline fragment shading rate and combiner operation, call:

     *
     *

     * void vkCmdSetFragmentShadingRateKHR(
     *     VkCommandBuffer                             commandBuffer,
     *     const VkExtent2D*                           pFragmentSize,
     *     const VkFragmentShadingRateCombinerOpKHR    combinerOps[2]);

     *
     *
Description

     *
     *
This command sets the pipeline fragment shading rate and combiner operation for subsequent drawing commands when the graphics pipeline is created with {@link #VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR} set in {@link VkPipelineDynamicStateCreateInfo}{@code ::pDynamicStates}. Otherwise, this state is specified by the {@link VkPipelineFragmentShadingRateStateCreateInfoKHR} values used to create the currently active pipeline.

     *
     *
Valid Usage

     *
     *

     *
If {@code pipelineFragmentShadingRate} is not enabled, {@code pFragmentSize→width} must be 1

     *
If {@code pipelineFragmentShadingRate} is not enabled, {@code pFragmentSize→height} must be 1

     *
One of {@code pipelineFragmentShadingRate}, {@code primitiveFragmentShadingRate}, or {@code attachmentFragmentShadingRate} must be enabled

     *
If the {@code primitiveFragmentShadingRate} feature is not enabled, {@code combinerOps}[0] must be {@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR}

     *
If the {@code attachmentFragmentShadingRate} feature is not enabled, {@code combinerOps}[1] must be {@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR}

     *
If the {@code fragmentSizeNonTrivialCombinerOps} limit is not supported, elements of {@code combinerOps} must be either {@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR} or {@link #VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR}

     *
{@code pFragmentSize→width} must be greater than or equal to 1

     *
{@code pFragmentSize→height} must be greater than or equal to 1

     *
{@code pFragmentSize→width} must be a power-of-two value

     *
{@code pFragmentSize→height} must be a power-of-two value

     *
{@code pFragmentSize→width} must be less than or equal to 4

     *
{@code pFragmentSize→height} must be less than or equal to 4

     *

     *
     *
Valid Usage (Implicit)

     *
     *

     *
{@code commandBuffer} must be a valid {@code VkCommandBuffer} handle

     *
{@code pFragmentSize} must be a valid pointer to a valid {@link VkExtent2D} structure

     *
Any given element of {@code combinerOps} must be a valid {@code VkFragmentShadingRateCombinerOpKHR} value

     *
{@code commandBuffer} must be in the recording state

     *
The {@code VkCommandPool} that {@code commandBuffer} was allocated from must support graphics operations

     *
This command must only be called outside of a video coding scope

     *

     *
     *
Host Synchronization

     *
     *

     *
Host access to {@code commandBuffer} must be externally synchronized

     *
Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from must be externally synchronized

     *

     *
     *
Command Properties

     *
     *

     *

Command Buffer Levels	Render Pass Scope	Video Coding Scope	Supported Queue Types	Command Type

     *

Primary Secondary	Both	Outside	Graphics	State

     *

     *
     *
See Also

     *
     *
{@link VkExtent2D}

     *
     * @param commandBuffer the command buffer into which the command will be recorded.
     * @param pFragmentSize specifies the pipeline fragment shading rate for subsequent drawing commands.
     * @param combinerOps   specifies a {@code VkFragmentShadingRateCombinerOpKHR} determining how the pipeline, primitive, and attachment shading rates are combined for fragments generated by subsequent drawing commands.
     */
    public static void vkCmdSetFragmentShadingRateKHR(VkCommandBuffer commandBuffer, @NativeType("VkExtent2D const *") VkExtent2D pFragmentSize, @NativeType("VkFragmentShadingRateCombinerOpKHR const *") IntBuffer combinerOps) {
        if (CHECKS) {
            check(combinerOps, 2);
        }
        nvkCmdSetFragmentShadingRateKHR(commandBuffer, pFragmentSize.address(), memAddress(combinerOps));
    }

    /** Array version of: {@link #vkGetPhysicalDeviceFragmentShadingRatesKHR GetPhysicalDeviceFragmentShadingRatesKHR} */
    @NativeType("VkResult")
    public static int vkGetPhysicalDeviceFragmentShadingRatesKHR(VkPhysicalDevice physicalDevice, @NativeType("uint32_t *") int[] pFragmentShadingRateCount, @Nullable @NativeType("VkPhysicalDeviceFragmentShadingRateKHR *") VkPhysicalDeviceFragmentShadingRateKHR.Buffer pFragmentShadingRates) {
        long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceFragmentShadingRatesKHR;
        if (CHECKS) {
            check(__functionAddress);
            check(pFragmentShadingRateCount, 1);
            checkSafe(pFragmentShadingRates, pFragmentShadingRateCount[0]);
        }
        return callPPPI(physicalDevice.address(), pFragmentShadingRateCount, memAddressSafe(pFragmentShadingRates), __functionAddress);
    }

    /** Array version of: {@link #vkCmdSetFragmentShadingRateKHR CmdSetFragmentShadingRateKHR} */
    public static void vkCmdSetFragmentShadingRateKHR(VkCommandBuffer commandBuffer, @NativeType("VkExtent2D const *") VkExtent2D pFragmentSize, @NativeType("VkFragmentShadingRateCombinerOpKHR const *") int[] combinerOps) {
        long __functionAddress = commandBuffer.getCapabilities().vkCmdSetFragmentShadingRateKHR;
        if (CHECKS) {
            check(__functionAddress);
            check(combinerOps, 2);
        }
        callPPPV(commandBuffer.address(), pFragmentSize.address(), combinerOps, __functionAddress);
    }

}


text:
<!doctype html>

<meta charset="utf-8">

<textarea rows="20" cols="60" id='source-text'>
BEGINNING-OF-PROGRAM
    DEFINE-NEW-INSTRUCTION turnright AS
    BEGIN
        turnleft;
        turnleft;
        turnleft
    END ;

    BEGINNING-OF-EXECUTION
        turnright;
        move;
        move;
        putbeeper;
        move;
        putbeeper;
        turnoff
    END-OF-EXECUTION
END-OF-PROGRAM
</textarea>
<input type="button" value="Run" id="run-button">
<input type="button" value="ReRun" id="rerun-button">


text:
<icegrid>
        <replica-group id="KafkaConsumerProxy" />

        <server-template id="KafkaConsumerProxy">
        <parameter name="Index" />
        <parameter name="Replica" default="KafkaConsumerProxy" />
        <parameter name="LogLevel" default="WARN" />
        <parameter name="Timeout" default="1000" />
        <parameter name="JavaXms" />
        <parameter name="JavaXmx" />
                <icebox id="KafkaConsumerProxy${Index}" exe="/opt/java/bin/java" activation="always">
                        <env>CLASSPATH=../lib64/KafkaConsumerProxy.jar</env>
                        <option>-server</option>
                        <option>-DLOG_PATH=../log/KafkaConsumerProxy${Index}</option>
                        <option>-Xss512k</option>
                        <option>-XX:ThreadStackSize=512</option>
                        <option>-Xms${JavaXms}</option>
                        <option>-Xmx${JavaXmx}</option>
                        <option>-XX:+UseParNewGC</option>
                        <option>-XX:+UseConcMarkSweepGC</option>
                        <option>-XX:NewRatio=2</option>
                        <option>-XX:+CMSIncrementalMode</option>
                        <option>-XX:-CMSIncrementalPacing</option>
                        <option>-XX:CMSIncrementalDutyCycle=90</option>
                        <option>-XX:CMSIncrementalDutyCycleMin=0</option>
                        <option>-XX:+UseCMSCompactAtFullCollection</option>

			<option>-verbosegc</option>
			<option>-XX:+PrintGCDetails</option>
                        <option>-XX:+PrintGCTimeStamps</option>
			<option>-Xloggc:../log/consumer-gc.log</option>

                        <option>IceBox.Server</option>

                        <property name="IceBox.UseSharedCommunicator.KafkaConsumerProxy${Index}" value="1"/>
                        <property name="Service.KafkaConsumerProxy${Index}.LogLevel" value="${LogLevel}"/>
                        <property name="Ice.ThreadPool.Server.Size" value="10"/>
                        <property name="Ice.ThreadPool.Server.SizeMax" value="2000"/>
                        <property name="Ice.ThreadPool.Server.StackSize" value="131072"/>
                        <service name="KafkaConsumerProxy${Index}" entry="bfd.kafkaconsumerclient.KafkaConsumerClientService">
                                <adapter name="KafkaConsumerProxy${Index}" id="KafkaConsumerProxy${Index}" endpoints="tcp -p 20002:udp" replica-group="${Replica}" >
                                        <property name="KafkaConsumerProxy${Index}.ThreadPool.Size" value="10"/>
                                        <property name="KafkaConsumerProxy${Index}.ThreadPool.SizeMax" value="2000"/>
                                        <property name="KafkaConsumerProxy${Index}.ThreadPool.StackSize" value="131072"/>
                                </adapter>
                        </service>
                </icebox>
        </server-template>
</icegrid>


text:
<?php
/**
 * REST Server implementation for Agile Toolkit
 *
 * This class takes advantage of the tight integration for Agile Toolkit
 * to enhance and make it super simple to create an awesome API for
 * your existing application.
 */
// @codingStandardsIgnoreStart because REST is acronym
class App_REST extends App_CLI
{
// @codingStandardsIgnoreEnd

    public $doc_page='app/rest';

    public $page;

    /**
     * init
     *
     * @return [type] [description]
     */
    public function init()
    {
        parent::init();
        try {
            // Extra 24-hour protection
            parent::init();

            $this->logger = $this->add('Logger');
            $this->add('Controller_PageManager')
                ->parseRequestedURL();

            // It's recommended that you use versioning inside your API,
            // for example http://api.example.com/v1/user
            //
            // This way version is accessible anywhere from $this->app->version
            list($this->version, $junk)=explode('_', $this->page, 2);

            // Add-ons may define additional endpoints for your API, but
            // you must activate them explicitly.
            $this->pathfinder->base_location->defineContents(array('endpoint'=>'endpoint'));

        } catch (Exception $e) {
            $this->caughtException($e);
        }
    }
    /**
     * Output will be properly fromatted
     *
     * @param [type] $data [description]
     *
     * @return [type]       [description]
     */
    public function encodeOutput($data)
    {

        // TODO - use HTTP_ACCEPT here ?
        //var_Dump($_SERVER['HTTP_ACCEPT']);

        if ($_GET['format'] == 'xml') {
            throw $this->exception('only JSON format is supported', null, 406);
        }
        if ($_GET['format'] == 'json_pretty') {
            header('Content-type: application/json');
            echo json_encode($data, JSON_PRETTY_PRINT);
            return;
        }
        if ($_GET['format'] == 'html') {
            echo '<pre>';
            echo json_encode($data, JSON_PRETTY_PRINT);
            return;
        }
        header('Content-type: application/json');

        if($data===null)$data=array();
        echo json_encode($data);
        return;
    }
    /**
     * main
     *
     * @return [type] [description]
     */
    function main(){
        $this->execute();
        $this->hook('saveDelayedModels');
    }
    public function execute()
    {
        try {
            try {
                $file = $this->api->locatePath('endpoint', str_replace('_', '/', $this->page) . '.php');
                include_once $file;

                $this->pm->base_path = '/';
            } catch (Exception $e) {
                http_response_code(500);
                if($e instanceof Exception_Pathfinder) {
                    $error = array(
                        'error'=>'No such endpoint',
                        'type'=>'API_Error'
                        );
                } else {
                    $error = array(
                        'error'=>'Problem with endpoint',
                        'type'=>'API_Error'
                        );
                }
                $this->caughtException($e);
                $this->encodeOutput($error, null);
                return;
            }

            try {

                $class = "endpoint_" . $this->page;
                $this->endpoint = $this->add($class);
                $this->endpoint->app = $this;
                $this->endpoint->api = $this; // compatibility

                $method=strtolower($_SERVER['REQUEST_METHOD']);
                $raw_post = file_get_contents("php://input");

                if ($raw_post && $raw_post[0]=='{') {
                    $args=json_decode($raw_post, true);
                } elseif ($method=='put') {
                    parse_str($raw_post, $args);
                } else {
                    $args=$_POST;
                }

                if($_GET['method'])$method.='_'.$_GET['method'];
                if (!$this->endpoint->hasMethod($method)) {
                    throw $this->exception('Method does not exist for this endpoint', null, 404)
                        ->addMoreInfo('method', $method)
                        ->addMoreInfo('endpoint', $this->endpoint)
                        ;
                }

                $this->logRequest($method, $args);

                // Perform the desired action
                $this->encodeOutput($this->endpoint->$method($args));

                $this->logSuccess();

            } catch (Exception $e) {
                $this->caughtException($e);
                http_response_code($e->getCode()?:500);

                $error = array(
                    'error'=>$e->getMessage(),
                    'type'=>get_class($e),
                    'more_info'=>$e instanceof BaseException ? $e->more_info:null
                );
                array_walk_recursive($error, function (&$item, $key) {
                    if (is_object($item)) $item=(string)$item;
                });
                $this->encodeOutput($error, null);
            }

        } catch (Exception $e) {
            $this->caughtException($e);
        }
    }
    /**
     * Override to extend the logging
     *
     * @param  [type] $method [description]
     * @param  [type] $args   [description]
     * @return [type]         [description]
     */
    function logRequest($method, $args) {

    }
    function logSuccess(){

    }
}


text:
<?xml version="1.0"?>

<project name="Gems Unit Tests" default="test">
    <property name="tests.codecoverage" value="false"/>

    <target name="clean">
        <delete dir="reports"/>
    </target>

    <target name="prepare">
        <mkdir dir="reports/coverage"/>
        <mkdir dir="reports/tests"/>
    </target>

    <target name="test" depends="clean, prepare">
        <if>
            <equals arg1="${tests.codecoverage}" arg2="true"/>
            <then>
                <coverage-setup database="reports/coverage.db">
                    <fileset dir="../library/classes">
                        <include name="**/*.php"/>
                    </fileset>
                </coverage-setup>
            </then>
        </if>
        <phpunit codecoverage="${tests.codecoverage}" haltonerror="true" haltonfailure="true"
                 bootstrap="bootstrap.php" printsummary="true">
            <formatter type="xml" usefile="true"
                       todir="reports" outfile="test-results.xml" />
            <formatter type="plain" usefile="false"/>
            <batchtest>
                <fileset dir="classes">
                    <include name="**/*Test.php"/>
                </fileset>
            </batchtest>
            <formatter type="clover"  usefile="true"
                       todir="reports" outfile="clover.xml" />
        </phpunit>
    </target>

</project>


text:
published: true
title: On the go
layout: post
---
Just testing out writing this from the phone. Seems to work just fine
-----


text:
<?php

namespace Drupal\ds\Form;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\ContextAwarePluginAssignmentTrait;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configure block fields.
 */
class BlockFieldConfigForm extends FieldFormBase implements ContainerInjectionInterface {

  use ContextAwarePluginAssignmentTrait;

  /**
   * The context repository.
   *
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
   */
  protected $contextRepository;

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactory $config_factory, EntityTypeManagerInterface $entity_type_manager, CacheTagsInvalidatorInterface $cache_invalidator, ModuleHandler $module_handler, ContextRepositoryInterface $context_repository) {
    parent::__construct($config_factory, $entity_type_manager, $cache_invalidator, $module_handler);
    $this->contextRepository = $context_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('entity_type.manager'),
      $container->get('cache_tags.invalidator'),
      $container->get('module_handler'),
      $container->get('context.repository')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $field_key = '') {
    // Fetch field.
    $field = $this->config('ds.field.' . $field_key)->get();

    // Save the field for future reuse.
    $this->field = $field;

    // Create an instance of the block.
    /* @var $block BlockPluginInterface */
    $manager = \Drupal::service('plugin.manager.block');
    $block_id = $field['properties']['block'];
    $block = $manager->createInstance($block_id);

    // Set block config form default values.
    if (isset($field['properties']['config'])) {
      $block->setConfiguration($field['properties']['config']);
    }

    // Get block config form.
    $form = $block->blockForm($form, $form_state);

    // If the block is context aware, attach the mapping widget.
    if ($block instanceof ContextAwarePluginInterface) {
      $form['context_mapping'] = $this->addContextAssignmentElement($block, $this->contextRepository->getAvailableContexts());
    }

    if (!$form) {
      return array('#markup' => $this->t("This block has no configuration options."));
    }

    // Some form items require this (core block manager also sets this).
    $form['#tree'] = TRUE;

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#weight' => 100,
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $field = $this->field;

    // Create an instance of the block.
    /* @var $block BlockPluginInterface */
    $manager = \Drupal::service('plugin.manager.block');
    $block_id = $field['properties']['block'];
    $block = $manager->createInstance($block_id);

    // Validate block config data using the block's validation handler.
    $block->validateConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $field = $this->field;

    // Create an instance of the block.
    /* @var $block BlockPluginInterface */
    $manager = \Drupal::service('plugin.manager.block');
    $block_id = $field['properties']['block'];
    $block = $manager->createInstance($block_id);

    // Process block config data using the block's submit handler.
    $block->blockSubmit($form, $form_state);

    // If the block is context aware, store the context mapping.
    if ($block instanceof ContextAwarePluginInterface && $block->getContextDefinitions()) {
      $context_mapping = $form_state->getValue('context_mapping', []);
      $block->setContextMapping($context_mapping);
    }

    $block_config = $block->getConfiguration();

    // Clear cache tags.
    $this->cacheInvalidator->invalidateTags($block->getCacheTags());

    // Save block config.
    $this->config('ds.field.' . $field['id'])->set('properties.config', $block_config)->save();

    // Clear caches and redirect.
    $this->finishSubmitForm($form, $form_state);
  }

}


text:
package com.eye.see.image.processing;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.media.jai.PlanarImage;

import com.eye.see.image.ClusteredImageAttibutes;
import com.eye.see.image.Color;
import com.eye.see.image.ColorHistogram;

/**
 * Class is responsible for creating regional color histograms for images that
 * have been separated into regions.  This classes uses a PlanarImage that will
 * be clustered and then each clusters color histogram will be created.
 *
 * @author Ozcan Huseyin
 */
public class LocalNeighbourhoodHistogramProcessor extends ColorHistogramProcessor {

	/**
	 * Method processes an image given the images file name.
	 *
	 * @param fileName of the file to calculate local color histograms for
	 * @return
	 */
	public ColorHistogram[] calculateLocalHNeighbourhoodHistogram(String fileName) {

		FuzzyCMeansClusteringImageProcessor fcmProcessor = new FuzzyCMeansClusteringImageProcessor();
		// Generate the clustered image
		ClusteredImageAttibutes clusteredImageAttributes = fcmProcessor.segmentImage(fileName);
		// Load the generated clustered image
		PlanarImage clusteredImage = loadImage(clusteredImageAttributes.getClusteredImageFileName());
		PlanarImage inputImage = loadImage(clusteredImageAttributes.getInputFileName());
		// Process the clustered image to calculate Local Neighbourhood Histograms
		ColorHistogram[] histograms = calculateLocalHistograms(clusteredImage, inputImage, clusteredImageAttributes);

		return histograms;
	}

	private ColorHistogram[] calculateLocalHistograms(PlanarImage clusteredImage, PlanarImage inputImage, ClusteredImageAttibutes imageAttributes) {
		// Get the image dimensions.
		int width = clusteredImage.getWidth();
		int height = clusteredImage.getHeight();
		int numBands = clusteredImage.getSampleModel().getNumBands();

		// Gets the whole clustered image data on memory.
		int[] clusteredData = getImageData(clusteredImage);
		// Get the whole input image data into memory
		int[] inputData = getImageData(inputImage);

		return processLNHs(clusteredData, inputData, height, width, numBands, imageAttributes);
	}

	private ColorHistogram[] processLNHs(int[] clusteredImageData, int[] inputImageData, int height, int width, int numBands, ClusteredImageAttibutes attribs) {
		// A single clustered pixel value
		float[] clusteredPixel = new float[numBands];
		// A single input image pixel value
		float[] inputImagePixel = new float[numBands];

		Hashtable<String, ColorHistogram> histograms = createHistogramStore(attribs);

		// For each pixel in the image...
		for(int h=0;h<height;h++) {
			for (int w=0;w<width;w++) {
				// Get a pixel (as a single array).
				int index = (h*width+w)*numBands;
				for(int b=0;b<numBands;b++) {
					clusteredPixel[b] = clusteredImageData[index+b];
					inputImagePixel[b] = inputImageData[index+b];
				}
				Color clusterPixel = new Color(clusteredPixel);
				Color inputPixel = new Color(inputImagePixel);
				// Get the color histogram for the cluster pixel value
				ColorHistogram histogram = histograms.get(clusterPixel.toString());
				// Count it
				histogram.countPixel(inputPixel);
			}
		}

		return getHistogramsFromStore(histograms);
	}

	private ColorHistogram[] getHistogramsFromStore(Hashtable<String, ColorHistogram> histograms) {

		ColorHistogram[] histogramArray = new ColorHistogram[histograms.size()];
		int count = 0;
		for (Enumeration<ColorHistogram> enumeration = histograms.elements(); enumeration.hasMoreElements(); ) {
			ColorHistogram histogram = enumeration.nextElement();
			histogramArray[count++] = histogram;
		}
		return histogramArray;
	}

	private Hashtable<String, ColorHistogram> createHistogramStore(ClusteredImageAttibutes attribs) {
		Color[] centerColors = attribs.getClusterCentersInColor();
		Hashtable<String, ColorHistogram> histograms = new Hashtable<String, ColorHistogram>();
		for (int i = 0; i < centerColors.length; i++) {
			Color color = centerColors[i];
			histograms.put(color.toString(), new ColorHistogram());
		}
		return histograms;
	}
}


text:
package com.servioticy.queueclient;

import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Properties;

/**
 * Created by alvaro on 07/09/15.
 */
public class KafkaClient extends QueueClient {
    private KafkaProducer<String, byte[]> producer;
    @Override
    protected boolean putImpl(Object item) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out ;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(item);
            byte[] msg = bos.toByteArray();
            bos.close();
            this.producer.send(new ProducerRecord<String, byte[]>(this.getQueueName(), null, msg)).get();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    protected Object getImpl() {
        return null;
    }

    @Override
    protected void connectImpl() throws QueueClientException {
        if(this.producer != null){
            return;
        }
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, this.getAddress().replace(" ", ","));
        props.put(ProducerConfig.RETRIES_CONFIG, "3");
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "none");
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 200);
        props.put(ProducerConfig.BLOCK_ON_BUFFER_FULL_CONFIG, true);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");

        this.producer = new KafkaProducer<String, byte[]>(props);

    }

    @Override
    protected void disconnectImpl() throws QueueClientException {
        if(this.producer == null){
            return;
        }

        this.producer.close();
        this.producer = null;
    }

    @Override
    protected void init(HierarchicalConfiguration config) throws QueueClientException {
        this.producer = null;
    }
}


text:
package no._0d.smooze.data;

import org.springframework.data.repository.CrudRepository;

public interface RegistrationRepository extends CrudRepository<Registration, Long> {
}