text:
package com.xujun.contralayout.UI.drawlayout;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.xujun.contralayout.R;
import com.xujun.contralayout.UI.ItemFragement;

public class DrawLayoutSample extends AppCompatActivity {

    private Toolbar mToolbar;
    private NavigationView mNavigationView;
    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_view);

        mToolbar = (Toolbar) findViewById(R.id.id_toolbar);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_navigation);
        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
        //<activity android:name=".NavigationActivity" android:theme="@style/AppThemeNoActionBar"></activity>
        //<style name="AppThemeNoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
        //初始化toolbar,这里得使用NoActionBar的主题,使用ToolBar替换系统自带的ActionBar达到自己的需求
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        //关联图标和侧滑栏
        actionBar.setHomeAsUpIndicator(R.drawable.menu);
        //设置actionBar和侧滑栏关联
        actionBar.setDisplayHomeAsUpEnabled(true);
        //初始化drawerlayout和navigationview
        if (mNavigationView != null) {
            //设置监听回调
            mNavigationView.setNavigationItemSelectedListener(new NavigationView
                    .OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    //根据选中不同的选项来进行不同的操作
                    switch (item.getItemId()) {
                        case R.id.nav_home:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,
                                    ItemFragement.newInstance("主页")).commit();
                            mToolbar.setTitle("主页");
                            break;
                        case R.id.nav_friends:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,
                                    ItemFragement.newInstance("我的好友")).commit();
                            mToolbar.setTitle("我的好友");
                            break;
                        case R.id.nav_discussion:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,
                                    ItemFragement.newInstance("热文论坛")).commit();
                            mToolbar.setTitle("热文论坛");
                            break;
                        case R.id.nav_messages:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,
                                    ItemFragement.newInstance("我的消息")).commit();
                            mToolbar.setTitle("我的消息");
                            break;
                        case R.id.sub1:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,
                                    ItemFragement.newInstance("子项1")).commit();
                            mToolbar.setTitle("子项1");
                            break;
                        case R.id.sub2:
                            getSupportFragmentManager().beginTransaction().replace(R.id.content,
                                    ItemFragement.newInstance("子项2")).commit();
                            mToolbar.setTitle("子项2");
                            break;
                    }
                    //设置选项选中效果
                    item.setChecked(true);
                    //选了侧边栏选项之后,关闭侧边栏
                    mDrawerLayout.closeDrawers();
                    //这里返回true有选中的效果,源码中有解释
                    return true;
                }
            });
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //点击左上角的菜单选项,这是在actionBar.setHomeAsUpIndicator(R.drawable.center_image_collection);
            // 这儿设置的。
            case android.R.id.home:
                //点击之后打开侧滑栏
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
<?php

namespace Oro\Bundle\ApiBundle\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

use Oro\Bundle\ApiBundle\Config\DescriptionsConfigExtra;
use Oro\Bundle\ApiBundle\Config\FiltersConfigExtra;
use Oro\Bundle\ApiBundle\Config\SortersConfigExtra;
use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Provider\RelationConfigProvider;
use Oro\Bundle\ApiBundle\Request\RequestType;
use Oro\Bundle\ApiBundle\Request\Version;
use Oro\Bundle\EntityBundle\Tools\EntityClassNameHelper;

class DumpConfigCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('oro:api:config:dump')
            ->setDescription('Dumps API configuration.')
            ->addArgument(
                'entity',
                InputArgument::REQUIRED,
                'The entity class name or alias'
            )
            // @todo: API version is not supported for now
            //->addArgument(
            //    'version',
            //    InputArgument::OPTIONAL,
            //    'API version',
            //    Version::LATEST
            //)
            ->addOption(
                'request-type',
                null,
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
                'API request type',
                [RequestType::REST, RequestType::JSON_API]
            )
            ->addOption(
                'section',
                null,
                InputOption::VALUE_REQUIRED,
                'The configuration section. Can be "entities" or "relations"',
                'entities'
            )
            ->addOption(
                'with-descriptions',
                null,
                InputOption::VALUE_NONE,
                'Whether human-readable descriptions should be added'
            );
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var EntityClassNameHelper $entityClassNameHelper */
        $entityClassNameHelper = $this->getContainer()->get('oro_entity.entity_class_name_helper');

        $entityClass = $entityClassNameHelper->resolveEntityClass($input->getArgument('entity'));
        $requestType = $input->getOption('request-type');
        // @todo: API version is not supported for now
        //$version     = $input->getArgument('version');
        $version = Version::LATEST;

        $extras = [new FiltersConfigExtra(), new SortersConfigExtra()];
        if ($input->getOption('with-descriptions')) {
            $extras[] = new DescriptionsConfigExtra();
        }

        switch ($input->getOption('section')) {
            case 'entities':
                $config = $this->getConfig($entityClass, $version, $requestType, $extras);
                break;
            case 'relations':
                $config = $this->getRelationConfig($entityClass, $version, $requestType, $extras);
                break;
            default:
                throw new \InvalidArgumentException(
                    'The section should be either "entities" or "relations".'
                );
        }

        array_walk_recursive(
            $config,
            function (&$val) {
                if ($val instanceof \Closure) {
                    $val = '\Closure';
                }
            }
        );
        $output->write(Yaml::dump($config, 100, 4, true, true));
    }

    /**
     * @param string   $entityClass
     * @param string   $version
     * @param string[] $requestType
     * @param array    $extras
     *
     * @return array
     */
    protected function getConfig($entityClass, $version, array $requestType, array $extras)
    {
        /** @var ConfigProvider $configProvider */
        $configProvider = $this->getContainer()->get('oro_api.config_provider');

        $config = $configProvider->getConfig($entityClass, $version, $requestType, $extras);

        return [
            'oro_api' => [
                'entities' => [
                    $entityClass => $config
                ]
            ]
        ];
    }

    /**
     * @param string   $entityClass
     * @param string   $version
     * @param string[] $requestType
     * @param array    $extras
     *
     * @return array
     */
    protected function getRelationConfig($entityClass, $version, array $requestType, array $extras)
    {
        /** @var RelationConfigProvider $configProvider */
        $configProvider = $this->getContainer()->get('oro_api.relation_config_provider');

        $config = $configProvider->getRelationConfig($entityClass, $version, $requestType, $extras);

        return [
            'oro_api' => [
                'relations' => [
                    $entityClass => $config
                ]
            ]
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="Drug Wars Game">
		<meta name="author" content="fidel">
		<link rel="shortcut icon" href="docs-assets/ico/favicon.png">
		<title>DrugWars - The Heisenberg Edition</title>

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

		<link href="css/starter-template.css" rel="stylesheet">

		<link rel="stylesheet" href="css/font-awesome-4.1.0/css/font-awesome.min.css">

		<link rel="stylesheet" href="js/blackbird-js-master/blackbird.css">

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

					<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
						Toggle navigation

					</button>
					DrugWars

 Home

 Highscore

							 Options

Settings

 Quotes

 Delete LocalStorage

 Start new game

 Development

 Code

 Issues

 Wiki

 Status ()

									0% Complete

 Location:

									Drug
									Pocket
									Market
									Buy
									Sell

									Acid
									0

									Coke
									0

 Actions

								<button type="button"  class="btn btn-xs" id="choose_buyd"> Buy</button>

								<button type="button"  class="btn btn-xs" id="choose_selld"> Sell</button>

								<button type="button"  class="btn btn-xs" id="choose_loan"> Money</button>

								Define next target:

								<select id="travelTarget">

										<option value="loc_white" selected disabled>The White Residence</option>
										<option value="loc_jesse">Jesse's House</option>
										<option value="loc_school">J. P. Wynne High School</option>
										<option value="loc_car">A1A Car Wash</option>
										<option value="loc_tuco">Tuco's Headquarters</option>
										<option value="loc_pest">Vamonos Pest Control</option>
										<option value="loc_schwartz">Schwartz Residence</option>
										<option value="loc_dea">DEA Field Office</option>
										<option value="loc_pollos">Los Pollos Hermanos</option>
										<option value="loc_gale">Gale's Apartment</option>
									</select>

								<button type="button" class="btn btn-xs" id="choose_city"> Travel</button>

Loan Shark

						<form class="form-inline" role="form">

								Ask the Loan Shark for $?

								<input type="number" class="form-control" id="getCash" placeholder="How much to borrow?">
								<button type="button" id="btn" class="btn btn-default">Borrow $</button>

						</form>

						<form class="form-inline" role="form" id="form_Loan_Payback">

								Pay off your debt?

								<input type="number" class="form-control" id="payDebt" placeholder="How much to pay back?">
								<button type="button" id="btn_payDebt" class="btn btn-default">Payback $</button>
								<button type="button" id="btn_payDebtMax" class="btn btn-default">Payback max $</button>
								<button type="button" id="btn_payDebtAll" class="btn btn-default">Payback all $</button>

						</form>

Bank

						Each transaction costs 0.01% - but at least 10$

						<form class="form-inline" role="form" id="form_Bank_deposit">

								Deposit money at bank (5% interest per Day)

								<input type="number" class="form-control" id="input_bank_depositValue" placeholder="How much to deposit?">
								<button type="button" id="btn_bank_depositMoney" class="btn btn-default">Deposit $</button>
								<button type="button" id="btn_bank_depositMoneyAll" class="btn btn-default">Deposit all $</button>

						</form>

						<form class="form-inline" role="form" id="form_Bank_payOut">

								Pay out

								<input type="number" class="form-control" id="input_bank_payOutValue" placeholder="How much to pay out?">
								<button type="button" id="btn_bank_payOutMoney" class="btn btn-default">Pay out $</button>
								<button type="button" id="btn_bank_payOutMoneyAll" class="btn btn-default">Pay out all $</button>

						</form>

					<form class="form-inline" role="form" id="form_Drugs_buy">

Buy Drugs

						What drug do you want to buy?
						<input type="checkbox" id="acid_tick" value="acid"> Acid
						<input type="checkbox" id="coke_tick" value="coke"> Coke

						How many drugs do you want to buy?

						<input type="number" class="form-control" id="buyDrugs" placeholder="How many units?">
						<button type="button" id="drugBtn" class="btn btn-default">Buy</button>

					</form>

					<form class="form-inline" role="form" id="form_Drugs_sell">

Sell Drugs

						What drug do you want to sell?
						<input type="checkbox" id="s_acid_tick" value="acid"> Acid
						<input type="checkbox" id="s_coke_tick" value="coke"> Coke

						How many drugs do you want to sell?

						<input type="number" class="form-control" id="sellDrugs" placeholder="How many units?">
						<button type="button" id="sellBtn" class="btn btn-default">Sell</button>

					</form>

 GAME OVER

Money

0

0

0

0

Luck

0

0

Result

0

Want more? If so start a new game.

 Local Highscore

30 Days

45 Days

90 Days

120 Days

 Setup

						<form action="#">
							<input type="text" id="fname" name="fname" placeholder="Playername" value="Heisenberg">

							<select id="gameLength">
								<option value="30" selected>30 Days</option>
								<option value="45">45 Days</option>
								<option value="90">90 Days</option>
								<option value="120">120 Days</option>
							</select>

							 Start
						</form>


text:
/* Gavaghan.Geodesy by Mike Gavaghan
 *
 * http://www.gavaghan.org/blog/free-source-code/geodesy-library-vincentys-formula/
 *
 * This code may be freely used and modified on any personal or professional
 * project.  It comes with no warranty.
 *
 * BitCoin tips graciously accepted at 1FB63FYQMy7hpC2ANVhZ5mSgAZEtY1aVLf
 */
using System;

namespace Gavaghan.Geodesy
{
  ///
  /// Encapsulation of an ellipsoid, and declaration of common reference ellipsoids.
  ///
  [Serializable]
  public struct Ellipsoid
  {
    /// Semi major axis (meters).
    private readonly double mSemiMajorAxis;

    /// Semi minor axis (meters).
    private readonly double mSemiMinorAxis;

    /// Flattening.
    private readonly double mFlattening;

    /// Inverse flattening.
    private readonly double mInverseFlattening;

    ///
    /// Construct a new Ellipsoid.  This is private to ensure the values are
    /// consistent (flattening = 1.0 / inverseFlattening).  Use the methods
    /// FromAAndInverseF() and FromAAndF() to create new instances.
    ///
    /// <param name="semiMajor"></param>
    /// <param name="semiMinor"></param>
    /// <param name="flattening"></param>
    /// <param name="inverseFlattening"></param>
    private Ellipsoid(double semiMajor, double semiMinor, double flattening, double inverseFlattening)
    {
      mSemiMajorAxis = semiMajor;
      mSemiMinorAxis = semiMinor;
      mFlattening = flattening;
      mInverseFlattening = inverseFlattening;
    }

    #region References Ellipsoids
    /// The WGS84 ellipsoid.
    static public readonly Ellipsoid WGS84 = FromAAndInverseF(6378137.0, 298.257223563);

    /// The GRS80 ellipsoid.
    static public readonly Ellipsoid GRS80 = FromAAndInverseF(6378137.0, 298.257222101);

    /// The GRS67 ellipsoid.
    static public readonly Ellipsoid GRS67 = FromAAndInverseF(6378160.0, 298.25);

    /// The ANS ellipsoid.
    static public readonly Ellipsoid ANS = FromAAndInverseF(6378160.0, 298.25);

    /// The WGS72 ellipsoid.
    static public readonly Ellipsoid WGS72 = FromAAndInverseF(6378135.0, 298.26);

    /// The Clarke1858 ellipsoid.
    static public readonly Ellipsoid Clarke1858 = FromAAndInverseF(6378293.645, 294.26);

    /// The Clarke1880 ellipsoid.
    static public readonly Ellipsoid Clarke1880 = FromAAndInverseF(6378249.145, 293.465);

    /// A spherical "ellipsoid".
    static public readonly Ellipsoid Sphere = FromAAndF(6371000, 0.0);
    #endregion

    ///
    /// Build an Ellipsoid from the semi major axis measurement and the inverse flattening.
    ///
    /// <param name="semiMajor">semi major axis (meters)</param>
    /// <param name="inverseFlattening"></param>
    /// <returns></returns>
    static public Ellipsoid FromAAndInverseF(double semiMajor, double inverseFlattening)
    {
      double f = 1.0 / inverseFlattening;
      double b = (1.0 - f) * semiMajor;

      return new Ellipsoid(semiMajor, b, f, inverseFlattening);
    }

    ///
    /// Build an Ellipsoid from the semi major axis measurement and the flattening.
    ///
    /// <param name="semiMajor">semi major axis (meters)</param>
    /// <param name="flattening"></param>
    /// <returns></returns>
    static public Ellipsoid FromAAndF(double semiMajor, double flattening)
    {
      double inverseF = 1.0 / flattening;
      double b = (1.0 - flattening) * semiMajor;

      return new Ellipsoid(semiMajor, b, flattening, inverseF);
    }

    /// Get semi major axis (meters).
    public double SemiMajorAxis
    {
      get { return mSemiMajorAxis; }
    }

    /// Get semi minor axis (meters).
    public double SemiMinorAxis
    {
      get { return mSemiMinorAxis; }
    }

    /// Get flattening.
    public double Flattening
    {
      get { return mFlattening; }
    }

    /// Get inverse flattening.
    public double InverseFlattening
    {
      get { return mInverseFlattening; }
    }
  }
}


text:
package org.fusesource.restygwt.client.basic;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.RestService;
import org.junit.Test;

import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;

public class ParameterizedTypeServiceInterfaces extends GWTTestCase
{
	@Override
	public String getModuleName()
	{
		return "org.fusesource.restygwt.ParameterizedTypeServiceInterface";
	}

	public static class Thing
	{
		public String name;
		public int shoeSize;
	}

	public static interface A<X> extends RestService
	{
		@GET
		@Produces("application/json")
		void getSomething(MethodCallback<X> callback);
	}

	@Path("/api/ptype/int")
	public static interface AOfInt extends A<Integer>
	{
	}

	@Path("/api/ptype/thing")
	public static interface AOfThing extends A<Thing>
	{
	}

	@Path("/api/ptype")
	public static interface SuperOfThing extends RestService
	{
		@Path("thing")
		public A<Thing> getThingInterface();

		@Path("int")
		public A<Integer> getIntInterface();
	}

	@Test
	public void testSimpleType()
	{
		AOfInt inter = GWT.create(AOfInt.class);
		inter.getSomething(new MethodCallback<Integer>()
		{
			@Override
			public void onFailure(Method method, Throwable exception)
			{
				fail(exception.getMessage());
			}

			@Override
			public void onSuccess(Method method, Integer response)
			{
				assertEquals(Integer.valueOf(123456), response);
				finishTest();
			}
		});
		delayTestFinish(10000);
	}

	@Test
	public void testComplexType()
	{
		AOfThing inter = GWT.create(AOfThing.class);
		inter.getSomething(new MethodCallback<Thing>()
		{
			@Override
			public void onFailure(Method method, Throwable exception)
			{
				fail(exception.getMessage());
			}

			@Override
			public void onSuccess(Method method, Thing value)
			{
				assertEquals("Fred Flintstone", value.name);
				assertEquals(12, value.shoeSize);
				finishTest();
			}
		});
		delayTestFinish(10000);
	}

	@Test
	public void testSubResource()
	{
		SuperOfThing inter = GWT.create(SuperOfThing.class);
		inter.getThingInterface().getSomething(new MethodCallback<Thing>()
		{
			@Override
			public void onFailure(Method method, Throwable exception)
			{
				fail(exception.getMessage());
			}

			@Override
			public void onSuccess(Method method, Thing value)
			{
				assertEquals("Fred Flintstone", value.name);
				assertEquals(12, value.shoeSize);
				finishTest();
			}
		});
		delayTestFinish(10000);
	}

	@Test
	public void testSubResource2()
	{
		SuperOfThing inter = GWT.create(SuperOfThing.class);
		inter.getIntInterface().getSomething(new MethodCallback<Integer>()
		{
			@Override
			public void onFailure(Method method, Throwable exception)
			{
				fail(exception.getMessage());
			}

			@Override
			public void onSuccess(Method method, Integer value)
			{
				assertEquals(Integer.valueOf(123456), value);
				finishTest();
			}
		});
		delayTestFinish(10000);
	}
}


text:
package org.apache.sysml.runtime.controlprogram.parfor;

import org.apache.sysml.hops.OptimizerUtils;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.caching.MatrixObject;
import org.apache.sysml.runtime.controlprogram.parfor.opt.OptimizerRuleBased;
import org.apache.sysml.runtime.controlprogram.parfor.stat.Timing;
import org.apache.sysml.runtime.matrix.MatrixCharacteristics;

public class ResultMergeLocalAutomatic extends ResultMerge
{

	private ResultMerge _rm = null;

	public ResultMergeLocalAutomatic( MatrixObject out, MatrixObject[] in, String outputFilename )
	{
		super( out, in, outputFilename );
	}

	@Override
	public MatrixObject executeSerialMerge()
		throws DMLRuntimeException
	{
		Timing time = new Timing(true);

		MatrixCharacteristics mc = _output.getMatrixCharacteristics();
		long rows = mc.getRows();
		long cols = mc.getCols();

		if( OptimizerRuleBased.isInMemoryResultMerge(rows, cols, OptimizerUtils.getLocalMemBudget()) )
			_rm = new ResultMergeLocalMemory( _output, _inputs, _outputFName );
		else
			_rm = new ResultMergeLocalFile( _output, _inputs, _outputFName );

		MatrixObject ret = _rm.executeSerialMerge();

		LOG.trace("Automatic result merge ("+_rm.getClass().getName()+") executed in "+time.stop()+"ms.");

		return ret;
	}

	@Override
	public MatrixObject executeParallelMerge(int par)
		throws DMLRuntimeException
	{
		MatrixCharacteristics mc = _output.getMatrixCharacteristics();
		long rows = mc.getRows();
		long cols = mc.getCols();

		if( OptimizerRuleBased.isInMemoryResultMerge(par * rows, cols, OptimizerUtils.getLocalMemBudget()) )
			_rm = new ResultMergeLocalMemory( _output, _inputs, _outputFName );
		else
			_rm = new ResultMergeLocalFile( _output, _inputs, _outputFName );

		return _rm.executeParallelMerge(par);
	}
}


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

<TITLE>
org.apache.fop.render.java2d Class Hierarchy (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.apache.fop.render.java2d

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.apache.fop.render.AbstractGenericSVGHandler (implements org.apache.fop.render.RendererContextConstants, org.apache.fop.render.XMLHandler)

org.apache.fop.render.java2d.Java2DSVGHandler (implements org.apache.fop.render.java2d.Java2DRendererContextConstants)

org.apache.fop.render.AbstractGraphics2DAdapter (implements org.apache.fop.render.Graphics2DAdapter)

org.apache.fop.render.java2d.Java2DGraphics2DAdapter

org.apache.fop.render.intermediate.AbstractIFPainter<T> (implements org.apache.fop.render.intermediate.IFPainter)

org.apache.fop.render.java2d.Java2DPainter

org.apache.fop.render.AbstractRenderer (implements org.apache.fop.fo.Constants, org.apache.fop.render.Renderer)

org.apache.fop.render.PrintRenderer

org.apache.fop.render.AbstractPathOrientedRenderer

org.apache.fop.render.java2d.Java2DRenderer (implements java.awt.print.Printable)

org.apache.fop.render.AbstractRendererConfigurator

org.apache.fop.render.PrintRendererConfigurator (implements org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator)

org.apache.fop.render.DefaultRendererConfigurator

org.apache.fop.render.java2d.Java2DRendererConfigurator

org.apache.fop.render.AbstractRenderingContext (implements org.apache.fop.render.RenderingContext)

org.apache.fop.render.java2d.Java2DRenderingContext

org.apache.fop.render.java2d.Base14FontCollection (implements org.apache.fop.fonts.FontCollection)

org.apache.fop.render.java2d.ConfiguredFontCollection (implements org.apache.fop.fonts.FontCollection)

org.apache.fop.render.java2d.InstalledFontCollection (implements org.apache.fop.fonts.FontCollection)

org.apache.fop.render.java2d.Java2DDocumentHandler (implements org.apache.fop.render.intermediate.IFDocumentHandler)

org.apache.fop.render.java2d.Java2DFontMetrics
org.apache.fop.render.java2d.Java2DGraphicsState
org.apache.fop.render.java2d.Java2DImageHandlerGraphics2D (implements org.apache.fop.render.ImageHandler)

org.apache.fop.render.java2d.Java2DImageHandlerRenderedImage (implements org.apache.fop.render.ImageHandler)

org.apache.fop.render.java2d.Java2DRendererConfig (implements org.apache.fop.render.RendererConfig)

org.apache.fop.render.java2d.Java2DRendererConfig.Java2DRendererConfigParser (implements org.apache.fop.render.RendererConfig.RendererConfigParser)

org.apache.fop.render.java2d.Java2DRenderingSettings
org.apache.fop.render.java2d.Java2DSVGHandler.Java2DInfo
org.apache.fop.render.java2d.Java2DUtil
org.apache.fop.fonts.Typeface (implements org.apache.fop.fonts.FontMetrics)

org.apache.fop.render.java2d.CustomFontMetricsMapper (implements org.apache.fop.render.java2d.FontMetricsMapper, org.apache.fop.complexscripts.fonts.Positionable, org.apache.fop.complexscripts.fonts.Substitutable)

org.apache.fop.render.java2d.SystemFontMetricsMapper (implements org.apache.fop.render.java2d.FontMetricsMapper)

Interface Hierarchy

org.apache.fop.fonts.FontMetrics

org.apache.fop.render.java2d.FontMetricsMapper

org.apache.fop.render.RendererContextConstants

org.apache.fop.render.java2d.Java2DRendererContextConstants

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

org.apache.fop.render.java2d.Java2DRendererOption (implements org.apache.fop.render.RendererConfigOption)

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
@implementation PHImageManager (CTAssetsPickerController)

+ (BOOL)ctassetsPickerNeedsiPadSupportSize {
    return [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPad"] && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad == false;
}

+ (CGSize)ctassetsPickerSizeForSize:(CGSize)size withMinimumDimension:(CGFloat)dimension {
    if (size.width >= dimension && size.height >= dimension) return size;
    if (size.width <= 0 || size.height <= 0) return size;

    CGFloat width, height;
    if (size.width < size.height) {
        width = 500;
        height = size.height/size.width*width;
    } else {
        height = 500;
        width = size.width/size.height*height;
    }
    return CGSizeMake(width, height);
}

- (PHImageRequestID)ctassetsPickerRequestImageForAsset:(PHAsset *)asset targetSize:(CGSize)targetSize contentMode:(PHImageContentMode)contentMode options:( PHImageRequestOptions *)options resultHandler:(void (^)(UIImage * result, NSDictionary * info))resultHandler {
    CGSize size = targetSize;
    if ([[self class] ctassetsPickerNeedsiPadSupportSize]) {
        size = [[self class] ctassetsPickerSizeForSize:targetSize withMinimumDimension:500];
    }
    return [self requestImageForAsset:asset targetSize:size contentMode:contentMode options:options resultHandler:resultHandler];
}

@end


text:
    {{$ctrl.i18n.MSG_RESOURCE_CARD_LIST_PAGINATION_ROW_SELECTOR_LABEL}}:

  <md-select ng-model="$ctrl.rowsLimit" class="kd-list-pagination-row-selector"
             md-selected-text="$ctrl.rowsLimit" ng-change="$ctrl.onRowsLimitUpdate()"
             aria-label="Rows per page">
    <md-option ng-repeat="rows in ::$ctrl.rowsLimitOptions" ng-value="{{rows}}">
      {{rows}}
    </md-option>
  </md-select>

  <dir-pagination-controls ng-if="::!$ctrl.serverSided" pagination-id="::$ctrl.paginationId"
                           class="kd-list-pagination-controls" boundary-links="true"
                           template-url="common/pagination/pagination.html">
  </dir-pagination-controls>
  <dir-pagination-controls ng-if="::$ctrl.serverSided" pagination-id="::$ctrl.paginationId"
                           class="kd-list-pagination-controls" boundary-links="true"
                           template-url="common/pagination/pagination.html"
                           on-page-change="$ctrl.pageChanged(newPageNumber)">
  </dir-pagination-controls>


text:
FROM anapsix/alpine-java:8
VOLUME /tmp
ADD eureka-service-0.0.1-SNAPSHOT.jar app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]


text:
from .client import ClearlyClient
from .display_modes import ModeTask, ModeWorker


text:
package edu.mayo.mprc.heme;

import edu.mayo.mprc.MprcException;
import edu.mayo.mprc.utilities.exceptions.ExceptionUtilities;

import java.io.*;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: m088378
 * Date: 7/21/14
 * Time: 11:56 AM
 * This class generates the serialized object of the fasta definitons look up table.
 * Generates a HashMap: key=> Accession Id <String> & value => Definition Title <String>
 * http://www.tutorialspoint.com/java/java_serialization.htm
 * Should be used as an optional class, to generate LookUp object when renewing DB or orig is missing
 */
public class SerializeFastaDB {
	private static final Pattern MASS_PATTERN = Pattern.compile(".+ (\\d+\\.\\d+)?"); //last double on line
	private static final Pattern SWISSPROT_PATTERN = Pattern.compile("^sp\\|[^|]*\\|(.*)$");

	public static void generateDesc(File inFasta, String outObjPath) {
		try {
			HashMap<String, String> cache = new HashMap<String, String>();
			String strRead;
			BufferedReader readbuffer = new BufferedReader(new FileReader(inFasta));
			while ((strRead = readbuffer.readLine()) != null) {
				if (strRead.charAt(0) == '>') {
					String[] definitionArr = strRead.split("\\s+");
					final String key = definitionArr[0].substring(1);
					cache.put(key, strRead);
					final Matcher matcher = SWISSPROT_PATTERN.matcher(key);
					if (matcher.matches()) {
						// Also store the key without the sp|whatever| part for the old, messy databases
						cache.put(matcher.group(1), strRead);
					}
				}
			}

			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outObjPath));
			out.writeObject(cache);
			out.close();

		} catch (IOException e) {
			throw new MprcException("Could not generate description cache for " + inFasta.getAbsolutePath() + " into " + outObjPath, e);
		}
	}

	public static void generateSequence(File inFasta, String outObjPath) {
		try {
			HashMap<String, String> cache = new HashMap<String, String>();
			String strRead;
			boolean isMut = false;
			String lastAcc = "";
			BufferedReader readbuffer = new BufferedReader(new FileReader(inFasta));
			while ((strRead = readbuffer.readLine()) != null) {
				if (strRead.charAt(0) == '>') {
					Matcher matcher = MASS_PATTERN.matcher(strRead);
					if (matcher.matches()) {
						String[] definitionArr = strRead.split("\\s+");
						lastAcc = definitionArr[0].substring(1);
						isMut = true;
					} else {
						isMut = false;
					}
				} else if (isMut) {
					cache.put(lastAcc, strRead);
				}
			}

			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outObjPath));
			out.writeObject(cache);
			out.close();

		} catch (IOException e) {
			throw new MprcException("Could not serialize fasta file " + inFasta.getAbsolutePath() + " to object storage " + outObjPath, e);
		}
	}

	public static HashMap<String, String> load(String path) {
		HashMap<String, String> loadedObj = null;
		try {
			final ObjectInputStream input = new ObjectInputStream(new FileInputStream(path));
			final Object o = input.readObject();
			if (o instanceof HashMap) {
				loadedObj = (HashMap<String, String>) o;
			} else {
				ExceptionUtilities.throwCastException(o, HashMap.class);
			}
		} catch (Exception e) {
			throw new MprcException("Could not load cached fasta data from " + path, e);
		}
		return loadedObj;
	}

}


