text:
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "internet.h"
#include "my_hostname.h"
#include "condor_attributes.h"
#include "condor_netdb.h"
#include "ipv6_hostname.h"
#include "condor_sinful.h"

static bool enable_convert_default_IP_to_socket_IP = false;
static std::set< std::string > configured_network_interface_ips;
static bool network_interface_matches_all;

const char* my_ip_string() {
    static MyString __my_ip_string;
	// TODO: Picking IPv4 arbitrarily. WARNING: This function
	// gets called while the configuration file is being loaded,
	// before we know if IPV4 and/or IPv6 is enabled.  It needs to
	// return a stable answer, because having it change midway
	// through parsing the file is a recipe for failure.
    __my_ip_string = get_local_ipaddr(CP_IPV4).to_ip_string();
    return __my_ip_string.Value();
}

//void
//init_full_hostname()
//{
//	char *tmp;
//
//	tmp = get_full_hostname( hostname );
//
//	if( full_hostname ) {
//		free( full_hostname );
//	}
//	if( tmp ) {
//			// Found it, use it.
//		full_hostname = strdup( tmp );
//		delete [] tmp;
//	} else {
//			// Couldn't find it, just use what we've already got.
//		full_hostname = strdup( hostname );
//	}
//}

bool
network_interface_to_ip(char const *interface_param_name,char const *interface_pattern,std::string & ipv4, std::string & ipv6, std::string & ipbest, std::set< std::string > *network_interface_ips)
{
	ASSERT( interface_pattern );
	if( !interface_param_name ) {
		interface_param_name = "";
	}

	if( network_interface_ips ) {
		network_interface_ips->clear();
	}

	condor_sockaddr addr;
	if (addr.from_ip_string(interface_pattern)) {
		if(addr.is_ipv4()) {
			ipv4 = interface_pattern;
			ipbest = ipv4;
		} else {
			ASSERT(addr.is_ipv6());
			ipv6 = interface_pattern;
			ipbest = ipv6;
		}
		if( network_interface_ips ) {
			network_interface_ips->insert( interface_pattern );
		}

		dprintf(D_HOSTNAME,"%s=%s, so choosing IP %s\n",
				interface_param_name,
				interface_pattern,
				ipbest.c_str());
				// addr.to_ip_string().Value());

		return true;
	}

	StringList pattern(interface_pattern);

	std::string matches_str;
	std::vector<NetworkDeviceInfo> dev_list;
	std::vector<NetworkDeviceInfo>::iterator dev;

	bool want_v4 = param_boolean("ENABLE_IPV4", true);
	bool want_v6 = param_boolean("ENABLE_IPV6", true);
	sysapi_get_network_device_info(dev_list, want_v4, want_v6);

		// Order of preference:
		//   * non-private IP
		//   * private IP (e.g. 192.168.*)
		//   * loopback
		// In case of a tie, choose the first device in the list.

	int best_so_far_v4 = -1;
	int best_so_far_v6 = -1;
	int best_overall = -1;

	for(dev = dev_list.begin();
		dev != dev_list.end();
		dev++)
	{
		bool matches = false;
		if( strcmp(dev->name(),"")!=0 &&
			pattern.contains_anycase_withwildcard(dev->name()) )
		{
			matches = true;
		}
		else if( strcmp(dev->IP(),"")!=0 &&
				 pattern.contains_anycase_withwildcard(dev->IP()) )
		{
			matches = true;
		}

		if( !matches ) {
			dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not match %s=%s.\n",
					dev->name(), dev->IP(), interface_param_name, interface_pattern);
			continue;
		}

		condor_sockaddr this_addr;
		if (!this_addr.from_ip_string(dev->IP())) {
			dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not have a useable IP address.\n",
					dev->name(), dev->IP());
			continue;
		}

		if( matches_str.size() ) {
			matches_str += ", ";
		}
		matches_str += dev->name();
		matches_str += " ";
		matches_str += dev->IP();

		if( network_interface_ips ) {
			network_interface_ips->insert( dev->IP() );
		}

		int desireability = this_addr.desirability();
		if(dev->is_up()) { desireability *= 10; }

		int * best_so_far = 0;
		std::string * ip = 0;
		if(this_addr.is_ipv4()) {
			best_so_far = & best_so_far_v4;
			ip = & ipv4;
		} else {
			ASSERT(this_addr.is_ipv6());
			best_so_far = & best_so_far_v6;
			ip = & ipv6;
		}

		//dprintf(D_HOSTNAME, "Considering %s (Ranked at %d) as possible local hostname versus %s (%d)\n", addr.to_ip_string().Value(), desireability, ip.c_str(), desireability);

		if( desireability > *best_so_far ) {
			*best_so_far = desireability;
			*ip = dev->IP();
		}

		if( desireability > best_overall ) {
			best_overall = desireability;
			ipbest = dev->IP();
		}

	}

	if( best_overall < 0 ) {
		dprintf(D_ALWAYS,"Failed to convert %s=%s to an IP address.\n",
				interface_param_name, interface_pattern);
		return false;
	}

	dprintf(D_HOSTNAME,"%s=%s matches %s, choosing IP %s\n",
			interface_param_name,
			interface_pattern,
			matches_str.c_str(),
			ipbest.c_str());

	return true;
}

void
init_network_interfaces( int config_done )
{
	dprintf( D_HOSTNAME, "Trying to getting network interface informations (%s)\n",
		 config_done ? "after reading config" : "config file not read" );

	std::string network_interface;

	if( config_done ) {
		param(network_interface,"NETWORK_INTERFACE");
	}
	if( network_interface.empty() ) {
		network_interface = "*";
	}

	network_interface_matches_all = (network_interface == "*");

	std::string network_interface_ipv4;
	std::string network_interface_ipv6;
	std::string network_interface_best;
	bool ok;
	ok = network_interface_to_ip(
		"NETWORK_INTERFACE",
		network_interface.c_str(),
		network_interface_ipv4,
		network_interface_ipv6,
		network_interface_best,
		&configured_network_interface_ips);

	if( !ok ) {
		EXCEPT("Failed to determine my IP address using NETWORK_INTERFACE=%s",
			   network_interface.c_str());
	}
}

//void
//init_ipaddr( int config_done )
//{
//    if( ! hostname ) {
//		init_hostnames();
//	}
//
//	dprintf( D_HOSTNAME, "Trying to initialize local IP address (%s)\n",
//		 config_done ? "after reading config" : "config file not read" );
//
//	std::string network_interface;
//
//	if( config_done ) {
//		param(network_interface,"NETWORK_INTERFACE");
//	}
//	if( network_interface.empty() ) {
//		network_interface = "*";
//	}
//
//	network_interface_matches_all = (network_interface == "*");
//
//	std::string network_interface_ip;
//	bool ok;
//	ok = network_interface_to_ip(
//		"NETWORK_INTERFACE",
//		network_interface.c_str(),
//		network_interface_ip,
//		&configured_network_interface_ips);
//
//	if( !ok ) {
//		EXCEPT("Failed to determine my IP address using NETWORK_INTERFACE=%s",
//			   network_interface.c_str());
//	}
//
//	if(!is_ipaddr(network_interface_ip.c_str(), &sin_addr) )
//	{
//		EXCEPT("My IP address is invalid: %s",network_interface_ip.c_str());
//	}
//
//	has_sin_addr = true;
//	ip_addr = ntohl( sin_addr.s_addr );
//	ipaddr_initialized = TRUE;
//}

#ifdef WIN32
	// see below comment in init_hostname() to learn why we must
	// include condor_io in this module.
#include "condor_io.h"
#endif

//void
//init_hostnames()
//{
//    char *tmp, hostbuf[MAXHOSTNAMELEN];
//    hostbuf[0]='\0';
//#ifdef WIN32
//	// There are a  tools in Condor, like
//	// condor_history, which do not use any CEDAR sockets but which call
//	// some socket helper functions like gethostbyname().  These helper
//	// functions will fail unless WINSOCK is initialized.  WINSOCK
//	// is initialized via a global constructor in CEDAR, so we must
//	// make certain we call at least one CEDAR function so the linker
//	// brings in the global constructor to initialize WINSOCK!
//	// In addition, some global constructors end up calling
//	// init_hostnames(), and thus will fail if the global constructor
//	// in CEDAR is not called first.  Instead of relying upon a
//	// specified global constructor ordering (which we cannot),
//	// we explicitly invoke SockInitializer::init() right here -Todd T.
//	SockInitializer startmeup;
//	startmeup.init();
//#endif
//
//    if( hostname ) {
//        free( hostname );
//    }
//    if( full_hostname ) {
//        free( full_hostname );
//        full_hostname = NULL;
//    }
//
//	dprintf( D_HOSTNAME, "Finding local host information, "
//			 "calling gethostname()\n" );
//
//        // Get our local hostname, and strip off the domain if
//        // gethostname returns it.
//    if( condor_gethostname(hostbuf, sizeof(hostbuf)) == 0 ) {
//        if( hostbuf[0] ) {
//            if( (tmp = strchr(hostbuf, '.')) ) {
//                    // There's a '.' in the hostname, assume we've got
//                    // the full hostname here, save it, and trim the
//                    // domain off and save that as the hostname.
//                full_hostname = strdup( hostbuf );
//				dprintf( D_HOSTNAME, "gethostname() returned fully "
//						 "qualified name \"%s\"\n", hostbuf );
//                *tmp = '\0';
//            } else {
//				dprintf( D_HOSTNAME, "gethostname() returned a host "
//						 "with no domain \"%s\"\n", hostbuf );
//			}
//            hostname = strdup( hostbuf );
//        } else {
//            EXCEPT( "gethostname succeeded, but hostbuf is empty" );
//        }
//    } else {
//        EXCEPT( "gethostname failed, errno = %d",
//#ifndef WIN32
//                errno );
//#else
//                WSAGetLastError() );
//#endif
//    }
//    if( ! full_hostname ) {
//		init_full_hostname();
//	}
//	hostnames_initialized = TRUE;
//}

// Returns true if given attribute is used by Condor to advertise the
// IP address of the sender.  This is used by
// ConvertDefaultIPToSocketIP().

static bool is_sender_ip_attr(char const *attr_name)
{
    if(strcasecmp(attr_name,ATTR_MY_ADDRESS) == 0) return true;
    if(strcasecmp(attr_name,ATTR_TRANSFER_SOCKET) == 0) return true;
	size_t attr_name_len = strlen(attr_name);
    if(attr_name_len >= 6 && strcasecmp(attr_name+attr_name_len-6,"IpAddr") == 0)
	{
        return true;
    }
    return false;
}

