text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Autofac.Integration.WebApi;
using AutoMapper;
using Data.Models;
using Data.Repositories;
using Newtonsoft.Json;
using Web.Models;

namespace Web.Controllers
{
    [Route("api/portfolio")]
    public class PortfolioController : ApiControllerBase
    {
        [Route("api/portfolio/{mustHaveImages:bool=false}")]
        [HttpGet]
        public List<PortfolioViewModel> Get(bool mustHaveImages)
        {
            var portfolios = new List<PortfolioViewModel>();

            if (Directory.Exists(PortfolioBase))
            {
                foreach (var directory in Directory.GetDirectories(PortfolioBase))
                {
                    var path = Path.Combine(directory, "data.json");
                    if (!File.Exists(path)) continue;
                    var jsonText = File.ReadAllText(path);
                    var model = JsonConvert.DeserializeObject<Portfolio>(jsonText);
                    model.Id = RelativeName(directory);
                    var viewModel = Mapper.Map<PortfolioViewModel>(model);
                    viewModel.Path = string.Format("{0}/{1}",RelativeBase.Replace("~/",""),RelativeName(directory));
                    if (mustHaveImages == false || (!string.IsNullOrEmpty(viewModel.Thumb) && viewModel.Images.Any()))
                    {
                        portfolios.Add(viewModel);
                    }
                }
            }

            return portfolios.OrderBy(p => p.Title).ToList();
        }

        [Route("api/portfolio/{id}")]
        [HttpGet]
        public Portfolio Get(string id)
        {
            return GetPortfolio(id);
        }

        private Portfolio GetPortfolio(string id)
        {
            var dataFileName = Path.Combine(PortfolioBase, id, "data.json");
            if (File.Exists(dataFileName))
            {
                var jsonText = File.ReadAllText(dataFileName);
                var model = JsonConvert.DeserializeObject<Portfolio>(jsonText);
                model.Path = string.Format("{0}/{1}", RelativeBase.Replace("~/", ""), id);
                model.Id = id;
                return model;
            }
            return new Portfolio();
        }

        private Portfolio PopulateNewPortfolio(Portfolio portfolio)
        {
            portfolio.Id = Guid.NewGuid().ToString().ToUpper();
            portfolio.Register =
                GetRegistry().Headings.Select(heading => new List<string> {heading, string.Empty}).ToList();
            return portfolio;
        }

        [Route("api/portfolio")]
        [HttpPost]
        public Portfolio Post(Portfolio portfolio)
        {
            if (string.IsNullOrEmpty(portfolio.Id))
            {
                portfolio = PopulateNewPortfolio(portfolio);
            }
            var jsonText = JsonConvert.SerializeObject(portfolio);
            var dataFileDirectory = Path.Combine(PortfolioBase, portfolio.Id);
            if (!Directory.Exists(dataFileDirectory))
            {
                Directory.CreateDirectory(dataFileDirectory);
            }
            var dataFileName = Path.Combine(PortfolioBase, portfolio.Id, "data.json");
            File.Delete(dataFileName);
            File.WriteAllText(dataFileName,jsonText);
            return GetPortfolio(portfolio.Id);
        }

        [Route("api/portfolio/{id}/remove")]
        [HttpPost]
        public List<PortfolioViewModel> Remove(string id)
        {
            var dataFileDirectory = Path.Combine(PortfolioBase, id);
            if (Directory.Exists(dataFileDirectory))
            {
                Directory.Delete(dataFileDirectory, true);
            }
            return Get(true);
        }

        [Route("api/portfolio/uploadfile")]
        [HttpPost]
        public async Task<Portfolio> UploadFile()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var bodyPartTempDir = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(bodyPartTempDir);

            var postedProject = String.Empty;
            var isThumbNail = false;

            // Read the form data and return an async task.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the form data.
            if (provider.FormData.AllKeys.Any(key => key.Equals("Project")))
            {
                postedProject = provider.FormData.GetValues("Project").FirstOrDefault();
            }
            if (provider.FormData.AllKeys.Any(key => key.Equals("IsThumbNail")))
            {
                isThumbNail = bool.Parse(provider.FormData.GetValues("IsThumbNail").FirstOrDefault());
            }

            if (string.IsNullOrEmpty(postedProject)) throw new HttpResponseException(HttpStatusCode.BadRequest);

            var portfolio = GetPortfolio(postedProject);
            var portfolioStore = Path.Combine(PortfolioBase, postedProject);
            // This illustrates how to get the file names for uploaded files.
            foreach (var file in provider.FileData)
            {
                var postedFile = new FileInfo(file.LocalFileName);
                var fileCategory = file.Headers.ContentDisposition.FileName.Contains("mp3") ? "audio" : "images";

                var portfolioImageStore = Path.Combine(portfolioStore, fileCategory);
                var fileName = Path.Combine(fileCategory,file.Headers.ContentDisposition.FileName.Replace("\"",""));
                var fileSavePath = Path.Combine(portfolioStore, fileName);
                var webFileName = fileName.Replace("\\", "/");

                if (!Directory.Exists(portfolioImageStore))
                {
                    Directory.CreateDirectory(portfolioImageStore);
                }

                if (File.Exists(fileSavePath))
                {
                    File.Delete(fileSavePath);
                }
                File.Copy(postedFile.FullName, fileSavePath);

                if (isThumbNail)
                {
                    portfolio.Thumb = webFileName;
                    isThumbNail = false;
                }
                else
                {
                    if (portfolio.Images == null)
                    {
                        portfolio.Images = new List<string>();
                    }
                    if (!portfolio.Images.Contains(webFileName))
                    {
                        portfolio.Images.Add(webFileName);
                    }
                }
            }
            Post(portfolio);
            return Get(postedProject);
        }

        [Route("api/portfolio/removeImage")]
        [HttpPost]
        public bool RemoveImage(RemoveImageViewmodel removeImageViewmodel)
        {
            try
            {
                var portfolioId = removeImageViewmodel.Portfolio;
                var fileName = removeImageViewmodel.FileName;
                var fullFileName = Path.Combine(PortfolioBase, portfolioId, fileName.Replace("/","\\"));

                var portfolio = GetPortfolio(portfolioId);
                if (File.Exists(fullFileName))
                {
                    File.Delete(fullFileName);
                    if (portfolio.Images.Any(img => img.Equals(fileName)))
                    {
                        portfolio.Images.Remove(fileName);
                    }
                    if (portfolio.Thumb.Equals(fileName)) {
                        portfolio.Thumb = null;
                    }
                }
                Post(portfolio);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private string RelativeName(string input)
        {
            var baseSegs = PortfolioBase.Split('\\').ToList();
            var inputSegs = input.Split('\\').ToList();

            var rem = string.Join("\\",inputSegs.Skip(baseSegs.Count));

            return rem;
        }
    }

    public class RemoveImageViewmodel
    {
        public string Portfolio { get; set; }
        public string FileName { get; set; }
    }
}


text:
package es.weso.rdf

import org.scalatest.FunSpec
import com.hp.hpl.jena.rdf.model.ModelFactory
import java.io.ByteArrayInputStream
import com.hp.hpl.jena.rdf.model.Model
import java.io.InputStream
import org.scalatest.Matchers
import es.weso.rdfgraph.nodes._
import es.weso.rdf.jena.JenaMapper._
import es.weso.rdfgraph.statements.RDFTriple
import es.weso.rdf.jena._

trait RDFBased extends Matchers {