text:
<?php

namespace OlajosCs\QueryBuilder\SQLite\Clauses;

use OlajosCs\QueryBuilder\Common\Clauses\WhereElement as WhereElementCommon;

/**
 * Class WhereElement
 *
 * Represents a where statement
 */
class WhereElement extends WhereElementCommon
{
}


text:
namespace cc {

OverlayCandidate::OverlayCandidate()
    : transform(gfx::OVERLAY_TRANSFORM_NONE),
      format(RGBA_8888),
      uv_rect(0.f, 0.f, 1.f, 1.f),
      resource_id(0),
      plane_z_order(0),
      overlay_handled(false) {}

OverlayCandidate::~OverlayCandidate() {}

// static
gfx::OverlayTransform OverlayCandidate::GetOverlayTransform(
    const gfx::Transform& quad_transform,
    bool flipped) {
  if (!quad_transform.IsIdentityOrTranslation())
    return gfx::OVERLAY_TRANSFORM_INVALID;

  return flipped ? gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL
                 : gfx::OVERLAY_TRANSFORM_NONE;
}

// static
gfx::Rect OverlayCandidate::GetOverlayRect(const gfx::Transform& quad_transform,
                                           const gfx::Rect& rect) {
  DCHECK(quad_transform.IsIdentityOrTranslation());

  gfx::RectF float_rect(rect);
  quad_transform.TransformRect(&float_rect);
  return gfx::ToNearestRect(float_rect);
}

}  // namespace cc