void ConfigConvertDefaultIPToSocketIP()
{
		// do not need to call init_ipaddr() since init_ipaddr() has no effect
		// on this function.
//	if( ! ipaddr_initialized ) {
//		init_ipaddr(0);
//	}

	enable_convert_default_IP_to_socket_IP = true;

	/*
	  When using TCP_FORWARDING_HOST, if we rewrite addresses, we will
	  insert the IP address of the local IP address in place of
	  the forwarding IP address.
	*/
	char *str = param("TCP_FORWARDING_HOST");
	if( str && *str ) {
		enable_convert_default_IP_to_socket_IP = false;
		dprintf(D_FULLDEBUG,"Disabling ConvertDefaultIPToSocketIP() because TCP_FORWARDING_HOST is defined.\n");
	}
	free( str );

	if( configured_network_interface_ips.size() <= 1 ) {
		enable_convert_default_IP_to_socket_IP = false;
		dprintf(D_FULLDEBUG,"Disabling ConvertDefaultIPToSocketIP() because NETWORK_INTERFACE does not match multiple IPs.\n");
	}

	if( !param_boolean("ENABLE_ADDRESS_REWRITING",true) ) {
		enable_convert_default_IP_to_socket_IP = false;
		dprintf(D_FULLDEBUG,"Disabling ConvertDefaultIPToSocketIP() because ENABLE_ADDRESS_REWRITING is false.\n");
	}
}

// Only needed for these next two functions;
// #include should be deleted when ConvertDefaultIPToSocketIP is.
#include "condor_daemon_core.h"

void ConvertDefaultIPToSocketIP(char const * attr_name, std::string & expr_string, Stream & s )
{
	static bool loggedNullDCMessage = false;
	static bool loggedConfigMessage = false;

	// We can't practically do a conversion if daemonCore isn't present; this
	// happens in standard universe.  We can't move this test into
	// ConfigConvertDefaultIPToSocketIP because it gets called before
	// daemonCore is created.
	if( daemonCore == NULL ) {
		if( ! loggedNullDCMessage ) {
			dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: disabled: no daemon core.\n" );
			loggedNullDCMessage = true;
		}
		return;
	}

	if( ! enable_convert_default_IP_to_socket_IP ) {
		if( ! loggedConfigMessage ) {
			dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: disabled: by configuration.\n" );
			loggedConfigMessage = true;
		}
		return;
	}

	if( ! is_sender_ip_attr( attr_name ) ) {
		// Reduce log spam.  Since all of our subsequent messages include the
		// attribute name, we don't have to print a message noting that we
		// tried to rewrite it.
		// dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: '%s' is not an attribute which might contain the sender's IP address.\n", attr_name );
		return;
	}

	// Skip if Stream doesn't have address associated with it
	condor_sockaddr connectionSA;
	if( ! connectionSA.from_ip_string( s.my_ip_str() ) ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: failed for attribute '%s' (%s): failed to generate socket address from stream's IP string (%s).\n", attr_name, expr_string.c_str(), s.my_ip_str() );
		return;
	}

	// Skip if it's not a string literal.
	if( * ( expr_string.rbegin() ) != '"' ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: failed for attribute '%s' (%s): failed to parse. Missing closing double quotation mark.\n", attr_name, expr_string.c_str() );
		return;
	}

	const char * delimiter = " = \"";
	size_t delimpos = expr_string.find( delimiter );
	// Skip if doesn't look like a string
	if( delimpos == std::string::npos ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: failed for attribute '%s' (%s): failed to parse. Missing assignment.\n", attr_name, expr_string.c_str() );
		return;
	}

	size_t string_start_pos = delimpos + strlen( delimiter );
	// string_end_pos is one beyond last character of String literal.
	size_t string_end_pos = expr_string.length() - 1;
	size_t string_len = string_end_pos - string_start_pos;

	// Skip if it doesn't look like a Sinful
	if( expr_string[string_start_pos] != '<' ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: failed for attribute '%s' (%s): failed to parse. Missing opening <.\n", attr_name, expr_string.c_str() );
		return;
	}
	if( expr_string[string_end_pos - 1] != '>' ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: failed for attribute '%s' (%s): failed to parse. Missing closing >.\n", attr_name, expr_string.c_str() );
		return;
	}

	std::string adSinfulString = expr_string.substr( string_start_pos, string_len);
	const char *cmd_sinful = daemonCore->InfoCommandSinfulString();
	if ( cmd_sinful == NULL ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: disabled: no command port sinful string.\n" );
		return;
	}
	std::string commandPortSinfulString = cmd_sinful;

	Sinful adSinful( adSinfulString.c_str() );
	condor_sockaddr adSA;
	adSA.from_sinful( adSinful.getSinful() );

	bool rewrite_port = true;
	if (commandPortSinfulString == adSinfulString)
	{
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: refused for attribute %s (%s): clients now choose addresses.\n", attr_name, expr_string.c_str() );
		return;
	}
	else if (param_boolean("SHARED_PORT_ADDRESS_REWRITING", false))
	{
		//
		// Wait a minute -- isn't this only supposed to happen in the collector?
		//
		const std::vector<Sinful> &commandSinfuls = daemonCore->InfoCommandSinfulStringsMyself();
		dprintf(D_NETWORK|D_VERBOSE, "Address rewriting: considering %ld command socket sinfuls.\n", commandSinfuls.size());

		bool acceptableMatch = false;
		std::vector<Sinful>::const_iterator it;
		for (it = commandSinfuls.begin(); it!=commandSinfuls.end(); it++)
		{
			commandPortSinfulString = it->getSinful();
			const Sinful &commandPortSinful = *it;
			// We assume that any sinful on the same shared port server
			// can also be rewritten.
			if ((adSinful.getSharedPortID() != NULL) && (strcmp(commandPortSinful.getHost(), adSinful.getHost()) == 0) && (commandPortSinful.getPortNum() == adSinful.getPortNum()))
			{
				acceptableMatch = true;
				break;
			}
			dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: refused for attribute %s (%s): the address isn't my default address. (Command socket considered: %s, found in ad: %s)\n", attr_name, expr_string.c_str(), commandPortSinfulString.c_str(), adSinfulString.c_str());
		}

		if (!acceptableMatch)
		{
			return;
		}
	}
	else
	{
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: refused for attribute %s (%s): the address isn't my default address. (Default: %s, found in ad: %s)\n", attr_name, expr_string.c_str(), commandPortSinfulString.c_str(), adSinfulString.c_str());
		return;
	}

	//
	// Although it's never useful to rewrite from a non-loopback to a loop-
	// back address, if there's more than one loopback address on a machine,
	// (generally but not always because the machine supports more than one
	// protocol), it's OK to rewrite from one to the other.
	//
	// Doing this is any other situation breaks, among other things,
	// ssh-to-job.  (In a design hack, the starter sends its external
	// address to the startd over the job-update socket, as part of every
	// job update ClassAd.  This causes rewriting to happen, but as the
	// the startd explicity binds the job-update socket to the loopback
	// address -- presumambly to ensure that it always works -- we need
	// to make sure we don't rewrite ATTR_STARTER_IP_ADDR when sending
	// job updates.  *sigh*)
	//
	if( (! adSA.is_loopback()) && connectionSA.is_loopback() ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: refused for attribute '%s' (%s): outbound interface is loopback but default interface is not.\n", attr_name, expr_string.c_str() );
		return;
	}

	if( adSinful.getSharedPortID() != NULL ) {
		// We're using shared port, so "our" port is actually the
		// shared port daemon's. We shouldn't be messing with that.
		// We'll rewrite the host on the bold assumption that shared
		// port daemon and I both use the same IP addresses.
		rewrite_port = false;
	}

	MyString my_sock_ip = connectionSA.to_ip_string( true );
	adSinful.setHost( my_sock_ip.Value() );
	if( rewrite_port ) {
		// connectionSA's port is whatever we happen to be using at the moment;
		// that will be meaningless if we established the connection.  What we
		// want is the port someone could contact us on.  Go rummage for one.
		int port = daemonCore->find_interface_command_port_do_not_use( connectionSA );

		// If port is 0, there is no matching listen socket. There is nothing
		// useful we can rewrite it do, so just give up and hope the default
		// is useful to someone.
		if( port == 0 ) {
			dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: failed for attribute '%s' (%s): unable to find command port for outbound interface '%s'.\n", attr_name, expr_string.c_str(), s.my_ip_str() );
			return;
		}

		adSinful.setPort( port );
	}

	if( adSinful.getSinful() == adSinfulString ) {
		dprintf( D_NETWORK | D_VERBOSE, "Address rewriting: refused for attribute '%s' (%s): socket is using same address as the default one; rewrite would do nothing.\n", attr_name, expr_string.c_str() );
		return;
	}

	std::string new_expr = expr_string.substr( 0, string_start_pos );
	new_expr.append( adSinful.getSinful() );
	new_expr.append( expr_string.substr( string_end_pos ) );

	expr_string = new_expr;

	dprintf( D_NETWORK, "Address rewriting: Replaced default IP %s with "
			"connection IP %s in outgoing ClassAd attribute %s.\n",
			adSinfulString.c_str(), adSinful.getSinful(), attr_name );
}


text:
Product.delete_all

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)

product_1 = Product.create(	title: 'Programming Ruby 1.9',
				description: 'Ruby is the fasters growing and most exciting dynamic language out there. If you need to get working programs delivered fast, you should add Ruby to your toolbox.',
				image_url: 'https://www.apple.com/product-red/images/hero.jpg',
				price: 49.95)
product_2 = Product.create(	title: 'Agile Web Development Rails 4',
				description: 'Agile Web Development with Rails does an excellent job of making the Rails environment accessible in an enjoyable and memorable way',
				image_url: 'http://ecx.images-amazon.com/images/I/51lbXFwhFvL._SL500_AA300_.jpg',
				price: 50.05)

redpajama_set_name: RedPajamaGithub


text:
class AddTimestampsToGiftCards < SolidusSupport::Migration[4.2]
  def change
    add_column :spree_virtual_gift_cards, :created_at, :datetime
    add_column :spree_virtual_gift_cards, :updated_at, :datetime
  end
end


text:
package ru.job4j.models;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *The class Item.
 * @author Alexander Mezgin
 * @since 08.12.2016
 * @version 1.0
 */
public class Item {

    /**
     *Private fild "comments" contains all comments for Item.
     */
    private List<Comment> comments = new ArrayList<>();
    /**
     *Private fild "id" for class Item.
     */
    private String id;
    /**
     *Private fild "name" for class Item.
     */
    private String name;
    /**
     *Private fild "description" for class Item.
     */
    private String description;
    /**
     *Private fild "dateCreat" for class Item.
     */
    private Date dateCreat;

    /**
     *Constructor for the class Item.
     *@param name for the Constructor
     *@param description for the Constructor
     */
    public Item(String name, String description) {
        this.name = name;
        this.description = description;
        this.dateCreat = new Date();
    }

    /**
     *Getter for the field "comment".
     *@return comments
     */
    public List<Comment> getAllComments() {
        return this.comments;
    }

    /**
     *This method add new comment in to list of comments.
     *@param comment of Item
     */
    public void addComments(Comment comment) {
        this.comments.add(comment);
    }

    /**
     *Getter for the field "id".
     *@return id of Item
     */
    public String getId() {
        return this.id;
    }

    /**
     *Setter for the field "id".
     *@param id of Item
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *Getter for the field "name".
     *@return name of Item
     */
    public String getName() {
        return this.name;
    }