  def shouldBeIsomorphic(r1: RDFReader, r2: RDFReader): Unit = {
    val str1 = r1.serialize("TURTLE")
    val str2 = r2.serialize("TURTLE")
    val m1 = RDFAsJenaModel.fromChars(str1,"TURTLE").get.model
    val m2 = RDFAsJenaModel.fromChars(str2,"TURTLE").get.model
    val b = m1.isIsomorphicWith(m2)
    if (!b) {
      println("Models are not isomorphic")
      println("-------------- Model 1:" + str1)
      println("-------------- Model 2:" + str2)
    }
    b should be(true)
  }

}

redpajama_set_name: RedPajamaGithub


text:
package net.cybersoft.visitorinfo;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MediaUtils {

	public static final String PUBLIC_DIR = "VisitorInfo";
	public static final String IMAGE_DIR  = "Images";
	public static final String VOICE_DIR = "Voice";
	public static final String VIDEO_DIR = "Video";
	public static final String SIGN_DIR = "Signature";
	private static final String FILE_NAME_FORMAT_DATE_PREFIX = "yyyyMMdd_HHmmss";
	private static final String TAG = MediaUtils.class.getSimpleName();

	public static File createFile(Context ctx, int mediaType ){
		switch (mediaType) {
		case 0:
			return createImageFile(ctx);
 		case 1:
 			return createVideoFile(ctx);
 		case 2:
 			return createVoiceFile(ctx, ".m4a");
 		default:
 			return createImageFile(ctx);
		}
	}

	@SuppressLint("SimpleDateFormat")
	private static File createImageFile(Context context){

		String imageFileName = new SimpleDateFormat(FILE_NAME_FORMAT_DATE_PREFIX).format(new Date());
		String extStore = Environment.getExternalStorageDirectory().getAbsolutePath();
		File storageDir = new File(extStore, String.format("%s/%s", PUBLIC_DIR, IMAGE_DIR));
		if(!storageDir.exists())
			storageDir.mkdirs();
		File image = null;
		try {
			image = File.createTempFile(
					imageFileName,  /* prefix */
					".jpg",         /* suffix */
					storageDir     /* directory */
					);
		} catch (IOException e) {
			Log.e(TAG , "createImageFile() " + e.getMessage());
		}

		return image;
	}

	private static File createSignFile(Context context){

		String imageFileName = new SimpleDateFormat(FILE_NAME_FORMAT_DATE_PREFIX, Locale.getDefault()).format(new Date());
		String extStore = Environment.getExternalStorageDirectory().getAbsolutePath();
		File storageDir = new File(extStore, String.format("%s/%s", PUBLIC_DIR, SIGN_DIR));
		File image = null;
		try {
			image = File.createTempFile(
					imageFileName,  /* prefix */
					".jpg",         /* suffix */
					storageDir     /* directory */
			);
		} catch (IOException e) {
			Log.e(TAG , "createImageFile() " + e.getMessage());
		}

		return image;
	}

	private static File createVideoFile(Context context){

		String imageFileName = new SimpleDateFormat(FILE_NAME_FORMAT_DATE_PREFIX).format(new Date());
		String extStore = Environment.getExternalStorageDirectory().getAbsolutePath();
		File storageDir = new File(extStore, String.format("%s/%s", PUBLIC_DIR, VIDEO_DIR));
		if(!storageDir.exists())
			storageDir.mkdirs();
		File image = null;
		try {
			image = File.createTempFile(
					imageFileName,  /* prefix */
					".mp4",         /* suffix */
					storageDir     /* directory */
					);
		} catch (IOException e) {
			Log.e(TAG , "createVideoFile() " + e.getMessage());
		}

		return image;
	}

	@SuppressLint("SimpleDateFormat")
	private static File createVoiceFile(Context context, String ext){

		String imageFileName = new SimpleDateFormat(FILE_NAME_FORMAT_DATE_PREFIX).format(new Date());
		String extStore = Environment.getExternalStorageDirectory().getAbsolutePath();
		File storageDir = new File(extStore, String.format("%s/%s", PUBLIC_DIR, VOICE_DIR));
		if(!storageDir.exists())
			storageDir.mkdirs();
		File image = null;
		try {
			image = File.createTempFile(
					imageFileName,  /* prefix */
					ext,         /* suffix */
					storageDir     /* directory */
					);
		} catch (IOException e) {
			Log.e(TAG , "createVoiceFile() " + e.getMessage());
		}

		return image;
	}

	public static String getRealImagePathFromUri(final ContentResolver cr, final Uri contentUri) {

        String res = null;
        Cursor cursor = null;

        try {
            String[] proj = { MediaStore.Images.Media.DATA };
        	cursor = cr.query(contentUri, proj, null, null, null);
        	if(cursor!=null && cursor.moveToFirst()) {
        		int column_index = cursor.getColumnIndexOrThrow(proj[0]);
        		res = cursor.getString(column_index);
        	}
    	} catch (IllegalArgumentException e) {
    		e.printStackTrace();
        } finally {
        	if (cursor != null) cursor.close();
        }
        return res;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
    <integer name="gtfs_rts_agency_type">3</integer>
    <string name="gtfs_rts_timezone">America/New_York</string>
    <string name="gtfs_rts_color">008E1A</string>
</resources>


text:
package org.elasticsearch.xpack.core.security.action.saml;

import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

/**
 * A response to complete the LogoutResponse from idP
 */
public final class SamlCompleteLogoutResponse extends ActionResponse {

    public SamlCompleteLogoutResponse(StreamInput in) throws IOException {
        super(in);
    }

    public SamlCompleteLogoutResponse() {
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Pie Chart Test</title>

  <link rel="stylesheet" type="text/css" href="../jquery.jqplot.css" />
  <link rel="stylesheet" type="text/css" href="examples.css" />

<?php include "nav.inc"; ?>

To create pie plots, you have to include the "jqplot.pieRenderer.js" file in your source.  You can view the javascript that generated these plots by clicking the "View Code" button below.

    <button id="seecode" onclick="$('#code').dialog('open');">View Code</button>

Below is a default pie plot.  Slices will highlight on mouseover.  Events are triggered when you mouseover a slice and also when you click on a slice.  Here We capture the 'jqplotDataClick' event and display the clicked series index, point index and data values.

You Clicked: Nothing yet

Below is a customized customized pie plot where options for sliceMargin and startAngle have been specified.  Here We capture the 'jqplotDataHighlight' event and display the currently highlighted series index, point index and data values.

The plot target also fires a 'jqplotDataMouseOver' when the cursor is moused over a slice even if highlighting is turned off.  This event will fire continuously as the user mouses over the slice.  'jqplotDataHighlight' fires only once when the user first passes over the slice.  Additionally, a 'jqplotDataUnhighlight' event is fired when the user moves out of a slice (if highlighting is enabled).

Moused Over: Nothing

The next example has the plot's 'captureRightClick' option set to true.  This causes the plot to fire a 'jqplotRightClick' event the the user clicks the right mouse button over a slice.

The 'highlightMouseDown' option is also set to true.  This will highlight a slice on mouse down instead of on move over.  Highlighting will occur for either left or right click.

You Right Clicked: Nothing yet

The last example shows a pie with all of the default colors.  Mouse over to see the default highlight colors.  Series colors can be specified with the "seriesColors" option on the plot.  The highlight colors are specified with the 'highlightColors' option on the series renderer.

A simple line chart is added to test for imcompatabilities.


text:
using namespace ci;
using namespace ci::app;
using namespace std;

class QTimeAdvApp : public App {
  public:
	static void prepareSettings( Settings *settings );
	void setup();

	void keyDown( KeyEvent event );
	void fileDrop( FileDropEvent event );

	void update();
	void draw();

	void addActiveMovie(MovieRef movie);
	void loadMovieUrl( const std::string &urlString );
	void loadMovieFile( const fs::path &path );

	fs::path mLastPath;
	// all of the actively playing movies
	vector<MovieRef> mMovies;
//	vector<qtime::MovieGlRef> mMovies;
	// movies we're still waiting on to be loaded
	vector<qtime::MovieLoaderRef> mLoadingMovies;
};

void QTimeAdvApp::prepareSettings( Settings *settings )
{
	settings->setWindowSize( 800, 800 );
	settings->setFullScreen( false );
	settings->setResizable( true );
}

void QTimeAdvApp::setup()
{
//	fs::path moviePath = getOpenFilePath();
//	if( ! moviePath.empty() )
//		loadMovieFile( moviePath );
}

void QTimeAdvApp::keyDown( KeyEvent event )
{
	if( event.getChar() == 'f' ) {
		setFullScreen( ! isFullScreen() );
	}
	else if( event.getChar() == 'o' ) {
		fs::path moviePath = getOpenFilePath();
		if( ! moviePath.empty() )
			loadMovieFile( moviePath );
	}
	else if( event.getChar() == 'O' ) {
		if( ! mLastPath.empty() )
			loadMovieFile( mLastPath );
	}
	else if( event.getChar() == 'x' ) {
		mMovies.clear();
		mLoadingMovies.clear();
	}
	else if( event.getChar() == '2' ) {
		if( ! mMovies.empty() )
			mMovies.back()->setRate( 2.0f );
	}
	else if( event.getChar() == 'd' ) {
		if( ! mMovies.empty() )
			mMovies.erase( mMovies.begin() + ( rand() % mMovies.size() ) );
	}
	else if( event.getChar() == 'u' ) {
//		vector<string> randomMovie;
//		randomMovie.push_back( "http://movies.apple.com/movies/us/hd_gallery/gl1800/480p/bbc_earth_m480p.mov" );
//		randomMovie.push_back( "http://movies.apple.com/media/us/quicktime/guide/hd/480p/noisettes_m480p.mov" );
//		randomMovie.push_back( "http://pdl.warnerbros.com/wbol/us/dd/med/northbynorthwest/quicktime_page/nbnf_airplane_explosion_qt_500.mov" );
//		loadMovieUrl( randomMovie[rand() % randomMovie.size()] );
		loadMovieUrl("file://F:/Projects/Tour Reservoir/Video/V0005.mp4");
	}
}

void QTimeAdvApp::addActiveMovie(MovieRef movie)
{
	console() << "Dimensions:" << movie->getWidth() << " x " << movie->getHeight() << std::endl;
	console() << "Duration:  " << movie->getDuration() << " seconds" << std::endl;
	console() << "Frames:    " << movie->getNumFrames() << std::endl;
	console() << "Framerate: " << movie->getFramerate() << std::endl;
	movie->setLoop(true, false);

	mMovies.push_back(movie);
	movie->play();
}

void QTimeAdvApp::loadMovieUrl( const string &urlString )
{
	try {
		mLoadingMovies.push_back( qtime::MovieLoader::create( Url( urlString ) ) );
	}
	catch( ci::Exception &exc ) {
		console() << "Exception caught trying to load the movie from URL: " << urlString << ", what: " << exc.what() << std::endl;
	}
}

void QTimeAdvApp::loadMovieFile( const fs::path &moviePath )
{
	qtime::MovieGlRef movie;

	try {
		movie = qtime::MovieGl::create( moviePath );

		addActiveMovie( movie );
		mLastPath = moviePath;
	}
	catch( ci::Exception &exc ) {
		console() << "Exception caught trying to load the movie from path: " << moviePath << ", what: " << exc.what() << std::endl;
		return;
	}
}

void QTimeAdvApp::fileDrop( FileDropEvent event )
{
	for( size_t s = 0; s < event.getNumFiles(); ++s )
		loadMovieFile( event.getFile( s ) );
}

void QTimeAdvApp::update()
{
	// let's see if any of our loading movies have finished loading and can be made active
	for( auto loaderIt = mLoadingMovies.begin(); loaderIt != mLoadingMovies.end(); ) {
		try {
			if( (*loaderIt)->checkPlaythroughOk() ) {
				addActiveMovie( qtime::MovieGl::create( *loaderIt ) );
				loaderIt = mLoadingMovies.erase( loaderIt );
			}
			else
				++loaderIt;
		}
		catch( ci::Exception &exc ) {
			console() << "Exception caught trying to load the movie from URL: " << *loaderIt << ", what: " << exc.what() << std::endl;
			loaderIt = mLoadingMovies.erase( loaderIt );
		}
	}
}

void QTimeAdvApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );

	int totalWidth = 0;
	for( size_t m = 0; m < mMovies.size(); ++m )
		totalWidth += mMovies[m]->getWidth();

	int drawOffsetX = 0;
	for( size_t m = 0; m < mMovies.size(); ++m )
	{
		float relativeWidth = mMovies[m]->getWidth() / (float)totalWidth;

//		gl::TextureRef texture = mMovies[m]->getTexture();
//		if( texture )
		{
			float drawWidth = getWindowWidth() * relativeWidth;
			float drawHeight = ( getWindowWidth() * relativeWidth ) / mMovies[m]->getAspectRatio();
			float x = drawOffsetX;
			float y = ( getWindowHeight() - drawHeight ) / 2.0f;
			Rectf r(x, y, x + drawWidth, y + drawHeight);
			mMovies[m]->draw(r);
//			gl::color( Color::white() );
//			gl::draw( texture, r );
		}
		drawOffsetX += getWindowWidth() * relativeWidth;
	}
}

//CINDER_APP( QTimeAdvApp, RendererGl )
CINDER_APP( QTimeAdvApp, RendererGl, QTimeAdvApp::prepareSettings)


text:
@interface NSNull : NSObject
{
}

+ (NSNull *)null;

+ (id)allocWithZone:(NSZone *)zone;
- (void)dealloc;

- (id)description;

- (id)retain;
- (oneway void)release;
- (id)autorelease;
- (unsigned)retainCount;

- (id)copyWithZone:(NSZone *)zone;
- (id)copy;

- (void)encodeWithCoder:(NSCoder *)aCoder;
- (instancetype)initWithCoder:(NSCoder *)aDecoder;

- (id)replacementObjectForCoder:(NSCoder *)aCoder;

- (id)valueForKey:(NSString *)key;

@end

#endif


text:
from __future__ import unicode_literals

import logging

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

from . import signals
from .constants import DEFAULT_ALIAS
from .utils import loading

__author__ = 'Daniel Lindsley'
__version__ = (2, 5, 'dev0')

# Setup default logging.
log = logging.getLogger('searchstack')
stream = logging.StreamHandler()
stream.setLevel(logging.INFO)
log.addHandler(stream)

# Help people clean up from 1.X.
if hasattr(settings, 'SEARCHSTACK_SITECONF'):
    raise ImproperlyConfigured('The SEARCHSTACK_SITECONF setting is no longer used & can be removed.')
if hasattr(settings, 'SEARCHSTACK_SEARCH_ENGINE'):
    raise ImproperlyConfigured('The SEARCHSTACK_SEARCH_ENGINE setting has been replaced with SEARCHSTACK_CONNECTIONS.')
if hasattr(settings, 'SEARCHSTACK_ENABLE_REGISTRATIONS'):
    raise ImproperlyConfigured('The SEARCHSTACK_ENABLE_REGISTRATIONS setting is no longer used & can be removed.')
if hasattr(settings, 'SEARCHSTACK_INCLUDE_SPELLING'):
    raise ImproperlyConfigured('The SEARCHSTACK_INCLUDE_SPELLING setting is now a per-backend setting & belongs in SEARCHSTACK_CONNECTIONS.')

# Check the 2.X+ bits.
if not hasattr(settings, 'SEARCHSTACK_CONNECTIONS'):
    raise ImproperlyConfigured('The SEARCHSTACK_CONNECTIONS setting is required.')
if DEFAULT_ALIAS not in settings.SEARCHSTACK_CONNECTIONS:
    raise ImproperlyConfigured("The default alias '%s' must be included in the SEARCHSTACK_CONNECTIONS setting." % DEFAULT_ALIAS)

# Load the connections.
connections = loading.ConnectionHandler(settings.SEARCHSTACK_CONNECTIONS)

# Just check SEARCHSTACK_ROUTERS setting validity, routers will be loaded lazily
if hasattr(settings, 'SEARCHSTACK_ROUTERS'):
    if not isinstance(settings.SEARCHSTACK_ROUTERS, (list, tuple)):
        raise ImproperlyConfigured("The SEARCHSTACK_ROUTERS setting must be either a list or tuple.")

# Load the router(s).
connection_router = loading.ConnectionRouter()

# Setup the signal processor.
signal_processor_path = getattr(settings, 'SEARCHSTACK_SIGNAL_PROCESSOR', 'searchstack.signals.BaseSignalProcessor')
signal_processor_class = loading.import_class(signal_processor_path)
signal_processor = signal_processor_class(connections, connection_router)

# Per-request, reset the ghetto query log.
# Probably not extraordinarily thread-safe but should only matter when
# DEBUG = True.
def reset_search_queries(**kwargs):
    for conn in connections.all():
        conn.reset_queries()

if settings.DEBUG:
    from django.core import signals as django_signals
    django_signals.request_started.connect(reset_search_queries)


text:
// Copyright (c) 2015 Christopher "BlayTheNinth" Baker

package net.blay09.mods.eirairc.api;

import net.blay09.mods.eirairc.api.irc.IRCContext;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;

import java.util.List;

/**
 * An interface that can be used to register your own sub-command to the /irc command.
 */
public interface SubCommand {

	/**
	 * @return the name of this command
	 */
	String getCommandName();

	/**
	 * @return whether this command should be registered as it's own Minecraft command if registerShortCommands is enabled
	 */
	boolean hasQuickCommand();

	/**
	 * @param sender the sender that issued the command
	 * @param context the context the command was run within or null
	 * @param args array of arguments the command was run with
	 * @param serverSide true if this command was run via the server-side irc command
	 * @return true if the command was handled
	 */
	boolean processCommand(ICommandSender sender, IRCContext context, String[] args, boolean serverSide) throws CommandException;

	/**
	 * @param list the list to add the tab completion options to
	 * @param sender the sender that issued the command
	 * @param args array of arguments the command was run with
	 */
	void addTabCompletionOptions(List<String> list, ICommandSender sender, String[] args);

	/**
	 * @param sender the sender that issued the command
	 * @return true if the sender is allowed to use this command
	 */
	boolean canCommandSenderUseCommand(ICommandSender sender);

	/**
	 * @param args array of arguments the command was run with
	 * @param idx the index being checked
	 * @return true if args[idx] is assumed to be a username
	 */
	boolean isUsernameIndex(String[] args, int idx);

	/**
	 * @param sender the sender that issued the command
	 * @return a language key to describe the command usage
	 */
	String getCommandUsage(ICommandSender sender);

	/**
	 * @return an array of aliases for this command or null
	 */
	String[] getAliases();

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Events;
using osu.Framework.Logging;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Edit.Tools;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components.RadioButtons;
using osu.Game.Screens.Edit.Compose;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
using Key = osuTK.Input.Key;

namespace osu.Game.Rulesets.Edit
{
    [Cached(Type = typeof(IPlacementHandler))]
    public abstract class HitObjectComposer<TObject> : HitObjectComposer, IPlacementHandler
        where TObject : HitObject
    {
        protected IRulesetConfigManager Config { get; private set; }

        protected readonly Ruleset Ruleset;

        [Resolved]
        protected IFrameBasedClock EditorClock { get; private set; }

        [Resolved]
        protected EditorBeatmap EditorBeatmap { get; private set; }

        [Resolved]
        private IAdjustableClock adjustableClock { get; set; }

        [Resolved]
        private IBeatSnapProvider beatSnapProvider { get; set; }

        protected ComposeBlueprintContainer BlueprintContainer { get; private set; }

        private DrawableEditRulesetWrapper<TObject> drawableRulesetWrapper;
        private Container distanceSnapGridContainer;
        private DistanceSnapGrid distanceSnapGrid;
        private readonly List<Container> layerContainers = new List<Container>();

        private InputManager inputManager;

        private RadioButtonCollection toolboxCollection;

        protected HitObjectComposer(Ruleset ruleset)
        {
            Ruleset = ruleset;
            RelativeSizeAxes = Axes.Both;
        }

        [BackgroundDependencyLoader]
        private void load(IFrameBasedClock framedClock)
        {
            EditorBeatmap.HitObjectAdded += addHitObject;
            EditorBeatmap.HitObjectRemoved += removeHitObject;
            EditorBeatmap.StartTimeChanged += UpdateHitObject;

            Config = Dependencies.Get<RulesetConfigCache>().GetConfigFor(Ruleset);

            try
            {
                drawableRulesetWrapper = new DrawableEditRulesetWrapper<TObject>(CreateDrawableRuleset(Ruleset, EditorBeatmap.PlayableBeatmap))
                {
                    Clock = framedClock,
                    ProcessCustomClock = false
                };
            }
            catch (Exception e)
            {
                Logger.Error(e, "Could not load beatmap sucessfully!");
                return;
            }

            var layerBelowRuleset = drawableRulesetWrapper.CreatePlayfieldAdjustmentContainer().WithChildren(new Drawable[]
            {
                distanceSnapGridContainer = new Container { RelativeSizeAxes = Axes.Both },
                new EditorPlayfieldBorder { RelativeSizeAxes = Axes.Both }
            });

            var layerAboveRuleset = drawableRulesetWrapper.CreatePlayfieldAdjustmentContainer().WithChild(BlueprintContainer = CreateBlueprintContainer());

            layerContainers.Add(layerBelowRuleset);
            layerContainers.Add(layerAboveRuleset);

            InternalChild = new GridContainer
            {
                RelativeSizeAxes = Axes.Both,
                Content = new[]
                {
                    new Drawable[]
                    {
                        new FillFlowContainer
                        {
                            Name = "Sidebar",
                            RelativeSizeAxes = Axes.Both,
                            Padding = new MarginPadding { Right = 10 },
                            Children = new Drawable[]
                            {
                                new ToolboxGroup { Child = toolboxCollection = new RadioButtonCollection { RelativeSizeAxes = Axes.X } }
                            }
                        },
                        new Container
                        {
                            Name = "Content",
                            RelativeSizeAxes = Axes.Both,
                            Children = new Drawable[]
                            {
                                layerBelowRuleset,
                                drawableRulesetWrapper,
                                layerAboveRuleset
                            }
                        }
                    },
                },
                ColumnDimensions = new[]
                {
                    new Dimension(GridSizeMode.Absolute, 200),
                }
            };

            toolboxCollection.Items = CompositionTools
                                      .Prepend(new SelectTool())
                                      .Select(t => new RadioButton(t.Name, () => toolSelected(t)))
                                      .ToList();

            setSelectTool();

            BlueprintContainer.SelectionChanged += selectionChanged;
        }

        protected override bool OnKeyDown(KeyDownEvent e)
        {
            if (e.Key >= Key.Number1 && e.Key <= Key.Number9)
            {
                var item = toolboxCollection.Items.ElementAtOrDefault(e.Key - Key.Number1);

                if (item != null)
                {
                    item.Select();
                    return true;
                }
            }

            return base.OnKeyDown(e);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            inputManager = GetContainingInputManager();
        }

        private double lastGridUpdateTime;

        protected override void Update()
        {
            base.Update();

            if (EditorClock.CurrentTime != lastGridUpdateTime && !(BlueprintContainer.CurrentTool is SelectTool))
                showGridFor(Enumerable.Empty<HitObject>());
        }

        protected override void UpdateAfterChildren()
        {
            base.UpdateAfterChildren();

            layerContainers.ForEach(l =>
            {
                l.Anchor = drawableRulesetWrapper.Playfield.Anchor;
                l.Origin = drawableRulesetWrapper.Playfield.Origin;
                l.Position = drawableRulesetWrapper.Playfield.Position;
                l.Size = drawableRulesetWrapper.Playfield.Size;
            });
        }

        private void selectionChanged(IEnumerable<HitObject> selectedHitObjects)
        {
            var hitObjects = selectedHitObjects.ToArray();

            if (hitObjects.Any())
            {
                // ensure in selection mode if a selection is made.
                setSelectTool();

                showGridFor(hitObjects);
            }
            else
                distanceSnapGridContainer.Hide();
        }

        private void setSelectTool() => toolboxCollection.Items.First().Select();

        private void toolSelected(HitObjectCompositionTool tool)
        {
            BlueprintContainer.CurrentTool = tool;

            if (tool is SelectTool)
                distanceSnapGridContainer.Hide();
            else
            {
                EditorBeatmap.SelectedHitObjects.Clear();
                showGridFor(Enumerable.Empty<HitObject>());
            }
        }

        private void showGridFor(IEnumerable<HitObject> selectedHitObjects)
        {
            distanceSnapGridContainer.Clear();
            distanceSnapGrid = CreateDistanceSnapGrid(selectedHitObjects);

            if (distanceSnapGrid != null)
            {
                distanceSnapGridContainer.Child = distanceSnapGrid;
                distanceSnapGridContainer.Show();
            }

            lastGridUpdateTime = EditorClock.CurrentTime;
        }

        private void addHitObject(HitObject hitObject) => UpdateHitObject(hitObject);

        private void removeHitObject(HitObject hitObject) => UpdateHitObject(null);

        public override IEnumerable<DrawableHitObject> HitObjects => drawableRulesetWrapper.Playfield.AllHitObjects;
        public override bool CursorInPlacementArea => drawableRulesetWrapper.Playfield.ReceivePositionalInputAt(inputManager.CurrentState.Mouse.Position);

        protected abstract IReadOnlyList<HitObjectCompositionTool> CompositionTools { get; }

        protected abstract ComposeBlueprintContainer CreateBlueprintContainer();

        protected abstract DrawableRuleset<TObject> CreateDrawableRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null);

        public void BeginPlacement(HitObject hitObject)
        {
            EditorBeatmap.PlacementObject.Value = hitObject;

            if (distanceSnapGrid != null)
                hitObject.StartTime = GetSnappedPosition(distanceSnapGrid.ToLocalSpace(inputManager.CurrentState.Mouse.Position), hitObject.StartTime).time;
        }

        public void EndPlacement(HitObject hitObject, bool commit)
        {
            EditorBeatmap.PlacementObject.Value = null;

            if (commit)
            {
                EditorBeatmap.Add(hitObject);

                adjustableClock.Seek(hitObject.GetEndTime());
            }

            showGridFor(Enumerable.Empty<HitObject>());
        }

        public void Delete(HitObject hitObject) => EditorBeatmap.Remove(hitObject);

        public override (Vector2 position, double time) GetSnappedPosition(Vector2 position, double time) => distanceSnapGrid?.GetSnappedPosition(position) ?? (position, time);

        public override float GetBeatSnapDistanceAt(double referenceTime)
        {
            DifficultyControlPoint difficultyPoint = EditorBeatmap.ControlPointInfo.DifficultyPointAt(referenceTime);
            return (float)(100 * EditorBeatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier * difficultyPoint.SpeedMultiplier / beatSnapProvider.BeatDivisor);
        }

        public override float DurationToDistance(double referenceTime, double duration)
        {
            double beatLength = beatSnapProvider.GetBeatLengthAtTime(referenceTime);
            return (float)(duration / beatLength * GetBeatSnapDistanceAt(referenceTime));
        }

        public override double DistanceToDuration(double referenceTime, float distance)
        {
            double beatLength = beatSnapProvider.GetBeatLengthAtTime(referenceTime);
            return distance / GetBeatSnapDistanceAt(referenceTime) * beatLength;
        }

        public override double GetSnappedDurationFromDistance(double referenceTime, float distance)
            => beatSnapProvider.SnapTime(referenceTime + DistanceToDuration(referenceTime, distance), referenceTime) - referenceTime;

        public override float GetSnappedDistanceFromDistance(double referenceTime, float distance)
        {
            var snappedEndTime = beatSnapProvider.SnapTime(referenceTime + DistanceToDuration(referenceTime, distance), referenceTime);

            return DurationToDistance(referenceTime, snappedEndTime - referenceTime);
        }

        public override void UpdateHitObject(HitObject hitObject) => EditorBeatmap.UpdateHitObject(hitObject);

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            if (EditorBeatmap != null)
            {
                EditorBeatmap.HitObjectAdded -= addHitObject;
                EditorBeatmap.HitObjectRemoved -= removeHitObject;
            }
        }
    }

    [Cached(typeof(HitObjectComposer))]
    [Cached(typeof(IDistanceSnapProvider))]
    public abstract class HitObjectComposer : CompositeDrawable, IDistanceSnapProvider
    {
        internal HitObjectComposer()
        {
            RelativeSizeAxes = Axes.Both;
        }

        /// <summary>
        /// All the <see cref="DrawableHitObject"/>s.
        /// </summary>
        public abstract IEnumerable<DrawableHitObject> HitObjects { get; }

        /// <summary>
        /// Whether the user's cursor is currently in an area of the <see cref="HitObjectComposer"/> that is valid for placement.
        /// </summary>
        public abstract bool CursorInPlacementArea { get; }

        /// <summary>
        /// Creates the <see cref="DistanceSnapGrid"/> applicable for a <see cref="HitObject"/> selection.
        /// </summary>
        /// <param name="selectedHitObjects">The <see cref="HitObject"/> selection.</param>
        /// <returns>The <see cref="DistanceSnapGrid"/> for <paramref name="selectedHitObjects"/>. If empty, a grid is returned for the current point in time.</returns>
        [CanBeNull]
        protected virtual DistanceSnapGrid CreateDistanceSnapGrid([NotNull] IEnumerable<HitObject> selectedHitObjects) => null;

        /// <summary>
        /// Updates a <see cref="HitObject"/>, invoking <see cref="HitObject.ApplyDefaults"/> and re-processing the beatmap.
        /// </summary>
        /// <param name="hitObject">The <see cref="HitObject"/> to update.</param>
        public abstract void UpdateHitObject([CanBeNull] HitObject hitObject);

        public abstract (Vector2 position, double time) GetSnappedPosition(Vector2 position, double time);

        public abstract float GetBeatSnapDistanceAt(double referenceTime);

        public abstract float DurationToDistance(double referenceTime, double duration);

        public abstract double DistanceToDuration(double referenceTime, float distance);

        public abstract double GetSnappedDurationFromDistance(double referenceTime, float distance);

        public abstract float GetSnappedDistanceFromDistance(double referenceTime, float distance);
    }
}


text:
package org.mifos.platform.questionnaire.persistence;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.platform.questionnaire.domain.QuestionEntity;
import org.mifos.platform.questionnaire.domain.QuestionState;
import org.mifos.platform.questionnaire.domain.QuestionnaireService;
import org.mifos.platform.questionnaire.service.QuestionDetail;
import org.mifos.platform.questionnaire.service.QuestionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mifos.platform.questionnaire.service.QuestionType.DATE;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/test-questionnaire-dbContext.xml", "/test-questionnaire-persistenceContext.xml", "/META-INF/spring/QuestionnaireContext.xml"})
@TransactionConfiguration(transactionManager = "platformTransactionManager", defaultRollback = true)
@SuppressWarnings("PMD")
public class QuestionDaoIntegrationTest {

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private QuestionnaireService questionnaireService;

    @Test
    @Transactional
    public void testCountOfQuestionsWithTitle() throws SystemException {
        String questionTitle = "Title" + System.currentTimeMillis();
        List<Long> result = questionDao.retrieveCountOfQuestionsWithText(questionTitle);
        assertEquals(Long.valueOf(0), result.get(0));
        defineQuestion(questionTitle, DATE);
        result = questionDao.retrieveCountOfQuestionsWithText(questionTitle);
        assertEquals(Long.valueOf(1), result.get(0));
    }

    @Test
    @Transactional
    public void testRetrieveByState() throws SystemException {
        QuestionDetail questionDetail2 = defineQuestion("Title2" + System.currentTimeMillis(), QuestionType.NUMERIC);
        QuestionDetail questionDetail1 = defineQuestion("Title1" + System.currentTimeMillis(), QuestionType.NUMERIC);
        List<String> expectedTitles = asList(questionDetail1.getText(), questionDetail2.getText());
        List<QuestionEntity> actualQuestions = questionDao.retrieveByState(QuestionState.ACTIVE.getValue());
        assertThat(actualQuestions.size(), is(2));
        assertThat(actualQuestions.get(0).getQuestionText(), is(expectedTitles.get(0)));
        assertThat(actualQuestions.get(1).getQuestionText(), is(expectedTitles.get(1)));
    }

    @Test
    @Transactional
    public void testRetrieveByStateExcluding() throws SystemException {
        QuestionDetail questionDetail3 = defineQuestion("Title3" + System.currentTimeMillis(), QuestionType.NUMERIC);
        QuestionDetail questionDetail2 = defineQuestion("Title2" + System.currentTimeMillis(), QuestionType.NUMERIC);
        QuestionDetail questionDetail1 = defineQuestion("Title1" + System.currentTimeMillis(), QuestionType.NUMERIC);
        List<String> expectedTitles = asList(questionDetail1.getText(), questionDetail2.getText());
        List<QuestionEntity> actualQuestions = questionDao.retrieveByStateExcluding(asList(questionDetail3.getId()), QuestionState.ACTIVE.getValue());
        assertThat(actualQuestions.size(), is(2));
        assertThat(actualQuestions.get(0).getQuestionText(), is(expectedTitles.get(0)));
        assertThat(actualQuestions.get(1).getQuestionText(), is(expectedTitles.get(1)));
    }

    private QuestionDetail defineQuestion(String questionTitle, QuestionType questionType) throws SystemException {
        return questionnaireService.defineQuestion(new QuestionDetail(questionTitle, questionType));
    }
}


text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.remote.util;

import build.bazel.remote.execution.v2.ActionResult;
import build.bazel.remote.execution.v2.Digest;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ExecutionRequirements;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnMetrics;
import com.google.devtools.build.lib.actions.SpawnResult;
import com.google.devtools.build.lib.actions.SpawnResult.Status;
import com.google.devtools.build.lib.remote.common.CacheNotFoundException;
import com.google.devtools.build.lib.remote.common.RemoteCacheClient.ActionKey;
import com.google.devtools.build.lib.remote.options.RemoteOutputsMode;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.Spawn.Code;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;
import javax.annotation.Nullable;

/** Utility methods for the remote package. * */
public class Utils {

  private Utils() {}

  /**
   * Returns the result of a {@link ListenableFuture} if successful, or throws any checked {@link
   * Exception} directly if it's an {@link IOException} or else wraps it in an {@link IOException}.
   */
  public static <T> T getFromFuture(ListenableFuture<T> f)
      throws IOException, InterruptedException {
    try {
      return f.get();
    } catch (ExecutionException e) {
      Throwable cause = e.getCause();
      if (cause instanceof InterruptedException) {
        throw (InterruptedException) cause;
      }
      if (cause instanceof IOException) {
        throw (IOException) cause;
      }
      if (cause instanceof RuntimeException) {
        throw (RuntimeException) cause;
      }
      throw new IOException(cause);
    }
  }

  /**
   * Returns the (exec root relative) path of a spawn output that should be made available via
   * {@link SpawnResult#getInMemoryOutput(ActionInput)}.
   */
  @Nullable
  public static PathFragment getInMemoryOutputPath(Spawn spawn) {
    String outputPath =
        spawn.getExecutionInfo().get(ExecutionRequirements.REMOTE_EXECUTION_INLINE_OUTPUTS);
    if (outputPath != null) {
      return PathFragment.create(outputPath);
    }
    return null;
  }

  /** Constructs a {@link SpawnResult}. */
  public static SpawnResult createSpawnResult(
      int exitCode,
      boolean cacheHit,
      String runnerName,
      @Nullable InMemoryOutput inMemoryOutput,
      SpawnMetrics spawnMetrics,
      String mnemonic) {
    SpawnResult.Builder builder =
        new SpawnResult.Builder()
            .setStatus(exitCode == 0 ? Status.SUCCESS : Status.NON_ZERO_EXIT)
            .setExitCode(exitCode)
            .setRunnerName(cacheHit ? runnerName + " cache hit" : runnerName)
            .setCacheHit(cacheHit)
            .setSpawnMetrics(spawnMetrics)
            .setRemote(true);
    if (exitCode != 0) {
      builder.setFailureDetail(
          FailureDetail.newBuilder()
              .setMessage(mnemonic + " returned a non-zero exit code when running remotely")
              .setSpawn(FailureDetails.Spawn.newBuilder().setCode(Code.NON_ZERO_EXIT))
              .build());
    }
    if (inMemoryOutput != null) {
      builder.setInMemoryOutput(inMemoryOutput.getOutput(), inMemoryOutput.getContents());
    }
    return builder.build();
  }

  /** Returns {@code true} if all spawn outputs should be downloaded to disk. */
  public static boolean shouldDownloadAllSpawnOutputs(
      RemoteOutputsMode remoteOutputsMode, int exitCode, boolean hasTopLevelOutputs) {
    return remoteOutputsMode.downloadAllOutputs()
        ||
        // In case the action failed, download all outputs. It might be helpful for debugging
        // and there is no point in injecting output metadata of a failed action.
        exitCode != 0
        ||
        // If one output of a spawn is a top level output then download all outputs. Spawns
        // are typically structured in a way that either all or no outputs are top level and
        // it's much simpler to implement under this assumption.
        (remoteOutputsMode.downloadToplevelOutputsOnly() && hasTopLevelOutputs);
  }

  /** Returns {@code true} if outputs contains one or more top level outputs. */
  public static boolean hasFilesToDownload(
      Collection<? extends ActionInput> outputs, ImmutableSet<ActionInput> filesToDownload) {
    if (filesToDownload.isEmpty()) {
      return false;
    }
    return !Collections.disjoint(outputs, filesToDownload);
  }

  public static String grpcAwareErrorMessage(IOException e) {
    io.grpc.Status errStatus = io.grpc.Status.fromThrowable(e);
    if (!errStatus.getCode().equals(io.grpc.Status.UNKNOWN.getCode())) {
      // If the error originated in the gRPC library then display it as "STATUS: error message"
      // to the user
      return String.format("%s: %s", errStatus.getCode().name(), errStatus.getDescription());
    }
    return e.getMessage();
  }

  @SuppressWarnings("ProtoParseWithRegistry")
  public static ListenableFuture<ActionResult> downloadAsActionResult(
      ActionKey actionDigest,
      BiFunction<Digest, OutputStream, ListenableFuture<Void>> downloadFunction) {
    ByteArrayOutputStream data = new ByteArrayOutputStream(/* size= */ 1024);
    ListenableFuture<Void> download = downloadFunction.apply(actionDigest.getDigest(), data);
    return FluentFuture.from(download)
        .transformAsync(
            (v) -> {
              try {
                return Futures.immediateFuture(ActionResult.parseFrom(data.toByteArray()));
              } catch (InvalidProtocolBufferException e) {
                return Futures.immediateFailedFuture(e);
              }
            },
            MoreExecutors.directExecutor())
        .catching(CacheNotFoundException.class, (e) -> null, MoreExecutors.directExecutor());
  }

  public static void verifyBlobContents(String expectedHash, String actualHash) throws IOException {
    if (!expectedHash.equals(actualHash)) {
      String msg =
          String.format(
              "An output download failed, because the expected hash"
                  + "'%s' did not match the received hash '%s'.",
              expectedHash, actualHash);
      throw new IOException(msg);
    }
  }

  /** An in-memory output file. */
  public static final class InMemoryOutput {
    private final ActionInput output;
    private final ByteString contents;

    public InMemoryOutput(ActionInput output, ByteString contents) {
      this.output = output;
      this.contents = contents;
    }

    public ActionInput getOutput() {
      return output;
    }

    public ByteString getContents() {
      return contents;
    }
  }
}


text:
//
// LocalVariableHideFieldIssue.cs
//
// Author:
//      Mansheng Yang <lightyang0@gmail.com>
//
// Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using ICSharpCode.NRefactory.Semantics;

namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
	[IssueDescription ("Local variable hides a member",
					   Description = "Local variable has the same name as a member and hides it.",
					   Category = IssueCategories.CodeQualityIssues,
					   Severity = Severity.Suggestion,
					   IssueMarker = IssueMarker.Underline)]
	public class LocalVariableHidesMemberIssue : VariableHidesMemberIssue
	{
		internal override GatherVisitorBase GetGatherVisitor (BaseRefactoringContext context)
		{
			return new GatherVisitor (context);
		}

		class GatherVisitor : GatherVisitorBase
		{
			public GatherVisitor (BaseRefactoringContext ctx)
				: base (ctx)
			{
			}

			public override void VisitVariableInitializer (VariableInitializer variableInitializer)
			{
				base.VisitVariableInitializer (variableInitializer);

				if (!(ctx.Resolve (variableInitializer) is LocalResolveResult))
					return;
				if (HidesMember (ctx, variableInitializer, variableInitializer.Name))
					AddIssue (variableInitializer.NameToken,
						ctx.TranslateString ("Local variable has the same name as a member and hides it"));
			}

			public override void VisitForeachStatement (ForeachStatement foreachStatement)
			{
				base.VisitForeachStatement (foreachStatement);

				if (HidesMember (ctx, foreachStatement, foreachStatement.VariableName))
					AddIssue (foreachStatement.VariableNameToken,
						ctx.TranslateString ("Local variable has the same name as a member and hides it"));
			}
		}
	}
}


text:
import unittest

from mock import patch, Mock
from boto.swf.layer1 import Layer1
from boto.exception import SWFResponseError

from swf.constants import REGISTERED
from swf.models.domain import Domain
from swf.models.workflow import WorkflowType, WorkflowExecution
from swf.querysets.workflow import BaseWorkflowQuerySet,\
                                   WorkflowTypeQuerySet,\
                                   WorkflowExecutionQuerySet
from swf.exceptions import DoesNotExistError, ResponseError
from swf.utils import datetime_timestamp, past_day

from ..mocks.workflow import mock_describe_workflow_type,\
                             mock_list_workflow_types,\
                             mock_list_open_workflow_executions,\
                             mock_list_closed_workflow_executions,\
                             mock_describe_workflow_execution

class TestBaseWorkflowTypeQuerySet(unittest.TestCase):