text:
#if defined(__MWERKS__) && !defined(__private_extern__)
#define __private_extern__ __declspec(private_extern)
#endif

/*
 * Global types, variables and routines declared in the file arm_reloc.c.
 *
 * The following include file need to be included before this file:
 * #include <reloc.h>
 * #include "section.h"
 */
__private_extern__ void arm_reloc(
    char *contents,
    struct relocation_info *relocs,
    struct section_map *section_map,
    struct live_refs *refs,
    unsigned long reloc_index);


text:
@(title: String)

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@title</title>

    <link href="@routes.Assets.at("bootstrap/css/bootstrap.min.css")" rel="stylesheet">
    <link href="@routes.Assets.at("stylesheets/fonts.css")" rel="stylesheet">

    <link rel="stylesheet" href="@routes.Assets.at("stylesheets/main.css")">

          <input id="search.input" type="search" class="search-bar" placeholder="Search here..." autofocus size="16" ng-model="query" ng-change="lookup()"/>

          <shrt></shrt>


text:
namespace rocksdb {
struct ColumnFamilyMetaData;
struct LevelMetaData;
struct SstFileMetaData;

// The metadata that describes a column family.
struct ColumnFamilyMetaData {
  ColumnFamilyMetaData() : size(0), name("") {}
  ColumnFamilyMetaData(const std::string& _name, uint64_t _size,
                       const std::vector<LevelMetaData>&& _levels) :
      size(_size), name(_name), levels(_levels) {}

  // The size of this column family in bytes, which is equal to the sum of
  // the file size of its "levels".
  uint64_t size;
  // The number of files in this column family.
  size_t file_count;
  // The name of the column family.
  std::string name;
  // The metadata of all levels in this column family.
  std::vector<LevelMetaData> levels;
};

// The metadata that describes a level.
struct LevelMetaData {
  LevelMetaData(int _level, uint64_t _size,
                const std::vector<SstFileMetaData>&& _files) :
      level(_level), size(_size),
      files(_files) {}

  // The level which this meta data describes.
  const int level;
  // The size of this level in bytes, which is equal to the sum of
  // the file size of its "files".
  const uint64_t size;
  // The metadata of all sst files in this level.
  const std::vector<SstFileMetaData> files;
};

// The metadata that describes a SST file.
struct SstFileMetaData {
  SstFileMetaData() {}
  SstFileMetaData(const std::string& _file_name,
                  const std::string& _path, uint64_t _size,
                  SequenceNumber _smallest_seqno,
                  SequenceNumber _largest_seqno,
                  const std::string& _smallestkey,
                  const std::string& _largestkey,
                  bool _being_compacted) :
    size(_size), name(_file_name),
    db_path(_path), smallest_seqno(_smallest_seqno), largest_seqno(_largest_seqno),
    smallestkey(_smallestkey), largestkey(_largestkey),
    being_compacted(_being_compacted) {}

  // File size in bytes.
  uint64_t size;
  // The name of the file.
  std::string name;
  // The full path where the file locates.
  std::string db_path;

  SequenceNumber smallest_seqno;  // Smallest sequence number in file.
  SequenceNumber largest_seqno;   // Largest sequence number in file.
  std::string smallestkey;     // Smallest user defined key in the file.
  std::string largestkey;      // Largest user defined key in the file.
  bool being_compacted;  // true if the file is currently being compacted.
};

// The full set of metadata associated with each SST file.
struct LiveFileMetaData : SstFileMetaData {
  std::string column_family_name;  // Name of the column family
  int level;               // Level at which this file resides.
};

}  // namespace rocksdb


text:
'use strict';
const fs = require('fs');
const path = require('path');
const util = require('util');
const got = require('got');
const unzip = require('unzip');
const {JSDOM} = require('jsdom');
const pathEnsure = require('path-ensure');

const cwd = path.dirname(__dirname);
const paths = pathEnsure({cwd});
const fsP = {
	writeFile: util.promisify(fs.writeFile),
	readFile: util.promisify(fs.readFile)
};

const KEMENDAGRI_DATA_LINK = 'http://www.kemendagri.go.id/pages/data-wilayah';

/**
 * Download all PDF files
 *
 * link: http://www.kemendagri.go.id/pages/data-wilayah
 */

async function getHtml() {
	const filepath = await paths('.tmp', 'html', 'file.html');
	const isCached = fs.existsSync(filepath);

	if (isCached) {
		return fsP.readFile(filepath, 'utf8');
	}

	try {
		const response = await got(KEMENDAGRI_DATA_LINK);

		await fsP.writeFile(filepath, response.body, 'utf8');

		return getHtml();
	} catch (err) {
		if (err.response.body || err.response) {
			return Promise.reject(err.response.body || err.response);
		}

		return Promise.reject(err);
	}
}

function downloadFromKemendagri(url) {
	const opts = {url};

	const urlFilter = /\.(pdf|zip)$/g;

	if (!opts.url || !urlFilter.test(opts.url)) {
		return;
	}

	const filename = path.basename(opts.url);

	paths('.tmp', 'pdf', filename).then(filepath => {
		if (filepath.endsWith('.pdf')) {
			got.stream(opts.url)
				.pipe(fs.createWriteStream(filepath));
		}

		if (filepath.endsWith('.zip')) {
			got.stream(opts.url)
				.pipe(unzip.Extract({path: path.dirname(filepath)})); // eslint-disable-line new-cap
		}
	});
}

getHtml()
	.then(body => {
		const {window} = new JSDOM(body);
		const selector = window.document.querySelector('ol').getElementsByTagName('a');
		const link = {
			googleDrive: {},
			kemendagri: {}
		};

		for (const a of selector) {
			if (a.href.includes('drive.google.com')) {
				link.googleDrive[a.textContent] = a.href;
			} else if (a.href.includes('kemendagri.go.id')) {
				link.kemendagri[a.textContent] = a.href;
			}
		}

		Object.values(link.kemendagri).forEach(downloadFromKemendagri);

		console.log();
		console.log('Download manualy from google drive.\n');
		console.log(JSON.stringify(link.googleDrive, null, 4));
		console.log();
	})
	.catch(err => {
		return console.error(err);
	});


text:
[[ -n "$(pgrep -f $(command -v startx))" ]] && echo "INFO: startx is already running" && exit 0

sudo touch /var/lock/console.lock
sudo mkdir -p /var/run/console
sudo touch /var/run/console/${USER}

# Set default session for user.
[[ ! -f ${HOME}/.xinitrc ]] && echo "xfce4-session" > ${HOME}/.xinitrc

nohup startx >${HOME}/.startx.log 2>&1 &


text:
package com.lyloou.android.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Handler;
import android.util.DisplayMetrics;

import com.lyloou.android.app.LouApp;
import com.lyloou.android.constants.Constant;
import com.lyloou.android.lou.activity.ListActivity;

import java.util.Locale;

public class LanguageUtil {
    // 语言;
    public static final String LAN_EN = "EN";
    public static final String LAN_FR = "FR";
    public static final String LAN_DE = "DE";
    public static final String LAN_NL = "NL";

    public static void switchTo(Context context, Locale locale) {
        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        if (!config.locale.equals(locale)) {
            config.locale = locale;
            DisplayMetrics dm = resources.getDisplayMetrics();
            resources.updateConfiguration(config, dm);
        }
    }

    public static void switchTo(Context context, String language) {
        Locale locale = new Locale(language);
        switch (language) {
            case LAN_EN:
                locale = Locale.ENGLISH;
                break;
            case LAN_DE:
                locale = Locale.GERMANY;
                break;
            case LAN_FR:
                locale = Locale.FRANCE;
                break;
            case LAN_NL:
                locale = new Locale("nl", "NL");
                break;
        }
        switchTo(context, locale);
    }

    // ~~~ 以下属于本应用特有
    public static void switchTo(final Context context, String language, boolean needRestart, SharedPreferencesUtil spu) {
        String currentLanguage = spu.getLanguage();

        // 如果要设置的语言和当前语言一样,则什么都不做
        if (currentLanguage.equals(language)) {
            return;
        }
        spu.saveLanguage(language);
        if (needRestart) {
            if (context instanceof Activity) {
                ToastUtil.show(context, "Please wait...");
            }

            // 关闭所有界面,并重新打开 MainActivity
            LouApp.finishAll();
            // 需要延时打开,否则会导致 服务中的 conn leak;
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    Intent intent = new Intent(context, ListActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(intent);
                }
            }, 3000);
        } else {
            switchTo(context, language);
        }
    }

}


text:
@interface BIColorAlertView : UIView
@property (nonatomic) float scale; // rate the situation from 0 to 10; 0 = worst; 10 = best
+ (UIColor *)colorForScale:(float)scale;
@end


text:
export * from './plan.model';
export * from './product.model';
export * from './old-ingredient.model';
export * from './ingredient.model';
export * from './old-meal.model';
export * from './meal.model';
export * from './custom-meal.model';
export * from './user.model';
export * from './serving.model';


text:
const typescript = require("rollup-plugin-typescript2");
const sourcemap = require("rollup-plugin-sourcemaps");
const path = require("path");
const process = require("process");

const pkg = {
  path: process.cwd(),
  meta: require(path.join(process.cwd(), "package.json"))
};

if (!pkg.meta.main) {
  throw new Error(
    'Missing "main" key in package.json - cannot compile CommonJS module.'
  );
}

