text:
package com.ibm.xsp.theme.bootstrap.renderkit.html.extlib.data;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import com.ibm.commons.util.StringUtil;
import com.ibm.xsp.component.FacesDataIterator;
import com.ibm.xsp.extlib.component.data.AbstractPager;
import com.ibm.xsp.extlib.component.data.UIPagerExpand;
import com.ibm.xsp.extlib.util.ExtLibUtil;

public class PagerExpandRenderer extends com.ibm.xsp.extlib.renderkit.html_extended.data.PagerExpandRenderer {

    @Override
    protected void writePagerContent(FacesContext context, ResponseWriter w, AbstractPager _pager, FacesDataIterator dataIterator) throws IOException {
        UIPagerExpand pager = (UIPagerExpand) _pager;
        w.startElement("div", null); // $NON-NLS-1$

        w.startElement("ul", null); // $NON-NLS-1$
        String styleClass = pager.getStyleClass();
        String pgClass = ExtLibUtil.concatStyleClasses("pagination", styleClass); // $NON-NLS-1$
        if (StringUtil.isNotEmpty(pgClass)) {
            w.writeAttribute("class", pgClass, null); // $NON-NLS-1$
        }

        writeCollapseAll(context, w, pager, dataIterator);
        writeSeparator(context, w, pager, dataIterator);
        writeExpandAll(context, w, pager, dataIterator);
        w.endElement("ul"); // $NON-NLS-1$

        w.endElement("div"); // $NON-NLS-1$
    }

    @Override
    protected void writeCollapseAll(FacesContext context, ResponseWriter w, UIPagerExpand pager, FacesDataIterator dataIterator) throws IOException {
        String text = pager.getCollapseText();
        if (StringUtil.isEmpty(text)) {
            text = (String)getProperty(PROP_COLLAPSETEXT);
        }
        if (StringUtil.isNotEmpty(text)) {
            w.startElement("li", null); // $NON-NLS-1$
            boolean selected = pager.isCollapseAll();
            if (selected) {
                w.writeAttribute("class", "active", null); // $NON-NLS-1$ $NON-NLS-2$
            }
            w.startElement("a", null);
            String clientId = pager.getClientId(context);
            String sourceId = clientId + "_ca"; // $NON-NLS-1$
            w.writeAttribute("id", sourceId, null); // $NON-NLS-1$
            w.writeAttribute("role", "button", null); // $NON-NLS-1$ $NON-NLS-2$
            if (selected) {
                w.writeAttribute("aria-pressed", "true", null); // $NON-NLS-1$ $NON-NLS-2$
            }else{
                w.writeAttribute("aria-pressed", "false", null); // $NON-NLS-1$ $NON-NLS-2$
            }
            w.writeAttribute("href", "javascript:;", null); // $NON-NLS-1$ $NON-NLS-2$
            setupSubmitOnClick(context, w, pager, dataIterator, clientId, sourceId);
            w.writeText(text, null);
            w.endElement("a");
            w.endElement("li"); // $NON-NLS-1$
        }
    }

    @Override
    protected void writeSeparator(FacesContext context, ResponseWriter w, UIPagerExpand pager, FacesDataIterator dataIterator) throws IOException {
        // not write any separator text, instead the separator is achieved using
        // CSS styles
        // so there are no character encoding issues in other countries
    }

    @Override
    protected void writeExpandAll(FacesContext context, ResponseWriter w, UIPagerExpand pager, FacesDataIterator dataIterator) throws IOException {
        String text = pager.getExpandText();
        if (StringUtil.isEmpty(text)) {
            text = (String)getProperty(PROP_EXPANDTEXT);
        }
        if (StringUtil.isNotEmpty(text)) {
            w.startElement("li", null); // $NON-NLS-1$
            boolean selected = pager.isExpandAll();
            if (selected) {
                w.writeAttribute("class", "active", null); // $NON-NLS-2$ $NON-NLS-1$
            }
            w.startElement("a", null);
            String clientId = pager.getClientId(context);
            String sourceId = clientId + "_ea"; // $NON-NLS-1$
            w.writeAttribute("id", sourceId, null); // $NON-NLS-1$
            w.writeAttribute("role", "button", null); // $NON-NLS-1$ $NON-NLS-2$
            if (selected) {
                w.writeAttribute("aria-pressed", "true", null); // $NON-NLS-1$ $NON-NLS-2$
            }else{
                w.writeAttribute("aria-pressed", "false", null); // $NON-NLS-1$ $NON-NLS-2$
            }
            w.writeAttribute("href", "javascript:;", null); // $NON-NLS-1$ $NON-NLS-2$
            setupSubmitOnClick(context, w, pager, dataIterator, clientId, sourceId);
            w.writeText(text, null);
            w.endElement("a");
            w.endElement("li"); // $NON-NLS-1$
        }
    }
}


text:
using abremir.AllMyBricks.AssetManagement.Interfaces;
using System.IO;