    /**
     *Setter for the field "name".
     *@param name of Item
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *Getter for the field "description".
     *@return description of Item
     */
    public String getDescription() {
        return this.description;
    }

    /**
     *Setter for the field "description".
     *@param description of Item
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     *Getter for the field "dateCreat".
     *@return dateCreat of Item
     */
    public Date getDateCreat() {
        return this.dateCreat;
    }

    /**
     *Setter for the field "dateCreat".
     *@param dateCreat of Item
     */
    public void setDateCreat(Date dateCreat) {
        this.dateCreat = dateCreat;
    }

    /**
     *Override the nethod toString".
     *@return item toString
     */
    @Override
    public String toString() {
        DateFormat dateFormat = new SimpleDateFormat("dd.MM.yy HH:mm");
        return "Item{"
                + "id = '" + id + '\''
                + ", name = '" + name + '\''
                + ", description = '" + description + '\''
                + ", dateCreat = " + dateFormat.format(dateCreat) + '\''
                + ", comment = '" + comments + '\''
                + '}';
    }
}


text:
package com.ts.controller.ai.task;

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

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ts.annotation.Rights;
import com.ts.controller.base.BaseController;
import com.ts.dao.DaoSupportAi;
import com.ts.entity.Page;
import com.ts.service.ai.manager.AIManager;
import com.ts.service.ai.task.manager.TaskAllotManager;
import com.ts.util.Jurisdiction;
import com.ts.util.PageData;
import com.ts.util.ai.AIConst;
import com.ts.util.ai.AILogs;
import com.ts.util.app.AppUtil;

/**
 * 任务分配
 * @ClassName: TaskAllotController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author zhy
 * @date 2016年10月31日 上午8:59:47
 *
 */
@Controller
@RequestMapping(value="/taskAllot")
public class TaskAllotController  extends BaseController {

	@Resource(name="taskAllotService")
	private TaskAllotManager taskAllotService;

	@Resource(name="aiService")
	private AIManager aiService;

	@Resource(name = "daoSupportAi")
	private DaoSupportAi dao;