if (!pkg.meta.module) {
  throw new Error(
    'Missing "module" key in package.json - cannot compile ES6 module.'
  );
}

export default {
  input: pkg.path + "/src/index.ts",
  output: [
    {
      file: pkg.path + "/" + pkg.meta.main,
      format: "cjs"
    },
    {
      file: pkg.path + "/" + pkg.meta.module,
      format: "esm"
    }
  ],
  external: Object.keys(
    Object.assign(pkg.meta.peerDependencies || {}, pkg.meta.dependencies || {})
  ),
  plugins: [
    typescript({
      clean: true,
      tsconfigOverride: {
        include: ["./src/**/*"],
        exclude: ["node_modules", "./test/**/*"]
      }
    }),
    sourcemap()
  ]
};


text:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationTypeName="EmployeeType" ApplicationTypeVersion="1.0.0" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <Parameters>
    <Parameter Name="Service_MinReplicaSetSize" DefaultValue="3" />
    <Parameter Name="Service_PartitionCount" DefaultValue="1" />
    <Parameter Name="Service_TargetReplicaSetSize" DefaultValue="3" />
  </Parameters>
  <!-- 从 ServicePackage 导入 ServiceManifest。ServiceManifestName 和 ServiceManifestVersion
       应与 ServiceManifest.xml 文件中定义的 ServiceManifest 元素的
       名称属性和版本属性相匹配。 -->
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="Employee.ServicePkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <DefaultServices>
    <!-- 在创建此应用程序类型时,以下部分
         将创建服务类型的实例。你还可以使用 ServiceFabric PowerShell 模块创建
          一个或多个服务类型实例。

         以下属性 ServiceTypeName 必须与导入的 ServiceManifest.xml 文件中所定义的名称相匹配。 -->
    <Service Name="Service">
      <StatefulService ServiceTypeName="ServiceType" TargetReplicaSetSize="[Service_TargetReplicaSetSize]" MinReplicaSetSize="[Service_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[Service_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
      </StatefulService>
    </Service>
  </DefaultServices>
</ApplicationManifest>


text:
On this page, you will find sample source codes which show you how to handle a complex task, such as, PDF to CSV API in C#. PDF to CSV API in C# can be applied with ByteScout Cloud API Server. ByteScout Cloud API Server is API server that is ready to use and can be installed and deployed in less than 30 minutes on your own Windows server or server in a cloud. It can save data and files on your local server-based file storage or in Amazon AWS S3 storage. Data is processed solely on the API server and is powered by ByteScout engine, no cloud services or Internet connection is required for data processing..

If you want to speed up the application's code writing then C# code samples for C# developers help to implement using ByteScout Cloud API Server. For implementation of this functionality, please copy and paste the code below into your app using code editor. Then compile and run your app. Want to see how it works with your data then code testing will allow the function to be tested and work properly.

Free! Free! Free! ByteScout free trial version is available for FREE download from our website. Programming tutorials along with source code samples are assembled.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Cloud%20API%20Server%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Cloud%20API%20Server%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****ByteScoutWebApiExample.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{1E1C2C34-017E-4605-AE2B-55EA3313BE51}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>ByteScoutWebApiExample</RootNamespace>
    <AssemblyName>ByteScoutWebApiExample</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>packages\Newtonsoft.Json.10.0.3\lib\net40\Newtonsoft.Json.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="packages.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****ByteScoutWebApiExample.sln:**

```

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.40629.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ByteScoutWebApiExample", "ByteScoutWebApiExample.csproj", "{1E1C2C34-017E-4605-AE2B-55EA3313BE51}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{1E1C2C34-017E-4605-AE2B-55EA3313BE51}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal

```

<!-- code block end -->

<!-- code block begin -->

##### ****Program.cs:**

```
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Threading;

// Cloud API asynchronous "PDF To CSV" job example.
// Allows to avoid timeout errors when processing huge or scanned PDF documents.

// Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
// If it's not then please replace this with with your hosting url.
namespace ByteScoutWebApiExample
{
	class Program
	{
		// Direct URL of source PDF file.
		const string SourceFileUrl = "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-to-csv/sample.pdf";
		// Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
		const string Pages = "";
		// PDF document password. Leave empty for unprotected documents.
		const string Password = "";
		// Destination CSV file name
		const string DestinationFile = @".\result.csv";
		// (!) Make asynchronous job
		const bool Async = true;

		static void Main(string[] args)
		{
			// Create standard .NET web client instance
			WebClient webClient = new WebClient();

			// Prepare URL for `PDF To CSV` API call
			string query = Uri.EscapeUriString(string.Format(
                "https://localhost/pdf/convert/to/csv?name={0}&password={1}&pages={2}&url={3}&async={4}",
				Path.GetFileName(DestinationFile),
				Password,
				Pages,
				SourceFileUrl,
				Async));

			try
			{
				// Execute request
				string response = webClient.DownloadString(query);

				// Parse JSON response
				JObject json = JObject.Parse(response);

                if (json["status"].ToString() != "error")
                {
					// Asynchronous job ID
					string jobId = json["jobId"].ToString();
					// URL of generated CSV file that will available after the job completion
					string resultFileUrl = json["url"].ToString();

					// Check the job status in a loop.
					// If you don't want to pause the main thread you can rework the code
					// to use a separate thread for the status checking and completion.
					do
					{
						string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success".

						// Display timestamp and status (for demo purposes)
						Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status);

						if (status == "success")
						{
							// Download CSV file
							webClient.DownloadFile(resultFileUrl, DestinationFile);

							Console.WriteLine("Generated CSV file saved as \"{0}\" file.", DestinationFile);
							break;
						}
						else if (status == "working")
						{
							// Pause for a few seconds
							Thread.Sleep(3000);
						}
						else
						{
							Console.WriteLine(status);
							break;
						}
					}
					while (true);
				}
				else
				{
					Console.WriteLine(json["message"].ToString());
				}
			}
			catch (WebException e)
			{
				Console.WriteLine(e.ToString());
			}

			webClient.Dispose();

			Console.WriteLine();
			Console.WriteLine("Press any key...");
			Console.ReadKey();
		}

		static string CheckJobStatus(string jobId)
		{
			using (WebClient webClient = new WebClient())
			{
				string url = "https://localhost/job/check?jobid=" + jobId;

				string response = webClient.DownloadString(url);
				JObject json = JObject.Parse(response);

				return Convert.ToString(json["status"]);
			}
		}
	}
}

```

<!-- code block end -->

<!-- code block begin -->

##### ****packages.config:**

```
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net40" />
</packages>
```

<!-- code block end -->


text:
package org.bouncycastle.pqc.legacy.crypto.qtesla;

import org.bouncycastle.crypto.digests.CSHAKEDigest;
import org.bouncycastle.crypto.digests.SHAKEDigest;

class HashUtils
{

    static final int SECURE_HASH_ALGORITHM_KECCAK_128_RATE = 168;
    static final int SECURE_HASH_ALGORITHM_KECCAK_256_RATE = 136;

    /***************************************************************************************************************************************************************
     * Description:    The Secure-Hash-Algorithm-3 Extendable-Output Function That Generally Supports 128 Bits of Security Strength, If the Output is Sufficiently Long
     ***************************************************************************************************************************************************************/
    static void secureHashAlgorithmKECCAK128(byte[] output, int outputOffset, int outputLength, byte[] input, int inputOffset, int inputLength)
    {
        SHAKEDigest dig = new SHAKEDigest(128);
        dig.update(input, inputOffset, inputLength);

        dig.doFinal(output, outputOffset, outputLength);
    }

    /***************************************************************************************************************************************************************
     * Description:    The Secure-Hash-Algorithm-3 Extendable-Output Function That Generally Supports 256 Bits of Security Strength, If the Output is Sufficiently Long
     ***************************************************************************************************************************************************************/
    static void secureHashAlgorithmKECCAK256(byte[] output, int outputOffset, int outputLength, byte[] input, int inputOffset, int inputLength)
    {
        SHAKEDigest dig = new SHAKEDigest(256);
        dig.update(input, inputOffset, inputLength);

        dig.doFinal(output, outputOffset, outputLength);
    }

    /* Customizable Secure Hash Algorithm KECCAK 128 / Customizable Secure Hash Algorithm KECCAK 256 */

    static void customizableSecureHashAlgorithmKECCAK128Simple(byte[] output, int outputOffset, int outputLength, short continuousTimeStochasticModelling, byte[] input, int inputOffset, int inputLength)
    {
        CSHAKEDigest dig = new CSHAKEDigest(128, null, new byte[]{(byte)continuousTimeStochasticModelling, (byte)(continuousTimeStochasticModelling >> 8)});
        dig.update(input, inputOffset, inputLength);

        dig.doFinal(output, outputOffset, outputLength);
    }

    static void customizableSecureHashAlgorithmKECCAK256Simple(byte[] output, int outputOffset, int outputLength, short continuousTimeStochasticModelling, byte[] input, int inputOffset, int inputLength)
    {
        CSHAKEDigest dig = new CSHAKEDigest(256, null, new byte[]{(byte)continuousTimeStochasticModelling, (byte)(continuousTimeStochasticModelling >> 8)});
        dig.update(input, inputOffset, inputLength);

        dig.doFinal(output, outputOffset, outputLength);
    }
}