namespace abremir.AllMyBricks.AssetManagement.Implementations
{
    public class FileStreamImplementation : IFileStream
    {
        public FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share)
        {
            return new FileStream(path, mode, access, share);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Planex.Web.Areas.Lead.Models
{
    using System.ComponentModel.DataAnnotations;
    using System.Linq;

    using AutoMapper;

    using Planex.Data.Models;
    using Planex.Web.Infrastructure.Mappings;

    public class ProjectIndexViewController : BaseProjectViewModel, IMapFrom<Project>, IHaveCustomMappings
    {
        [Required]
        [UIHint("Number")]
        public int Completed { get; set; }

        public void CreateMappings(IConfiguration configuration)
        {
            configuration.CreateMap<Project, ProjectIndexViewController>(string.Empty)
                .ForMember(m => m.Manager, opt => opt.MapFrom(c => c.Manager.FirstName + " " + c.Manager.LastName))
                .ForMember(m => m.UploadedAttachmentFiles, opt => opt.MapFrom(c => c.Attachments.Select(x => x.Name)))
                .ForMember(m => m.Completed, opt => opt.MapFrom(c => 0));
        }
    }
}


text:
require 'test_helper'

class Api::FavouritesControllerTest < ActionDispatch::IntegrationTest
  # test "the truth" do
  #   assert true
  # end
end


text:
The parser of [Ranking of Universities](http://webometrics.info/en/).

![Sreenshot](https://raw.githubusercontent.com/lassana/webometrics-parser/master/Screenshot_20160217_140205.png)

## License
The code is licensed under [the BSD 2-Clause](LICENSE) license.

The Webometrics Ranking is not a part of this project. For more info see [Ranking FAQs](http://webometrics.info/en/node/36):
>**What is your policy about data sharing?**

>Only the published data are available for non-profit purposes. We do not supply additional info to anonymous or commercial requests. For academic purposes we are open to share our results on the basis of joint academic projects.


text:
Hancock.rails_admin_configure do |config|
  config.action_visible_for :sitemap, Proc.new { false }
  config.action_visible_for :sitemap_for_model, 'Hancock::Seo::SitemapData'

  config.action_visible_for :robots_txt, Proc.new { false }
  config.action_visible_for :robots_txt_for_model, 'Hancock::Seo::Seo'
end


text:
/**
 * Implement wildcard pattern matching with support for '?' and '*'.
 * '?' Matches any single character.
 * '*' Matches any sequence of characters (including the empty sequence).
 *
 * The matching should cover the entire input string (not partial).
 *
 * The function prototype should be:
 * bool isMatch(const char *s, const char *p)
 *
 * Some examples:
 * isMatch("aa","a") → false
 * isMatch("aa","aa") → true
 * isMatch("aaa","aa") → false
 * isMatch("aa", "*") → true
 * isMatch("aa", "a*") → true
 * isMatch("ab", "?*") → true
 * isMatch("aab", "c*a*b") → false
 *
 * My own examples:
 * isMatch("aab", "a*a*b") → true
 * isMatch("a", "a*") → true
 *
 * Tags: DP, Backtracking, Greedy, String
 */
class WildcardMatching {
    public static void main(String[] args) {
        WildcardMatching w = new WildcardMatching();
        /*input validation*/
        // System.out.println(w.isMatch("", "a")); // false
        // System.out.println(w.isMatch("a", "")); // false
        // System.out.println(w.isMatch("", "")); // true
        // System.out.println(w.isMatch(null, null)); // true
        // System.out.println(w.isMatch("a", null)); // false
        // System.out.println(w.isMatch(null, "null")); // false
        /*letters*/
        // System.out.println(w.isMatch("a", "aa")); // false
        // System.out.println(w.isMatch("aa", "a")); // false
        // System.out.println(w.isMatch("aa", "aa")); // true
        // System.out.println(w.isMatch("aa", "ab")); // false
        /**s*/
        // System.out.println(w.isMatch("aa", "*")); // true
        /*?s*/
        // System.out.println(w.isMatch("aa", "?")); // false
        // System.out.println(w.isMatch("a", "?")); // true
        /*letters and *s*/
        // System.out.println(w.isMatch("abc", "a*")); // true
        // System.out.println(w.isMatch("ab", "a*")); // true
        // System.out.println(w.isMatch("ab", "*a")); // false
        // System.out.println(w.isMatch("a", "a*")); // true
        // System.out.println(w.isMatch("bcsa", "*a")); // true
        // System.out.println(w.isMatch("bcs", "*a")); // false
        // System.out.println(w.isMatch("bbbbbbbbbb", "*bbbbb")); // true

        /* * and ? */
        // System.out.println(isMatch("b", "*?*?")); // false
    }

    /**
     * DP, two pointers
     * remember the index of * and matched sequence
     * advance only pattern pointer when * is found
     * match the sequence after * in pattern with the rest of the string
     */
    public boolean isMatch(String str, String pattern) {
        if (str == null && pattern == null) return true;
        if (str == null || pattern == null) return false;

        int s = 0, p = 0, match = 0, astroIdx = -1; // must be -1
        while (s < str.length()) {
            if (p < pattern.length()  && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))){ // found ? or same chars
                s++; // move both pointers
                p++;
            } else if (p < pattern.length() && pattern.charAt(p) == '*') { // found *
                astroIdx = p; // save astroid index in pattern
                match = s; // save current index of string
                p++; // only move pattern pointer forward
            } else if (astroIdx != -1){ // try to find last astroid
                p = astroIdx + 1; // move to * one char behind astroid
                match++; // move current index of string
                s = match;
            } else return false; // 1) not ?, not same char, 2) not *, 3) don't match
        }
        // check remaining characters in pattern, can only be astroid
        while (p < pattern.length() && pattern.charAt(p) == '*') p++;
        return p == pattern.length(); // no remaining
    }
}


text:
#include <cassert>
#include <iostream>

#include "Utils.hpp"
#include "Log.hpp"
#include "Context.hpp"

#include "syntax/Syntax.hpp"

#include "options/OptionBase.hpp"
#include "options/OptionCommand.hpp"
#include "options/OptionParam.hpp"
#include "options/OptionOperand.hpp"
#include "options/OptionText.hpp"

#include "Grammar.hpp"

namespace Train
{

Grammar::Grammar(std::shared_ptr<Syntax const> syntax)
: m_syntax(syntax)
{ }

Grammar::~Grammar()
{ }

void Grammar::build(std::shared_ptr<OptionCommand> command)
{
	assert(command);

	m_command = command;

	for (auto &option : command->children())
		option->dispatch(shared_from_this());
}

void Grammar::add(std::shared_ptr<OptionCommand> command)
{
	assert(command);

	auto grammar = std::make_shared<Grammar>(m_syntax);
	grammar->build(command);

	m_commands.push_back(grammar);
}

void Grammar::add(std::shared_ptr<OptionParam> param)
{
	assert(param);

	m_params.push_back(param);
}

void Grammar::add(std::shared_ptr<OptionOperand> operand)
{
	assert(operand);

	m_operands.push_back(operand);
}

void Grammar::add(std::shared_ptr<OptionText>)
{ }

size_t Grammar::parse(const std::vector<std::string> &args)
{
	assert(m_command);
	assert(!args.empty());

	m_context = std::make_shared<Context>(args);

	parse();

	return m_context->position();
}

bool Grammar::parse()
{
	if (m_context->end())
		return false;

	if (!parseName())
		return false;

	if (!parseOptions())
		return false;

	parseCommands();

	if (!m_context->end()) {
		m_command->dumpScreenUnknownArg(m_context->current());
		m_context->finilize();
		return false;
	}

	return true;
}

bool Grammar::parseName()
{
	if (m_context->end())
		return false;

	auto name = m_syntax->command(m_context->current());

	if (!Utils::found(name, m_command->names()))
		return false;

	if (m_command->type().greedy()) {
		do {
			if (name.empty())
				name = m_context->current();

			if (m_command->parse(name)) {
				if (m_command->finilizes())
				{
					m_context->finilize();
					return true;
				}

				m_context->next();
			} else {
				return m_command->handleMismatchedTypes();
			}

			name.clear();
		} while(!m_context->end());
		return true;
	}

	if (m_command->parse(name)) {
		if (m_command->finilizes())
		{
			m_context->finilize();
			return true;
		}

		m_context->next();
		return true;
	} else {
		return false;
	}

	return true;
}

bool Grammar::parseOptions()
{
	for (; !m_context->end(); m_context->next()) {
		if (parseParams())
			continue;

		if (parseOperands())
			continue;

		break;
	}

	if (!m_command->handleMissingRequired())
		return true;

	m_context->finilize();
	return false;
}

bool Grammar::parseParams()
{
	for (; !m_context->end(); m_context->next()) {
		if (parseSingleParams())
			continue;

		if (parseSplittedParams())
			continue;

		for (auto &param : m_params)
		{
			if (param->handleMismatchedTypes())
			{
				m_context->finilize();
				return false;
			}
		}

		return false;
	}

	return false;
}

bool Grammar::parseSingleParams()
{
	if (m_context->end())
		return false;

	for (auto &param : m_params)
		if (parseSingleParam(param))
			return true;

	return false;
}

bool Grammar::parseSingleParam(std::shared_ptr<OptionParam> param) {
	if (m_context->end())
		return false;

	std::string key;
	std::string val;
	tie(key, val) = m_syntax->keyval(m_context->current());

	if (!Utils::found(key, param->names()))
		return false;

	if (param->type().greedy()) {
		if (val.empty()) {
			if (m_context->last()) {
				if (param->defaults().empty()) {
					param->dumpMissingValueScreen(key);
					m_context->finilize();
					return true;
				} else {
					val = param->defaults();
				}
			} else {
				m_context->next();
				val = m_context->current();
			}
		}

		do {
			if (val.empty())
				val = m_context->current();

			if (param->parse(key, val)) {
				if (param->finilizes())
					m_context->finilize();
				m_context->next();
			} else {
				return false;
			}

			val.clear();

		} while (!m_context->end());

		return true;
	}

	if (!val.empty()) {
		if (param->parse(key, val))
		{
			if (param->finilizes())
				m_context->finilize();

			return true;
		}

		if (!param->placeholder().empty()) {
			param->handleMismatchedTypes();
			return false;
		}

		if (!param->placeholder().empty() && param->defaults().empty()) {
			if (m_context->last()) {
				param->dumpMissingValueScreen(key);
				m_context->finilize();
				return true;
			}

			if (param->parse(key, m_context->peek()))
			{
				m_context->next();
				if (param->finilizes())
					m_context->finilize();
				return true;
			}
		} else {
			return false;
		}

		return true;
	}

	if (param->placeholder().empty()) {
		if (param->parse(key, param->defaults()))
		{
			if (param->finilizes())
				m_context->finilize();

			return true;
		}

		return false;

	}

	if (param->defaults().empty()) {
		if (m_context->last()) {
			param->dumpMissingValueScreen(key);
			m_context->finilize();
			return true;
		}

		m_context->next();

		if (param->parse(key, m_context->current()))
		{
			if (param->finilizes())
				m_context->finilize();

			return true;
		}

		return false;

	}

	if (m_context->last()) {
		if (param->parse(key, param->defaults()))
		{
			if (param->finilizes())
				m_context->finilize();
			return true;
		}

		return false;
	}

	if (param->parse(key, m_context->peek())) {
		m_context->next();
		if (param->finilizes())
			m_context->finilize();
		return true;
	}

	if (param->parse(key, param->defaults()))
	{
		if (param->finilizes())
			m_context->finilize();
		return true;
	}

	return false;
}

bool Grammar::parseSplittedParams()
{
	if (m_context->end())
		return false;

	auto splitted = std::make_shared<Context>(m_syntax->split(m_context->current()));

	if (splitted->end())
		return false;

	while (!splitted->end()) {
		bool parsed = false;

		for (auto &param : m_params) {
			if (!parseSplittedParam(splitted, param))
				continue;

			parsed = true;
			break;
		}

		if (!parsed)
			return false;

		splitted->next();
	}

	return true;
}

bool Grammar::parseSplittedParam(
		std::shared_ptr<Context> splitted,
		std::shared_ptr<OptionParam> param)
{
	if (splitted->end())
		return false;

	std::string key;
	std::string val;
	tie(key, val) = m_syntax->keyval(splitted->current());

	if (!Utils::found(key, param->names()))
		return false;

	if (param->type().greedy()) {
		if (val.empty()) {
			if (splitted->last() && m_context->last()) {
				if (param->defaults().empty()) {
					param->dumpMissingValueScreen(key);
					m_context->finilize();
					return true;
				}

				val = param->defaults();

				if (param->parse(key, val)) {
					if (param->finilizes())
						m_context->finilize();
					splitted->next();
					return true;
				} else {
					return false;
				}
			}
		} else {
			val = splitted->current();
		}

		if (!splitted->last()) {
			splitted->next();
			val = splitted->current();

			do {
				if (val.empty())
					val = splitted->current();

				if (param->parse(key, val)) {
					if (param->finilizes())
						m_context->finilize();
					splitted->next();
				} else {
					return false;
				}

				val.clear();
			} while (!splitted->end());

		}

		if (!m_context->last()) {
			m_context->next();
			do {
				if (val.empty())
					val = m_context->current();

				if (param->parse(key, val)) {
					if (param->finilizes())
						m_context->finilize();
					m_context->next();
				} else {
					return false;
				}

				val.clear();

			} while (!m_context->end());
		}

		return true;
	}

	if (param->placeholder().empty()) {
		if (val.empty())
			val = param->defaults();

		if (param->parse(key, val)) {
			if (param->finilizes())
				m_context->finilize();

			return true;
		} else {
			return false;
		}

	} else {
		if (val.empty())
			return false;

		if (param->parse(key, val)) {
			if (param->finilizes())
				m_context->finilize();

			return true;
		} else {
			return false;
		}

		// if (param->parse(param->defaults(), val)) {
		// 	if (param->finilizes())
		// 		m_context->finilize();
        //
		// 	return true;
		// }

	}

	// if (!param->placeholder().empty() && param->defaults().empty()) {
		// return false;
	// }

	// if (val.empty())
	// 	val = param->defaults();
    //
	// if (val.empty()) {
	// 	param->dumpMissingValueScreen(key);
	// 	return false;
	// }
    //
	// if (param->parse(key, val)) {
	// 	if (param->finilizes())
	// 		m_context->finilize();
    //
	// 	return true;
	// }

	return false;
}

bool Grammar::parseOperands()
{
	if (m_context->end())
		return m_operands.empty();

	for (auto &operand : m_operands)
		if (parseOperand(operand))
			return true;

	for (auto &operand : m_operands) {
		if (operand->handleMismatchedTypes()) {
			m_context->finilize();
			return true;
		}
	}

	return false;
}

bool Grammar::parseOperand(std::shared_ptr<OptionOperand> operand)
{
	if (m_context->end())
		return false;

	if (operand->type().greedy()) {
		do {
			if (operand->parse(m_context->current()))
			{
				if (operand->finilizes())
				{
					m_context->finilize();
					return true;
				}

				m_context->next();
			} else {
				return false;
			}

		} while (!m_context->end());

		return true;
	}

	if (operand->type().multiple()) {
		if (operand->parse(m_context->current()))
		{
			if (operand->finilizes())
				m_context->finilize();

			return true;
		}

		return false;
	}

	if (!operand->parsed()) {
		if (operand->parse(m_context->current()))
		{
			if (operand->finilizes())
				m_context->finilize();
			return true;
		}
		return false;
	}

	return false;
}

void Grammar::parseCommands()
{
	if (m_context->end())
		return;

	for (auto &command : m_commands) {
		command->m_context = m_context;
		if (command->parse())
			return;
	}
}

} /* Train */


text:
1. __`AssemblyVersion`__ and __`AssemblyFileVersion`__ attributes are updated in these solutions:
    * __`Spect.Net.CodeDiscover.ProjectType`__
    * __`Spect.Net.VsPackage`__
 1. Version numbers use semantic versioning:
    * __Major version__: New features even with potential breaking changes
    * __Minor version__: New features while keeping compatibility with previous versions
    * __Build version__: Patches, hotfixes, minor corrections
    * __Revision number__: Cosmetic changes
1. VSIX manifest info (new version and other potential changes) updated in the source.extension.vsixmanifest files of these projects:
    * __`Spect.Net.CodeDiscover.ProjectType`__
    * __`Spect.Net.VsPackage`__
1. Check that all source files within the `Spect.Net.CodeDiscover.ProjectType` project's
`BuildSystem\DeployedBuildSystem` and `BuildSystem\Rules` folder are linked into the
`Spect.Net.VsPackage` project's `DeploymentResources` folder. The __Build Action__ property
of these items should be __Embedded Resource__.
1. The `CURRENT_CPS_VERSION` value in `SpectNetPackage.cs` (`Spect.Net.VsPackage project`) is updated
1. The `InstalledProductRegistration` attribute of `SpectNetPackage` class is updated
to the number used within the VSX manifest info.
1. The entire soution builds with the Release configuration (__Clean Solution__, __Rebuil Solution__)
1. All unit tests run successfully (no failed or ignored test cases)
1. You can uploade the new VSIX to the Visual Studio Marketplace.


text:
@interface Validator : NSObject
@property (nonatomic) NSRegularExpression * regex;
@property (nonatomic, copy) NSString * errorDescription;
+ (Validator *)validatorWithRule:(NSRegularExpression *)rule description:(NSString *)description;
@end

@implementation Validator

+ (Validator *)validatorWithRule:(NSRegularExpression *)rule description:(NSString *)description {
    Validator * v = [Validator new];
    v.regex = rule;
    v.errorDescription = description;
    return v;
}

- (BOOL)isEqual:(id)other {
    if (other == self)
        return YES;
    if (!other || ![other isKindOfClass:[self class]])
        return NO;
    return [self isEqualToValidator:other];
}

- (BOOL)isEqualToValidator:(Validator *)aValidator {
    if (self == aValidator)
        return YES;
    if (![(id)[self regex] isEqual:[aValidator regex]])
        return NO;
    return YES;
}
@end

@interface FormValidator()
@property (nonatomic) NSMutableArray * arrPatterns;
@property (nonatomic) NSMutableDictionary * patterns;
@end

@implementation FormValidator

- (id)initWithItems:(NSArray *)formItems {
    self = [super init];
    if (self) {
        self.patterns = [NSMutableDictionary new];
        self.arrPatterns = [NSMutableArray new];
        for (NSArray * section in formItems) {
            for (id <FormItemProtocol>formItem in section) {
                //skip readonly fields
                if ([formItem.type isEqualToString:FormItemTypeLabel] ||
                    [formItem.type isEqualToString:FormItemTypeAgree] ||
                    [formItem.type isEqualToString:FormItemTypeDescription] ||
                    [formItem.type isEqualToString:FormItemTypeNestedGroup])
                    continue;
                NSString * key = [formItem bindingKey];
                //specific regex
                NSString * pattern = [formItem validationPattern];
                [self addPattern:pattern forKey:key description:@"Input value have invalid format"];
                //max length
                if ([formItem.maxLength integerValue] > 0 &&
                    ([formItem.type isEqualToString:FormItemTypeText] || [formItem.type isEqualToString:FormItemTypeTextArea])) {
                    NSNumber * maxLength = formItem.maxLength;
                    NSString * maxLengthPattern = [NSString stringWithFormat:@"^.{0,%d}$", [maxLength integerValue]];
                    [self addPattern:maxLengthPattern forKey:key description:[NSString stringWithFormat:@"Max length for this field is %d", [maxLength integerValue]]];
                }
                //mandatory
                //by default all fields are mandatory

                if (!formItem.optional) {
                    if (key == nil) {
                        NSLog(@"sd");
                    }

                    NSString * notEmptyPattern = @"^.{1,2049}$";
                    [self addPattern:notEmptyPattern forKey:key description:@"The field is mandatory"];
                }
            }
        }
    }
    return self;
}

- (void)addPattern:(NSString *)pattern forKey:(NSString *)key description:(NSString *)description {
    NSError * error = nil;
    if (!pattern || pattern.length == 0)
        return;
    NSRegularExpression * regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    Validator * v = [Validator validatorWithRule:regex description:description];
    if (!error) {
        NSMutableArray * validators = [self.patterns objectForKey:key];
        if (!validators) {
            validators = [NSMutableArray array];
        }
        if (![validators containsObject:v])
            [validators addObject:v];
        [self.patterns setObject:validators forKey:key];
    } else {
        NSLog(@"can't create regex %@", error.localizedDescription);
    }
}

- (void)validateValue:(NSString *)value forKey:(NSString *)key result:(ValidationResultBlock)resultBlock {
    NSMutableArray * validators = [self.patterns objectForKey:key];
    if (!validators || validators.count == 0) {
        resultBlock(nil, YES);
        return;
    }
    for (Validator * validator in validators) {
        value = value ? value : @"";
        NSTextCheckingResult *match = [validator.regex firstMatchInString:value options:0 range:NSMakeRange(0, [value length])];
        BOOL success = match != nil;
        NSLog(@"validate <%@> which is <%@>, result: %@", key, value, success ? @"success" : @"fail");
        if (!success) {
            resultBlock(validator.errorDescription, success);
            return;
        }
    }
    resultBlock(nil, YES);
}

@end


text:
package madgik.exareme.master.engine.scheduler.sync;

import madgik.exareme.common.schema.QueryScript;
import madgik.exareme.master.engine.scheduler.AdpDBScheduler;
import madgik.exareme.master.engine.scheduler.AdpDBSchedulerInfo;
import madgik.exareme.master.engine.scheduler.QueryScriptStatus;

import java.rmi.RemoteException;

/**
 * @author herald
 */
public class AdpDBSchedulerSynchronized implements AdpDBScheduler {

    private final AdpDBScheduler scheduler;

    public AdpDBSchedulerSynchronized(AdpDBScheduler scheduler) {
        this.scheduler = scheduler;
    }

    public AdpDBSchedulerInfo getInfo() throws RemoteException {
        synchronized (scheduler) {
            return scheduler.getInfo();
        }
    }

    public QueryScriptStatus schedule(String query, String database) throws RemoteException {
        synchronized (scheduler) {
            return scheduler.schedule(query, database);
        }
    }

    public QueryScriptStatus schedule(QueryScript query, String database) throws RemoteException {
        synchronized (scheduler) {
            return scheduler.schedule(query, database);
        }
    }

    public void stopScheduler() throws RemoteException {
        synchronized (scheduler) {
            scheduler.stopScheduler();
        }
    }
}


text:
#ifndef _USB_RDL_H
#define _USB_RDL_H

/* Control messages: bRequest values */
#define DL_GETSTATE	0	/* returns the rdl_state_t struct */
#define DL_CHECK_CRC	1	/* currently unused */
#define DL_GO		2	/* execute downloaded image */
#define DL_START	3	/* initialize dl state */
#define DL_REBOOT	4	/* reboot the device in 2 seconds */
#define DL_GETVER	5	/* returns the bootrom_id_t struct */
#define DL_GO_PROTECTED	6	/* execute the downloaded code and set reset
				 * event to occur in 2 seconds.  It is the
				 * responsibility of the downloaded code to
				 * clear this event
				 */
#define DL_EXEC		7	/* jump to a supplied address */
#define DL_RESETCFG	8	/* To support single enum on dongle
				 * - Not used by bootloader
				 */
#define DL_DEFER_RESP_OK 9	/* Potentially defer the response to setup
				 * if resp unavailable
				 */

/* states */
#define DL_WAITING	0	/* waiting to rx first pkt */
#define DL_READY	1	/* hdr was good, waiting for more of the
				 * compressed image */
#define DL_BAD_HDR	2	/* hdr was corrupted */
#define DL_BAD_CRC	3	/* compressed image was corrupted */
#define DL_RUNNABLE	4	/* download was successful,waiting for go cmd */
#define DL_START_FAIL	5	/* failed to initialize correctly */
#define DL_NVRAM_TOOBIG	6	/* host specified nvram data exceeds DL_NVRAM
				 * value */
#define DL_IMAGE_TOOBIG	7	/* download image too big (exceeds DATA_START
				 *  for rdl) */

struct rdl_state_le {
	__le32 state;
	__le32 bytes;
};

struct bootrom_id_le {
	__le32 chip;	/* Chip id */
	__le32 chiprev;	/* Chip rev */
	__le32 ramsize;	/* Size of  RAM */
	__le32 remapbase;	/* Current remap base address */
	__le32 boardtype;	/* Type of board */
	__le32 boardrev;	/* Board revision */
};

#define RDL_CHUNK	1500  /* size of each dl transfer */

#define TRX_OFFSETS_DLFWLEN_IDX	0
#define TRX_OFFSETS_JUMPTO_IDX	1
#define TRX_OFFSETS_NVM_LEN_IDX	2

#define TRX_OFFSETS_DLBASE_IDX  0

#endif  /* _USB_RDL_H */


text:
"""IP6 VRF Multi-instance Test Case HLD:

**NOTES:**
    - higher number of pg-ip6 interfaces causes problems => only 15 pg-ip6 \
    interfaces in 5 VRFs are tested
    - jumbo packets in configuration with 15 pg-ip6 interfaces leads to \
    problems too

**config 1**
    - add 15 pg-ip6 interfaces
    - configure 5 hosts per pg-ip6 interface
    - configure 4 VRFs
    - add 3 pg-ip6 interfaces per VRF

**test 1**
    - send IP6 packets between all pg-ip6 interfaces in all VRF groups

**verify 1**
    - check VRF data by parsing output of ip6_fib_dump API command
    - all packets received correctly in case of pg-ip6 interfaces in VRF
    - no packet received in case of pg-ip6 interfaces not in VRF

**config 2**
    - reset 2 VRFs

**test 2**
    - send IP6 packets between all pg-ip6 interfaces in all VRF groups

**verify 2**
    - check VRF data by parsing output of ip6_fib_dump API command
    - all packets received correctly in case of pg-ip6 interfaces in VRF
    - no packet received in case of pg-ip6 interfaces not in VRF

**config 3**
    - add 1 of reset VRFs and 1 new VRF

**test 3**
    - send IP6 packets between all pg-ip6 interfaces in all VRF groups

**verify 3**
    - check VRF data by parsing output of ip6_fib_dump API command
    - all packets received correctly in case of pg-ip6 interfaces in VRF
    - no packet received in case of pg-ip6 interfaces not in VRF

**config 4**
    - reset all VRFs (i.e. no VRF except VRF=0 created)

**test 4**
    - send IP6 packets between all pg-ip6 interfaces in all VRF groups

**verify 4**
    - check VRF data by parsing output of ip6_fib_dump API command
    - all packets received correctly in case of pg-ip6 interfaces in VRF
    - no packet received in case of pg-ip6 interfaces not in VRF
"""

import unittest
import random
import socket

from scapy.packet import Raw
from scapy.layers.l2 import Ether
from scapy.layers.inet6 import UDP, IPv6, ICMPv6ND_NS, ICMPv6ND_RA, \
    RouterAlert, IPv6ExtHdrHopByHop
from scapy.utils6 import in6_ismaddr, in6_isllsnmaddr, in6_getAddrType
from scapy.pton_ntop import inet_ntop
from scapy.data import IPV6_ADDR_UNICAST

from framework import VppTestCase, VppTestRunner
from util import ppp

# VRF status constants
VRF_NOT_CONFIGURED = 0
VRF_CONFIGURED = 1
VRF_RESET = 2

def is_ipv6_misc_ext(p):
    """ Is packet one of uninteresting IPv6 broadcasts (extended to filter out
    ICMPv6 Neighbor Discovery - Neighbor Advertisement packets too)? """
    if p.haslayer(ICMPv6ND_RA):
        if in6_ismaddr(p[IPv6].dst):
            return True
    if p.haslayer(ICMPv6ND_NS):
        if in6_isllsnmaddr(p[IPv6].dst):
            return True
    if p.haslayer(IPv6ExtHdrHopByHop):
        for o in p[IPv6ExtHdrHopByHop].options:
            if isinstance(o, RouterAlert):
                return True
    return False

class TestIP6VrfMultiInst(VppTestCase):
    """ IP6 VRF  Multi-instance Test Case """

    @classmethod
    def setUpClass(cls):
        """
        Perform standard class setup (defined by class method setUpClass in
        class VppTestCase) before running the test case, set test case related
        variables and configure VPP.
        """
        super(TestIP6VrfMultiInst, cls).setUpClass()

        # Test variables
        cls.hosts_per_pg = 5
        cls.nr_of_vrfs = 5
        cls.pg_ifs_per_vrf = 3

        try:
            # Create pg interfaces
            cls.create_pg_interfaces(
                range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf))