    def setUp(self):
        self.domain = Domain("TestDomain")
        self.bw = BaseWorkflowQuerySet(self.domain)

    def tearDown(self):
        pass

    def test_get_domain_property_instantiates_private_attribute(self):
        bw = BaseWorkflowQuerySet(self.domain)
        delattr(bw, '_domain')
        bw.domain

        self.assertTrue(hasattr(bw, '_domain'))

    def test_instantiation_with_valid_domain(self):
        bw = BaseWorkflowQuerySet(self.domain)

        self.assertIsInstance(bw.domain, Domain)
        self.assertEqual(bw._domain, bw.domain)

    def test_instantiation_with_invalid_domain(self):
        with self.assertRaises(TypeError):
            BaseWorkflowQuerySet("WrongType")

    def test__list_isnt_implemented(self):
        with self.assertRaises(NotImplementedError):
            self.bw._list()

class TestWorkflowTypeQuerySet(unittest.TestCase):

    def setUp(self):
        self.domain = Domain("TestDomain")
        self.wtq = WorkflowTypeQuerySet(self.domain)

    def tearDown(self):
        pass

    def test_valid_workflow_type(self):
        with patch.object(
            self.wtq.connection,
            'describe_workflow_type',
            mock_describe_workflow_type
        ):
            wt = self.wtq.get("TestType", "0.1")
            self.assertIsNotNone(wt)
            self.assertIsInstance(wt, WorkflowType)