text:
import json
from NearBeach.models import (
    kanban_column,
    kanban_level,
    object_assignment,
    group,
    user_group,
)
from NearBeach.views.tools.internal_functions import (
    kanban_card,
    kanban_board,
    project,
    requirement,
    task,
)
from NearBeach.decorators.check_user_permissions import (
    check_user_permissions,
    check_user_kanban_permissions,
)
from NearBeach.forms import (
    AddKanbanLinkForm,
    KanbanCardArchiveForm,
    CheckKanbanBoardName,
    MoveKanbanCardForm,
    NewKanbanCardForm,
    NewKanbanForm,
    KanbanCardForm,
)
from django.contrib.auth.decorators import login_required
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Max, Q
from django.http import HttpResponse, HttpResponseBadRequest
from django.template import loader
from django.urls import reverse
from django.views.decorators.http import require_http_methods
from django.views.decorators.cache import never_cache

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_permissions(min_permission_level=2, object_lookup="kanban_board_id")
def add_kanban_link(request, kanban_board_id, object_lookup, *args, **kwargs):
    """
    :param request:
    :param destination:
    :param location_id:
    :return:
    """
    # CHECK USER PERMISSION LATER

    # Get form data and check
    form = AddKanbanLinkForm(request.POST)
    if not form.is_valid():
        return HttpResponseBadRequest(form.errors)

    # Get the newest card number id
    kanban_card_sort_number = get_max_sort_id(kanban_board_id, form)

    # Submit the kanban board link
    kanban_card_submit = kanban_card(
        change_user=request.user,
        kanban_board_id=kanban_board_id,
        kanban_column=form.cleaned_data["kanban_column"],
        kanban_level=form.cleaned_data["kanban_level"],
        kanban_card_sort_number=kanban_card_sort_number + 1,
    )

    # Check the data
    if object_lookup == "project":
        kanban_card_submit.project = form.cleaned_data[object_lookup]
    elif object_lookup == "task":
        kanban_card_submit.task = form.cleaned_data[object_lookup]
    elif object_lookup == "requirement":
        kanban_card_submit.requirement = form.cleaned_data[object_lookup]

    kanban_card_submit.kanban_card_text = form.cleaned_data[object_lookup]

    # Save the data
    kanban_card_submit.save()

    # Send back the data we just created
    kanban_card_results = kanban_card.objects.get(
        kanban_card_id=kanban_card_submit.kanban_card_id
    )

    return HttpResponse(
        serializers.serialize("json", [kanban_card_results]),
        content_type="application/json",
    )

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_permissions(min_permission_level=2, object_lookup="kanban_board_id")
def archive_kanban_cards(request, *args, **kwargs):
    """Archive the kanban cards."""
    form = KanbanCardArchiveForm(request.POST)
    if not form.is_valid():
        return HttpResponseBadRequest(form.errors)

    # Get all cards from POST
    card_list = request.POST.getlist("kanban_card_id")

    # Update all cards
    kanban_card.objects.filter(kanban_card_id__in=card_list,).update(
        is_archived=True,
    )

    # Return success
    return HttpResponse("")

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_permissions(min_permission_level=3, object_lookup="kanban_board_id")
def check_kanban_board_name(request, *args, **kwargs):
    """
    The following will get a list of all kanban boards with the same name. The idea is that each kanban board should
    have a unique name.
    :param request:
    :return:
    """
    # Get the form data
    form = CheckKanbanBoardName(request.POST)
    if not form.is_valid():
        return HttpResponseBadRequest(form.errors)

    kanban_board_results = kanban_board.objects.filter(
        is_deleted=False,
        kanban_board_name=form.cleaned_data["kanban_board_name"],
    )

    # Send back data
    return HttpResponse(
        serializers.serialize("json", kanban_board_results),
        content_type="application/json",
    )

# Internal function
def get_context(kanban_board_id):
    # Get the kanban data
    kanban_board_results = kanban_board.objects.get(kanban_board_id=kanban_board_id)

    column_results = kanban_column.objects.filter(
        is_deleted=False,
        kanban_board_id=kanban_board_id,
    ).order_by(
        "kanban_column_sort_number",
    )

    level_results = kanban_level.objects.filter(
        is_deleted=False,
        kanban_board_id=kanban_board_id,
    ).order_by(
        "kanban_level_sort_number",
    )

    # Context
    c = {
        "kanban_board_results": serializers.serialize("json", [kanban_board_results]),
        "column_results": serializers.serialize("json", column_results),
        "kanban_board_id": kanban_board_id,
        "level_results": serializers.serialize("json", level_results),
        "nearbeach_title": f"Kanban Information {kanban_board_id}",
    }

    return c

# Internal function
def get_max_sort_id(kanban_board_id, form):
    """Get the newest card number id"""
    kanban_card_sort_number = kanban_card.objects.filter(
        is_deleted=False,
        kanban_board_id=kanban_board_id,
        kanban_column=form.cleaned_data["kanban_column"],
        kanban_level=form.cleaned_data["kanban_level"],
    ).aggregate(Max("kanban_card_sort_number"))

    # If the card is new in that particular column & row - then we need to implement a sort number of 0
    if kanban_card_sort_number["kanban_card_sort_number__max"] is None:
        kanban_card_sort_number["kanban_card_sort_number__max"] = 0

    return kanban_card_sort_number["kanban_card_sort_number__max"]

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_permissions(min_permission_level=3, object_lookup="kanban_board_id")
def kanban_close_board(request, kanban_board_id, *args, **kwargs):
    """Close the kanban board"""
    # Close the kanban board
    kanban_update = kanban_board.objects.get(kanban_board_id=kanban_board_id)
    kanban_update.kanban_board_status = "Closed"
    kanban_update.save()

    # Return Success
    return HttpResponse("")

@never_cache
@login_required(login_url="login", redirect_field_name="")
@check_user_permissions(min_permission_level=3, object_lookup="kanban_board_id")
def kanban_edit_board(request, kanban_board_id, *args, **kwargs):
    """Edit the permissions of the kanban board"""
    user_level = kwargs["user_level"]

    # Get group results
    group_results = object_assignment.objects.filter(
        is_deleted=False,
        group_id__isnull=False,
        kanban_board_id=kanban_board_id,
    )

    # Get context
    c = get_context(kanban_board_id)
    c["user_level"] = user_level
    c["group_results"] = serializers.serialize("json", group_results)

    # Get the template
    t = loader.get_template("NearBeach/kanban/kanban_edit_board.html")

    # Get the context
    return HttpResponse(t.render(c, request))

@never_cache
@login_required(login_url="login", redirect_field_name="")
@check_user_permissions(min_permission_level=1, object_lookup="kanban_board_id")
def kanban_information(request, kanban_board_id, *args, **kwargs):
    """
    :param request:
    :param kanban_board_id:
    :return:
    """
    user_level = kwargs["user_level"]

    # Get kanban card results
    kanban_card_results = kanban_card.objects.filter(
        is_archived=False,
        is_deleted=False,
        kanban_board_id=kanban_board_id,
    ).order_by("kanban_card_sort_number")

    # Get context
    c = get_context(kanban_board_id)
    c["user_level"] = user_level
    c["kanban_card_results"] = serializers.serialize("json", kanban_card_results)

    # Get the template
    t = loader.get_template("NearBeach/kanban/kanban_information.html")

    return HttpResponse(t.render(c, request))

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_permissions(min_permission_level=1, object_lookup="kanban_board_id")
def kanban_link_list(request, kanban_board_id, object_lookup, *args, **kwargs):
    """
    :param request:
    :param kanban_board_id:
    :return:
    """
    # CHECK USER PERMISSIONS

    # Get a list of all existing cards
    existing_objects = kanban_card.objects.filter(
        is_deleted=False,
        kanban_board_id=kanban_board_id,
    )

    # Get the results we require
    if object_lookup == "Project":
        object_results = project.objects.filter(is_deleted=False,).exclude(
            project_id__in=existing_objects.exclude(project_id__isnull=True).values(
                "project_id"
            )
        )
    elif object_lookup == "Requirement":
        object_results = requirement.objects.filter(is_deleted=False,).exclude(
            requirement_id__in=existing_objects.exclude(
                requirement_id__isnull=True
            ).values("requirement_id")
        )
    elif object_lookup == "Task":
        object_results = task.objects.filter(is_deleted=False,).exclude(
            task_id__in=existing_objects.exclude(
                task_id__isnull=True,
            ).values("task_id")
        )
    else:
        return HttpResponseBadRequest(
            "Sorry - there was an issue with your object lookup"
        )

    return HttpResponse(
        serializers.serialize("json", object_results), content_type="application/json"
    )

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_kanban_permissions(min_permission_level=2)
def move_kanban_card(request, kanban_card_id, *args, **kwargs):
    """
    :param request:
    :param kanban_board_id:
    :return:
    """
    kanban_card_update = kanban_card.objects.get(kanban_card_id=kanban_card_id)

    # Get the form data
    form = MoveKanbanCardForm(request.POST)
    if not form.is_valid():
        return HttpResponseBadRequest(form.errors)

    # Update the card data
    kanban_card_update.kanban_column = form.cleaned_data["new_card_column"]
    kanban_card_update.kanban_level = form.cleaned_data["new_card_level"]
    kanban_card_update.kanban_card_sort_number = form.cleaned_data[
        "new_card_sort_number"
    ]
    kanban_card_update.save()

    """
    Update the sort order
    ~~~~~~~~~~~~~~~~~~~~~

    If both the old and new level/column destination are the same, we take the difference between the two values
    Otherwise we apply two sort orders to both the old and the new
    """
    if (
        form.cleaned_data["new_card_column"] == form.cleaned_data["old_card_column"]
        and form.cleaned_data["new_card_level"] == form.cleaned_data["old_card_level"]
    ):
        # The card has stayed in the same column/level
        resort_array = kanban_card.objects.filter(
            Q(
                Q(
                    is_deleted=False,
                    kanban_card_sort_number__range=[
                        form.cleaned_data["old_card_sort_number"],
                        form.cleaned_data["new_card_sort_number"],
                    ],
                )
                | Q(
                    is_deleted=False,
                    kanban_card_sort_number__range=[
                        form.cleaned_data["new_card_sort_number"],
                        form.cleaned_data["old_card_sort_number"],
                    ],
                )
            )
            & ~Q(
                kanban_card_id=kanban_card_id,
            )
        ).order_by("kanban_card_sort_number")

        # Determine if we are using a positive or negative delta - using math
        delta = (-1) * (
            form.cleaned_data["new_card_sort_number"]
            > form.cleaned_data["old_card_sort_number"]
        ) + (
            form.cleaned_data["new_card_sort_number"]
            < form.cleaned_data["old_card_sort_number"]
        )

        # Send the data away to get manipulated
        update_sort_number(resort_array, delta)
    else:
        """
        The cards have been moved outside the origianl column/level. We need to update both the old and new location's
        sort orders.

        The old location will have a delta -1, to move the higher cards into the place left by the card

        The new location will have a delta +1, to move the higher cards away, to create a space for the card
        """
        old_resort_array = kanban_card.objects.filter(
            Q(
                is_deleted=False,
                kanban_card_sort_number__gte=form.cleaned_data["old_card_sort_number"],
            )
            & ~Q(
                kanban_card_id=kanban_card_id,
            )
        ).order_by("kanban_card_sort_number")

        new_resort_array = kanban_card.objects.filter(
            Q(
                is_deleted=False,
                kanban_card_sort_number__gte=form.cleaned_data["new_card_sort_number"],
            )
            & ~Q(
                kanban_card_id=kanban_card_id,
            )
        ).order_by("kanban_card_sort_number")

        update_sort_number(old_resort_array, -1)
        update_sort_number(new_resort_array, 1)

    return HttpResponse("")