            # Packet flows mapping pg0 -> pg1, pg2 etc.
            cls.flows = dict()
            for i in range(len(cls.pg_interfaces)):
                multiplicand = i / cls.pg_ifs_per_vrf
                pg_list = [
                    cls.pg_interfaces[multiplicand * cls.pg_ifs_per_vrf + j]
                    for j in range(cls.pg_ifs_per_vrf)
                    if (multiplicand * cls.pg_ifs_per_vrf + j) != i]
                cls.flows[cls.pg_interfaces[i]] = pg_list

            # Packet sizes - jumbo packet (9018 bytes) skipped
            cls.pg_if_packet_sizes = [64, 512, 1518]

            # Set up all interfaces
            for pg_if in cls.pg_interfaces:
                pg_if.admin_up()
                pg_if.generate_remote_hosts(cls.hosts_per_pg)

            # Create list of VRFs
            cls.vrf_list = list()

            # Create list of reset VRFs
            cls.vrf_reset_list = list()

            # Create list of pg_interfaces in VRFs
            cls.pg_in_vrf = list()

            # Create list of pg_interfaces not in BDs
            cls.pg_not_in_vrf = [pg_if for pg_if in cls.pg_interfaces]

            # Create mapping of pg_interfaces to VRF IDs
            cls.pg_if_by_vrf_id = dict()
            for i in range(cls.nr_of_vrfs):
                vrf_id = i + 1
                pg_list = [
                    cls.pg_interfaces[i * cls.pg_ifs_per_vrf + j]
                    for j in range(cls.pg_ifs_per_vrf)]
                cls.pg_if_by_vrf_id[vrf_id] = pg_list