	/**
	 * 问题单列表
	 * @Title: listQuestion
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param page
	 * @param @return
	 * @param @throws Exception    设定文件
	 * @return ModelAndView    返回类型
	 * @throws
	 */
	@RequestMapping(value="/listQuestion")
	public ModelAndView listQuestion(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		try{
			PageData pd = new PageData();
			pd = this.getPageData();
			String keywords = pd.getString("keywords");				//关键词检索条件
			if(null != keywords && !"".equals(keywords)){
				pd.put("keywords", keywords.trim());
			}
			String createStart = pd.getString("createStart");	//开始时间
			String createEnd = pd.getString("createEnd");		//结束时间
			if(createStart != null && !"".equals(createStart)){
				pd.put("createStart", createStart+" 00:00:00");
			}
			if(createEnd != null && !"".equals(createEnd)){
				pd.put("createEnd", createEnd+" 23:59:59");
			}
			page.setPd(pd);

			if(pd.keySet().isEmpty()){
				pd.put("TASK_TYPE_ID", "84002");
				pd.put("TASK_TYPE_CHILD_ID", "85001");
				pd.put("EXP_ID", 1);
			}

			//设置查询条件的值,此处为了防止页面更改查询条件,但是并未做查询的处理
			pd.put("SEARCH_ORIGIN_ID",pd.get("ORIGIN_ID") );
			pd.put("SEARCH_TASK_TYPE_ID",pd.get("TASK_TYPE_ID") );
			pd.put("SEARCH_TASK_TYPE_CHILD_ID",pd.get("TASK_TYPE_CHILD_ID") );
			pd.put("SEARCH_EXP_ID",pd.get("EXP_ID") );
			pd.put("SEARCH_createStart",pd.get("createStart") );
			pd.put("SEARCH_createEnd",pd.get("createEnd") );
			pd.put("SEARCH_keywords",pd.get("keywords") );

			List<PageData>	questionList = taskAllotService.questionList(page);
			mv.addObject("questionList", questionList);//列表信息

			//设置任务类型及任务子类型列表
			pd.put("dt_id",AIConst.AI_DICT_TASK_TYPE );
			List<PageData>	taskTypeList = aiService.dictList(pd);
			pd.put("dt_id",AIConst.AI_DICT_TASK_TYPE_CHILD );
			List<PageData>	taskTypeChildList = aiService.dictList(pd);
			//设置数据来源列表
			pd.put("dt_id",AIConst.AI_DICT_ORIGIN );
			List<PageData>	originList = aiService.dictList(pd);

			mv.addObject("originList", originList);
			mv.addObject("taskTypeList", taskTypeList);
			mv.addObject("taskTypeChildList", taskTypeChildList);
			pd.put("createStart", createStart);
			pd.put("createEnd",createEnd );
			mv.addObject("pd", pd);
			mv.setViewName("ai/task/taskallot");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 任务分配的窗口
	 * @Title: toAdd
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @return
	 * @param @throws Exception    设定文件
	 * @return ModelAndView    返回类型
	 * @throws
	 */
	@RequestMapping(value="/toAllot")
	@Rights(code="taskAllot/toAllot")
	public ModelAndView toAllot(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();

		//获取角色配置
		String role=taskAllotService.getRole(pd);
		pd.put("ROLE_ID", role);

		page.setPd(pd);
		List<PageData> userList=aiService.listUsersByRole(page);
		mv.addObject("userList",userList);

		//
		mv.setViewName("ai/task/taskallot_userlist");

		mv.addObject("pd", pd);
		return mv;
	}
	/**
	 * @throws Exception
	 * 执行任务分配的方法
	 * @Title: allot
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @return    设定文件
	 * @return Object    返回类型
	 * @throws
	 */
	@RequestMapping(value="/allot")
	@ResponseBody
	public Object allot() throws Exception{
		AILogs.saveOpLogs(Jurisdiction.getUsername()+"分配任务",dao, null);

		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(taskAllotService.allot(pd) != null){
				errInfo = "error";
			}
			logger.info(Jurisdiction.getUsername()+"分配任务");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);				//返回结果
		return AppUtil.returnObject(new PageData(), map);
	}
	/**跳过NLP审核
	 * @return
	 */
	@RequestMapping(value="/skipNLP")
	@ResponseBody
	public Object skipNLP() throws Exception {
		AILogs.saveOpLogs(Jurisdiction.getUsername()+"跳过NLP审核",dao, null);
		logBefore(logger, Jurisdiction.getUsername()+"跳过NLP审核");
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String Q_IDS = pd.getString("Q_IDS");
			if(null != Q_IDS && !"".equals(Q_IDS)){
				String ArrayP_IDS[] = Q_IDS.split(",");
				taskAllotService.skipNLP(ArrayP_IDS);
				map.put("result", "success");

			}else{
				map.put("result", "未包含相关信息!");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
}


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ConstDependency = require("./ConstDependency");
const ParserHelpers = require("../ParserHelpers");

class SystemPlugin {
	constructor(options) {
		this.options = options;
	}

	apply(compiler) {
		compiler.plugin("compilation", (compilation, params) => {
			params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {

				if(typeof parserOptions.system !== "undefined" && !parserOptions.system)
					return;

				function setNotSupported(name) {
					parser.plugin("evaluate typeof " + name, ParserHelpers.evaluateToString("undefined"));
					parser.plugin("expression " + name,
						ParserHelpers.expressionIsUnsupported(name + " is not supported by webpack.")
					);
				}

				parser.plugin("typeof System", ParserHelpers.toConstantDependency("object"));
				parser.plugin("evaluate typeof System", ParserHelpers.evaluateToString("object"));

				parser.plugin("typeof System.import", ParserHelpers.toConstantDependency("function"));
				parser.plugin("evaluate typeof System.import", ParserHelpers.evaluateToString("function"));

				setNotSupported("System.set");
				setNotSupported("System.get");
				setNotSupported("System.register");
				parser.plugin("expression System", (expr) => {
					const dep = new ConstDependency("{}", expr.range);
					dep.loc = expr.loc;
					parser.state.current.addDependency(dep);
					return true;
				});
			});
		});
	}
}
module.exports = SystemPlugin;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pycnocarpon parashoreae Syd.

### Remarks
null


text:
package com.lanceolata.leetcode_easy;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lance on 2018/9/23.
 */
public class Question_590_N_ary_Tree_Postorder_Traversal {
    class Node {
        public int val;
        public List<Node> children;

        public Node() {}

        public Node(int _val,List<Node> _children) {
            val = _val;
            children = _children;
        }
    };

    public List<Integer> postorder(Node root) {
        List<Integer> res = new ArrayList<>();
        help(root, res);
        return res;
    }

    private void help(Node root, List<Integer> res) {
        if (root == null) return;
        for (Node n : root.children) {
            help(n, res);
        }
        res.add(root.val);
    }
}


text:
<?php

namespace wcmf\lib\model;

use wcmf\lib\model\Node;

/**
 * NodeIterator is used to iterate over a tree/list built of Nodes
 * using a Depth-First-Algorithm. Classes used with the NodeIterator must
 * implement the getChildren() and getOID() methods.
 *
 * The following example shows the usage:
 *
 * @code
 * // load the node with depth 10
 * $node = ObjectFactory::getInstance('persistenceFacade')->load(new ObjectId('Page', 300), 10);
 *
 * // iterate over all children
 * $it = new NodeIterator($node);
 * foreach($it as $oid => $obj) {
 *   echo("current object id: ".$oid);
 *   echo("current object: ".$obj);
 * }
 * @endcode
 *
 * @author ingo herwig <ingo@wemove.com>
 */
class NodeIterator implements \Iterator {

  protected $end;              // indicates if the iteration is ended
  protected $nodeList;         // the list of seen nodes
  protected $processedOidList; // the list of processed object ids
  protected $currentNode;      // the node the iterator points to
  protected $startNode;        // the start node
  protected $aggregationKinds; // array of aggregation kind values to follow (empty: all)

  /**
   * Constructor.
   * @param $node The node to start from.
   * @param $aggregationKinds Array of aggregation kind values of relations to follow
   *   possible values: 'none', 'shared', 'composite'. Empty array means all (default: empty)
   */
  public function __construct($node, $aggregationKinds=[]) {
    $this->end = false;
    $this->nodeList = [];
    $this->processedOidList = [];
    $this->currentNode = $node;
    $this->startNode = $node;
    $this->aggregationKinds = $aggregationKinds;
  }

  /**
   * Return the current element
   * @return Node instance
   */
  public function current() {
    return $this->currentNode;
  }

  /**
   * Return the key of the current element
   * @return String, the serialized object id
   */
  public function key() {
    return $this->currentNode->getOID()->__toString();
  }

  /**
   * Move forward to next element
   */
  public function next() {
    // the current node was processed
    $this->processedOidList[] = $this->currentNode->getOID()->__toString();

    // collect navigable children for the given aggregation kinds
    $childrenArray = [];
    $mapper = $this->currentNode->getMapper();
    $relations = $mapper->getRelations('child');
    $followAll = sizeof($this->aggregationKinds) == 0;
    foreach ($relations as $relation) {
      $aggregationKind = $relation->getOtherAggregationKind();
      if ($relation->getOtherNavigability() && ($followAll || in_array($aggregationKind, $this->aggregationKinds))) {
        $childValue = $this->currentNode->getValue($relation->getOtherRole());
        if ($childValue != null) {
          $children = $relation->isMultiValued() ? $childValue : [$childValue];
          foreach ($children as $child) {
            $childrenArray[] = $child;
          }
        }
      }
    }
    $this->addToQueue($childrenArray);

    // set current node
    if (sizeof($this->nodeList) != 0) {
      $node = array_pop($this->nodeList);
      $oidStr = $node->getOID()->__toString();
      // not the last node -> search for unprocessed nodes
      while (sizeof($this->nodeList) > 0 && in_array($oidStr, $this->processedOidList)) {
        $node = array_pop($this->nodeList);
        $oidStr = $node->getOID()->__toString();
      }
      // last node found, but it was processed already
      if (sizeof($this->nodeList) == 0 && in_array($oidStr, $this->processedOidList)) {
        $this->end = true;
      }
      $this->currentNode = $node;
    }
    else {
      $this->end = true;
    }
    return $this;
  }

  /**
   * Rewind the Iterator to the first element
   */
  public function rewind() {
    $this->end = false;
    $this->nodeList = [];
    $this->processedOidList = [];
    $this->currentNode = $this->startNode;
  }

  /**
   * Checks if current position is valid
   */
  public function valid() {
    return !$this->end;
  }

  /**
   * Add nodes to the processing queue.
   * @param $nodeList An array of nodes.
   */
  protected function addToQueue($nodeList) {
    for ($i=sizeof($nodeList)-1; $i>=0; $i--) {
      if ($nodeList[$i] instanceof Node) {
        $this->nodeList[] = $nodeList[$i];
      }
    }
  }
}
?>


text:
@import Foundation;
@import SwiftName;

@interface PointerWrapper
@property void * __null_unspecified voidPtr;
@property int * __null_unspecified intPtr;
@property __null_unspecified id __autoreleasing * __null_unspecified idPtr;
@end

#pragma clang assume_nonnull begin
@interface SwiftNameTest : NSObject

// "Factory methods" that we'd rather have as initializers.
+ (instancetype)a SWIFT_NAME(init());
+ (instancetype)b SWIFT_NAME(init(dummyParam:));
+ (instancetype)c:(nullable id)x SWIFT_NAME(init(cc:));
+ (instancetype):(int)x SWIFT_NAME(init(empty:));

// Would-be initializers.
+ (instancetype)testZ SWIFT_NAME(zz());
+ (instancetype)testY:(nullable id)x SWIFT_NAME(yy(aa:));
+ (instancetype)testX:(nullable id)x xx:(nullable id)xx SWIFT_NAME(xx(_:bb:));
+ (instancetype):(int)x :(int)y SWIFT_NAME(empty(_:_:));

// Things that Clang won't catch as problematic, but we should.
+ (instancetype)f:(id)x SWIFT_NAME(init(f:ff:));
+ (instancetype)g:(id)x outParam:(int *)foo SWIFT_NAME(init(g:));
+ (instancetype)testW:(id)x out:(id *)outObject SWIFT_NAME(ww(_:));
+ (instancetype)test SWIFT_NAME(test(a:b:));
+ (instancetype)test:(id)x more:(id)y SWIFT_NAME(test());

- (void)methodInt:(NSInteger)value SWIFT_NAME(theMethod(number:));
- (void):(NSInteger)a b:(NSInteger)b SWIFT_NAME(empty(a:b:));

@property (readonly) int someProp SWIFT_NAME(renamedSomeProp);
@property (readonly, class) int classProp SWIFT_NAME(renamedClassProp);
@end

@interface SwiftNameTestError : NSObject
// Factory methods with NSError.
+ (nullable instancetype)err1:(NSError **)err SWIFT_NAME(init(error:));
+ (nullable instancetype)err2:(nullable id)x error:(NSError **)err SWIFT_NAME(init(aa:error:));
+ (nullable instancetype)err3:(nullable id)x error:(NSError **)err callback:(void(^)(void))block SWIFT_NAME(init(aa:error:block:));
+ (nullable instancetype)err4:(NSError **)err callback:(void(^)(void))block SWIFT_NAME(init(error:block:));

+ (nullable instancetype)err5:(nullable id)x error:(NSError **)err SWIFT_NAME(init(aa:));
+ (nullable instancetype)err6:(nullable id)x error:(NSError **)err callback:(void(^)(void))block SWIFT_NAME(init(aa:block:));
+ (nullable instancetype)err7:(NSError **)err callback:(void(^)(void))block SWIFT_NAME(init(block:));

// Would-be initializers.
+ (nullable instancetype)testW:(nullable id)x error:(NSError **)err SWIFT_NAME(ww(_:));
+ (nullable instancetype)testW2:(nullable id)x error:(NSError **)err SWIFT_NAME(w2(_:error:));
+ (nullable instancetype)testV:(NSError **)err SWIFT_NAME(vv());
+ (nullable instancetype)testV2:(NSError **)err SWIFT_NAME(v2(error:));
@end

@interface SwiftNameTestSub : SwiftNameTest
@end

@interface SwiftNameTestErrorSub : SwiftNameTestError
@end

int global_int SWIFT_NAME(GlobalInt);

#pragma clang assume_nonnull end


text:
package org.jkiss.dbeaver.model.sql.format.tokenized;

import org.jkiss.dbeaver.model.DBPIdentifierCase;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.sql.format.SQLFormatter;
import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import org.jkiss.utils.Pair;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * SQL formatter
 */
public class SQLTokenizedFormatter implements SQLFormatter {

    public static final String FORMATTER_ID = "DEFAULT";

    private static final String[] JOIN_BEGIN = { "LEFT", "RIGHT", "INNER", "OUTER", "JOIN" };

    private SQLFormatterConfiguration formatterCfg;
    private List<Boolean> functionBracket = new ArrayList<>();
    private List<String> statementDelimiters = new ArrayList<>(2);
    private String delimiterRedefiner;

    @Override
    public String format(final String argSql, SQLFormatterConfiguration configuration)
    {
        formatterCfg = configuration;

        for (String delim : formatterCfg.getSyntaxManager().getStatementDelimiters()) {
            statementDelimiters.add(delim.toUpperCase(Locale.ENGLISH));
        }
        delimiterRedefiner = formatterCfg.getSyntaxManager().getDialect().getScriptDelimiterRedefiner();
        if (delimiterRedefiner != null) {
            delimiterRedefiner = delimiterRedefiner.toUpperCase(Locale.ENGLISH);
        }
        SQLTokensParser fParser = new SQLTokensParser(formatterCfg);

        functionBracket.clear();

        boolean isSqlEndsWithNewLine = false;
        if (argSql.endsWith("\n")) { //$NON-NLS-1$
            isSqlEndsWithNewLine = true;
        }

        List<FormatterToken> list = fParser.parse(argSql);
        list = format(list);

        StringBuilder after = new StringBuilder(argSql.length() + 20);
        for (FormatterToken token : list) {
            after.append(token.getString());
        }

        if (isSqlEndsWithNewLine) {
            after.append(GeneralUtils.getDefaultLineSeparator());
        }

        return after.toString();
    }

    private List<FormatterToken> format(final List<FormatterToken> argList) {
        if (argList.isEmpty()) {
            return argList;
        }

        FormatterToken token = argList.get(0);
        if (token.getType() == TokenType.SPACE) {
            argList.remove(0);
            if (argList.isEmpty()) {
                return argList;
            }
        }

        token = argList.get(argList.size() - 1);
        if (token.getType() == TokenType.SPACE) {
            argList.remove(argList.size() - 1);
            if (argList.isEmpty()) {
                return argList;
            }
        }

        final DBPIdentifierCase keywordCase = formatterCfg.getKeywordCase();
        for (int index = 0; index < argList.size(); index++) {
            token = argList.get(index);
            if (token.getType() == TokenType.KEYWORD) {
                token.setString(keywordCase.transform(token.getString()));
            }
        }

        // Remove extra tokens (spaces, etc)
        for (int index = argList.size() - 1; index >= 1; index--) {
            token = argList.get(index);
            FormatterToken prevToken = argList.get(index - 1);
            if (token.getType() == TokenType.SPACE && (prevToken.getType() == TokenType.SYMBOL || prevToken.getType() == TokenType.COMMENT)) {
                argList.remove(index);
            } else if ((token.getType() == TokenType.SYMBOL || token.getType() == TokenType.COMMENT) && prevToken.getType() == TokenType.SPACE) {
                argList.remove(index - 1);
            } else if (token.getType() == TokenType.SPACE) {
                token.setString(" "); //$NON-NLS-1$
            }
        }

        for (int index = 0; index < argList.size() - 2; index++) {
            FormatterToken t0 = argList.get(index);
            FormatterToken t1 = argList.get(index + 1);
            FormatterToken t2 = argList.get(index + 2);

            String tokenString = t0.getString().toUpperCase(Locale.ENGLISH);
            String token2String = t2.getString().toUpperCase(Locale.ENGLISH);;
            // Concatenate tokens
            if (t0.getType() == TokenType.KEYWORD && t1.getType() == TokenType.SPACE && t2.getType() == TokenType.KEYWORD) {
                if (((tokenString.equals("ORDER") || tokenString.equals("GROUP") || tokenString.equals("CONNECT")) && token2String.equals("BY")) ||
                    ((tokenString.equals("START")) && token2String.equals("WITH")))
                {
                    t0.setString(t0.getString() + " " + t2.getString());
                    argList.remove(index + 1);
                    argList.remove(index + 1);
                }
            }

            // Oracle style joins
            if (tokenString.equals("(") && t1.getString().equals("+") && token2String.equals(")")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                t0.setString("(+)"); //$NON-NLS-1$
                argList.remove(index + 1);
                argList.remove(index + 1);
            }
        }

        int indent = 0;
        final List<Integer> bracketIndent = new ArrayList<>();
        FormatterToken prev = new FormatterToken(TokenType.SPACE, " "); //$NON-NLS-1$
        boolean encounterBetween = false;
        for (int index = 0; index < argList.size(); index++) {
            token = argList.get(index);
            String tokenString = token.getString().toUpperCase(Locale.ENGLISH);
            if (token.getType() == TokenType.SYMBOL) {
                if (tokenString.equals("(")) { //$NON-NLS-1$
                    functionBracket.add(formatterCfg.isFunction(prev.getString()) ? Boolean.TRUE : Boolean.FALSE);
                    bracketIndent.add(indent);
                    indent++;
                    index += insertReturnAndIndent(argList, index + 1, indent);
                } else if (tokenString.equals(")") && !bracketIndent.isEmpty() && !functionBracket.isEmpty()) { //$NON-NLS-1$
                    indent = bracketIndent.remove(bracketIndent.size() - 1);
                    index += insertReturnAndIndent(argList, index, indent);
                    functionBracket.remove(functionBracket.size() - 1);
                } else if (tokenString.equals(",")) { //$NON-NLS-1$
                    index += insertReturnAndIndent(argList, index + 1, indent);
                } else if (statementDelimiters.contains(tokenString)) { //$NON-NLS-1$
                    indent = 0;
                    index += insertReturnAndIndent(argList, index, indent);
                }
            } else if (token.getType() == TokenType.KEYWORD) {
                switch (tokenString) {
                    case "DELETE":
                    case "SELECT":
                    case "UPDATE": //$NON-NLS-1$
                    case "INSERT":
                    case "INTO":
                    case "CREATE":
                    case "DROP":
                    case "TRUNCATE":
                    case "TABLE":
                    case "CASE":  //$NON-NLS-1$
                        indent++;
                        index += insertReturnAndIndent(argList, index + 1, indent);
                        break;
                    case "FROM":
                    case "WHERE":
                    case "SET":
                    case "START WITH":
                    case "CONNECT BY":
                    case "ORDER BY":
                    case "GROUP BY":
                    case "HAVING":  //$NON-NLS-1$
                        index += insertReturnAndIndent(argList, index, indent - 1);
                        index += insertReturnAndIndent(argList, index + 1, indent);
                        break;
                    case "LEFT":
                    case "RIGHT":
                    case "INNER":
                    case "OUTER":
                    case "JOIN":
                        if (isJoinStart(argList, index)) {
                            index += insertReturnAndIndent(argList, index, indent - 1);
                        }
                        if (tokenString.equals("JOIN")) {
                            //index += insertReturnAndIndent(argList, index + 1, indent);
                        }
                        break;
                    case "VALUES":  //$NON-NLS-1$
                        indent--;
                        index += insertReturnAndIndent(argList, index, indent);
                        break;
                    case "END":  //$NON-NLS-1$
                        indent--;
                        index += insertReturnAndIndent(argList, index, indent);
                        break;
                    case "OR":
                    case "WHEN":
                    case "ELSE":  //$NON-NLS-1$
                        index += insertReturnAndIndent(argList, index, indent);
                        break;
                    case "ON":
                        //indent++;
                        index += insertReturnAndIndent(argList, index + 1, indent);
                        break;
                    case "USING":  //$NON-NLS-1$ //$NON-NLS-2$
                        index += insertReturnAndIndent(argList, index, indent + 1);
                        break;
                    case "UNION":
                    case "INTERSECT":
                    case "EXCEPT": //$NON-NLS-1$
                        indent -= 2;
                        index += insertReturnAndIndent(argList, index, indent);
                        //index += insertReturnAndIndent(argList, index + 1, indent);
                        indent++;
                        break;
                    case "BETWEEN":  //$NON-NLS-1$
                        encounterBetween = true;
                        break;
                    case "AND":  //$NON-NLS-1$
                        if (!encounterBetween) {
                            index += insertReturnAndIndent(argList, index, indent);
                        }
                        encounterBetween = false;
                        break;
                }
            } else if (token.getType() == TokenType.COMMENT) {
                boolean isComment = false;
                String[] slComments = formatterCfg.getSyntaxManager().getDialect().getSingleLineComments();
                if (slComments != null) {
                    for (String slc : slComments) {
                        if (token.getString().startsWith(slc)) {
                            isComment = true;
                            break;
                        }
                    }
                }
                if (!isComment) {
                    Pair<String, String> mlComments = formatterCfg.getSyntaxManager().getDialect().getMultiLineComments();
                    if (mlComments != null) {
                        if (token.getString().startsWith(mlComments.getFirst())) {
                            index += insertReturnAndIndent(argList, index + 1, indent);
                        }
                    }
                }
            } else if (token.getType() == TokenType.COMMAND) {
                indent = 0;
                if (index > 0) {
                    index += insertReturnAndIndent(argList, index, 0);
                }
                index += insertReturnAndIndent(argList, index + 1, 0);
                if (!CommonUtils.isEmpty(delimiterRedefiner) && token.getString().startsWith(delimiterRedefiner)) {
                    final String command = token.getString().trim().toUpperCase(Locale.ENGLISH);
                    final int divPos = command.lastIndexOf(' ');
                    if (divPos > 0) {
                        String delimiter = command.substring(divPos).trim();
                        if (!CommonUtils.isEmpty(delimiter)) {
                            statementDelimiters.clear();
                            statementDelimiters.add(delimiter);
                        }
                    }
                }
            } else {
                if (statementDelimiters.contains(tokenString)) {
                    indent = 0;
                    index += insertReturnAndIndent(argList, index + 1, indent);
                }
            }
            prev = token;
        }

        for (int index = argList.size() - 1; index >= 4; index--) {
            if (index >= argList.size()) {
                continue;
            }

            FormatterToken t0 = argList.get(index);
            FormatterToken t1 = argList.get(index - 1);
            FormatterToken t2 = argList.get(index - 2);
            FormatterToken t3 = argList.get(index - 3);
            FormatterToken t4 = argList.get(index - 4);

            if (t4.getString().equals("(") //$NON-NLS-1$
                    && t3.getString().trim().isEmpty()
                    && t1.getString().trim().isEmpty()
                    && t0.getString().equalsIgnoreCase(")")) //$NON-NLS-1$
            {
                t4.setString(t4.getString() + t2.getString() + t0.getString());
                argList.remove(index);
                argList.remove(index - 1);
                argList.remove(index - 2);
                argList.remove(index - 3);
            }
        }

        for (int index = 1; index < argList.size(); index++) {
            prev = argList.get(index - 1);
            token = argList.get(index);

            if (prev.getType() != TokenType.SPACE &&
                token.getType() != TokenType.SPACE &&
                !token.getString().startsWith("("))
            {
                if (token.getString().equals(",") || statementDelimiters.contains(token.getString())) { //$NON-NLS-1$
                    continue;
                }
                if (formatterCfg.isFunction(prev.getString())
                        && token.getString().equals("(")) { //$NON-NLS-1$
                    continue;
                }
                if (token.getType() == TokenType.VALUE && prev.getType() == TokenType.NAME) {
                    // Do not add space between name and value [JDBC:MSSQL]
                    continue;
                }
                if (token.getType() == TokenType.SYMBOL && isEmbeddedToken(token) ||
                    prev.getType() == TokenType.SYMBOL && isEmbeddedToken(prev))
                {
                    // Do not insert spaces around colons
                    continue;
                }
                if (token.getType() == TokenType.SYMBOL && prev.getType() == TokenType.SYMBOL) {
                    // Do not add space between symbols
                    continue;
                }
                argList.add(index, new FormatterToken(TokenType.SPACE, " ")); //$NON-NLS-1$
            }
        }

        return argList;
    }

    private static  boolean isEmbeddedToken(FormatterToken token) {
        return ":".equals(token.getString()) || ".".equals(token.getString());
    }

    private boolean isJoinStart(List<FormatterToken> argList, int index) {
        // Keyword sequence must start from LEFT, RIGHT, INNER, OUTER or JOIN and must end with JOIN
        // And we must be in the beginning of sequence

        // check current token
        if (!ArrayUtils.contains(JOIN_BEGIN, argList.get(index).getString())) {
            return false;
        }
        // check previous token
        for (int i = index - 1; i >= 0; i--) {
            FormatterToken token = argList.get(i);
            if (token.getType() == TokenType.SPACE) {
                continue;
            }
            if (ArrayUtils.contains(JOIN_BEGIN, token.getString())) {
                // It is not the begin of sequence
                return false;
            } else {
                break;
            }
        }
        // check last token
        for (int i = index; i < argList.size(); i++) {
            FormatterToken token = argList.get(i);
            if (token.getType() == TokenType.SPACE) {
                continue;
            }
            if (token.getString().equals("JOIN")) {
                return true;
            }
            if (!ArrayUtils.contains(JOIN_BEGIN, token.getString())) {
                // It is not the begin of sequence
                return false;
            }
        }
        return false;
    }

    private int insertReturnAndIndent(final List<FormatterToken> argList, final int argIndex, final int argIndent)
    {
        if (functionBracket.contains(Boolean.TRUE))
            return 0;
        try {
            String s = GeneralUtils.getDefaultLineSeparator();
            if (argIndex > 0) {
                final FormatterToken prevToken = argList.get(argIndex - 1);
                if (prevToken.getType() == TokenType.COMMENT &&
                    SQLUtils.isCommentLine(formatterCfg.getSyntaxManager().getDialect(), prevToken.getString()))
                {
                    s = ""; //$NON-NLS-1$
                }
            }
            for (int index = 0; index < argIndent; index++) {
                s += formatterCfg.getIndentString();
            }

            FormatterToken token = argList.get(argIndex);
            if (token.getType() == TokenType.SPACE) {
                token.setString(s);
                return 0;
            }
            boolean isDelimiter = statementDelimiters.contains(token.getString().toUpperCase());

            if (!isDelimiter) {
                token = argList.get(argIndex - 1);
                if (token.getType() == TokenType.SPACE) {
                    token.setString(s);
                    return 0;
                }
            }

            if (isDelimiter) {
                if (argList.size() > argIndex + 1) {
                    argList.add(argIndex + 1, new FormatterToken(TokenType.SPACE, s + s));
                }
            } else {
                argList.add(argIndex, new FormatterToken(TokenType.SPACE, s));
            }
            return 1;
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            return 0;
        }
    }

}


text:
Quark
=====

REV Motor Controller

This directory will house all the schematics for the Motor Controller used in our electric cars.


text:
namespace MySQL
{
    using System.Collections.Generic;
    using Telerik.OpenAccess.Metadata;
    using Telerik.OpenAccess.Metadata.Fluent;

    public partial class FluentModelMetadataSource : FluentMetadataSource
    {
        protected override IList<MappingConfiguration> PrepareMapping()
        {
            List<MappingConfiguration> configurations = new List<MappingConfiguration>();

            var customerMapping = new MappingConfiguration<VehicleInformation>();
            customerMapping.MapType(k => new
            {
                VehicleID = k.VehicleID,
                VehicleType = k.VehicleType,
                Manufactorer = k.Manufactorer,
                VehicleModel = k.VehicleModel,
                FuelType = k.FuelType,
                DriverFirstName = k.DriverFirstName,
                DriverLastName = k.DriverLastName
            }).ToTable("VehicleInformation");
            customerMapping.HasProperty(c => c.VehicleID).IsIdentity();

            configurations.Add(customerMapping);

            return configurations;
        }

        protected override void SetContainerSettings(MetadataContainer container)
        {
            container.Name = "FluentModel";
            container.DefaultNamespace = "MySQL";
            container.NameGenerator.SourceStrategy = Telerik.OpenAccess.Metadata.NamingSourceStrategy.Property;
            container.NameGenerator.RemoveCamelCase = false;
        }
    }
}


text:
import pytest

@pytest.mark.base
def test_main():
    from pySDC.projects.PinTSimE.estimation_check import check

    check()


text:
class GURL;

namespace content {
class RenderFrameHost;

// Helper for waiting until the navigation in a specific frame tree node (and
// all of its subframes) has completed loading.
class TestFrameNavigationObserver : public WebContentsObserver {
 public:
  // Create and register a new TestFrameNavigationObserver which will track
  // navigations performed in the frame tree node associated with |adapter|.
  // Note that RenderFrameHost associated with |frame| might be destroyed during
  // the navigation (e.g. if the content commits in a new renderer process).
  explicit TestFrameNavigationObserver(const ToRenderFrameHost& adapter);

  ~TestFrameNavigationObserver() override;

  // Runs a nested message loop and blocks until the full load has
  // completed.
  void Wait();

  // Runs a nested message loop and blocks until the navigation in the
  // associated FrameTreeNode has committed.
  void WaitForCommit();

 private:
  // WebContentsObserver
  void DidStartProvisionalLoadForFrame(RenderFrameHost* render_frame_host,
                                       const GURL& validated_url,
                                       bool is_error_page,
                                       bool is_iframe_srcdoc) override;
  void DidCommitProvisionalLoadForFrame(
      RenderFrameHost* render_frame_host,
      const GURL& url,
      ui::PageTransition transition_type) override;
  void DidStopLoading() override;

  // The id of the FrameTreeNode in which navigations are peformed.
  int frame_tree_node_id_;

  // If true the navigation has started.
  bool navigation_started_;

  // If true, the navigation has committed.
  bool has_committed_;

  // If true, this object is waiting for commit only, not for the full load
  // of the document.
  bool wait_for_commit_;

  // The MessageLoopRunner used to spin the message loop.
  scoped_refptr<MessageLoopRunner> message_loop_runner_;

  DISALLOW_COPY_AND_ASSIGN(TestFrameNavigationObserver);
};

}  // namespace content

#endif  // CONTENT_TEST_TEST_FRAME_NAVIGATION_OBSERVER_H_


text:
class Registration < BaseForm
  attr_reader :organisation, :user

  attribute :name     , String
  attribute :email    , String
  attribute :password , String

  validates :name, presence: true, length: {within: 2..100}

  validates :password, presence: true, length: {within: PASSWORD_LENGTH..100}
  validates_email_format_of :email

  delegate :tenant, to: :organisation

  def register
    return false unless valid?

    commit_or_rollback do
      res = create_organisation && create_user

      set_errors(organisation, user) unless res
      res
    end
  end

  private

    def create_user
      @user = User.new(email: email, password: password)
      @user.set_confirmation_token

      @user.active_links.build(
        organisation_id: organisation.id, tenant: organisation.tenant,
        role: 'admin', master_account: true,
        api_token: api_token
      )

      @user.save
    end

    def create_organisation
      @organisation = Organisation.new(name: name, inventory: true)
      @organisation.valid?
      @organisation.save
    end

    def api_token
      SecureRandom.urlsafe_base64(32)
    end

end


text:
<!doctype html>

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

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

VIS 2014 Schedule Browser

authored by Connor Gramazio, CS PhD Candidate @ Brown

A Google Spreadsheet of this data can be found here.

        Title search
        <input id="titleSearch" type="text" class="form-control" placeholder="Enter title to search">

        Author search
        <input id="authorSearch" type="text" class="form-control" placeholder="Enter author to search">

      <form class="form-inline" role="form" style="margin-bottom: 15px">

Start

            <input id="startTime" class="form-control" type="email" placeholder="HH:MM">

End

            <input id="endTime" class="form-control" type="email" placeholder="HH:MM">

      </form>

          <input type="checkbox" autocomplete="off" data-day="Sunday"> Sunday

          <input type="checkbox" autocomplete="off" data-day="Monday"> Monday

          <input type="checkbox" autocomplete="off" data-day="Tuesday"> Tuesday

          <input type="checkbox" autocomplete="off" data-day="Wednesday"> Wednesday

          <input type="checkbox" autocomplete="off" data-day="Thursday"> Thursday

          <input type="checkbox" autocomplete="off" data-day="Friday"> Friday

          <input type="radio" name="options" id="option2" autocomplete="off" data-type="All"> All

          <input type="radio" name="options" id="option1" autocomplete="off" checked  data-type="Papers"> Papers

          <input type="radio" name="options" id="option2" autocomplete="off" data-type="Workshops"> Workshops

          <input type="radio" name="options" id="option3" autocomplete="off" data-type="Panels"> Panels

      Filter by award: <input type="checkbox" id="filterByAward">

      Show/Hide Table


text:
package com.navercorp.pinpoint.plugin.spring.beans;

import static com.navercorp.pinpoint.common.trace.HistogramSchema.*;

import com.navercorp.pinpoint.common.trace.ServiceType;

/**
 * @author Jongho Moon
 *
 */
public final class SpringBeansConstants {
    private SpringBeansConstants() {
    }

    public static final ServiceType SERVICE_TYPE = ServiceType.of(5071, "SPRING_BEAN", "SPRING_BEAN", NORMAL_SCHEMA);
}


text:
const gulp = require('gulp');
/**
 * @param {{
 * htmlmin
 * plumber,
 * angularEmbedTemplates,
 * angularFilesort,
 * ngAnnotate,
 * autoprefixer,
 * concatCss,
 * cleanCss,
 * angularTemplatecache
 * runSequence
 * }} Dynamic methods
 */
const $ = require('gulp-load-plugins')({pattern: '*'});

const paths = {
    templates: '**/*.tpl.html',
};

function minifyHtml() {
    return $.htmlmin({
        collapseBooleanAttributes: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true,
        removeEmptyAttributes: true,
        removeRedundantAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true
    });
}

function minifyScript(dest) {
    const optionsEmbed = {
        basePath: 'src/' //Pegando os templates pela pasta src
    };
    return gulp.src(['!**/smn-ui.*', '**/*.js',], {cwd: 'src'})
        .pipe($.plumber())
        .pipe($.babel())
        .pipe($.angularEmbedTemplates(optionsEmbed))
        .pipe($.angularFilesort())
        .pipe($.concat('smn-ui.min.js'))
        .pipe($.ngAnnotate())
        .pipe($.uglify())
        .pipe(gulp.dest(dest));
}

function minifyStyle(src, dest, concat) {
    return gulp.src(src, {cwd: 'src'})
        .pipe($.plumber())
        .pipe($.autoprefixer({
            browsers: ['> 1%', 'IE 7'],
            cascade: false
        }))
        .pipe($.if(concat, $.concatCss('smn-ui.min.css')))
        .pipe($.cleanCss())
        .pipe(gulp.dest(dest));
}

gulp.task('template', () => {
    const templates = gulp.src(paths.templates, {cwd: 'src'}).pipe($.plumber());

    return templates
        .pipe(minifyHtml())
        .pipe($.angularTemplatecache('app.templates.js', {
            module: 'smn-ui'
        }))
        .pipe(gulp.dest('src/'));
});

gulp.task('minify:css', () => {
    return minifyStyle(['!**/smn-ui.*', '**/*.css'], 'src/', true);
});

gulp.task('minify:js', () => {
    return minifyScript('src/');
});

gulp.task('concat:css', () => {
    return gulp.src(['!**/smn-ui.*', '**/*.css'], {cwd: 'src'})
        .pipe($.plumber())
        .pipe($.autoprefixer({
            browsers: ['> 1%', 'IE 7'],
            cascade: false
        }))
        .pipe($.concatCss('smn-ui.css'))
        .pipe(gulp.dest('src/'));
});

gulp.task('concat:js', () => {
    const optionsEmbed = {
        basePath: 'src/' //Pegando os templates pela pasta src
    };
    return gulp.src(['!**/smn-ui.*', '**/*.js'], {cwd: 'src'})
        .pipe($.plumber())
        .pipe($.babel())
        .pipe($.angularEmbedTemplates(optionsEmbed))
        .pipe($.angularFilesort())
        .pipe($.concat('smn-ui.js'))
        .pipe($.ngAnnotate())
        .pipe(gulp.dest('src/'));
});

gulp.task('clean', () => {
    return gulp.src(['dist', 'src/*.min.*', 'src/app.templates.js'], {read: false})
        .pipe($.clean());
});

gulp.task('dist', () => {
    gulp.src('src/smn-ui.*')
        .pipe(gulp.dest('dist/'));
});

gulp.task('build', ['clean'], () => {
    $.runSequence('template', ['concat:css', 'concat:js', 'minify:css', 'minify:js'], 'dist');
});


text:
Plugin to support [Tinkerforge](http://www.tinkerforge.com/en) devices on the [HomeBridge Platform](https://github.com/nfarina/homebridge).

# Installation

1. Install homebridge using: npm install -g homebridge
2. Install homebridge-tinkerforge using: npm install -g homebridge-tinkerforge
3. Update your configuration file. See sample-config.json in this repository for a sample.

# Currently Supported Bricklets

Below, find a list of currently supported bricklets and the options available to configure them. If some parameters seem unclear, please check the Tinkerforge API. If a parameter is optional, a standard value is given in square brackets.

## BrickletRemoteSwitch
Fully supported.

* String `accessory`: needs to be "BrickletRemoteSwitch"
* String `uid`: the uid of the BrickletRemoteSwitch
* String `name`: displayed name of object, also used by Siri
* Number `address`: address (or houseCode or systemCode) of to be switched socket
* Number `unit`: unit (or receiverCode or deviceCode) of to be switched socket
* String `host` ["localhost"]: ip address of machine with brickd
* Number `port`: [4223]: socket of brickd
* String `type`: ["switchB"]: type of the to be switched socket ("switchA", "dimB", "switchB" or "switchC")

# How to contribute

Add more bricklet types and improve existing ones. Also solve issues. No maximum line length.

# Notes for implementation

## Possible Characteristics and Services
Description of characteristics (available methods and how to build listener) can be found [here]( https://github.com/KhaosT/HAP-NodeJS/blob/master/lib/Characteristic.js). Characteristics hava a setValue() and a getValue() method.

Overview of all available characteristics and services can be found [here](https://github.com/KhaosT/HAP-NodeJS/blob/master/lib/gen/HomeKitTypes.js).

When adding characteristics:
* getCharacteristic: Searches for characteristic in service and returns it. If non existent but optional -> create one and return it
* setCharacteristic: getCharacteristic + setValue()

## Start in Developer Mode

To start the plugin in developer mode run `homebridge -D -P . -U ~/.homebridge-dev/` while beeing in the root directory. A sample config has to be saved at `~/.homebridge-dev/`.


text:
            <button class="btn btn-default pull-right" ng-click="toggleFilters()">{{filterState}} Filters </button>

                                {{filter.display}}

Search Index

                <input type="text" class="form-control" ng-model="searchInput" ng-keypress="handleEnter($event)" style="height: 40px">

                    clear

                    <button class="btn btn-default" type="button" ng-click="searchClick()" style="margin-left: -1px">
                         Search
                    </button>

                Name	 Type	 Size

                    {{doc.name}}
                    {{doc.format}}
                    {{doc.size}}

                {{field}}

                        {{doc[field]}}

            <button class="btn btn-warning" ng-click="closeBrowser()">Cancel</button>


text:
package net.distilledcode.httpclient.impl;

import net.distilledcode.httpclient.impl.metatype.HttpClientConfigurationMetaType;
import net.distilledcode.httpclient.impl.metatype.MetaTypeBeanUtil;
import net.distilledcode.httpclient.impl.metatype.reflection.SetterAdapter;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.osgi.services.HttpClientBuilderFactory;

import java.util.Map;

class PreconfiguredHttpClientBuilderFactory implements HttpClientBuilderFactory {

    private final HttpClientBuilderFactory httpClientBuilderFactory;

    private final Map<String, Object> effectiveConfiguration;

    public PreconfiguredHttpClientBuilderFactory(final HttpClientBuilderFactory factory, final Map<String, Object> effectiveConfiguration) {
        this.httpClientBuilderFactory = factory;
        this.effectiveConfiguration = effectiveConfiguration;
    }

    @Override
    public HttpClientBuilder newBuilder() {
        final HttpClientBuilder httpClientBuilder = httpClientBuilderFactory.newBuilder();
        configure(httpClientBuilder);
        return httpClientBuilder;
    }

    private void configure(HttpClientBuilder httpClientBuilder) {
        final RequestConfig.Builder requestConfigBuilder = RequestConfig.copy(RequestConfig.DEFAULT);
        MetaTypeBeanUtil.applyConfiguration(HttpClientConfigurationMetaType.REQUEST_CONFIG_NAMESPACE, effectiveConfiguration,
                new SetterAdapter(requestConfigBuilder, HttpClientConfigurationMetaType.SETTERS_REQUEST_CONFIG_BUILDER));
        final RequestConfig requestConfig = requestConfigBuilder.build();
        MetaTypeBeanUtil.applyConfiguration("", effectiveConfiguration,
                new SetterAdapter(httpClientBuilder, HttpClientConfigurationMetaType.SETTERS_HTTP_CLIENT_BUILDER));
        httpClientBuilder.setDefaultRequestConfig(requestConfig);
    }
}


text:
<!DOCTYPE html>

Test decreasing the width of the containing block of a scrollable container with percent width.

One vertical scrollbar should be seen below.


text:
<?php

namespace Acme\TrivialWarsServerBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Partida
 *
 * @ORM\Table(name="partida", uniqueConstraints={@ORM\UniqueConstraint(name="id_partida", columns={"id_partida"}), @ORM\UniqueConstraint(name="nombre", columns={"nombre"})})
 * @ORM\Entity(repositoryClass="Acme\TrivialWarsServerBundle\Entity\Repository\PartidaRepository")
 */
class Partida
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id_partida", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="numero_jugadores", type="integer", nullable=true)
     */
    private $numeroJugadores;

    /**
     * @var integer
     *
     * @ORM\Column(name="turno", type="integer", nullable=false)
     */
    private $turno;

    /**
     * @var string
     *
     * @ORM\Column(name="nombre", type="string", length=100, nullable=false)
     */
    private $nombre;

    /**
     * Get idPartida
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set numeroJugadores
     *
     * @param integer $numeroJugadores
     * @return Partida
     */
    public function setNumeroJugadores($numeroJugadores)
    {
        $this->numeroJugadores = $numeroJugadores;

        return $this;
    }

    /**
     * Get numeroJugadores
     *
     * @return integer
     */
    public function getNumeroJugadores()
    {
        return $this->numeroJugadores;
    }

    /**
     * Set turno
     *
     * @param integer $turno
     * @return Partida
     */
    public function setTurno($turno)
    {
        $this->turno = $turno;

        return $this;
    }

    /**
     * Get turno
     *
     * @return integer
     */
    public function getTurno()
    {
        return $this->turno;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return Partida
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }
}


text:
PYTHON_BASE_DIR=/usr/local/opt/python
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=$PYTHON_BASE_DIR/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--no-site-packages'
export PIP_VIRTUALENV_BASE=$WORKON_HOME
export PIP_RESPECT_VIRTUALENV=true
if [[ -r /usr/local/bin/virtualenvwrapper.sh ]]; then
   source /usr/local/bin/virtualenvwrapper.sh
else
   echo "WARNING: Can't find virtualenvwrapper.sh"
fi

# pip should only run if there is a virtualenv currently activated
export PIP_REQUIRE_VIRTUALENV=true

syspip3() {
   PIP_REQUIRE_VIRTUALENV="" pip3 "$@"
}


text: Materials for Visual Studio Live! 2015 in San Francisco.


text:
package org.wildfly.security.credential.store.impl;

import java.io.IOException;

import org.junit.Test;

import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

public class VaultObjectInputStreamTest {

    @Test
    public void shouldSupportPicketboxSerializedVaultData() throws IOException, ClassNotFoundException {
        try (VaultObjectInputStream in = new VaultObjectInputStream(
                VaultObjectInputStreamTest.class.getResourceAsStream("/picketbox-vault.dat"))) {
            assertThat(in.readObject(), instanceOf(SecurityVaultData.class));
        }
    }

}


text:
<?php

declare(strict_types=1);

namespace Psi\Component\ContentType\Standard\Field;

use Psi\Component\ContentType\FieldInterface;
use Psi\Component\ContentType\OptionsResolver\FieldOptionsResolver;
use Psi\Component\ContentType\Standard\Storage;
use Psi\Component\ContentType\Standard\View;
use Symfony\Component\Form\Extension\Core\Type as Form;

class DateTimeField implements FieldInterface
{
    public function getViewType(): string
    {
        return View\DateTimeType::class;
    }

    public function getFormType(): string
    {
        return Form\DateTimeType::class;
    }

    public function getStorageType(): string
    {
        return Storage\DateTimeType::class;
    }

    public function configureOptions(FieldOptionsResolver $options)
    {
        $options->setFormMapper(function ($options, $shared) {
            $options['input'] = 'datetime';

            return $options;
        });
    }
}


text:
#ifndef __I_GUI_MESH_VIEWER_H_INCLUDED__
#define __I_GUI_MESH_VIEWER_H_INCLUDED__

#include "IGUIElement.h"

namespace irr
{

namespace video
{
	class SMaterial;
} // end namespace video

namespace scene
{
	class IAnimatedMesh;
} // end namespace scene

namespace gui
{

	//! 3d mesh viewing GUI element.
	class IGUIMeshViewer : public IGUIElement
	{
	public:

		//! constructor
		IGUIMeshViewer(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle)
			: IGUIElement(EGUIET_MESH_VIEWER, environment, parent, id, rectangle) {}

		//! Sets the mesh to be shown
		virtual void setMesh(scene::IAnimatedMesh* mesh) = 0;

		//! Gets the displayed mesh
		virtual scene::IAnimatedMesh* getMesh() const = 0;

		//! Sets the material
		virtual void setMaterial(const video::SMaterial& material) = 0;

		//! Gets the material
		virtual const video::SMaterial& getMaterial() const = 0;
	};

} // end namespace gui
} // end namespace irr

#endif


text:
package com.nedap.archie.rm.datavalues.quantity.datetime;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.nedap.archie.json.DateDeserializer;
import com.nedap.archie.rm.datavalues.SingleValuedDataValue;
import com.nedap.archie.xml.adapters.DateXmlAdapter;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.Temporal;

/**
 * TODO: implement java.time.Temporal for this
 * TODO: implement java.time.Temporal for this
 * Created by pieter.bos on 04/11/15.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DV_DATE", propOrder = {
        "value"
})
public class DvDate extends DvTemporal<Long> implements SingleValuedDataValue<Temporal> {
    //TODO: in XML this should be a string probably
    @XmlJavaTypeAdapter(DateXmlAdapter.class)
    private Temporal value;

    @Override
//    @XmlElements({
//            @XmlElement(type=LocalDate.class),
//            @XmlElement(type=YearMonth.class),
//            @XmlElement(type=Year.class)
//
//    })
    @JsonDeserialize(using= DateDeserializer.class)
    public Temporal getValue() {
        return value;
    }

    @Override
    public void setValue(Temporal value) {
        if(value.isSupported(ChronoField.HOUR_OF_DAY)) {
            //TODO: do we really need this validation?
            throw new IllegalArgumentException("value must only have a year, month or date, but this supports hours: " + value);
        }
        this.value = value;
    }

    @Override
    public Long getMagnitude() {
        return value == null ? null : (long) LocalDate.from(value).toEpochDay();
    }

    public void setMagnitude(Long magnitude) {
        if(magnitude == null) {
            value = null;
        } else {
            value = LocalDate.ofEpochDay(magnitude);
        }
    }
}


text:
from django.utils.translation import ugettext_lazy as _

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from . import settings
from .forms import VideoForm
from .models import Video

class VideoPlugin(CMSPluginBase):
    model = Video
    name = _("Video")
    form = VideoForm

    render_template = "cms/plugins/video.html"

    general_fields = [
        ('movie', 'movie_url'),
        'image',
        ('width', 'height'),
        'auto_play',
        'auto_hide',
        'fullscreen',
        'loop',
    ]
    color_fields = [
        'bgcolor',
        'textcolor',
        'seekbarcolor',
        'seekbarbgcolor',
        'loadingbarcolor',
        'buttonoutcolor',
        'buttonovercolor',
        'buttonhighlightcolor',
    ]

    fieldsets = [
        (None, {
            'fields': general_fields,
        }),
    ]
    if settings.VIDEO_PLUGIN_ENABLE_ADVANCED_SETTINGS:
        fieldsets += [
            (_('Color Settings'), {
                'fields': color_fields,
                'classes': ('collapse',),
            }),
        ]

    def render(self, context, instance, placeholder):
        context.update({
            'object': instance,
            'placeholder': placeholder,
        })
        return context

plugin_pool.register_plugin(VideoPlugin)


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/services/storage/public/cpp/filesystem/filesystem_proxy.h"

#include <memory>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/task/post_task.h"
#include "base/util/type_safety/pass_key.h"
#include "build/build_config.h"
#include "components/services/storage/public/cpp/filesystem/filesystem_impl.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"

namespace storage {

namespace {

size_t GetNumPathComponents(const base::FilePath& path) {
  std::vector<base::FilePath::StringType> components;
  path.GetComponents(&components);
  return components.size();
}

class LocalFileLockImpl : public FilesystemProxy::FileLock {
 public:
  LocalFileLockImpl(base::FilePath path, base::File lock)
      : path_(std::move(path)), lock_(std::move(lock)) {}
  ~LocalFileLockImpl() override {
    if (lock_.IsValid())
      Release();
  }

  // FilesystemProxy::FileLock implementation:
  base::File::Error Release() override {
    base::File::Error error = base::File::FILE_OK;
#if !defined(OS_FUCHSIA)
    error = lock_.Unlock();
#endif
    lock_.Close();
    FilesystemImpl::UnlockFileLocal(path_);
    return error;
  }

 private:
  const base::FilePath path_;
  base::File lock_;
};

class RemoteFileLockImpl : public FilesystemProxy::FileLock {
 public:
  explicit RemoteFileLockImpl(mojo::PendingRemote<mojom::FileLock> remote_lock)
      : remote_lock_(std::move(remote_lock)) {}
  ~RemoteFileLockImpl() override {
    if (remote_lock_)
      Release();
  }

  // FilesystemProxy::FileLock implementation:
  base::File::Error Release() override {
    DCHECK(remote_lock_);
    base::File::Error error = base::File::FILE_ERROR_IO;
    mojo::Remote<mojom::FileLock>(std::move(remote_lock_))->Release(&error);
    return error;
  }

 private:
  mojo::PendingRemote<mojom::FileLock> remote_lock_;
};

}  // namespace

FilesystemProxy::FilesystemProxy(decltype(UNRESTRICTED),
                                 const base::FilePath& root)
    : root_(root) {
  DCHECK(root_.IsAbsolute() || root_.empty());
}

FilesystemProxy::FilesystemProxy(
    decltype(RESTRICTED),
    const base::FilePath& root,
    mojo::PendingRemote<mojom::Directory> directory,
    scoped_refptr<base::SequencedTaskRunner> ipc_task_runner)
    : root_(root),
      num_root_components_(GetNumPathComponents(root_)),
      remote_directory_(std::move(directory)) {
  DCHECK(root_.IsAbsolute());
}

FilesystemProxy::~FilesystemProxy() = default;

bool FilesystemProxy::PathExists(const base::FilePath& path) {
  if (!remote_directory_)
    return base::PathExists(MaybeMakeAbsolute(path));

  bool exists = false;
  remote_directory_->PathExists(MakeRelative(path), &exists);
  return exists;
}

FileErrorOr<std::vector<base::FilePath>> FilesystemProxy::GetDirectoryEntries(
    const base::FilePath& path,
    DirectoryEntryType type) {
  const mojom::GetEntriesMode mode =
      type == DirectoryEntryType::kFilesOnly
          ? mojom::GetEntriesMode::kFilesOnly
          : mojom::GetEntriesMode::kFilesAndDirectories;
  if (!remote_directory_)
    return FilesystemImpl::GetDirectoryEntries(MaybeMakeAbsolute(path), mode);

  base::File::Error error = base::File::FILE_ERROR_IO;
  std::vector<base::FilePath> entries;
  remote_directory_->GetEntries(MakeRelative(path), mode, &error, &entries);
  if (error != base::File::FILE_OK)
    return error;

  // Fix up all the relative paths to be absolute.
  const base::FilePath root = path.IsAbsolute() ? path : root_.Append(path);
  for (auto& entry : entries)
    entry = root.Append(entry);
  return entries;
}

FileErrorOr<base::File> FilesystemProxy::OpenFile(const base::FilePath& path,
                                                  int flags) {
  if (!remote_directory_) {
    base::File file(MaybeMakeAbsolute(path), flags);
    if (!file.IsValid())
      return file.error_details();
    return file;
  }

  // NOTE: Remote directories only support a subset of |flags| values.
  const int kModeMask = base::File::FLAG_OPEN | base::File::FLAG_CREATE |
                        base::File::FLAG_OPEN_ALWAYS |
                        base::File::FLAG_CREATE_ALWAYS |
                        base::File::FLAG_OPEN_TRUNCATED;
  const int kWriteMask = base::File::FLAG_WRITE | base::File::FLAG_APPEND;
  const int kSupportedFlagsMask =
      kModeMask | kWriteMask | base::File::FLAG_READ;
  DCHECK((flags & ~kSupportedFlagsMask) == 0) << "Unsupported flags: " << flags;

  const int mode_flags = flags & kModeMask;
  mojom::FileOpenMode mode;
  switch (mode_flags) {
    case base::File::FLAG_OPEN:
      mode = mojom::FileOpenMode::kOpenIfExists;
      break;
    case base::File::FLAG_CREATE:
      mode = mojom::FileOpenMode::kCreateAndOpenOnlyIfNotExists;
      break;
    case base::File::FLAG_OPEN_ALWAYS:
      mode = mojom::FileOpenMode::kAlwaysOpen;
      break;
    case base::File::FLAG_CREATE_ALWAYS:
      mode = mojom::FileOpenMode::kAlwaysCreate;
      break;
    case base::File::FLAG_OPEN_TRUNCATED:
      mode = mojom::FileOpenMode::kOpenIfExistsAndTruncate;
      break;
    default:
      NOTREACHED() << "Invalid open mode flags: " << mode_flags;
      return base::File::FILE_ERROR_FAILED;
  }

  mojom::FileReadAccess read_access =
      (flags & base::File::FLAG_READ) != 0
          ? mojom::FileReadAccess::kReadAllowed
          : mojom::FileReadAccess::kReadNotAllowed;

  const int write_flags = flags & kWriteMask;
  mojom::FileWriteAccess write_access;
  switch (write_flags) {
    case 0:
      write_access = mojom::FileWriteAccess::kWriteNotAllowed;
      break;
    case base::File::FLAG_WRITE:
      write_access = mojom::FileWriteAccess::kWriteAllowed;
      break;
    case base::File::FLAG_APPEND:
      write_access = mojom::FileWriteAccess::kAppendOnly;
      break;
    default:
      NOTREACHED() << "Invalid write access flags: " << write_flags;
      return base::File::FILE_ERROR_FAILED;
  }

  base::File::Error error = base::File::FILE_ERROR_IO;
  base::File file;
  remote_directory_->OpenFile(MakeRelative(path), mode, read_access,
                              write_access, &error, &file);
  if (error != base::File::FILE_OK)
    return error;
  return file;
}

bool FilesystemProxy::RemoveFile(const base::FilePath& path) {
  if (!remote_directory_)
    return base::DeleteFile(MaybeMakeAbsolute(path), /*recursive=*/false);

  bool success = false;
  remote_directory_->RemoveFile(MakeRelative(path), &success);
  return success;
}

base::File::Error FilesystemProxy::CreateDirectory(const base::FilePath& path) {
  base::File::Error error = base::File::FILE_ERROR_IO;
  if (!remote_directory_) {
    if (!base::CreateDirectoryAndGetError(MaybeMakeAbsolute(path), &error))
      return error;
    return base::File::FILE_OK;
  }

  remote_directory_->CreateDirectory(MakeRelative(path), &error);
  return error;
}

bool FilesystemProxy::RemoveDirectory(const base::FilePath& path) {
  if (!remote_directory_) {
    const base::FilePath full_path = MaybeMakeAbsolute(path);
    if (!base::DirectoryExists(full_path))
      return false;
    return base::DeleteFile(full_path, /*recursive=*/false);
  }

  bool success = false;
  remote_directory_->RemoveDirectory(MakeRelative(path), &success);
  return success;
}

base::Optional<base::File::Info> FilesystemProxy::GetFileInfo(
    const base::FilePath& path) {
  if (!remote_directory_) {
    base::File::Info info;
    if (base::GetFileInfo(MaybeMakeAbsolute(path), &info))
      return info;
    return base::nullopt;
  }

  base::Optional<base::File::Info> info;
  remote_directory_->GetFileInfo(MakeRelative(path), &info);
  return info;
}

base::File::Error FilesystemProxy::RenameFile(const base::FilePath& old_path,
                                              const base::FilePath& new_path) {
  base::File::Error error = base::File::FILE_ERROR_IO;
  if (!remote_directory_) {
    if (!base::ReplaceFile(MaybeMakeAbsolute(old_path),
                           MaybeMakeAbsolute(new_path), &error)) {
      return error;
    }
    return base::File::FILE_OK;
  }

  remote_directory_->RenameFile(MakeRelative(old_path), MakeRelative(new_path),
                                &error);
  return error;
}

FileErrorOr<std::unique_ptr<FilesystemProxy::FileLock>>
FilesystemProxy::LockFile(const base::FilePath& path) {
  if (!remote_directory_) {
    base::FilePath full_path = MaybeMakeAbsolute(path);
    FileErrorOr<base::File> result = FilesystemImpl::LockFileLocal(full_path);
    if (result.is_error())
      return result.error();
    std::unique_ptr<FileLock> lock = std::make_unique<LocalFileLockImpl>(
        std::move(full_path), std::move(result.value()));
    return lock;
  }

  mojo::PendingRemote<mojom::FileLock> remote_lock;
  base::File::Error error = base::File::FILE_ERROR_IO;
  if (!remote_directory_->LockFile(MakeRelative(path), &error, &remote_lock))
    return error;
  if (error != base::File::FILE_OK)
    return error;

  std::unique_ptr<FileLock> lock =
      std::make_unique<RemoteFileLockImpl>(std::move(remote_lock));
  return lock;
}

base::FilePath FilesystemProxy::MakeRelative(const base::FilePath& path) const {
  DCHECK(remote_directory_);
  DCHECK(!path.ReferencesParent());

  // For a remote Directory, returned paths must always be relative to |root|.
  if (!path.IsAbsolute() || path.empty())
    return path;

  if (path == root_)
    return base::FilePath();

  // Absolute paths need to be rebased onto |root_|.
  std::vector<base::FilePath::StringType> components;
  path.GetComponents(&components);
  base::FilePath relative_path;
  for (size_t i = num_root_components_; i < components.size(); ++i)
    relative_path = relative_path.Append(components[i]);
  return relative_path;
}

base::FilePath FilesystemProxy::MaybeMakeAbsolute(
    const base::FilePath& path) const {
  DCHECK(!remote_directory_);
  if (path.IsAbsolute() || root_.empty())
    return path;

  return root_.Append(path);
}

}  // namespace storage


text:
package com.danidemi.jlubricant.embeddable;

public class ServerStopException extends ServerException {