    def test_get_non_existent_workflow_type(self):
        with patch.object(self.wtq.connection, 'describe_workflow_type') as mock:
            with self.assertRaises(DoesNotExistError):
                mock.side_effect = SWFResponseError(
                    400,
                    "mocked exception",
                    {
                        "__type": "UnknownResourceFault",
                        "message": "Whatever",
                    }
                )
                self.wtq.get("NonExistentWorkflowType", "0.1")

    def test_get_whatever_failing_workflow_type(self):
        with patch.object(self.wtq.connection, 'describe_workflow_type') as mock:
            with self.assertRaises(ResponseError):
                mock.side_effect = SWFResponseError(
                    400,
                    "mocked exception",
                    {
                        "__type": "Whatever Error",
                        "message": "Whatever",
                    }
                )
                self.wtq.get("NonExistentWorkflowType", "0.1")

    def test_get_or_create_existing_workflow_type(self):
        with patch.object(Layer1, 'describe_workflow_type', mock_describe_workflow_type):
            workflow_type = self.wtq.get_or_create("TestActivityType", "testversion")

            self.assertIsInstance(workflow_type, WorkflowType)

    def test_get_or_create_non_existent_workflow_type(self):
        with patch.object(Layer1, 'describe_workflow_type') as mock:
            mock.side_effect = DoesNotExistError("Mocked exception")