        except Exception:
            super(TestIP6VrfMultiInst, cls).tearDownClass()
            raise

    def setUp(self):
        """
        Clear trace and packet infos before running each test.
        """
        super(TestIP6VrfMultiInst, self).setUp()
        self.reset_packet_infos()

    def tearDown(self):
        """
        Show various debug prints after each test.
        """
        super(TestIP6VrfMultiInst, self).tearDown()
        if not self.vpp_dead:
            self.logger.info(self.vapi.ppcli("show ip6 fib"))
            self.logger.info(self.vapi.ppcli("show ip6 neighbors"))

    def create_vrf_and_assign_interfaces(self, count, start=1):
        """
        Create required number of FIB tables / VRFs, put 3 l2-pg interfaces
        to every FIB table / VRF.

        :param int count: Number of FIB tables / VRFs to be created.
        :param int start: Starting number of the FIB table / VRF ID. \
        (Default value = 1)
        """
        for i in range(count):
            vrf_id = i + start
            pg_if = self.pg_if_by_vrf_id[vrf_id][0]
            dest_addr = pg_if.remote_hosts[0].ip6n
            dest_addr_len = 64
            self.vapi.ip_add_del_route(
                dest_addr, dest_addr_len, pg_if.local_ip6n, is_ipv6=1,
                table_id=vrf_id, create_vrf_if_needed=1, is_multipath=1)
            self.logger.info("IPv6 VRF ID %d created" % vrf_id)
            if vrf_id not in self.vrf_list:
                self.vrf_list.append(vrf_id)
            if vrf_id in self.vrf_reset_list:
                self.vrf_reset_list.remove(vrf_id)
            for j in range(self.pg_ifs_per_vrf):
                pg_if = self.pg_if_by_vrf_id[vrf_id][j]
                pg_if.set_table_ip6(vrf_id)
                self.logger.info("pg-interface %s added to IPv6 VRF ID %d"
                                 % (pg_if.name, vrf_id))
                if pg_if not in self.pg_in_vrf:
                    self.pg_in_vrf.append(pg_if)
                if pg_if in self.pg_not_in_vrf:
                    self.pg_not_in_vrf.remove(pg_if)
                pg_if.config_ip6()
                pg_if.disable_ipv6_ra()
                pg_if.configure_ipv6_neighbors()
        self.logger.debug(self.vapi.ppcli("show ip6 fib"))
        self.logger.debug(self.vapi.ppcli("show ip6 neighbors"))

    def reset_vrf(self, vrf_id):
        """
        Reset required FIB table / VRF.

        :param int vrf_id: The FIB table / VRF ID to be reset.
        """
        # self.vapi.reset_vrf(vrf_id, is_ipv6=1)
        self.vapi.reset_fib(vrf_id, is_ipv6=1)
        if vrf_id in self.vrf_list:
            self.vrf_list.remove(vrf_id)
        if vrf_id not in self.vrf_reset_list:
            self.vrf_reset_list.append(vrf_id)
        for j in range(self.pg_ifs_per_vrf):
            pg_if = self.pg_if_by_vrf_id[vrf_id][j]
            pg_if.unconfig_ip6()
            if pg_if in self.pg_in_vrf:
                self.pg_in_vrf.remove(pg_if)
            if pg_if not in self.pg_not_in_vrf:
                self.pg_not_in_vrf.append(pg_if)
        self.logger.info("IPv6 VRF ID %d reset" % vrf_id)
        self.logger.debug(self.vapi.ppcli("show ip6 fib"))
        self.logger.debug(self.vapi.ppcli("show ip6 neighbors"))

    def create_stream(self, src_if, packet_sizes):
        """
        Create input packet stream for defined interface using hosts list.

        :param object src_if: Interface to create packet stream for.
        :param list packet_sizes: List of required packet sizes.
        :return: Stream of packets.
        """
        pkts = []
        src_hosts = src_if.remote_hosts
        for dst_if in self.flows[src_if]:
            for dst_host in dst_if.remote_hosts:
                src_host = random.choice(src_hosts)
                pkt_info = self.create_packet_info(src_if, dst_if)
                payload = self.info_to_payload(pkt_info)
                p = (Ether(dst=src_if.local_mac, src=src_host.mac) /
                     IPv6(src=src_host.ip6, dst=dst_host.ip6) /
                     UDP(sport=1234, dport=1234) /
                     Raw(payload))
                pkt_info.data = p.copy()
                size = random.choice(packet_sizes)
                self.extend_packet(p, size)
                pkts.append(p)
        self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
                          % (src_if.name, len(pkts)))
        return pkts

    def verify_capture(self, pg_if, capture):
        """
        Verify captured input packet stream for defined interface.

        :param object pg_if: Interface to verify captured packet stream for.
        :param list capture: Captured packet stream.
        """
        last_info = dict()
        for i in self.pg_interfaces:
            last_info[i.sw_if_index] = None
        dst_sw_if_index = pg_if.sw_if_index
        for packet in capture:
            try:
                ip = packet[IPv6]
                udp = packet[UDP]
                payload_info = self.payload_to_info(str(packet[Raw]))
                packet_index = payload_info.index
                self.assertEqual(payload_info.dst, dst_sw_if_index)
                self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
                                  (pg_if.name, payload_info.src, packet_index))
                next_info = self.get_next_packet_info_for_interface2(
                    payload_info.src, dst_sw_if_index,
                    last_info[payload_info.src])
                last_info[payload_info.src] = next_info
                self.assertIsNotNone(next_info)
                self.assertEqual(packet_index, next_info.index)
                saved_packet = next_info.data
                # Check standard fields
                self.assertEqual(ip.src, saved_packet[IPv6].src)
                self.assertEqual(ip.dst, saved_packet[IPv6].dst)
                self.assertEqual(udp.sport, saved_packet[UDP].sport)
                self.assertEqual(udp.dport, saved_packet[UDP].dport)
            except:
                self.logger.error(ppp("Unexpected or invalid packet:", packet))
                raise
        for i in self.pg_interfaces:
            remaining_packet = self.get_next_packet_info_for_interface2(
                i, dst_sw_if_index, last_info[i.sw_if_index])
            self.assertIsNone(
                remaining_packet,
                "Port %u: Packet expected from source %u didn't arrive" %
                (dst_sw_if_index, i.sw_if_index))

    def verify_vrf(self, vrf_id):
        """
        Check if the FIB table / VRF ID is configured.

        :param int vrf_id: The FIB table / VRF ID to be verified.
        :return: 1 if the FIB table / VRF ID is configured, otherwise return 0.
        """
        ip6_fib_dump = self.vapi.ip6_fib_dump()
        vrf_exist = False
        vrf_count = 0
        for ip6_fib_details in ip6_fib_dump:
            if ip6_fib_details[2] == vrf_id:
                if not vrf_exist:
                    vrf_exist = True
                addr = inet_ntop(socket.AF_INET6, ip6_fib_details[4])
                addrtype = in6_getAddrType(addr)
                vrf_count += 1 if addrtype == IPV6_ADDR_UNICAST else 0
        if not vrf_exist and vrf_count == 0:
            self.logger.info("IPv6 VRF ID %d is not configured" % vrf_id)
            return VRF_NOT_CONFIGURED
        elif vrf_exist and vrf_count == 0:
            self.logger.info("IPv6 VRF ID %d has been reset" % vrf_id)
            return VRF_RESET
        else:
            self.logger.info("IPv6 VRF ID %d is configured" % vrf_id)
            return VRF_CONFIGURED

    def run_verify_test(self):
        """
        Create packet streams for all configured l2-pg interfaces, send all \
        prepared packet streams and verify that:
            - all packets received correctly on all pg-l2 interfaces assigned
              to bridge domains
            - no packet received on all pg-l2 interfaces not assigned to bridge
              domains

        :raise RuntimeError: If no packet captured on l2-pg interface assigned
            to the bridge domain or if any packet is captured on l2-pg
            interface not assigned to the bridge domain.
        """
        # Test
        # Create incoming packet streams for packet-generator interfaces
        for pg_if in self.pg_interfaces:
            pkts = self.create_stream(pg_if, self.pg_if_packet_sizes)
            pg_if.add_stream(pkts)

        # Enable packet capture and start packet sending
        self.pg_enable_capture(self.pg_interfaces)
        self.pg_start()

        # Verify
        # Verify outgoing packet streams per packet-generator interface
        for pg_if in self.pg_interfaces:
            if pg_if in self.pg_in_vrf:
                capture = pg_if.get_capture(remark="interface is in VRF")
                self.verify_capture(pg_if, capture)
            elif pg_if in self.pg_not_in_vrf:
                pg_if.assert_nothing_captured(remark="interface is not in VRF",
                                              filter_out_fn=is_ipv6_misc_ext)
                self.logger.debug("No capture for interface %s" % pg_if.name)
            else:
                raise Exception("Unknown interface: %s" % pg_if.name)

    def test_ip6_vrf_01(self):
        """ IP6 VRF  Multi-instance test 1 - create 4 VRFs
        """
        # Config 1
        # Create 4 VRFs
        self.create_vrf_and_assign_interfaces(4)

        # Verify 1
        for vrf_id in self.vrf_list:
            self.assertEqual(self.verify_vrf(vrf_id), VRF_CONFIGURED)

        # Test 1
        self.run_verify_test()

    def test_ip6_vrf_02(self):
        """ IP6 VRF  Multi-instance test 2 - reset 2 VRFs
        """
        # Config 2
        # Delete 2 VRFs
        self.reset_vrf(1)
        self.reset_vrf(2)

        # Verify 2
        for vrf_id in self.vrf_reset_list:
            self.assertEqual(self.verify_vrf(vrf_id), VRF_RESET)
        for vrf_id in self.vrf_list:
            self.assertEqual(self.verify_vrf(vrf_id), VRF_CONFIGURED)

        # Test 2
        self.run_verify_test()

        # Reset routes learned from ICMPv6 Neighbor Discovery
        for vrf_id in self.vrf_reset_list:
            self.reset_vrf(vrf_id)

    def test_ip6_vrf_03(self):
        """ IP6 VRF  Multi-instance 3 - add 2 VRFs
        """
        # Config 3
        # Add 1 of reset VRFs and 1 new VRF
        self.create_vrf_and_assign_interfaces(1)
        self.create_vrf_and_assign_interfaces(1, start=5)

        # Verify 3
        for vrf_id in self.vrf_reset_list:
            self.assertEqual(self.verify_vrf(vrf_id), VRF_RESET)
        for vrf_id in self.vrf_list:
            self.assertEqual(self.verify_vrf(vrf_id), VRF_CONFIGURED)

        # Test 3
        self.run_verify_test()

        # Reset routes learned from ICMPv6 Neighbor Discovery
        for vrf_id in self.vrf_reset_list:
            self.reset_vrf(vrf_id)

    def test_ip6_vrf_04(self):
        """ IP6 VRF  Multi-instance test 4 - reset 4 VRFs
        """
        # Config 4
        # Reset all VRFs (i.e. no VRF except VRF=0 created)
        for i in range(len(self.vrf_list)):
            self.reset_vrf(self.vrf_list[0])

        # Verify 4
        for vrf_id in self.vrf_reset_list:
            self.assertEqual(self.verify_vrf(vrf_id), VRF_RESET)
        for vrf_id in self.vrf_list:
            self.assertEqual(self.verify_vrf(vrf_id), VRF_CONFIGURED)

        # Test 4
        self.run_verify_test()

if __name__ == '__main__':
    unittest.main(testRunner=VppTestRunner)


text:
package attribute