@login_required(login_url="login", redirect_field_name="")
@check_user_permissions(min_permission_level=3, object_lookup="kanban_board_id")
def new_kanban(request, *args, **kwargs):
    """
    :param request:
    :return:
    """
    # Check user permissions

    # Get data
    group_results = group.objects.filter(
        is_deleted=False,
    )

    # Get list of user groups
    user_group_results = (
        user_group.objects.filter(
            is_deleted=False,
            username=request.user,
        )
        .values(
            "group_id",
            "group__group_name",
        )
        .distinct()
    )

    # Get tempalte
    t = loader.get_template("NearBeach/kanban/new_kanban.html")

    # Context
    c = {
        "group_results": serializers.serialize("json", group_results),
        "user_group_results": json.dumps(
            list(user_group_results), cls=DjangoJSONEncoder
        ),
    }

    return HttpResponse(t.render(c, request))

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_permissions(min_permission_level=2, object_lookup="kanban_board_id")
def new_kanban_card(request, kanban_board_id, *args, **kwargs):
    """Add a new kanban card"""
    kanban_instance = kanban_board.objects.get(kanban_board_id=kanban_board_id)

    # Get the form data
    form = NewKanbanCardForm(request.POST)
    if not form.is_valid():
        return HttpResponseBadRequest(form.errors)

    # Get the newest card number id
    kanban_card_sort_number = get_max_sort_id(kanban_board_id, form)

    # Save the data
    submit_kanban_card = kanban_card(
        change_user=request.user,
        kanban_board=kanban_instance,
        kanban_card_text=form.cleaned_data["kanban_card_text"],
        kanban_card_description=form.cleaned_data["kanban_card_description"],
        kanban_column=form.cleaned_data["kanban_column"],
        kanban_level=form.cleaned_data["kanban_level"],
        kanban_card_sort_number=kanban_card_sort_number + 1,
    )
    submit_kanban_card.save()

    # Send back the kanban card data
    kanban_card_results = kanban_card.objects.get(
        kanban_card_id=submit_kanban_card.kanban_card_id
    )
    return HttpResponse(
        serializers.serialize("json", [kanban_card_results]),
        content_type="application/json",
    )

@require_http_methods(["POST"])
@login_required(login_url="login", redirect_field_name="")
@check_user_permissions(min_permission_level=3, object_lookup="kanban_board_id")
def new_kanban_save(request, *args, **kwargs):
    """
    :param request:
    :return:
    """
    # Check the user form
    form = NewKanbanForm(request.POST)
    if not form.is_valid():
        print(form.errors)
        return HttpResponseBadRequest(form.errors)

    # Create the kanban board
    submit_kanban_board = kanban_board(
        change_user=request.user,
        creation_user=request.user,
        kanban_board_name=form.cleaned_data["kanban_board_name"],
    )
    submit_kanban_board.save()

    # Get both lists
    column_title_list = request.POST.getlist("column_title")
    level_title_list = request.POST.getlist("level_title")

    # Loop through the column title list to save the titles
    for index, column_title in enumerate(column_title_list):
        submit_column_title = kanban_column(
            change_user=request.user,
            kanban_column_name=column_title,
            kanban_board=submit_kanban_board,
            kanban_column_sort_number=index,
        )
        submit_column_title.save()

    # Loop throuhg the level title list to save the titles
    for index, level_title in enumerate(level_title_list):
        submit_level_title = kanban_level(
            change_user=request.user,
            kanban_level_name=level_title,
            kanban_board=submit_kanban_board,
            kanban_level_sort_number=index,
        )
        submit_level_title.save()

    # Get the group list and apply the permissions
    group_list = request.POST.getlist("group_list")

    for single_group in group_list:
        # Get the group instance
        group_instance = group.objects.get(group_id=single_group)

        # Save the group instance against object assignment
        submit_object_assignment = object_assignment(
            group_id=group_instance,
            kanban_board=submit_kanban_board,
            change_user=request.user,
        )

        # Save
        submit_object_assignment.save()

    # Send back project_information URL
    return HttpResponse(
        reverse("kanban_information", args={submit_kanban_board.kanban_board_id})
    )

@login_required(login_url="login", redirect_field_name="")
@require_http_methods(["POST"])
@check_user_permissions(min_permission_level=2, object_lookup="kanban_board_id")
def update_card(request, *args, **kwargs):
    """
    The following function will update the card information
    from which is sent through the form in POST
    """
    form = KanbanCardForm(request.POST)
    if not form.is_valid():
        return HttpResponseBadRequest(form.errors)

    # Save the data
    kanban_card_update = form.cleaned_data["kanban_card_id"]
    kanban_card_update.kanban_card_text = form.cleaned_data["kanban_card_text"]
    kanban_card_update.kanban_card_description = form.cleaned_data[
        "kanban_card_description"
    ]
    kanban_card_update.kanban_column = form.cleaned_data["kanban_column"]
    kanban_card_update.kanban_level = form.cleaned_data["kanban_level"]
    kanban_card_update.save()

    return HttpResponse("")

# Internal Function
def update_sort_number(resort_array, delta):
    """
    The following function will loop through the resort array and apply the delta (which should be either a 1 or -1)
    :param resort_array:
    :param delta:
    :return:
    """
    for row in resort_array:
        row.kanban_card_sort_number = row.kanban_card_sort_number + delta
        row.save()


text:
package cat.calidos.morfeu.model.metadata.injection;

import java.util.List;
import java.util.Optional;

import javax.annotation.Nullable;
import javax.inject.Named;

import org.w3c.dom.Node;

import com.sun.xml.xsom.XSAnnotation;

import dagger.BindsInstance;
import dagger.Component;

/**
* @author daniel giribet
*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Component(modules=MetadataAnnotationModule.class)
public interface MetadataAnnotationComponent {

List<Node> values();

@Component.Builder
interface Builder {

	@BindsInstance Builder from(@Nullable XSAnnotation annotation);
	@BindsInstance Builder andTag(String tag);

	MetadataAnnotationComponent build();

}

}


text:
package com.maximchuk.rest.api.client.auth;

/**
 * @author Maxim Maximchuk
 *         date 26.09.2015.
 */
public class BasicHttpAuthCredential implements Credentials {

    private String authString;

    public BasicHttpAuthCredential(String username, String password, Base64Encoder base64encoder) {
        authString = "Basic " + base64encoder.encode(username + ":" + password);
    }

    @Override
    public String getAuthorizationString() {
        return authString;
    }

}


text:
      <form name="form">

Username: <input type="text" name="username" ng-model="account.username" required />

Username cannot be empty

E-mail: <input type="email" name="email" ng-model="account.email" required />

Please enter a valid email-address

Please enter an email-address

Password: <input type="password" ng-model="account.passwdHash" />

Confirm Password: <input type="password" ng-model="passwordConfirm" />

The passwords do not match!

<button class="btn btn-primary" ng-click="save()" ng-disabled="!form.$valid || account.passwdHash != passwordConfirm">Save</button>

      </form>


text:
.app-container {
    display: flex;
    flex-direction: column;
}

.header-container {
    width: 95vw;
    background-color: #1976D2;
    color: #ffffff;
    text-indent: 10px;
}

.toolbar-container {
    width: 95vw;
    background-color: #BBDEFB;
    color: #000000;
    text-indent: 10px;
}

.content-block {
    display: flex;
    flex-direction: row;
}

.graph {
    width: 70vw;
    height: 80vh;
    background-color: #E3F2FD;
}

.panel {
    width: 25vw;
    height: 80vh;
    background-color: #90CAF9;
    word-wrap: break-word;
    overflow: auto;
}

.footer {
    display: flex;
    width: 95vw;
    background-color: #1976D2;
    color: white;
    justify-content: flex-end;
}

.browser-nav {
    display: flex;
    flex-direction: row;
    margin: auto;
    flex-flow: row wrap;
    justify-content: center;
    flex-grow: 1;

}

[class^="browser-nav__item"] {
    display: flex;
    flex-grow: 1;
    letter-spacing: 2px;

    justify-content: center;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;

}

.browser-nav__item--active {

    background-color: #90CAF9;
    border-bottom: inset;
    border-bottom-width: 1px;

}

.browser-nav__item--inactive {
    cursor: pointer;
    background-color: #5f89af;
    width: inherit;

}

::-webkit-scrollbar {
    width: 4px; /* for vertical scrollbars */
    height: 4px; /* for horizontal scrollbars */
}

::-webkit-scrollbar-track {
    background: #BBDEFB;
}

::-webkit-scrollbar-thumb {
    background: #0D47A1;
}


text:
package ClimbingStairs_70;

/**
 * You are climbing a stair case. It takes n steps to reach to the top.
 * Each time you can either climb 1 or 2 steps.
 * In how many distinct ways can you climb to the top?
 *
 * Note: Given n will be a positive integer.
 */
public class Solution {
    public static int climbStairs(int n) {
        if(n<3) return n;
        int[] ways = new int[n];
        ways[0] = 1;
        ways[1] = 2;
        for (int i = 2; i < n; i++) ways[i] = ways[i-1]+ways[i-2];
        return ways[n-1];
    }
}


text: Collection of demos using modern openGL


text:
<?php

namespace Kunstmaan\LeadGenerationBundle\Form\Rule;

use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;

class MaxXTimeAdminType extends AbstractRuleAdminType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('times', IntegerType::class, [
            'label' => 'kuma_lead_generation.form.max_x_time.times.label',
        ]);
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'max_x_times_form';
    }
}


text:
layout: page
title: Castaneda Champion Tech Seminar
date: 2016-05-24
author: Carol Bowman
tags: weekly links, java
status: published
summary: Nullam iaculis nec libero ac scelerisque.
banner: images/banner/office-01.jpg
booking:
  startDate: 06/17/2019
  endDate: 06/18/2019
  ctyhocn: MTLGAHX
  groupCode: CCTS