            with patch.object(Layer1, 'register_workflow_type', mock_describe_workflow_type):
                workflow_type = self.wtq.get_or_create("TestDomain", "testversion")

                self.assertIsInstance(workflow_type, WorkflowType)

    def test__list_non_empty_workflow_types(self):
        with patch.object(
            self.wtq.connection,
            'list_workflow_types',
            mock_list_workflow_types
        ):
            wt = self.wtq._list()
            self.assertIsNotNone(wt)
            self.assertIsInstance(wt, dict)

            for workflow in wt[WorkflowTypeQuerySet._infos_plural]:
                self.assertIsInstance(workflow, dict)

    def test_filter_with_registered_status(self):
        # Nota: mock_list_workfflow_types returned
        # values are REGISTERED
        with patch.object(
            self.wtq.connection,
            'list_workflow_types',
            mock_list_workflow_types
        ):
            types = self.wtq.filter(registration_status=REGISTERED)
            self.assertIsNotNone(types)
            self.assertIsInstance(types, list)

            for wt in types:
                self.assertIsInstance(wt, WorkflowType)
                self.assertEqual(wt.status, REGISTERED)

    def test_create_workflow_type(self):
        with patch.object(Layer1, 'register_workflow_type'):
            new_wt = self.wtq.create(
                self.domain,
                "TestWorkflowType",
                "0.test",
            )