// The code in here is pretty simple. It has a global lock that's held whenever doing anything.
// So this isn't great for high contention scenarios. The code also iterates through the dictionaries
// while holding the lock.
//
// This is all fine and dandy, since this code ends up being seldom used. Typically, this
// is called only when a gRPC stream is initiated, which is a pretty rare situation.
// And typically, there will be 1 dictionary for all of the mixer.

import (
	"sync"
)

type dictionary map[int32]string

type dictionaryEntry struct {
	// immutable dictionary
	dictionary dictionary

	// current use count
	useCount int
}

// dictionaries provides a thread safe interning solution for
// attribute dictionaries. This allows identical
// dictionaries to be shared within the mixer, which reduces
// memory consumption and improves processor cache efficiency.
type dictionaries struct {
	sync.Mutex
	entries []dictionaryEntry
}

// See if two dictionaries are identical
func compareDictionaries(d1 dictionary, d2 dictionary) bool {
	if len(d1) != len(d2) {
		return false
	}

	for k, v := range d1 {
		if d2[k] != v {
			return false
		}
	}

	return true
}

// Intern inserts a dictionary into the interning tables.
// If another equivalent dictionary is already in the tables, then that
// dictionary instance is returned. Otherwise, the input dictionary is
// returned.
//
// This function maintains a use count. When the caller is
// done with a dictionary, it should call the Release function to
// decrement the use count. When the use count of a dictionary drops to
// 0, it is removed from the interning tables such that it can be cleaned up
// by the GC.
//
// Callers must treat the returned map as immutable, otherwise bad bad things
// will happen.
//
// This call is thread-safe.
func (d *dictionaries) Intern(dict dictionary) dictionary {
	d.Lock()
	defer d.Unlock()

	for i := range d.entries {
		entry := &d.entries[i]
		if compareDictionaries(dict, entry.dictionary) {
			entry.useCount++
			return entry.dictionary
		}
	}

	d.entries = append(d.entries, dictionaryEntry{dict, 1})
	return dict
}

// Release decrements the use count of the given dictionary. If
// the use count drops to 0, the dictionary is removed from the
// interning tables such that it can be cleaned up by the GC.
//
// This call is thread-safe.
func (d *dictionaries) Release(dict dictionary) {
	d.Lock()
	defer d.Unlock()

	for i := range d.entries {
		entry := &d.entries[i]
		if compareDictionaries(dict, entry.dictionary) {

			// if use count drops to zero, remove from the list
			entry.useCount--
			if entry.useCount == 0 {
				d.entries = append(d.entries[:i], d.entries[i+1:]...)
			}
			break
		}
	}
}


text:
package com.sc.td.business.controller.scfuncindex;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sc.td.business.service.scfuncindex.ScFuncIndexService;
import com.sc.td.common.config.SystemConfig;
import com.sc.td.common.utils.StringUtils;
import com.sc.td.common.utils.image.Pic;

@Controller
@RequestMapping("/operate/scfuncindex")
public class ScFuncIndexController {

	@Autowired
	private ScFuncIndexService scFuncIndexService;

	@Autowired
	private SystemConfig systemConfig;

	/**
	 * 获取指标信息
	 *
	 * @param propertyName
	 * @return
	 */

	@RequestMapping(value = "/getIdxInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String getIdxInfo() {
		return scFuncIndexService.getIdxInfo();
	}