	private static final long serialVersionUID = 633200033705652785L;

	public ServerStopException() {
		super();
	}

	public ServerStopException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

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

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

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

}


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//session_start();
class Categoria_proyecto extends MX_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('template');
		$this->load->library('menu');
		//$this->load->model('contrato_model');
		$this->load->model('grl/general_model');
    }

	public function index()
    {
		if($this->session->userdata('id')):
     		$session_data = $this->session->userdata();
     		$data['usuario'] = $session_data['username'];
	 		$data['iduser'] = $session_data['id'];
			$data['idperfil'] = $session_data['idperfil'];
			$data["menu"] = $this->menu->crea_menu($data['idperfil']);
			//$data["menu_doc"] = $this->menu->crea_menu_doc($data['idperfil'],$data['iduser']);
			$data['css'] = '';
			$data['js'] = '<script src="'.base_url('assets/js/jquery-ui.min.js').'"></script>';
			$data['js'] .= '<script src="'.base_url('assets/js/doc-cat.js').'"></script>';
			$data["proyectos"] = $this->general_model->desplega_lista_proyectos();
			$this->template->load('template','categoria_proyecto',$data);
		else:
			redirect('login/index', 'refresh');
		endif;
    }

	public function agregar()
	{
		if($this->session->userdata('id')):
     		$session_data = $this->session->userdata();
     		$data['usuario'] = $session_data['username'];
	 		$data['iduser'] = $session_data['id'];
			$data['idperfil'] = $session_data['idperfil'];
			$categoria = $this->input->get('categoria');
			echo '{"msg":1}';
		else:
			redirect('login/index', 'refresh');
		endif;
	}

}