published: true
---
Curabitur eget risus a eros scelerisque tincidunt id sit amet odio. Nulla vel odio tempor, porta mi a, accumsan augue. Fusce laoreet eros in vestibulum tempus. Praesent fringilla ante ipsum, sollicitudin egestas tellus vehicula et. Sed nec tempor ante, sed pulvinar metus. Donec dui massa, rutrum non nunc ut, fermentum tristique dolor. Maecenas posuere efficitur dui. Fusce a mauris quam. Mauris elit ante, scelerisque at tincidunt in, pretium vel urna. In tempus nec dolor ac accumsan. Ut vitae viverra tellus, ac iaculis est. Proin lobortis orci nisi, ut tempor elit ultricies ut. In at mauris a libero luctus facilisis eu ut risus. Duis ut semper ipsum, et aliquet elit.

* Maecenas volutpat nisl vitae nibh porttitor faucibus
* Cras et sem efficitur, iaculis orci vel, porttitor sem
* Fusce at tellus eget quam ullamcorper congue
* Fusce in urna eu orci tincidunt convallis.

Aliquam sollicitudin nunc tellus, in placerat quam hendrerit sed. Vivamus feugiat interdum felis sit amet pulvinar. Cras vitae lectus eu est tristique cursus quis ac tortor. Suspendisse vel metus vel leo rhoncus tristique. Nulla vestibulum pellentesque arcu, pulvinar dapibus mauris aliquam eu. Donec egestas tortor vitae urna aliquet sagittis. Praesent accumsan nisl semper, tempus sapien eget, ullamcorper dui. Suspendisse lobortis nibh at nibh suscipit, a porttitor velit commodo. Aliquam scelerisque dui est, vel ornare velit congue in. Proin at urna enim. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed molestie aliquet odio eget rutrum. Nulla eu nisl nec lorem faucibus ornare quis nec tortor.


text:
<?php
	// Load Initialization File
	require_once '../../core/init.php';
	// Load CSS Name
	$cssFileName = Config::get('links/css_root') . 'admin/dbmanage/' . basename(__FILE__, '.php') . '.css';
	// Load the User
	$user = new User;

	// Is the user logged in
	if($user->isLoggedIn()) {
		// If the user does NOT have admin permission
		if(!$user->hasPermission(array('admin'))) {
			// User Not Logged In Redirect to Home Page
			Session::flash('home', 'You do not have permission to view that page', 'danger');
			Redirect::to('index.php');
		} else { // Authorization correct
			// Does input in the URL exist?
			if(Input::exists('get')) {

					// Grab Inputs
					$tableName = Input::get('tableName');

					// Get New DB
					$_db = DB::getInstance();

					$tableFields = $_db->getTableFields($tableName);

					// Enable this line below for debugging
					// echo '
' , print_r($tableFields) , '
';

			} else { // Input does not exist
				$error404 = true;
			}

		}
	} else {
		// User Not Logged In Redirect to Home Page
		Session::flash('home', 'You are not logged in.', 'warning');
		Redirect::to('index.php');
	}

?>

<!DOCTYPE html>

	<title>Admin - Create Table - Makoto</title>

	<?php include(Config::get('file/head_contents')); ?>

	<link rel="stylesheet" type="text/css" href="<?php echo $cssFileName; ?>">

	<?php include(Config::get('file/navbar/default')); ?>
	<?php
		// Session Flash Message
		if(Session::exists('admin-create-table')) {
			echo Session::flash('admin-create-table');
		}

		// If 404 Error Occurs
		if(isset($error404)) {
			Redirect::to(404);
		}
	?>

<a href="<?php echo Config::get('links/app_root'); ?>">Home

Admin

Database Management

Edit Table Fields

'<?php if(isset($tableName)) { echo $tableName; } ?>' Information

Please edit the information below, and then click 'Save'.

Table Fields & Values

		<form class="form-horizontal" action="edittableconfirm.php" method="post">

			<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">

			<input type="hidden" name="numFields" value="<?php echo $numFields; ?>">

			<input type="hidden" name="tableName" value="<?php echo $tableName; ?>">

			<?php
				// Dynamically generate number of fields and type

				$i = 1;
				foreach($tableFields as $column){

					$fieldName = $column->Field;
					$fieldType = $column->Type;
					// Skip Fields if field is ID or DateTime
					if($fieldName == 'id' || $fieldName == 'datetime') {
						continue;
					} else {
						switch($fieldType) {
							case "text":
								$fieldTypeHTML = "
									<option value='' disabled>Hover Each Type For Description</option>
									<option value='' disabled>-------------------------------</option>
									<option value='text' title='Holds a string with a maximum length of 65,535 characters' selected>Text</option>
									<option value='int' title='-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.'>Integer</option>
									<option value='varchar32' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (32)</option>
									<option value='varchar64' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (64)</option>
									<option value='varchar128' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (128)</option>
									<option value='varchar255' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (255)</option>
								";
							break;
							case "int(11)":
								$fieldTypeHTML = "
									<option value='' disabled>Hover Each Type For Description</option>
									<option value='' disabled>-------------------------------</option>
									<option value='text' title='Holds a string with a maximum length of 65,535 characters'>Text</option>
									<option value='int' title='-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.' selected>Integer</option>
									<option value='varchar32' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (32)</option>
									<option value='varchar64' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (64)</option>
									<option value='varchar128' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (128)</option>
									<option value='varchar255' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (255)</option>
								";
							break;
							case "varchar(32)":
								$fieldTypeHTML = "
									<option value='' disabled>Hover Each Type For Description</option>
									<option value='' disabled>-------------------------------</option>
									<option value='text' title='Holds a string with a maximum length of 65,535 characters'>Text</option>
									<option value='int' title='-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.'>Integer</option>
									<option value='varchar32' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.' selected>Varchar (32)</option>
									<option value='varchar64' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (64)</option>
									<option value='varchar128' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (128)</option>
									<option value='varchar255' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (255)</option>
								";
							break;
							case "varchar(64)":
								$fieldTypeHTML = "
									<option value='' disabled>Hover Each Type For Description</option>
									<option value='' disabled>-------------------------------</option>
									<option value='text' title='Holds a string with a maximum length of 65,535 characters'>Text</option>
									<option value='int' title='-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.'>Integer</option>
									<option value='varchar32' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (32)</option>
									<option value='varchar64' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.' selected>Varchar (64)</option>
									<option value='varchar128' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (128)</option>
									<option value='varchar255' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (255)</option>
								";
							break;
							case "varchar(128)":
								$fieldTypeHTML = "
									<option value='' disabled>Hover Each Type For Description</option>
									<option value='' disabled>-------------------------------</option>
									<option value='text' title='Holds a string with a maximum length of 65,535 characters'>Text</option>
									<option value='int' title='-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.'>Integer</option>
									<option value='varchar32' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (32)</option>
									<option value='varchar64' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (64)</option>
									<option value='varchar128' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.' selected>Varchar (128)</option>
									<option value='varchar255' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (255)</option>
								";
							break;
							case "varchar(255)":
								$fieldTypeHTML = "
									<option value='' disabled>Hover Each Type For Description</option>
									<option value='' disabled>-------------------------------</option>
									<option value='text' title='Holds a string with a maximum length of 65,535 characters'>Text</option>
									<option value='int' title='-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.'>Integer</option>
									<option value='varchar32' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (32)</option>
									<option value='varchar64' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (64)</option>
									<option value='varchar128' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.'>Varchar (128)</option>
									<option value='varchar255' title='Holds a string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 Characters.' selected>Varchar (255)</option>
								";
							break;

						}

						echo "

								Field {$i}

										<input type='text' class='form-control' id='field{$i}' name='field{$i}name' value='{$fieldName}' pattern='^\S+$' title='No Spaces are allowed' required>

										<select name='field{$i}type' class='form-control' required>
											{$fieldTypeHTML}
										</select>

						";

						$i++;
					}

				}

			?>

Go Back

<button class="btn btn-block btn-success hvr-pop" type="submit">Save</button>

		</form>


text:
namespace google {
namespace cloud {
namespace spanner {
inline namespace SPANNER_CLIENT_NS {
namespace {

TEST(RetryPolicyTest, PermanentFailure) {
  EXPECT_FALSE(internal::SafeGrpcRetry::IsPermanentFailure(Status()));
  EXPECT_FALSE(internal::SafeGrpcRetry::IsPermanentFailure(
      Status(StatusCode::kUnavailable, "try again")));
  EXPECT_FALSE(internal::SafeGrpcRetry::IsPermanentFailure(
      Status(StatusCode::kResourceExhausted, "slow down please")));
  EXPECT_TRUE(internal::SafeGrpcRetry::IsPermanentFailure(
      Status(StatusCode::kDeadlineExceeded, "not enough time")));
  EXPECT_TRUE(internal::SafeGrpcRetry::IsPermanentFailure(
      Status(StatusCode::kAborted, "nothing done")));
  EXPECT_TRUE(internal::SafeGrpcRetry::IsPermanentFailure(
      Status(StatusCode::kPermissionDenied, "uh oh")));
}

TEST(TransactionRerunPolicyTest, PermanentFailure) {
  EXPECT_FALSE(internal::SafeTransactionRerun::IsPermanentFailure(Status()));
  EXPECT_FALSE(internal::SafeTransactionRerun::IsPermanentFailure(
      Status(StatusCode::kAborted, "nothing done")));
  EXPECT_TRUE(internal::SafeTransactionRerun::IsPermanentFailure(
      Status(StatusCode::kUnavailable, "try again")));
  EXPECT_TRUE(internal::SafeTransactionRerun::IsPermanentFailure(
      Status(StatusCode::kResourceExhausted, "slow down please")));
  EXPECT_TRUE(internal::SafeTransactionRerun::IsPermanentFailure(
      Status(StatusCode::kDeadlineExceeded, "not enough time")));
  EXPECT_TRUE(internal::SafeTransactionRerun::IsPermanentFailure(
      Status(StatusCode::kPermissionDenied, "uh oh")));
}

}  // namespace
}  // namespace SPANNER_CLIENT_NS
}  // namespace spanner
}  // namespace cloud
}  // namespace google