            self.assertIsNotNone(new_wt)
            self.assertIsInstance(new_wt, WorkflowType)

class TestWorkflowExecutionQuerySet(unittest.TestCase):

    def setUp(self):
        self.domain = Domain("TestDomain")
        self.wt = WorkflowType(self.domain, "TestType", "0.1")
        self.weq = WorkflowExecutionQuerySet(self.domain)

    def tearDown(self):
        pass

    def test__is_valid_open_status_param(self):
        status = WorkflowExecution.STATUS_OPEN

        self.assertTrue(
            self.weq._is_valid_status_param(status, 'oldest_date'),
        )

    def test__is_invalid_open_status_param(self):
        status = WorkflowExecution.STATUS_OPEN

        self.assertFalse(
            self.weq._is_valid_status_param(status, 'start_oldest_date'),
        )

    def test__is_valid_closed_status_param(self):
        status = WorkflowExecution.STATUS_CLOSED

        self.assertTrue(
            self.weq._is_valid_status_param(status, 'start_oldest_date'),
        )

    def test__is_invalid_closed_status_param(self):
        status = WorkflowExecution.STATUS_CLOSED

        self.assertFalse(
            self.weq._is_valid_status_param(status, 'oldest_date'),
        )

    def test_validate_valid_open_status_parameters(self):
        params = ['oldest_date', 'latest_date']
        status = WorkflowExecution.STATUS_OPEN

        self.assertEqual(
            self.weq._validate_status_parameters(status, params),
            []
        )

    def test_validate_invalid_open_status_parameters(self):
        params = ['oldest_date', 'start_latest_date']
        status = WorkflowExecution.STATUS_OPEN

        self.assertEqual(
            self.weq._validate_status_parameters(status, params),
            ['start_latest_date']
        )

    def test_validate_valid_closed_status_parameters(self):
        params = ['start_oldest_date', 'start_latest_date']
        status = WorkflowExecution.STATUS_CLOSED

        self.assertEqual(
            self.weq._validate_status_parameters(status, params),
            []
        )

    def test_validate_invalid_closed_status_parameters(self):
        params = ['oldest_date', 'start_latest_date']
        status = WorkflowExecution.STATUS_CLOSED

        self.assertEqual(
            self.weq._validate_status_parameters(status, params),
            ['oldest_date']
        )

    def test_list_open_workflows_executions_with_start_oldest_date(self):
        with patch.object(
            self.weq.connection,
            'list_open_workflow_executions',
            mock_list_open_workflow_executions
        ):
            we = self.weq.list_workflow_executions(
                WorkflowExecution.STATUS_OPEN,
                self.domain.name,
                start_oldest_date=int(datetime_timestamp(past_day(3)))
            )
            self.assertIsNotNone(we)
            self.assertIsInstance(we, dict)

            self.assertTrue(we['executionInfos'][0]['executionStatus'] == WorkflowExecution.STATUS_OPEN)

    def test_list_closed_workflows_executions(self):
        with patch.object(
            self.weq.connection,
            'list_closed_workflow_executions',
            mock_list_closed_workflow_executions
        ):
            we = self.weq.list_workflow_executions(
                WorkflowExecution.STATUS_CLOSED,
                self.domain.name,
                start_oldest_date=int(datetime_timestamp(past_day(3)))
            )
            self.assertIsNotNone(we)
            self.assertIsInstance(we, dict)

            self.assertTrue(we['executionInfos'][0]['executionStatus'] == WorkflowExecution.STATUS_CLOSED)

    def test_list_invalid_status_workflow_executions(self):
        with self.assertRaises(ValueError):
            self.weq.list_workflow_executions(
                "INVALID_STATUS",
                self.domain.name,
                start_oldest_date=int(datetime_timestamp(past_day(3)))
            )

    def test_get_workflow_type(self):
        execution_info = mock_list_open_workflow_executions()['executionInfos'][0]

        with patch.object(
            Layer1,
            'describe_workflow_type',
            mock_describe_workflow_type
        ):
            wt = self.weq.get_workflow_type(execution_info)
            self.assertIsNotNone(wt)
            self.assertIsInstance(wt, WorkflowType)
            self.assertTrue(wt.name == execution_info['workflowType']['name'])

    def test_get_valid_workflow_execution(self):
        pass
        # with patch.object(
        #     self.weq.connection,
        #     'describe_workflow_execution',
        #     mock_describe_workflow_execution
        # ):
        #     we = self.weq.get("mocked-workflow-id", "mocked-run-id")
        #     self.assertIsNotNone(we)
        #     self.assertIsInstance(we, WorkflowExecution)

    def test_get_non_existent_workflow_execution(self):
        with patch.object(self.weq.connection, 'describe_workflow_execution') as mock:
            with self.assertRaises(DoesNotExistError):
                mock.side_effect = SWFResponseError(
                    400,
                    "mocked exception",
                    {
                        "__type": "UnknownResourceFault",
                        "message": "Whatever",
                    }
                )
                self.weq.get("mocked-workflow-id", "mocked-run-id")

    def test_get_invalid_workflow_execution(self):
        with patch.object(self.weq.connection, 'describe_workflow_execution') as mock:
            with self.assertRaises(ResponseError):
                mock.side_effect = SWFResponseError(
                    400,
                    "mocked exception",
                    {
                        "__type": "WhateverFault",
                        "message": "Whatever",
                    }
                )
                self.weq.get("mocked-workflow-id", "mocked-run-id")

    def test_filter_without_close_time_filter(self):
        self.weq._list_items = Mock(return_value=[])
        qs = self.weq.filter()
        self.weq._list_items.assert_called_once()
        kwargs = self.weq._list_items.call_args[1]
        self.assertIsInstance(kwargs["start_oldest_date"], int)

    def test_filter_with_close_time_filter(self):
        self.weq._list_items = Mock(return_value=[])
        qs = self.weq.filter(status=WorkflowExecution.STATUS_CLOSED,
                             close_latest_date=5)
        self.weq._list_items.assert_called_once()
        kwargs = self.weq._list_items.call_args[1]
        self.assertIsNone(kwargs["start_oldest_date"])
        self.assertIsInstance(kwargs["close_latest_date"], int)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoDeploy
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            //Application.Run(new FormFastChoose());
            //Application.Run(new FormServer());
        }
    }
}