	/**
	 * 获得图标
	 *
	 * @param request
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/getIcon", method = { RequestMethod.POST, RequestMethod.GET })
	public void getIcon(HttpServletRequest request, HttpServletResponse response, String fileName)
			throws IOException {
		String path = request.getServletContext().getRealPath("/") + systemConfig.getUserfilesIconUrl();
		Pic pic = new Pic();
		BufferedImage img = pic.loadImageLocal(path + fileName);
		String suffixImg=null;
		// 将文件上传至服务器
		if (img != null && StringUtils.isNotBlank(fileName)) {
			suffixImg=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
			response.setContentType("image/"+suffixImg);
			OutputStream os = response.getOutputStream();
			ImageIO.write(img, suffixImg, os);
		}
	}
}


text:
				Quote
				Link


text:
import * as React from 'react';

export function grid1(GridComponent, items: Object[], mobileQuery = false) {
  let [ first, ...rest ] = items;

  return (

        {items.map((post, key) => <GridComponent style={{ width: mobileQuery ? '100vw' : '15vw', height: mobileQuery ? '56.25vw' : '15vw' }} key={key} {...post} />)}

  );
}

const styles = {
  root: {
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    userSelect: 'none',
    flexDirection: 'column',
    color: '#fff'
  },
  rss: {
    width: '100%',
    display: 'flex',
    justifyContent: 'flex-end',
    padding: '1em'
  },
  article: {
    display: 'flex',
    flex: '0 1 auto',
    justifyContent: 'center',
    flexWrap: 'wrap',
    alignItems: 'center',
    width: '100%',
    maxWidth: 1280
  },
  blogPost: {
    display: 'flex',
    height: 280,
    alignItems: 'flex-end',
    backgroundSize: 'cover',
    backgroundPosition: 'center'
  }
};


text:
{-# LANGUAGE CPP #-}

{- |
Module      : Language.Scheme.Compiler.Types
Copyright   : Justin Ethier
Licence     : MIT (see LICENSE in the distribution)

Maintainer  : github.com/justinethier
Stability   : experimental
Portability : portable

This module contains data types used by the compiler.
-}

module Language.Scheme.Compiler.Types
    (
    -- * Data types
      CompOpts (..)
    , CompLibOpts (..)
    , defaultCompileOptions
    , HaskAST (..)
    -- * Utility functions
    , ast2Str
    , asts2Str
    , createAstFunc
    , createAstCont
    , joinL
    , moduleRuntimeVar
    , showValAST
    -- * Headers appended to output file
    , header
    , headerComment
    , headerModule
    , headerImports
    )
where
import qualified Language.Scheme.Core as LSC (version)
import Language.Scheme.Types
import qualified Language.Scheme.Util (escapeBackslashes)
import qualified Data.Array
import qualified Data.ByteString as BS
import qualified Data.Complex as DC
import qualified Data.List
import qualified Data.Map
import qualified Data.Ratio as DR

-- |A type to store options passed to compile.
--  Eventually all of this might be able to be
--  integrated into a Compile monad.
data CompOpts = CompileOptions {
    coptsThisFunc :: String,
    -- ^Immediate name to use when creating a compiled function.
    --  Presumably there is other code that is expecting
    --  to call into it.

    coptsThisFuncUseValue :: Bool,
    -- ^Whether to include the /value/ parameter in the current function

    coptsThisFuncUseArgs :: Bool,
    -- ^Whether to include the /args/ parameter in the current function

    coptsNextFunc :: Maybe String
    -- ^The name to use for the next function after the current
    --  compiler recursion is finished. For example, after compiling
    --  a block of code, the control flow would be expected to go
    --  to this function.
    }

-- |The default compiler options
defaultCompileOptions :: String -> CompOpts
defaultCompileOptions thisFunc = CompileOptions thisFunc False False Nothing

-- |Options passed to the compiler library module
data CompLibOpts = CompileLibraryOptions {
    compBlock :: String -> Maybe String -> Env
              -> [HaskAST] -> [LispVal] -> IOThrowsError [HaskAST],
    compLisp :: Env -> String -> String -> Maybe String
              -> IOThrowsError [HaskAST]
    }

-- |Runtime reference to module data structure
moduleRuntimeVar :: String
moduleRuntimeVar = " modules "

-- |Create code for a function
createAstFunc
  :: CompOpts  -- ^ Compilation options
  -> [HaskAST] -- ^ Body of the function
  -> HaskAST -- ^ Complete function code
createAstFunc (CompileOptions thisFunc useVal useArgs _) funcBody = do
  let val = if useVal then "value" else "_"
      args = if useArgs then "(Just args)" else "_"
  AstFunction thisFunc (" env cont " ++ val ++ " " ++ args ++ " ") funcBody

-- |Create code for a continutation
createAstCont
  :: CompOpts -- ^ Compilation options
  -> String -- ^ Value to send to the continuation
  -> String -- ^ Extra leading indentation (or blank string if none)
  -> HaskAST -- ^ Generated code
createAstCont (CompileOptions _ _ _ (Just nextFunc)) var indentation = do
  AstValue $ indentation ++ "  " ++ nextFunc ++ " env cont " ++ var ++ " (Just [])"
createAstCont (CompileOptions _ _ _ Nothing) var indentation = do
  AstValue $ indentation ++ "  continueEval env cont " ++ var ++ " Nothing"

--  FUTURE: is this even necessary? Would just a string be good enough?

-- |A very basic type to store a Haskell AST.
data HaskAST = AstAssignM String HaskAST
  | AstFunction {astfName :: String,
--                 astfType :: String,
                 astfArgs :: String,
                 astfCode :: [HaskAST]
                }
 | AstValue String
 | AstRef String
 | AstContinuation {astcNext :: String,
                    astcArgs :: String
                   }

-- |Generate code based on the given Haskell AST
showValAST :: HaskAST -> String
showValAST (AstAssignM var val) = "  " ++ var ++ " <- " ++ show val
showValAST (AstFunction name args code) = do
  let typeSig = "\n" ++ name ++ " :: Env -> LispVal -> LispVal -> Maybe [LispVal] -> IOThrowsError LispVal "
  let fheader = "\n" ++ name ++ args ++ " = do "
  let fbody = unwords . map (\x -> '\n' : x ) $ map showValAST code
#ifdef UseDebug
  let appendArg arg = do
        if Data.List.isInfixOf arg args
           then " ++ \" \" ++ " ++ (show arg) ++
                " ++ \" [\" ++ (show " ++ arg ++ ")" ++
                " ++ \"] \""
           else ""
  let fdebug = "\n  _ <- liftIO $ (trace (\"" ++
               name ++ "\"" ++
               (appendArg "value") ++
               (appendArg "args") ++
               ") getCPUTime)"
  typeSig ++ fheader ++ fdebug ++ fbody
#else
  typeSig ++ fheader ++ fbody
#endif
showValAST (AstValue v) = v
showValAST (AstRef v) = v
showValAST (AstContinuation nextFunc args) =
    "  continueEval env (makeCPSWArgs env cont " ++
       nextFunc ++ " " ++ args ++ ") (Nil \"\") Nothing "

instance Show HaskAST where show = showValAST

-- |A utility function to join list members together
joinL
  :: forall a. [[a]] -- ^ Original list-of-lists
  -> [a] -- ^ Separator
  -> [a] -- ^ Joined list
joinL ls sep = Data.List.intercalate sep ls

-- |Convert abstract syntax tree to a string
ast2Str :: LispVal -> String
ast2Str (String s) = "String " ++ show s
ast2Str (Char c) = "Char " ++ show c
ast2Str (Atom a) = "Atom " ++ show a
ast2Str (Number n) = "Number (" ++ show n ++ ")"
ast2Str (Complex c) = "Complex $ (" ++ (show $ DC.realPart c) ++ ") :+ (" ++ (show $ DC.imagPart c) ++ ")"
ast2Str (Rational r) = "Rational $ (" ++ (show $ DR.numerator r) ++ ") % (" ++ (show $ DR.denominator r) ++ ")"
ast2Str (Float f) = "Float (" ++ show f ++ ")"
ast2Str (Bool True) = "Bool True"
ast2Str (Bool False) = "Bool False"
ast2Str (HashTable ht) = do
 let ls = Data.Map.toList ht
     conv (a, b) = "(" ++ ast2Str a ++ "," ++ ast2Str b ++ ")"
 "HashTable $ Data.Map.fromList $ [" ++ joinL (map conv ls) "," ++ "]"
ast2Str (Vector v) = do
  let ls = Data.Array.elems v
      size = (length ls) - 1
  "Vector (listArray (0, " ++ show size ++ ")" ++ "[" ++ joinL (map ast2Str ls) "," ++ "])"
ast2Str (ByteVector bv) = do
  let ls = BS.unpack bv
  "ByteVector ( BS.pack " ++ "[" ++ joinL (map show ls) "," ++ "])"
ast2Str (List ls) = "List [" ++ joinL (map ast2Str ls) "," ++ "]"
ast2Str (DottedList ls l) =
  "DottedList [" ++ joinL (map ast2Str ls) "," ++ "] $ " ++ ast2Str l
ast2Str l = show l -- Error?

-- |Convert a list of abstract syntax trees to a list of strings
asts2Str :: [LispVal] -> String
asts2Str ls = do
    "[" ++ (joinL (map ast2Str ls) ",") ++ "]"

-- |Header comment used at the top of a Haskell program generated
--  by the compiler
headerComment:: [String]
headerComment = [
   "--"
 , "-- This file was automatically generated by the husk scheme compiler (huskc)"
 , "--"
 , "--  http://justinethier.github.io/husk-scheme "
 , "--  (c) 2010 Justin Ethier "
 , "--  Version " ++ LSC.version
 , "--"]

-- |Main module used in a compiled Haskell program
headerModule :: [String]
headerModule = ["module Main where "]

-- |Imports used for a compiled program
headerImports :: [String]
headerImports = [
   "Language.Scheme.Core "
 , "Language.Scheme.Numerical "
 , "Language.Scheme.Macro "
 , "Language.Scheme.Primitives "
 , "Language.Scheme.Types     -- Scheme data types "
 , "Language.Scheme.Variables -- Scheme variable operations "
 , "Control.Monad.Error "
 , "Data.Array "
 , " qualified Data.ByteString as BS "
 , "Data.Complex "
 , " qualified Data.Map "
 , "Data.Ratio "
 , "Data.Word "
 , "System.IO "
#ifdef UseDebug
 , "System.CPUTime "
 , "Debug.Trace "
#endif
 ]

-- |Block of code used in the header of a Haskell program
--  generated by the compiler.
header :: String -> Bool -> String -> [String]
header filepath useCompiledLibs langRev = do
  let env = if useCompiledLibs
            then "primitiveBindings"
            else case langRev of
                   "7" -> "r7rsEnv"
                   _ -> "r5rsEnv"
      initSrfi55 =
        case langRev of
          "7" -> []
          _ -> [ "exec55_3 env cont _ _ = do "
               , "  liftIO $ registerExtensions env getDataFileName' "
               , "  continueEval env (makeCPSWArgs env cont exec []) (Nil \"\") Nothing"]
  [ " "
    , " "
    , "-- |Get variable at runtime "
    , "getRTVar env var = do "
    , "  v <- getVar env var "
    , "  return $ case v of "
    , "    List _ -> Pointer var env "
    , "    DottedList _ _ -> Pointer var env "
    , "    String _ -> Pointer var env "
    , "    Vector _ -> Pointer var env "
    , "    ByteVector _ -> Pointer var env "
    , "    HashTable _ -> Pointer var env "
    , "    _ -> v "
    , " "
-- TODO:  this is just a temporary function until calls to continueEval can be purged from the compiler
    , "continueEval' env cont value = continueEval env cont value Nothing "
    , " "
    , "applyWrapper env cont (Nil _) (Just (a:as))  = do "
    , "  apply cont a as "
    , " "
    , "applyWrapper env cont value (Just (a:as))  = do "
    , "  apply cont a $ as ++ [value] "
    , " "
    , "getDataFileName' :: FilePath -> IO FilePath "
    , "getDataFileName' name = return $ \"" ++ (Language.Scheme.Util.escapeBackslashes filepath) ++ "\" ++ name "
    , " "]
    ++ initSrfi55 ++
    [ " "
    , "main :: IO () "
    , "main = do "
    , "  env <- " ++ env ++ " "
    , "  result <- (runIOThrows $ liftM show $ hsInit env (makeNullContinuation env) (Nil \"\") Nothing) "
    , "  case result of "
    , "    Just errMsg -> putStrLn errMsg "
    , "    _ -> return () "
    , " "
    , "hsInit env cont _ _ = do "
    , "  _ <- defineVar env \"" ++ moduleRuntimeVar ++ "\" $ HashTable $ Data.Map.fromList [] "
    , "  run env cont (Nil \"\") (Just [])"
    , " "]


text:
Angular + Typescript version of the AIFH vol1 project ( https://github.com/jeffheaton/aifh/tree/master/vol1 )

To test the code, clone the repo and run the following commands: (node, npm, angular, angular-cli needed)

    npm install

    ng serve --open


text:
<!doctype html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<html lang="">

<head>
  <meta charset="utf-8">

  <title>Tagcloud environment</title>

  <!-- build:css styles/main.css -->
  <link rel="stylesheet" href="styles/main.css">
  <!-- endbuild-->

  <!-- build:js bower_components/webcomponentsjs/webcomponents-lite.min.js -->
  <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
  <!-- endbuild -->

  <!-- will be replaced with elements/elements.vulcanized.html -->
  <link rel="import" href="elements/elements.html">
  <!-- endreplace-->

</head>
<body unresolved class="fullbleed layout vertical">

  <my-tagcloud-environment></my-tagcloud-environment>

</body>

</html>


text:
C++ library for Google Genomics
===============================

This directory contains the C++ code for this R package. Almost all the code here is to bind into
the gRPC C++ stubs for Google Genomics API.

Code Organization
-----------------

google/
  This directory contains the protocol buffer files for Google Genomics and dependencies. They were
  copied as-is from the `googleapis repo <https://github.com/googleapis/googleapis>`_ with the same
  directory structure. If you are updating the protocol buffer files, please only copy the files
  needed by the genomics API as otherwise it increases the package compilation time. If there are
  new methods, then the corresponding client-\*.cc file will need to add that method, and the method
  will need to be registered in init.cc.

client-common.*
  These files contain utility functions, templated functions, and macros to interface any given
  C++ stub method with an R object that is either a JSON string or an RProtoBuf object. It also
  handles passing authentication to gRPC from the R package.

client-\*.cc
  These are Genomics API services that have a macro each for each service method. The macros will
  check if this is a paginated RPC or not, and handle accordingly.

init.*
  Package initialization and visible method registration. Any new C++ method to be made visible to R
  code (including new service methods) will need to be registered here.

rprotobuf.*
  Methods to wrap and unwrap RProtoBuf objects, and create a new RProtoBuf object using the
  descriptor pool of this shared library. RProtoBuf shared library that is loaded when the RProtoBuf
  package is loaded will not be able to search genomics protocol buffer names as each shared
  library has its own internal descriptor pool.


text:
from cloudmesh.shell.clusters import Clusters

clusterobj = Clusters()

# list clusters

# show a group of cluster
group = clusterobj.group("deef")


text:
package com.yahoo.athenz.zpe_policy_updater;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.yahoo.rdl.Timestamp;
import com.yahoo.athenz.auth.util.Crypto;
import com.yahoo.athenz.common.utils.SignUtils;
import com.yahoo.athenz.zts.Assertion;
import com.yahoo.athenz.zts.AssertionEffect;
import com.yahoo.athenz.zts.DomainMetrics;
import com.yahoo.athenz.zts.DomainSignedPolicyData;
import com.yahoo.athenz.zts.Policy;
import com.yahoo.athenz.zts.PolicyData;
import com.yahoo.athenz.zts.PublicKeyEntry;
import com.yahoo.athenz.zts.RoleToken;
import com.yahoo.athenz.zts.ServiceIdentity;
import com.yahoo.athenz.zts.ServiceIdentityList;
import com.yahoo.athenz.zts.SignedPolicyData;
import com.yahoo.athenz.zts.ZTSClientException;
import com.yahoo.athenz.zts.ZTSRDLGeneratedClient;

public class ZTSMock extends ZTSRDLGeneratedClient {
    private PrivateKey ztsPrivateKeyK0 = null;
    private PrivateKey ztsPrivateKeyK1 = null;
    private PrivateKey zmsPrivateKeyK0 = null;
    private String keyId = "0";

    public ZTSMock() throws IOException {
        super("http://localhost:10080");
        loadKeys();
    }

    private void loadKeys() throws IOException {
        Path path = Paths.get("./src/test/resources/zts_private_k0.pem");
        ztsPrivateKeyK0 = Crypto.loadPrivateKey(new String(Files.readAllBytes(path)));

        path = Paths.get("./src/test/resources/zts_private_k1.pem");
        ztsPrivateKeyK1 = Crypto.loadPrivateKey(new String(Files.readAllBytes(path)));

        path = Paths.get("./src/test/resources/zms_private_k0.pem");
        zmsPrivateKeyK0 = Crypto.loadPrivateKey(new String(Files.readAllBytes(path)));
    }

    void setPublicKeyId(String keyId) {
        this.keyId = keyId;
    }

    @Override
    public DomainSignedPolicyData getDomainSignedPolicyData(String domainName,
            String matchingTag, Map<String, List<String>> responseHeaders) {

        DomainSignedPolicyData result = null;
        if (!domainName.equals("sports") &&
            !domainName.equals("sys.auth") &&
            !domainName.equals("expiredDomain")) {
            return result;
        }

        SignedPolicyData signedPolicyData = new SignedPolicyData();

        Timestamp expires;
        if (domainName.equals("expiredDomain")) {
            expires = Timestamp.fromMillis(System.currentTimeMillis()
                - (1000L * 60));
        } else {
            expires = Timestamp.fromMillis(System.currentTimeMillis()
                + (1000L * 60 * 60 * 24 * 7));
        }
        signedPolicyData.setExpires(expires);

        Timestamp modified = Timestamp.fromMillis(System.currentTimeMillis());
        signedPolicyData.setModified(modified);

        String policyName = domainName + ":policy." + "admin";
        Policy policy = new Policy();
        policy.setName(policyName);

        Assertion assertion = new Assertion();
        assertion.setAction("*");
        assertion.setEffect(AssertionEffect.ALLOW);
        assertion.setResource("*");

        String roleName = domainName + ":role." + "admin";
        assertion.setRole(roleName);

        List<Assertion> assertList = new ArrayList<Assertion>();
        assertList.add(assertion);

        assertion = new Assertion();
        assertion.setAction("*");
        assertion.setEffect(AssertionEffect.DENY);
        assertion.setResource("*");

        roleName = domainName + ":role." + "non-admin";
        assertion.setRole(roleName);
        assertList.add(assertion);

        policy.setAssertions(assertList);

        List<Policy> listOfPolicies = new ArrayList<Policy>();
        listOfPolicies.add(policy);

        PolicyData policyData = new PolicyData();
        policyData.setPolicies(listOfPolicies);
        policyData.setDomain(domainName);

        signedPolicyData.setPolicyData(policyData);
        signedPolicyData.setZmsKeyId("0");
        signedPolicyData.setZmsSignature(Crypto.sign(SignUtils.asCanonicalString(policyData), zmsPrivateKeyK0));

        DomainSignedPolicyData domainSignedPolicyData = new DomainSignedPolicyData();
        domainSignedPolicyData.setSignedPolicyData(signedPolicyData);

        PrivateKey ztsKey = null;
        if ("0".equals(keyId)) {
            ztsKey = ztsPrivateKeyK0;
        } else if ("1".equals(keyId)) {
            ztsKey = ztsPrivateKeyK1;
        }

        String signature = Crypto.sign(SignUtils.asCanonicalString(signedPolicyData), ztsKey);
        domainSignedPolicyData.setKeyId(keyId);
        domainSignedPolicyData.setSignature(signature);

        return domainSignedPolicyData;
    }

    @Override
    public RoleToken getRoleToken(String domainName, String role,
            Integer minExpiryTime, Integer maxExpiryTime, String proxyForPrincipal) {
        return null;
    }

    @Override
    public ServiceIdentity getServiceIdentity(String domainName, String serviceName) {
        return null;
    }

    @Override
    public ServiceIdentityList getServiceIdentityList(String domainName) {
        return null;
    }

    @Override
    public PublicKeyEntry getPublicKeyEntry(String domainName, String serviceName,
            String keyId) {
        PublicKeyEntry keyEntry = null;
        if ("2".equals(keyId)) {
            keyEntry = new PublicKeyEntry();
            Path path = Paths.get("./src/test/resources/zts_public_k1.pem");
            keyEntry.setId(keyId);
            try {
                keyEntry.setKey(Crypto.ybase64(Files.readAllBytes(path)));
            } catch (IOException e) {
            }
        }
        if (keyEntry == null) {
            throw new ZTSClientException(404, "Unknown ZTS Public Key");
        } else {
            return keyEntry;
        }
    }

    @Override
    public DomainMetrics postDomainMetrics(String arg0, DomainMetrics arg1) {
        return null;
    }
}


text:
class Gprof2dot < Formula
  desc "Convert the output from many profilers into a Graphviz dot graph"
  homepage "https://github.com/jrfonseca/gprof2dot"
  url "https://files.pythonhosted.org/packages/9d/36/f977122502979f3dfb50704979c9ed70e6b620787942b089bf1af15f5aba/gprof2dot-2017.9.19.tar.gz"
  sha256 "cebc7aa2782fd813ead415ea1fae3409524343485eadc7fb60ef5bd1e810309e"
  revision 1
  head "https://github.com/jrfonseca/gprof2dot.git"

  bottle do
    cellar :any_skip_relocation
    sha256 "2b090e85c705d72b374cbcd0edebfcee857966b487e27438d74ca67710f31ed0" => :mojave
    sha256 "f638c54489227411236cc969200a20c49bf59caa19ace82ab81589ba857e353e" => :high_sierra
    sha256 "f638c54489227411236cc969200a20c49bf59caa19ace82ab81589ba857e353e" => :sierra
  end

  depends_on "graphviz"
  depends_on "python"

  def install
    xy = Language::Python.major_minor_version "python3"
    ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python#{xy}/site-packages"
    system "python3", *Language::Python.setup_install_args(libexec)

    bin.install Dir[libexec/"bin/*"]
    bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"])
  end

  test do
    (testpath/"gprof.output").write <<~EOS
      Flat profile:

      Each sample counts as 0.01 seconds.
       no time accumulated

        %   cumulative   self              self     total
       time   seconds   seconds    calls  Ts/call  Ts/call  name
        0.00      0.00     0.00        2     0.00     0.00  manager
        0.00      0.00     0.00        2     0.00     0.00  worker1
        0.00      0.00     0.00        2     0.00     0.00  worker2
        0.00      0.00     0.00        1     0.00     0.00  project1
        0.00      0.00     0.00        1     0.00     0.00  project2

       %         the percentage of the total running time of the
      time       program used by this function.

      cumulative a running sum of the number of seconds accounted
       seconds   for by this function and those listed above it.

       self      the number of seconds accounted for by this
      seconds    function alone.  This is the major sort for this
                 listing.

      calls      the number of times this function was invoked, if
                 this function is profiled, else blank.

       self      the average number of milliseconds spent in this
      ms/call    function per call, if this function is profiled,
             else blank.

       total     the average number of milliseconds spent in this
      ms/call    function and its descendents per call, if this
             function is profiled, else blank.

      name       the name of the function.  This is the minor sort
                 for this listing. The index shows the location of
             the function in the gprof listing. If the index is
             in parenthesis it shows where it would appear in
             the gprof listing if it were to be printed.

                   Call graph (explanation follows)

      granularity: each sample hit covers 2 byte(s) no time propagated

      index % time    self  children    called     name
                      0.00    0.00       1/2           project1 [4]
                      0.00    0.00       1/2           project2 [5]
      [1]      0.0    0.00    0.00       2         manager [1]
                      0.00    0.00       2/2           worker1 [2]
                      0.00    0.00       2/2           worker2 [3]
      -----------------------------------------------
                      0.00    0.00       2/2           manager [1]
      [2]      0.0    0.00    0.00       2         worker1 [2]
      -----------------------------------------------
                      0.00    0.00       2/2           manager [1]
      [3]      0.0    0.00    0.00       2         worker2 [3]
      -----------------------------------------------
                      0.00    0.00       1/1           main [12]
      [4]      0.0    0.00    0.00       1         project1 [4]
                      0.00    0.00       1/2           manager [1]
      -----------------------------------------------
                      0.00    0.00       1/1           main [12]
      [5]      0.0    0.00    0.00       1         project2 [5]
                      0.00    0.00       1/2           manager [1]
      -----------------------------------------------

       This table describes the call tree of the program, and was sorted by
       the total amount of time spent in each function and its children.

       Each entry in this table consists of several lines.  The line with the
       index number at the left hand margin lists the current function.
       The lines above it list the functions that called this function,
       and the lines below it list the functions this one called.
       This line lists:
           index    A unique number given to each element of the table.
              Index numbers are sorted numerically.
              The index number is printed next to every function name so
              it is easier to look up where the function in the table.

           % time    This is the percentage of the `total' time that was spent
              in this function and its children.  Note that due to
              different viewpoints, functions excluded by options, etc,
              these numbers will NOT add up to 100%.

           self    This is the total amount of time spent in this function.

           children    This is the total amount of time propagated into this
              function by its children.

           called    This is the number of times the function was called.
              If the function called itself recursively, the number
              only includes non-recursive calls, and is followed by
              a `+' and the number of recursive calls.

           name    The name of the current function.  The index number is
              printed after it.  If the function is a member of a
              cycle, the cycle number is printed between the
              function's name and the index number.

       For the function's parents, the fields have the following meanings:

           self    This is the amount of time that was propagated directly
              from the function into this parent.

           children    This is the amount of time that was propagated from
              the function's children into this parent.

           called    This is the number of times this parent called the
              function `/' the total number of times the function
              was called.  Recursive calls to the function are not
              included in the number after the `/'.

           name    This is the name of the parent.  The parent's index
              number is printed after it.  If the parent is a
              member of a cycle, the cycle number is printed between
              the name and the index number.

       If the parents of the function cannot be determined, the word
       `<spontaneous>' is printed in the `name' field, and all the other
       fields are blank.

       For the function's children, the fields have the following meanings:

           self    This is the amount of time that was propagated directly
              from the child into the function.

           children    This is the amount of time that was propagated from the
              child's children to the function.

           called    This is the number of times the function called
              this child `/' the total number of times the child
              was called.  Recursive calls by the child are not
              listed in the number after the `/'.

           name    This is the name of the child.  The child's index
              number is printed after it.  If the child is a
              member of a cycle, the cycle number is printed
              between the name and the index number.

       If there are any cycles (circles) in the call graph, there is an
       entry for the cycle-as-a-whole.  This entry shows who called the
       cycle (as parents) and the members of the cycle (as children.)
       The `+' recursive calls entry shows the number of function calls that
       were internal to the cycle, and the calls entry for each member shows,
       for that member, how many times it was called from other members of
       the cycle.

      Index by function name

         [1] manager                 [5] project2                [3] worker2
         [4] project1                [2] worker1
    EOS
    system bin/"gprof2dot", testpath/"gprof.output", "-o", testpath/"call_graph.dot"
    assert_predicate testpath/"call_graph.dot", :exist?
  end
end


text:
//
//  TableViewCellTypeC.m
//  2-23多类型cell
//
//  Created by wyman on 2017/2/23.
//  Copyright © 2017年 wyman. All rights reserved.
//

#import "TableViewCellTypeC.h"
#import "ModelTypeC.h"

@implementation TableViewCellTypeC

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

/**
 *  获取循环利用的cell
 */
+ (instancetype)reusedCellWithTable:(UITableView *)table {

    TableViewCellTypeC *cell = [table dequeueReusableCellWithIdentifier:@"C"];
    if (!cell) {
        cell = [[TableViewCellTypeC alloc] initWithStyle:0 reuseIdentifier:@"C"];
    }
    return cell;

}

/**
 *  给cell配置模型
 */
- (void)setModel:(NSObject *)model {

    ModelTypeC *modelC = (ModelTypeC *)model;
    self.textLabel.text = @"modelC类型的cell";

}

@end


text:
package org.broadinstitute.sting.utils.interval;

/**
 * set operators for combining lists of intervals
 */
public enum IntervalSetRule {
    /** Take the union of all intervals */
    UNION,
    /** Take the intersection of intervals (the subset that overlaps all intervals specified) */
    INTERSECTION;
}


text:
@font-face {
	font-family: 'sow-elegantline';
	src:url('font/elegantline.eot?map0iz');
	src:url('font/elegantline.eot?#iefixmap0iz') format('embedded-opentype'),
	url('font/elegantline.woff?map0iz') format('woff'),
	url('font/elegantline.ttf?map0iz') format('truetype');
	font-weight: normal;
	font-style: normal;
}

.sow-icon-elegantline {
	font-family: 'sow-elegantline';
	display: inline-block;
	speak: none;
	font-style: normal;
	font-weight: normal;
	font-variant: normal;
	text-transform: none;
	line-height: 1;

	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.sow-icon-elegantline[data-sow-icon]:before {
	content: attr(data-sow-icon);
}


text:
Use units and quantities with pandas.

Attaching physical units to your data seems important to most of us if we are
writing down calculations by hand or drawing graphs but as soon as we step into
the digital world of floats and doubles they don't seem to matter any more. The
[unitframe](http://www.github.com/daviskirk/unitframe) module is an attempt to
attach physical unit information to
[pandas](http://www.github.com/pydata/pandas) objects using
[pint](http://www.github.com/hgrecco/pint). In theory we would like to combine
the awesome numerical framework of
[pandas](http://www.github.com/pydata/pandas) with the nifty unit calculation
and parsing abilities of [pint](http://www.github.com/hgrecco/pint).

## Requirements

* [numpy](http://www.github.com/numpy/numpy)
* [pandas](http://www.github.com/pydata/pandas)
* [pint](http://www.github.com/hgrecco/pint)
* [pytest](http://pytest.org/) (only for testing)

## Installing

Because at the moment I am just using this for personal projects there is no
"nice" way of installing `unitframe` via setuptools or pip. Just copy the
`unitframe/unitframe.py` file to wherever you want it and import the objects
using:

```python
from unitframe import UnitFrame, UnitSeries
```

## Example

```python
from unitframe import UnitFrame, UnitSeries

uf = UnitFrame([[4.0,5.0],[1.2,1.0]],
               index=list('AB'),
               units=['m','kg'],
               columns=list('ab'))
```

Math with UnitFrames works along each column and works with scalars:
```python
uf_new = uf + 10
```

as well as with other UnitFrames if they are compatible:
```python
uf2 = UnitFrame([[100,200],[0,0]],
                index=list('AB'),
                units=['mm','kg'],
                columns=list('ab'))
uf_new = uf + uf2
```

the same goes for `UnitSeries` objects. These are `pandas.Series` objects with
a single attached unit:
```python
us = UnitSeries([5,6], index=list('AB'), unit='m')
uf_new = uf + uf2
```

## Tests

Testing requires [pytest](http://pytest.org/) to be installed. To run the tests

```sh
py.test tests
```

## TODO

* The unit registry `UREG` is hard coded into the module. If there is any way
  to use generic unit registries it would be nice. Some of the code relies on
  type checking for unit registry quantities so that using a different registry
  leads to type checking errors.
* Implement pickling... there seem to be many many problems with pickling
  metadata of subclassed pandas objects
* setuptools, pip and or conda stuff

## Contribute

As stated above I just threw this up here because I know other people have had
problems with getting physical units, conversions and quantities to work well
in a numerical framework like [numpy](http://www.github.com/numpy/numpy) or [pandas](http://www.github.com/pydata/pandas). If anyone has better Ideas
or ways of improving this (at best) modest solution I would be happy to help in
any way.


text:
from mldb import mldb, ResponseException

import unittest

class myTest(unittest.TestCase):

    def test_sequence(self):
        with self.assertRaisesRegex(ResponseException, "Executing builtin function exp: Can't convert value 'a' of type 'ASCII_STRING' to double") as re:
            query = "SELECT exp('a')"
            mldb.query(query)
        with self.assertRaisesRegex(ResponseException, "Binding builtin function sqrt: expected 1 argument, got 3") as re:
            query = "SELECT sqrt(1,2,3)"
            mldb.query(query)

mldb.run_tests()


text:
/**
 * @file menu.h
 * @brief Command-line Interface library header.
 * @authors Lukas Ferreira Machado (12/0127377)
 *
 * This file contains all the function signatures used in the menus
 * and in the user choices processing.
 */

#ifndef _MENU_H
#define _MENU_H

#include <stdio.h>
#include <stdint.h>
#include "class.hpp"

/**
 * @todo Brief
 * @todo Description
 */
double decoderVersion (uint16_t);

/**
 * @todo Brief
 * @todo Description
 */
void printConstantPool();

/**
 * @todo Brief
 * @todo Description
 */
void showConstantPool();

/**
 * @todo Brief
 * @todo Description
 */
void showInterfaces();

/**
 * @todo Brief
 * @todo Description
 */
void showFields();

/**
 * @todo Brief
 * @todo Description
 */
void showMethods();

/**
 * @todo Brief
 * @todo Description
 * @todo Parameters
 */
void showAttributes(Attribute*, int);

/**
 * @todo Brief
 * @todo Description
 * @todo Parameters
 */
void showAttribute(Attribute);

/**
 * @todo Brief
 * @todo Description
 * @todo Parameters
 */
void showCode(uint8_t*, int);

/**
 * @todo Brief
 * @todo Description
 * @todo Parameters
 */
void showExceptionTable(ExceptionTableEntry*, int);

/**
 * @brief Menu to specify .class file.
 *
 * @todo Description
 */
void chooseFile();

/**
 * @brief Shows the .class main menu.
 *
 * Shows the application main menu as CLI and gets the user option to do some
 * action. The available options are "Choose a .class file" and "Quit".
 */
void menu(char*);

/**
 * @brief Process the user's option received on the .class viewer menu.
 *
 * @todo Description
 */
void displayOption(int);

/**
 * @brief Gets the name of the file .class.
 *
 * @todo Description
 */
char* getNewName();

/**
 * @brief Put some definitions for Instructions
 * @todo Description
 */
void get_instr_def(int);

/**
 * @brief Clear the screen.
 *
 * @todo Description
 */
void clearScreen();

#endif //_MENU_H


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

/**
 * @fileoverview Class to encapsulate an editable field that blends into the
 * style of the page and never uses an iframe.  The field's height can be
 * controlled by CSS styles like min-height, max-height, and overflow.  This is
 * a goog.editor.Field, but overrides everything iframe related to use
 * contentEditable divs.  This is essentially a much lighter alternative to
 * goog.editor.SeamlessField, but only works in Firefox 3+, and only works
 * *well* in Firefox 12+ due to
 * https://bugzilla.mozilla.org/show_bug.cgi?id=669026.
 *
 * @author gboyer@google.com (Garrett Boyer)
 * @author jparent@google.com (Julie Parent)
 * @author nicksantos@google.com (Nick Santos)
 * @author ojan@google.com (Ojan Vafai)
 */

goog.provide('goog.editor.ContentEditableField');

goog.require('goog.asserts');
goog.require('goog.editor.Field');
goog.require('goog.log');

/**
 * This class encapsulates an editable field that is just a contentEditable
 * div.
 *
 * To see events fired by this object, please see the base class.
 *
 * @param {string} id An identifer for the field. This is used to find the
 *     field and the element associated with this field.
 * @param {Document=} opt_doc The document that the element with the given
 *     id can be found in.
 * @constructor
 * @extends {goog.editor.Field}
 */
goog.editor.ContentEditableField = function(id, opt_doc) {
  goog.editor.Field.call(this, id, opt_doc);
};
goog.inherits(goog.editor.ContentEditableField, goog.editor.Field);

/**
 * @override
 */
goog.editor.ContentEditableField.prototype.logger =
    goog.log.getLogger('goog.editor.ContentEditableField');

/** @override */
goog.editor.ContentEditableField.prototype.usesIframe = function() {
  // Never uses an iframe in any browser.
  return false;
};

// Overridden to improve dead code elimination only.
/** @override */
goog.editor.ContentEditableField.prototype.turnOnDesignModeGecko =
    goog.nullFunction;

/** @override */
goog.editor.ContentEditableField.prototype.installStyles = function() {
  goog.asserts.assert(!this.cssStyles, 'ContentEditableField does not support' +
      ' CSS styles; instead just write plain old CSS on the main page.');
};

/** @override */
goog.editor.ContentEditableField.prototype.makeEditableInternal = function(
    opt_iframeSrc) {
  var field = this.getOriginalElement();
  if (field) {
    this.setupFieldObject(field);
    // TODO(gboyer): Allow clients/plugins to override with 'plaintext-only'
    // for WebKit.
    field.contentEditable = true;

    this.injectContents(field.innerHTML, field);

    this.handleFieldLoad();
  }
};

/**
 * @override
 *
 * ContentEditableField does not make any changes to the DOM when it is made
 * editable other than setting contentEditable to true.
 */
goog.editor.ContentEditableField.prototype.restoreDom =
    goog.nullFunction;


text:
namespace ui {

NativeDisplayDelegateOzone::NativeDisplayDelegateOzone() {
}

NativeDisplayDelegateOzone::~NativeDisplayDelegateOzone() {
}

void NativeDisplayDelegateOzone::Initialize() {
  DisplaySnapshot_Params params;
  if (CreateSnapshotFromCommandLine(&params)) {
    DCHECK_NE(DISPLAY_CONNECTION_TYPE_NONE, params.type);
    displays_.push_back(make_scoped_ptr(new DisplaySnapshotProxy(params)));
  }
}

void NativeDisplayDelegateOzone::GrabServer() {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::UngrabServer() {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::TakeDisplayControl(
    const DisplayControlCallback& callback) {
  NOTIMPLEMENTED();
  callback.Run(false);
}

void NativeDisplayDelegateOzone::RelinquishDisplayControl(
    const DisplayControlCallback& callback) {
  NOTIMPLEMENTED();
  callback.Run(false);
}

void NativeDisplayDelegateOzone::SyncWithServer() {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::SetBackgroundColor(uint32_t color_argb) {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::ForceDPMSOn() {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::GetDisplays(
    const GetDisplaysCallback& callback) {
  std::vector<DisplaySnapshot*> displays;
  for (const auto& display : displays_)
    displays.push_back(display.get());
  callback.Run(displays);
}

void NativeDisplayDelegateOzone::AddMode(const ui::DisplaySnapshot& output,
                                         const ui::DisplayMode* mode) {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::Configure(const ui::DisplaySnapshot& output,
                                           const ui::DisplayMode* mode,
                                           const gfx::Point& origin,
                                           const ConfigureCallback& callback) {
  NOTIMPLEMENTED();
  callback.Run(true);
}

void NativeDisplayDelegateOzone::CreateFrameBuffer(const gfx::Size& size) {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::GetHDCPState(
    const ui::DisplaySnapshot& output,
    const GetHDCPStateCallback& callback) {
  NOTIMPLEMENTED();
  callback.Run(false, HDCP_STATE_UNDESIRED);
}

void NativeDisplayDelegateOzone::SetHDCPState(
    const ui::DisplaySnapshot& output,
    ui::HDCPState state,
    const SetHDCPStateCallback& callback) {
  NOTIMPLEMENTED();
  callback.Run(false);
}

std::vector<ui::ColorCalibrationProfile>
NativeDisplayDelegateOzone::GetAvailableColorCalibrationProfiles(
    const ui::DisplaySnapshot& output) {
  NOTIMPLEMENTED();
  return std::vector<ui::ColorCalibrationProfile>();
}

bool NativeDisplayDelegateOzone::SetColorCalibrationProfile(
    const ui::DisplaySnapshot& output,
    ui::ColorCalibrationProfile new_profile) {
  NOTIMPLEMENTED();
  return false;
}

bool NativeDisplayDelegateOzone::SetColorCorrection(
    const ui::DisplaySnapshot& output,
    const std::vector<GammaRampRGBEntry>& degamma_lut,
    const std::vector<GammaRampRGBEntry>& gamma_lut,
    const std::vector<float>& correction_matrix) {
  NOTIMPLEMENTED();
  return false;
}

void NativeDisplayDelegateOzone::AddObserver(NativeDisplayObserver* observer) {
  NOTIMPLEMENTED();
}

void NativeDisplayDelegateOzone::RemoveObserver(
    NativeDisplayObserver* observer) {
  NOTIMPLEMENTED();
}

}  // namespace ui


text:
<!DOCTYPE html>

    <title>Nature, Poem 15: The Bee | The Poems of Emily Dickinson: Series One | Emily Dickinson | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      The Poems of Emily Dickinson: Series One

      by Emily Dickinson

      Nature, Poem 15: The Bee

        Additional Information

            Year Published:
            1896

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Dickenson, E. (1896). The Poems of Emily Dickinson: Series One.Boston, MA: Roberts Brothers.

            Readability:

                Flesch–Kincaid Level:
                6.6

            Word Count:
            78

            Genre:
            Poetry

            Keywords:
            19th century literature, american literature, emily dickinson, poems, poetry, series 1

            ✎ Cite This

  Share
  |

Downloads

          Audio

            APA

            MLA

            Chicago

            Dickinson, E. (1896). Nature, Poem 15: The Bee. The Poems of Emily Dickinson: Series One (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/114/the-poems-of-emily-dickinson-series-one/2618/nature-poem-15-the-bee/

            Dickinson, Emily. "Nature, Poem 15: The Bee." The Poems of Emily Dickinson: Series One. Lit2Go Edition. 1896. Web. <http://etc.usf.edu/lit2go/114/the-poems-of-emily-dickinson-series-one/2618/nature-poem-15-the-bee/>. February 15, 2016.

            Emily Dickinson, "Nature, Poem 15: The Bee," The Poems of Emily Dickinson: Series One, Lit2Go Edition, (1896), accessed February 15, 2016, http://etc.usf.edu/lit2go/114/the-poems-of-emily-dickinson-series-one/2618/nature-poem-15-the-bee/.

Back

Next

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/the-poems-of-emily-dickinson-series-one-058-nature-poem-15-the-bee.2618.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/the-poems-of-emily-dickinson-series-one-058-nature-poem-15-the-bee.2618.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	Like trains of cars on tracks of plush

	I hear the level bee:

	A jar across the flowers goes,

	Their velvet masonry

	Withstands until the sweet assault

	Their chivalry consumes,

	While he, victorious, tilts away

	To vanquish other blooms.

	His feet are shod with gauze,

	His helmet is of gold;

	His breast, a single onyx

	With chrysoprase, inlaid.

	His labor is a chant,

	His idleness a tune;

	Oh, for a bee's experience

	Of clovers and of noon!

Back

Next

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/114/the-poems-of-emily-dickinson-series-one/2618/nature-poem-15-the-bee/.

Lit2Go: The Poems of Emily Dickinson: Series One

Nature, Poem 15: The Bee


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 39: 283 (1941)

#### Original name
Dothidea kalmiae Peck, 1873

### Remarks
null