text:
<?php

defined('_JEXEC') or die;

/**
 * Class FieldtestFrontendHelper
 *
 * @since  1.6
 */
class FieldtestFrontendHelper
{
	/**
	 * Get an instance of the named model
	 *
	 * @param   string  $name  Model name
	 *
	 * @return null|object
	 */
	public static function getModel($name)
	{
		$model = null;

		// If the file exists, let's
		if (file_exists(JPATH_SITE . '/components/com_fieldtest/models/' . strtolower($name) . '.php'))
		{
			require_once JPATH_SITE . '/components/com_fieldtest/models/' . strtolower($name) . '.php';
			$model = JModelLegacy::getInstance($name, 'FieldtestModel');
		}

		return $model;
	}
}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/libcore/luni/src/main/java/java/text/Format.java
//

#include "../../J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_JavaTextFormat")
#ifdef RESTRICT_JavaTextFormat
#define INCLUDE_ALL_JavaTextFormat 0
#else
#define INCLUDE_ALL_JavaTextFormat 1
#endif
#undef RESTRICT_JavaTextFormat

#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#if !defined (JavaTextFormat_) && (INCLUDE_ALL_JavaTextFormat || defined(INCLUDE_JavaTextFormat))
#define JavaTextFormat_

#define RESTRICT_JavaIoSerializable 1
#define INCLUDE_JavaIoSerializable 1
#include "../../java/io/Serializable.h"

@class JavaLangStringBuffer;
@class JavaTextFieldPosition;
@class JavaTextParsePosition;
@protocol JavaTextAttributedCharacterIterator;

/*!
 @brief The base class for all formats.

 This is an abstract base class which specifies the protocol for classes which
 convert other objects or values, such as numeric values and dates, and their
 string representations. In some cases these representations may be localized
 or contain localized characters or strings. For example, a numeric formatter
 such as DecimalFormat may convert a numeric value such as 12345 to
 the string "$12,345". It may also parse the string back into a numeric value.
 A date and time formatter like SimpleDateFormat may represent a
 specific date, encoded numerically, as a string such as "Wednesday, February
 26, 1997 AD".

 Many of the concrete subclasses of Format employ the notion of a
 pattern. A pattern is a string representation of the rules which govern the
 conversion between values and strings. For example, a DecimalFormat
 object may be associated with the pattern "$#,##0.00;($#,##0.00)", which is a
 common US English format for currency values, yielding strings such as
 "$1,234.45" for 1234.45, and "($987.65)" for -987.6543. The specific syntax
 of a pattern is defined by each subclass. Even though many subclasses use
 patterns, the notion of a pattern is not inherent to Format classes
 in general, and is not part of the explicit base class protocol.

 Two complex formatting classes are worth mentioning: MessageFormat
 and ChoiceFormat. ChoiceFormat is a subclass of
 NumberFormat which allows the user to format different number ranges
 as strings. For instance, 0 may be represented as "no files", 1 as "one
 file", and any number greater than 1 as "many files". MessageFormat
 is a formatter which utilizes other Format objects to format a string
 containing multiple values. For instance, a MessageFormat object
 might produce the string "There are no files on the disk MyDisk on February
 27, 1997." given the arguments 0, "MyDisk", and the date value of 2/27/97.
 See the ChoiceFormat and MessageFormat descriptions for
 further information.
 */
@interface JavaTextFormat : NSObject < JavaIoSerializable, NSCopying >

#pragma mark Public

/*!
 @brief Returns a copy of this Format instance.
 @return a shallow copy of this format.
 - seealso: java.lang.Cloneable
 */
- (id)clone;

/*!
 @brief Formats the specified object using the rules of this format.
 @param object
 the object to format.
 @return the formatted string.
 @throws IllegalArgumentException
 if the object cannot be formatted by this format.
 */
- (NSString *)formatWithId:(id)object;

/*!
 @brief Appends the specified object to the specified string buffer using the
 rules of this format.

 field is an input/output parameter. If its field
 member contains an enum value specifying a field on input, then its
 beginIndex and endIndex members will be updated with the
 text offset of the first occurrence of this field in the formatted text.
 @param object
 the object to format.
 @param buffer
 the string buffer where the formatted string is appended to.
 @param field
 on input: an optional alignment field; on output: the offsets
 of the alignment field in the formatted text.
 @return the string buffer.
 @throws IllegalArgumentException
 if the object cannot be formatted by this format.
 */
- (JavaLangStringBuffer *)formatWithId:(id)object
              withJavaLangStringBuffer:(JavaLangStringBuffer *)buffer
             withJavaTextFieldPosition:(JavaTextFieldPosition *)field;

/*!
 @brief Formats the specified object using the rules of this format and returns
 an AttributedCharacterIterator with the formatted string and no
 attributes.

 Subclasses should return an AttributedCharacterIterator with the
 appropriate attributes.
 @param object
 the object to format.
 @return an AttributedCharacterIterator with the formatted object
 and attributes.
 @throws IllegalArgumentException
 if the object cannot be formatted by this format.
 */
- (id<JavaTextAttributedCharacterIterator>)formatToCharacterIteratorWithId:(id)object;

/*!
 @brief Parses the specified string using the rules of this format.
 @param string
 the string to parse.
 @return the object resulting from the parse.
 @throws ParseException
 if an error occurs during parsing.
 */
- (id)parseObjectWithNSString:(NSString *)string;

/*!
 @brief Parses the specified string starting at the index specified by
 position.
 If the string is successfully parsed then the index of
 the ParsePosition is updated to the index following the parsed
 text. On error, the index is unchanged and the error index of
 ParsePosition is set to the index where the error occurred.
 @param string
 the string to parse.
 @param position
 input/output parameter, specifies the start index in
 string from where to start parsing. If parsing is
 successful, it is updated with the index following the parsed
 text; on error, the index is unchanged and the error index is
 set to the index where the error occurred.
 @return the object resulting from the parse or null if there is
 an error.
 */
- (id)parseObjectWithNSString:(NSString *)string
    withJavaTextParsePosition:(JavaTextParsePosition *)position;

#pragma mark Protected

/*!
 @brief Used by subclasses.
 This was public in Java 5.
 */
- (instancetype)init;

#pragma mark Package-Private

+ (jboolean)upToWithNSString:(NSString *)string
   withJavaTextParsePosition:(JavaTextParsePosition *)position
    withJavaLangStringBuffer:(JavaLangStringBuffer *)buffer
                    withChar:(jchar)stop;

+ (jboolean)upToWithQuotesWithNSString:(NSString *)string
             withJavaTextParsePosition:(JavaTextParsePosition *)position
              withJavaLangStringBuffer:(JavaLangStringBuffer *)buffer
                              withChar:(jchar)stop
                              withChar:(jchar)start;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaTextFormat)

FOUNDATION_EXPORT void JavaTextFormat_init(JavaTextFormat *self);

FOUNDATION_EXPORT jboolean JavaTextFormat_upToWithNSString_withJavaTextParsePosition_withJavaLangStringBuffer_withChar_(NSString *string, JavaTextParsePosition *position, JavaLangStringBuffer *buffer, jchar stop);

FOUNDATION_EXPORT jboolean JavaTextFormat_upToWithQuotesWithNSString_withJavaTextParsePosition_withJavaLangStringBuffer_withChar_withChar_(NSString *string, JavaTextParsePosition *position, JavaLangStringBuffer *buffer, jchar stop, jchar start);

J2OBJC_TYPE_LITERAL_HEADER(JavaTextFormat)

#endif

#if !defined (JavaTextFormat_Field_) && (INCLUDE_ALL_JavaTextFormat || defined(INCLUDE_JavaTextFormat_Field))
#define JavaTextFormat_Field_

#define RESTRICT_JavaTextAttributedCharacterIterator 1
#define INCLUDE_JavaTextAttributedCharacterIterator_Attribute 1
#include "../../java/text/AttributedCharacterIterator.h"

/*!
 @brief Inner class used to represent Format attributes in the
 AttributedCharacterIterator that the
 formatToCharacterIterator() method returns in Format
 subclasses.
 */
@interface JavaTextFormat_Field : JavaTextAttributedCharacterIterator_Attribute

#pragma mark Protected

/*!
 @brief Constructs a new instance of Field with the given field name.
 @param fieldName
 the field name.
 */
- (instancetype)initWithNSString:(NSString *)fieldName;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaTextFormat_Field)

FOUNDATION_EXPORT void JavaTextFormat_Field_initWithNSString_(JavaTextFormat_Field *self, NSString *fieldName);

FOUNDATION_EXPORT JavaTextFormat_Field *new_JavaTextFormat_Field_initWithNSString_(NSString *fieldName) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT JavaTextFormat_Field *create_JavaTextFormat_Field_initWithNSString_(NSString *fieldName);

J2OBJC_TYPE_LITERAL_HEADER(JavaTextFormat_Field)

#endif

#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_JavaTextFormat")


text:
'use strict';

import * as q from 'q';
import * as async from 'async';

import './inversify.config';

import { inject, injectable } from 'inversify';

import { IDENTIFIERS } from './constants/indentifiers';

import { IApp, ILaunch, ILaunchSync } from './interfaces/app.interface';

import { Routes } from './routes';
import { Server } from './server';

import { AfterMiddleware } from './middlewares/after';

import { ConfigService } from './services/config.service';
import { SocketService } from './services/socket.service';

import { Subscription } from 'rxjs/Subscription';

@injectable()
export class App implements IApp {

  constructor (
    @inject(IDENTIFIERS.Server) private server: Server,
    @inject(IDENTIFIERS.Routes) private routes: Routes,
    @inject(IDENTIFIERS.AfterMiddleware) private after: AfterMiddleware,
    @inject(IDENTIFIERS.ConfigService) private config: ConfigService,
    @inject(IDENTIFIERS.SocketService) private sockets: SocketService
  ) {

    this
      .postInversion()
      .launch();

    return this;

  }

  /**
   * After Inversion of Control, we need to set this config service onto server; but
   * it's a circular dependency for IOC; so we are setting it manually here before
   * doing anything else.
   * @method postInversion
   * @returns {App}
   */

  private postInversion (): App {

    this.server.config = this.config;

    return this;

  }

  private launch (): void {

    let subscription: Subscription =  null;

    subscription = this
      .config
      .ready
      .subscribe((
        ready: boolean
      ): void => {

        if (ready) {

          subscription.unsubscribe();

          let launchers: (ILaunch|ILaunchSync)[] = [
            {

              'context': this.server,

              'fn': this.server.auth

            },
            {

              'context': this.server,

              'fn': this.server.configure

            },
            this.routes,
            this.after,
            this.server,
            this.sockets
          ];

          async.eachSeries(launchers, (
            launch: ILaunch|ILaunchSync,
            next: Function
          ): void => {

            const sync: ILaunchSync = (<any>launch),

              isSync: boolean = !!sync.fn;

            if (isSync) {

              sync.fn.apply(sync.context);

              next();

            } else {

              const promise: q.Promise<boolean>|void = (<ILaunch>launch).start();

              if (!promise) {

                next();

              } else {

                (<q.Promise<boolean>>promise).then((): void => {

                  next();

                });

              }

            }

          }, () => {

            this
              .server
              .msg('Application successfully started!');

          });

        }

      });

  }

}


text:
This test passes if it does not crash.
<textarea></textarea>

<embed>


text: Dir.glob(File.expand_path('../**/*_test.rb', __FILE__)).each { |test| require test }


text:
Users Module description here

 Главная

Список пользователей

{{vm.usereditdata.data.name}}

Редактирование

Edit User

        <form class="form-horizontal" name="userForm" ng-submit="vm.save(userForm.$valid)" novalidate>

{{alert.title}}

{{alert.msg}}

              Отображаемое Имя

                <input type="text" class="form-control" ng-model="vm.usereditdata.data.name" name="name" placeholder="Name" required>

Имя уже занято.

              Логин

                <input type="text" class="form-control" ng-model="vm.usereditdata.data.email" name="email" placeholder="Email" required>

Логин уже занят.

This is not a valid email.

              Права доступа

                    <input type="checkbox" checklist-model="vm.usereditdata.data.role" checklist-value="role.id"> {{role.name}}

             Назад
            <button type="submit" class="btn btn-primary pull-right">Обновить</button>

        </form>


text:
using namespace yy;

#undef  YY_DECL
#define YY_DECL int Lexer::yylex()

class Lexer : public yyFlexLexer
{
private:
	int yylex ();
	Parser::semantic_type *yylval;
	yy::location location_;

public:
	Lexer (std::istream *input) : yyFlexLexer (input), yylval (NULL) { };

	// Get and set location
	yy::location getLocation () const { return location_; }
	void setLocation (yy::location loc) { location_ = loc; }

	int yylex (Parser::semantic_type *lval)
	{
		yylval = lval;
		return yylex ();
	}
};

#endif


text:
package org.apache.geode.internal.cache.tx;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Set;

import org.apache.logging.log4j.Logger;

import org.apache.geode.DataSerializer;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.EntryNotFoundException;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.DistributionMessage;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.ReplyException;
import org.apache.geode.distributed.internal.ReplyMessage;
import org.apache.geode.distributed.internal.ReplyProcessor21;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.NanoTimer;
import org.apache.geode.internal.cache.LocalRegion;
import org.apache.geode.internal.cache.RegionEntry;
import org.apache.geode.internal.cache.RemoteOperationException;
import org.apache.geode.internal.cache.versions.VersionTag;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.log4j.LogMarker;

/**
 * This message is used to request a VersionTag from a remote member.
 *
 * DistributedRegions with DataPolicy NORMAL, PRELOADED, use this message to fetch VersionTag for a
 * key when a tx is in progress (see TXEntryState.fetchRemoteVersionTag).
 *
 * @since GemFire 7.0
 */
public class RemoteFetchVersionMessage extends RemoteOperationMessage {

  private static final Logger logger = LogService.getLogger();

  private Object key;

  /** for deserialization */
  public RemoteFetchVersionMessage() {}

  /**
   * Send RemoteFetchVersionMessage to the recipient for the given key
   *
   * @param recipient
   * @param r
   * @param key
   * @return the processor used to fetch the VersionTag for the key
   * @throws RemoteOperationException if the member is no longer available
   */
  public static FetchVersionResponse send(InternalDistributedMember recipient, LocalRegion r,
      Object key) throws RemoteOperationException {
    FetchVersionResponse response = new FetchVersionResponse(r.getSystem(), recipient);
    RemoteFetchVersionMessage msg =
        new RemoteFetchVersionMessage(recipient, r.getFullPath(), response, key);
    Set<?> failures = r.getDistributionManager().putOutgoing(msg);
    if (failures != null && failures.size() > 0) {
      throw new RemoteOperationException(
          LocalizedStrings.GetMessage_FAILED_SENDING_0.toLocalizedString(msg));
    }
    return response;
  }

  private RemoteFetchVersionMessage(InternalDistributedMember recipient, String regionPath,
      ReplyProcessor21 processor, Object key) {
    super(recipient, regionPath, processor);
    this.key = key;
  }

  @Override
  public int getDSFID() {
    return R_FETCH_VERSION_MESSAGE;
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    super.fromData(in);
    this.key = DataSerializer.readObject(in);
  }

  @Override
  public void toData(DataOutput out) throws IOException {
    super.toData(out);
    DataSerializer.writeObject(this.key, out);
  }

  @Override
  protected boolean operateOnRegion(ClusterDistributionManager dm, LocalRegion r, long startTime)
      throws RemoteOperationException {
    r.waitOnInitialization();
    VersionTag<?> tag;
    try {
      RegionEntry re = r.getRegionEntry(key);
      if (re == null) {
        if (logger.isTraceEnabled(LogMarker.DM)) {
          logger.trace(LogMarker.DM, "RemoteFetchVersionMessage did not find entry for key:{}",
              key);
        }
        r.checkEntryNotFound(key);
      }
      tag = re.getVersionStamp().asVersionTag();
      if (logger.isTraceEnabled(LogMarker.DM)) {
        logger.debug("RemoteFetchVersionMessage for key:{} returning tag:{}", key, tag);
      }
      FetchVersionReplyMessage.send(getSender(), processorId, tag, dm);

    } catch (EntryNotFoundException e) {
      sendReply(getSender(), getProcessorId(), dm, new ReplyException(e), r, startTime);
    }
    return false;
  }

  /**
   * This message is used to send a reply for RemoteFetchVersionMessage.
   *
   */
  public static class FetchVersionReplyMessage extends ReplyMessage {
    private VersionTag<?> tag;

    /** for deserialization */
    public FetchVersionReplyMessage() {}

    private FetchVersionReplyMessage(int processorId, VersionTag<?> tag) {
      setProcessorId(processorId);
      this.tag = tag;
    }

    public static void send(InternalDistributedMember recipient, int processorId, VersionTag<?> tag,
        DistributionManager dm) {
      FetchVersionReplyMessage reply = new FetchVersionReplyMessage(processorId, tag);
      reply.setRecipient(recipient);
      dm.putOutgoing(reply);
    }

    @Override
    public void process(DistributionManager dm, ReplyProcessor21 processor) {
      final long startTime = getTimestamp();
      final boolean isDebugEnabled = logger.isTraceEnabled(LogMarker.DM);

      if (isDebugEnabled) {
        logger.trace(LogMarker.DM,
            "FetchVersionReplyMessage process invoking reply processor with processorId:{}",
            this.processorId);
      }

      if (processor == null) {
        if (isDebugEnabled) {
          logger.debug("FetchVersionReplyMessage processor not found");
        }
        return;
      }
      processor.process(this);

      if (isDebugEnabled) {
        logger.trace(LogMarker.DM, "{}  Processed  {}", processor, this);
      }
      dm.getStats().incReplyMessageTime(NanoTimer.getTime() - startTime);
    }

    @Override
    public int getDSFID() {
      return R_FETCH_VERSION_REPLY;
    }

    @Override
    public void toData(DataOutput out) throws IOException {
      super.toData(out);
      DataSerializer.writeObject(this.tag, out);
    }

    @Override
    public void fromData(DataInput in) throws IOException, ClassNotFoundException {
      super.fromData(in);
      this.tag = DataSerializer.readObject(in);
    }
  }

  /**
   * A processor to capture the VersionTag returned by RemoteFetchVersion message.
   *
   */
  public static class FetchVersionResponse extends RemoteOperationResponse {

    private volatile VersionTag<?> tag;

    public FetchVersionResponse(InternalDistributedSystem dm, InternalDistributedMember member) {
      super(dm, member, true);
    }

    @Override
    public void process(DistributionMessage msg) {
      try {
        if (msg instanceof FetchVersionReplyMessage) {
          FetchVersionReplyMessage reply = (FetchVersionReplyMessage) msg;
          this.tag = reply.tag;
          if (logger.isTraceEnabled(LogMarker.DM)) {
            logger.trace(LogMarker.DM, "FetchVersionResponse return tag is {}", this.tag);
          }
        }
      } finally {
        super.process(msg);
      }
    }

    public VersionTag<?> waitForResponse() throws RemoteOperationException {
      try {
        waitForRemoteResponse();
      } catch (RemoteOperationException e) {
        logger.debug("RemoteFetchVersionMessage threw", e);
        throw e;
      } catch (EntryNotFoundException e) {
        logger.debug("RemoteFetchVersionMessage threw", e);
        throw e;
      } catch (CacheException e) {
        logger.debug("RemoteFetchVersionMessage threw", e);
        throw new RemoteOperationException("RemoteFetchVersionMessage threw exception", e);
      }
      return tag;
    }
  }
}