text:
import codecs
import linecache
import os
import re
import tempfile
import threading
from ast import literal_eval
from contextlib import contextmanager
from itertools import chain, islice
from typing import (
    List, Union, Set, Optional, Dict, Any, Iterator, Type, NoReturn, Tuple
)

import jinja2
import jinja2.ext
import jinja2.nativetypes  # type: ignore
import jinja2.nodes
import jinja2.parser
import jinja2.sandbox

from dbt.utils import (
    get_dbt_macro_name, get_docs_macro_name, get_materialization_macro_name,
    deep_map
)

from dbt.clients._jinja_blocks import BlockIterator, BlockData, BlockTag
from dbt.contracts.graph.compiled import CompiledSchemaTestNode
from dbt.contracts.graph.parsed import ParsedSchemaTestNode
from dbt.exceptions import (
    InternalException, raise_compiler_error, CompilationException,
    invalid_materialization_argument, MacroReturn
)
from dbt.flags import MACRO_DEBUGGING
from dbt.logger import GLOBAL_LOGGER as logger  # noqa

def _linecache_inject(source, write):
    if write:
        # this is the only reliable way to accomplish this. Obviously, it's
        # really darn noisy and will fill your temporary directory
        tmp_file = tempfile.NamedTemporaryFile(
            prefix='dbt-macro-compiled-',
            suffix='.py',
            delete=False,
            mode='w+',
            encoding='utf-8',
        )
        tmp_file.write(source)
        filename = tmp_file.name
    else:
        # `codecs.encode` actually takes a `bytes` as the first argument if
        # the second argument is 'hex' - mypy does not know this.
        rnd = codecs.encode(os.urandom(12), 'hex')  # type: ignore
        filename = rnd.decode('ascii')

    # put ourselves in the cache
    cache_entry = (
        len(source),
        None,
        [line + '\n' for line in source.splitlines()],
        filename
    )
    # linecache does in fact have an attribute `cache`, thanks
    linecache.cache[filename] = cache_entry  # type: ignore
    return filename

class MacroFuzzParser(jinja2.parser.Parser):
    def parse_macro(self):
        node = jinja2.nodes.Macro(lineno=next(self.stream).lineno)

        # modified to fuzz macros defined in the same file. this way
        # dbt can understand the stack of macros being called.
        #  - @cmcarthur
        node.name = get_dbt_macro_name(
            self.parse_assign_target(name_only=True).name)

        self.parse_signature(node)
        node.body = self.parse_statements(('name:endmacro',),
                                          drop_needle=True)
        return node

class MacroFuzzEnvironment(jinja2.sandbox.SandboxedEnvironment):
    def _parse(self, source, name, filename):
        return MacroFuzzParser(self, source, name, filename).parse()

    def _compile(self, source, filename):
        """Override jinja's compilation to stash the rendered source inside
        the python linecache for debugging when the appropriate environment
        variable is set.

        If the value is 'write', also write the files to disk.
        WARNING: This can write a ton of data if you aren't careful.
        """
        if filename == '<template>' and MACRO_DEBUGGING:
            write = MACRO_DEBUGGING == 'write'
            filename = _linecache_inject(source, write)

        return super()._compile(source, filename)  # type: ignore

class NativeSandboxEnvironment(MacroFuzzEnvironment):
    code_generator_class = jinja2.nativetypes.NativeCodeGenerator

class TextMarker(str):
    """A special native-env marker that indicates that a value is text and is
    not to be evaluated. Use this to prevent your numbery-strings from becoming
    numbers!
    """

def quoted_native_concat(nodes):
    """This is almost native_concat from the NativeTemplate, except in the
    special case of a single argument that is a quoted string and returns a
    string, the quotes are re-inserted.
    """
    head = list(islice(nodes, 2))

    if not head:
        return None

    if len(head) == 1:
        raw = head[0]
        if isinstance(raw, TextMarker):
            return str(raw)
    else:
        raw = "".join([str(v) for v in chain(head, nodes)])

    try:
        result = literal_eval(raw)
    except (ValueError, SyntaxError, MemoryError):
        return raw

    return result

class NativeSandboxTemplate(jinja2.nativetypes.NativeTemplate):  # mypy: ignore
    environment_class = NativeSandboxEnvironment

    def render(self, *args, **kwargs):
        """Render the template to produce a native Python type. If the
        result is a single node, its value is returned. Otherwise, the
        nodes are concatenated as strings. If the result can be parsed
        with :func:`ast.literal_eval`, the parsed value is returned.
        Otherwise, the string is returned.
        """
        vars = dict(*args, **kwargs)

        try:
            return quoted_native_concat(
                self.root_render_func(self.new_context(vars))
            )
        except Exception:
            return self.environment.handle_exception()

NativeSandboxEnvironment.template_class = NativeSandboxTemplate  # type: ignore

class TemplateCache:
    def __init__(self):
        self.file_cache: Dict[str, jinja2.Template] = {}

    def get_node_template(self, node) -> jinja2.Template:
        key = node.macro_sql

        if key in self.file_cache:
            return self.file_cache[key]

        template = get_template(
            string=node.macro_sql,
            ctx={},
            node=node,
        )

        self.file_cache[key] = template
        return template

    def clear(self):
        self.file_cache.clear()

template_cache = TemplateCache()

class BaseMacroGenerator:
    def __init__(self, context: Optional[Dict[str, Any]] = None) -> None:
        self.context: Optional[Dict[str, Any]] = context

    def get_template(self):
        raise NotImplementedError('get_template not implemented!')

    def get_name(self) -> str:
        raise NotImplementedError('get_name not implemented!')

    def get_macro(self):
        name = self.get_name()
        template = self.get_template()
        # make the module. previously we set both vars and local, but that's
        # redundant: They both end up in the same place
        module = template.make_module(vars=self.context, shared=False)
        macro = module.__dict__[get_dbt_macro_name(name)]
        module.__dict__.update(self.context)
        return macro

    @contextmanager
    def exception_handler(self) -> Iterator[None]:
        try:
            yield
        except (TypeError, jinja2.exceptions.TemplateRuntimeError) as e:
            raise_compiler_error(str(e))

    def call_macro(self, *args, **kwargs):
        if self.context is None:
            raise InternalException(
                'Context is still None in call_macro!'
            )
        assert self.context is not None

        macro = self.get_macro()

        with self.exception_handler():
            try:
                return macro(*args, **kwargs)
            except MacroReturn as e:
                return e.value

class MacroStack(threading.local):
    def __init__(self):
        super().__init__()
        self.call_stack = []

    @property
    def depth(self) -> int:
        return len(self.call_stack)

    def push(self, name):
        self.call_stack.append(name)

    def pop(self, name):
        got = self.call_stack.pop()
        if got != name:
            raise InternalException(f'popped {got}, expected {name}')

class MacroGenerator(BaseMacroGenerator):
    def __init__(
        self,
        macro,
        context: Optional[Dict[str, Any]] = None,
        node: Optional[Any] = None,
        stack: Optional[MacroStack] = None
    ) -> None:
        super().__init__(context)
        self.macro = macro
        self.node = node
        self.stack = stack

    def get_template(self):
        return template_cache.get_node_template(self.macro)

    def get_name(self) -> str:
        return self.macro.name

    @contextmanager
    def exception_handler(self) -> Iterator[None]:
        try:
            yield
        except (TypeError, jinja2.exceptions.TemplateRuntimeError) as e:
            raise_compiler_error(str(e), self.macro)
        except CompilationException as e:
            e.stack.append(self.macro)
            raise e

    @contextmanager
    def track_call(self):
        if self.stack is None or self.node is None:
            yield
        else:
            unique_id = self.macro.unique_id
            depth = self.stack.depth
            # only mark depth=0 as a dependency
            if depth == 0:
                self.node.depends_on.add_macro(unique_id)
            self.stack.push(unique_id)
            try:
                yield
            finally:
                self.stack.pop(unique_id)

    def __call__(self, *args, **kwargs):
        with self.track_call():
            return self.call_macro(*args, **kwargs)

class QueryStringGenerator(BaseMacroGenerator):
    def __init__(
        self, template_str: str, context: Dict[str, Any]
    ) -> None:
        super().__init__(context)
        self.template_str: str = template_str
        env = get_environment()
        self.template = env.from_string(
            self.template_str,
            globals=self.context,
        )

    def get_name(self) -> str:
        return 'query_comment_macro'

    def get_template(self):
        """Don't use the template cache, we don't have a node"""
        return self.template

    def __call__(self, connection_name: str, node) -> str:
        return str(self.call_macro(connection_name, node))

class MaterializationExtension(jinja2.ext.Extension):
    tags = ['materialization']

    def parse(self, parser):
        node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno)
        materialization_name = \
            parser.parse_assign_target(name_only=True).name

        adapter_name = 'default'
        node.args = []
        node.defaults = []

        while parser.stream.skip_if('comma'):
            target = parser.parse_assign_target(name_only=True)

            if target.name == 'default':
                pass

            elif target.name == 'adapter':
                parser.stream.expect('assign')
                value = parser.parse_expression()
                adapter_name = value.value

            else:
                invalid_materialization_argument(
                    materialization_name, target.name
                )

        node.name = get_materialization_macro_name(
            materialization_name, adapter_name
        )

        node.body = parser.parse_statements(('name:endmaterialization',),
                                            drop_needle=True)

        return node

class DocumentationExtension(jinja2.ext.Extension):
    tags = ['docs']

    def parse(self, parser):
        node = jinja2.nodes.Macro(lineno=next(parser.stream).lineno)
        docs_name = parser.parse_assign_target(name_only=True).name

        node.args = []
        node.defaults = []
        node.name = get_docs_macro_name(docs_name)
        node.body = parser.parse_statements(('name:enddocs',),
                                            drop_needle=True)
        return node

def _is_dunder_name(name):
    return name.startswith('__') and name.endswith('__')

def create_undefined(node=None):
    class Undefined(jinja2.Undefined):
        def __init__(self, hint=None, obj=None, name=None, exc=None):
            super().__init__(hint=hint, name=name)
            self.node = node
            self.name = name
            self.hint = hint
            # jinja uses these for safety, so we have to override them.
            # see https://github.com/pallets/jinja/blob/master/jinja2/sandbox.py#L332-L339 # noqa
            self.unsafe_callable = False
            self.alters_data = False

        def __getitem__(self, name):
            # Propagate the undefined value if a caller accesses this as if it
            # were a dictionary
            return self

        def __getattr__(self, name):
            if name == 'name' or _is_dunder_name(name):
                raise AttributeError(
                    "'{}' object has no attribute '{}'"
                    .format(type(self).__name__, name)
                )

            self.name = name

            return self.__class__(hint=self.hint, name=self.name)

        def __call__(self, *args, **kwargs):
            return self

        def __reduce__(self):
            raise_compiler_error(f'{self.name} is undefined', node=node)

    return Undefined

def get_environment(
    node=None,
    capture_macros: bool = False,
    native: bool = False,
) -> jinja2.Environment:
    args: Dict[str, List[Union[str, Type[jinja2.ext.Extension]]]] = {
        'extensions': ['jinja2.ext.do']
    }

    if capture_macros:
        args['undefined'] = create_undefined(node)

    args['extensions'].append(MaterializationExtension)
    args['extensions'].append(DocumentationExtension)

    env_cls: Type[jinja2.Environment]
    text_filter: Type
    if native:
        env_cls = NativeSandboxEnvironment
        text_filter = TextMarker
    else:
        env_cls = MacroFuzzEnvironment
        text_filter = str

    env = env_cls(**args)
    env.filters['as_text'] = text_filter

    return env

@contextmanager
def catch_jinja(node=None) -> Iterator[None]:
    try:
        yield
    except jinja2.exceptions.TemplateSyntaxError as e:
        e.translated = False
        raise CompilationException(str(e), node) from e
    except jinja2.exceptions.UndefinedError as e:
        raise CompilationException(str(e), node) from e
    except CompilationException as exc:
        exc.add_node(node)
        raise

def parse(string):
    with catch_jinja():
        return get_environment().parse(str(string))

def get_template(
    string: str,
    ctx: Dict[str, Any],
    node=None,
    capture_macros: bool = False,
    native: bool = False,
):
    with catch_jinja(node):
        env = get_environment(node, capture_macros, native=native)

        template_source = str(string)
        return env.from_string(template_source, globals=ctx)

def render_template(template, ctx: Dict[str, Any], node=None) -> str:
    with catch_jinja(node):
        return template.render(ctx)

def _requote_result(raw_value: str, rendered: str) -> str:
    double_quoted = raw_value.startswith('"') and raw_value.endswith('"')
    single_quoted = raw_value.startswith("'") and raw_value.endswith("'")
    if double_quoted:
        quote_char = '"'
    elif single_quoted:
        quote_char = "'"
    else:
        quote_char = ''
    return f'{quote_char}{rendered}{quote_char}'

# performance note: Local benmcharking (so take it with a big grain of salt!)
# on this indicates that it is is on average slightly slower than
# checking two separate patterns, but the standard deviation is smaller with
# one pattern. The time difference between the two was ~2 std deviations, which
# is small enough that I've just chosen the more readable option.
_HAS_RENDER_CHARS_PAT = re.compile(r'({[{%]|[}%]})')

def get_rendered(
    string: str,
    ctx: Dict[str, Any],
    node=None,
    capture_macros: bool = False,
    native: bool = False,
) -> str:
    # performance optimization: if there are no jinja control characters in the
    # string, we can just return the input. Fall back to jinja if the type is
    # not a string or if native rendering is enabled (so '1' -> 1, etc...)
    # If this is desirable in the native env as well, we could handle the
    # native=True case by passing the input string to ast.literal_eval, like
    # the native renderer does.
    if (
        not native and
        isinstance(string, str) and
        _HAS_RENDER_CHARS_PAT.search(string) is None
    ):
        return string
    template = get_template(
        string,
        ctx,
        node,
        capture_macros=capture_macros,
        native=native,
    )
    return render_template(template, ctx, node)

def undefined_error(msg) -> NoReturn:
    raise jinja2.exceptions.UndefinedError(msg)

def extract_toplevel_blocks(
    data: str,
    allowed_blocks: Optional[Set[str]] = None,
    collect_raw_data: bool = True,
) -> List[Union[BlockData, BlockTag]]:
    """Extract the top level blocks with matching block types from a jinja
    file, with some special handling for block nesting.

    :param data: The data to extract blocks from.
    :param allowed_blocks: The names of the blocks to extract from the file.
        They may not be nested within if/for blocks. If None, use the default
        values.
    :param collect_raw_data: If set, raw data between matched blocks will also
        be part of the results, as `BlockData` objects. They have a
        `block_type_name` field of `'__dbt_data'` and will never have a
        `block_name`.
    :return: A list of `BlockTag`s matching the allowed block types and (if
        `collect_raw_data` is `True`) `BlockData` objects.
    """
    return BlockIterator(data).lex_for_blocks(
        allowed_blocks=allowed_blocks,
        collect_raw_data=collect_raw_data
    )

SCHEMA_TEST_KWARGS_NAME = '_dbt_schema_test_kwargs'

def add_rendered_test_kwargs(
    context: Dict[str, Any],
    node: Union[ParsedSchemaTestNode, CompiledSchemaTestNode],
    capture_macros: bool = False,
) -> None:
    """Render each of the test kwargs in the given context using the native
    renderer, then insert that value into the given context as the special test
    keyword arguments member.
    """
    looks_like_func = r'^\s*(env_var|ref|var|source|doc)\s*\(.+\)\s*$'

    def _convert_function(
        value: Any, keypath: Tuple[Union[str, int], ...]
    ) -> Any:
        if isinstance(value, str):
            if keypath == ('column_name',):
                # special case: Don't render column names as native, make them
                # be strings
                return value

            if re.match(looks_like_func, value) is not None:
                # curly braces to make rendering happy
                value = f'{{{{ {value} }}}}'

            value = get_rendered(
                value, context, node, capture_macros=capture_macros,
                native=True
            )

        return value

    kwargs = deep_map(_convert_function, node.test_metadata.kwargs)
    context[SCHEMA_TEST_KWARGS_NAME] = kwargs


text:
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import messages
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login as auth_login ,logout as auth_logout

#myApp package
from accounts.forms import  RegisterForm, LoginForm

def register(request):
    '''注册视图'''
    template_var={}
    form = RegisterForm()
    if request.method=="POST":
        form=RegisterForm(request.POST.copy())
        if form.is_valid():
            username=form.cleaned_data["username"]
            email=form.cleaned_data["email"]
            password=form.cleaned_data["password"]
            user=User.objects.create_user(username,email,password)
            user.save()
            _login(request,username,password)#注册完毕 直接登陆
            return HttpResponseRedirect("/jizhang/first_login")
    template_var["form"]=form
    return render_to_response("accounts/register.html",template_var,context_instance=RequestContext(request))

def login(request):
    '''登陆视图'''
    template_var={}
    form = LoginForm()
    if request.method == 'POST':
        form=LoginForm(request.POST.copy())
        if form.is_valid():
            _login(request,form.cleaned_data["username"],form.cleaned_data["password"])
            return HttpResponseRedirect("/")
    template_var["form"]=form
    return render_to_response("accounts/login.html",template_var,context_instance=RequestContext(request))

def _login(request,username,password):
    '''登陆核心方法'''
    ret=False
    user=authenticate(username=username,password=password)
    if user is not None:
        if user.is_active:
            auth_login(request,user)
            ret=True
        else:
            messages.add_message(request, messages.INFO, (u'用户没有激活'))
    else:
        messages.add_message(request, messages.INFO, (u'用户不存在'))
    return ret

def logout(request):
	auth_logout(request)
	return render_to_response('accounts/logout.html',RequestContext(request,{'hello2you':'Thanks for your visit!'}))

redpajama_set_name: RedPajamaGithub


text:
RUSTC ?= rustc
RFLAGS ?= -g

dummy1 := $(shell mkdir bin 2> /dev/null)

all:
	$(RUSTC) $(RFLAGS) -o bin/algorithms --lib crate.rc

check:
	RUST_LOG=rustc=0,::rt::backtrace $(RUSTC) $(RFLAGS) -o bin/test-algorithms --test crate.rc
	 $(DEBUGGER) bin/test-algorithms

check1:
	$(RUSTC) $(RFLAGS) -o bin/test-algorithms --test crate.rc
	export RUST_LOG=test-algorithms::algorithms=3 && $(DEBUGGER) bin/test-algorithms test_algorithms

clean:
	rm -rf bin


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

<title>CREATE-EMPTY-LORENZ-CURVE</title>

I set up and label a plot named "Wealth Distribution" that

	DRAW-LORENZ-CURVE draws upon.

	Begin micro-behaviour

CREATE-EMPTY-LORENZ-CURVE

	Begin NetLogo code:

create-plot
  "550" "309" ; lower left corner
  "950" "709" ; upper right corner
  "Wealth Distribution" ; unique name (and label) for this plot
  "% of Population" ; X axis label
  "% of Wealth" ; Y axis label

	End NetLogo code

Variants

You may change the labels or location.

Related Micro-behaviours

	DRAW-LORENZ-CURVE uses this.

Source

Based on page 37 of [1].

History

This was implemented by Ken Kahn.

References

[1] Growing Artificial Societies by Joshua M. Epstein and Robert

	Axtell, Brookings Institute Press, The MIT Press, 1996.


text:
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.db.models import Q
from django.contrib.comments import signals
from django.contrib.comments.models import Comment
from django.contrib.comments.views.comments import CommentPostBadRequest
from django.utils.html import escape

from primer.utils import paginate
from primer.likes.models import Like

from forms import get_comment_form

MAX_COMMENTS_PER_PAGE = 50

def delete(request):
    """
    Delete a comment. We dont actually delete it, we just set is removed
    This view will only let the comment author delete it
    """
    if request.method == 'POST':
        try:
            comment = Comment.objects.get(pk = request.POST.get('comment_id'), user = request.user)
            comment.is_removed = True
            comment.save()
        except Comment.DoesNotExist:
            pass

    return {}

def like(request):
    """
    Likes a comment
    """
    pk = request.POST.get('comment')
    unlike = int(request.POST.get('unlike', 0))
    details = int(request.POST.get('details', 0))

    if details:
        view_template = 'comments/likes_details.html'
    else:
        view_template = 'comments/likes_short.html'

    if pk:
        try:
            comment = Comment.objects.get(pk = pk)
        except Comment.DoesNotExist:
            comment = None
            pass

        if comment:

            if unlike:
                Like.objects.remove_for_object(comment, request.user)
            else:
                Like.objects.create_for_object(comment, request.user)

            return {
                'comment' : comment,
                'view_template': view_template
            }

    return HttpResponse('')

def post(request, next = None, using = None):

    if request.method == 'POST':

        # Fill out some initial data fields from an authenticated user, if present
        data = request.POST.copy()
        comments_type = data.get('comments_type', 'comments')

        if request.user.is_authenticated():
            if not data.get('name', ''):
                data['name'] = request.user.get_full_name() or request.user.username
            if not data.get('email', ''):
                data['email'] = request.user.email

        # Look up the object we're trying to comment about
        ctype = data.get('content_type')
        object_pk = data.get('object_pk')
        if ctype is None or object_pk is None:
            return CommentPostBadRequest("Missing content_type or object_pk field.")
        try:
            model = models.get_model(*ctype.split(".", 1))
            target = model._default_manager.using(using).get(pk=object_pk)
        except TypeError:
            return CommentPostBadRequest(
                "Invalid content_type value: %r" % escape(ctype))
        except AttributeError:
            return CommentPostBadRequest(
                "The given content-type %r does not resolve to a valid model." % \
                    escape(ctype))
        except ObjectDoesNotExist:
            return CommentPostBadRequest(
                "No object matching content-type %r and object PK %r exists." % \
                    (escape(ctype), escape(object_pk)))
        except (ValueError, ValidationError), e:
            return CommentPostBadRequest(
                "Attempting go get content-type %r and object PK %r exists raised %s" % \
                    (escape(ctype), escape(object_pk), e.__class__.__name__))

        # Construct the comment form
        CommentForm = get_comment_form(data['formclass'])
        form = CommentForm(target, comments_type = comments_type, data=data)

        # Check security information
        if form.security_errors():
            return CommentPostBadRequest(
                "The comment form failed security verification: %s" % \
                    escape(str(form.security_errors())))

        # If there are errors or if we requested a preview show the comment
        if form.errors:
            # handle errors or preview
            pass

        # Otherwise create the comment
        comment = form.get_comment_object()
        comment.ip_address = request.META.get("REMOTE_ADDR", None)
        if request.user.is_authenticated():
            comment.user = request.user

        # Signal that the comment is about to be saved
        responses = signals.comment_will_be_posted.send(
            sender  = comment.__class__,
            comment = comment,
            request = request
        )

        for (receiver, response) in responses:
            if response == False:
                return CommentPostBadRequest(
                    "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

        # Save the comment and signal that it was saved
        comment.save()
        signals.comment_was_posted.send(
            sender  = comment.__class__,
            comment = comment,
            request = request
        )

        comments = Comment.objects.filter(pk = comment.pk)
        comments = comments.select_related('user')
        comments = comments.prefetch_related('children__user', 'likes')
        comment = comments[0]
        comment.set_comment_template_dir(comments_type)

    return {
        'comment' : comment,
        'view_template' : comment.template()
    }

def load(request):
    """
    Post Params
        content: the hash that is set in primer_comment_hashes which points to the content to lookup
        display: basically the template to render, either comments or wall for now
    """

    comments = None
    remaining_comments_count = 0
    view_template = 'comments/list.html'

    # get all of our get/post params
    content_types_hash = request.REQUEST.get('content')
    limit = int(request.REQUEST.get('limit', MAX_COMMENTS_PER_PAGE))
    comments_type = request.REQUEST.get('type', 'comments')
    is_reversed = int(request.REQUEST.get('isReversed', 0))
    object_pk = request.REQUEST.get('pk')
    current_page = int(request.REQUEST.get('page', 1))

    load_more = False

    # make sure our limit is within range
    if limit > MAX_COMMENTS_PER_PAGE:
        limit = MAX_COMMENTS_PER_PAGE

    # get our content types to lookup out of our session
    comments_setup = request.session['primer_comment_hashes'][content_types_hash]
    content_types = comments_setup['content_types']

    # we have an explicit object_pk, get the replies for this comment
    if object_pk:
        comments = Comment.objects.filter(parent_id = object_pk)
        limit = 15
        view_template = 'comments/list_replies.html'

    # we have contenttypes to lookup
    elif content_types:

        # start our comment expression
        expression = None

        # loop through the objects in our list, and build an expression for our query
        for obj in content_types:

            ctype = ContentType.objects.get_by_natural_key(
                obj['app_label'], obj['content_type'])

            # the expression for this loop iteration
            exp = Q(content_type=ctype, object_pk=obj['object_pk'], site__pk=settings.SITE_ID)

            # if no expression has been set
            if not expression:
                expression = exp
            else:
                # or it against our current expression
                expression = (expression | exp)

        # filter our comments with our expression
        comments = Comment.objects.filter(expression)

    if comments:
        comments = comments.select_related('user')
        comments = comments.prefetch_related('likes', 'children__user', 'children__likes')
        comments = comments.order_by('-created')

        # filter public and removed
        comments = comments.filter(is_public=True)

        if getattr(settings, 'COMMENTS_HIDE_REMOVED', True):
            comments = comments.filter(is_removed = False)

        # paginate our comments
        page = paginate(comments, limit)
        comments = list(page.object_list)

        if is_reversed or object_pk:
            comments.reverse()

        for comment in comments:
            comment.set_comment_template_dir(comments_type)

        if object_pk and current_page == 1:
            comments = comments[:-3]

        # check to see if we need a load more link
        if page.has_next():
            load_more = True
        elif current_page > page.paginator.num_pages:
            comments = []

        remaining_comments_count = page.paginator.count - page.end_index()

    return {
        'view_template' : view_template,
        'comments' : comments,
        'remaining_comments_count' : remaining_comments_count,
        'load_more' : load_more,
        'comments_type' : comments_type,
        'is_reversed' : is_reversed,
        'read_only' : comments_setup.get('read_only', False)
    }


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Ominify
{
    public static class OminifyExtensions
    {
        public static Action<Func<Func<IDictionary<string, object>, Task>, Func<IDictionary<string, object>, Task>>> UseOminifier(
            this Action<Func<Func<IDictionary<string, object>, Task>, Func<IDictionary<string, object>, Task>>> app, Action<OminifyOptions> withOptions)
        {
            var options = new OminifyOptions();
            withOptions.Invoke(options);
            return app.UseOminifier(options);
        }

        public static Action<Func<Func<IDictionary<string, object>, Task>, Func<IDictionary<string, object>, Task>>> UseOminifier(
            this Action<Func<Func<IDictionary<string, object>, Task>, Func<IDictionary<string, object>, Task>>> app, OminifyOptions options)
        {
            Ominifier.Initialize(options);
            app(next => new Ominifier(next).Invoke);
            return app;
        }

        public static T With<T>(this T package, string filePath) where T : OminifyPackage
        {
            package.AddFilePath(filePath);
            return package;
        }

        public static T With<T>(this T package, params string[] filePaths) where T : OminifyPackage
        {
            package.AddFilePaths(filePaths);
            return package;
        }
    }
}


text:
	// Added by ClassView
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Main.h : header file
//

/////////////////////////////////////////////////////////////////////////////
// CMain dialog

class CMain : public CDialog
{
// Construction
public:
	CUp upp;
	CUping uping;
	CDone donee;
	CDoing doing;

	CMain(CWnd* pParent = NULL);   // standard constructor

// Dialog Data
	//{{AFX_DATA(CMain)
	enum { IDD = IDD_MAIN_DIALOG };
		// NOTE: the ClassWizard will add data members here
	//}}AFX_DATA

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CMain)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:

	// Generated message map functions
	//{{AFX_MSG(CMain)
	afx_msg void OnBtnPerson();
	afx_msg void OnBtnCenter();
	afx_msg void OnBtnSousuo();
	afx_msg void OnBtnYixiazai();
	afx_msg void OnBtnXiazaizhong();
	afx_msg void OnBtnYishangchuan();
	afx_msg void OnBtnShangchuanzhong();
	virtual BOOL OnInitDialog();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_MAIN_H__6B20D035_ACF7_4E99_A824_466C65680C22__INCLUDED_)


text:
#include "XPathInit.hpp"

#include "FunctionLang.hpp"
#include "XObject.hpp"
#include "XUnknown.hpp"
#include "XPath.hpp"
#include "XPathEnvSupportDefault.hpp"
#include "XPathProcessorImpl.hpp"

XALAN_CPP_NAMESPACE_BEGIN

unsigned long   XPathInit::s_initCounter = 0;

XPathInit::XPathInit(MemoryManager& theManager) :
    m_platformSupportInit(theManager),
    m_domSupportInit(theManager)
{
    ++s_initCounter;

    if (s_initCounter == 1)
    {
        initialize(theManager);
    }
}

XPathInit*
XPathInit::create(MemoryManager&    theManager)
{
    XPathInit*  theResult;

    return XalanConstruct(theManager, theResult, theManager);
}

XPathInit::~XPathInit()
{
    --s_initCounter;

    if (s_initCounter == 0)
    {
        terminate();
    }
}

void
XPathInit::initialize(MemoryManager& theManager)
{
    FunctionLang::initialize(theManager);

    XObject::initialize(theManager);

    XUnknown::initialize(theManager);

    XPath::initialize(theManager);

    XPathEnvSupportDefault::initialize(theManager);
}

void
XPathInit::terminate()
{
    XPathEnvSupportDefault::terminate();

    XPath::terminate();

    XUnknown::terminate();

    XObject::terminate();

    FunctionLang::terminate();
}

XALAN_CPP_NAMESPACE_END


text:
require "rails_helper"

RSpec.describe PapersForReviewFinder, type: :finder do
  let(:reviewer) { FactoryGirl.create(:user, :reviewer) }

  subject(:finder) { described_class.new(reviewer) }

  describe "#reviewed" do
    context "with a mix of reviewed and unreviewed papers" do
      let(:reviewed_paper)   { FactoryGirl.create(:paper, :scrubbed) }
      let(:unreviewed_paper) { FactoryGirl.create(:paper, :scrubbed) }

      before { FactoryGirl.create(:review, paper: reviewed_paper, user: reviewer) }

      it { expect(finder.reviewed).to contain_exactly(reviewed_paper) }
    end

    context "when there are reviews made by others" do
      let(:other_reviewer) { FactoryGirl.create(:user,  :reviewer) }
      let(:reviewed_paper) { FactoryGirl.create(:paper, :scrubbed) }

      before { FactoryGirl.create(:review, paper: reviewed_paper, user: other_reviewer) }

      it { expect(finder.reviewed).to be_empty }
    end
  end

  describe "#unreviewed" do
    context "with a mix of reviewed and unreviewed papers" do
      let(:reviewed_paper)   { FactoryGirl.create(:paper, :scrubbed) }
      let(:unreviewed_paper) { FactoryGirl.create(:paper, :scrubbed) }

      before { FactoryGirl.create(:review, paper: reviewed_paper, user: reviewer) }

      it { expect(finder.unreviewed).to contain_exactly(unreviewed_paper) }
    end

    context "when there are unscrubbed papers" do
      let(:reviewed_paper) { FactoryGirl.create(:paper, :submitted) }

      it { expect(finder.reviewed).to be_empty }
    end
  end
end


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "C:/Users/Queen/Desktop/Algorithm/MyAlgorithmWithC-/03-Sorting-Advance/02-Merge-Sort-Advance/main.cpp" "C:/Users/Queen/Desktop/Algorithm/MyAlgorithmWithC-/03-Sorting-Advance/02-Merge-Sort-Advance/cmake-build-debug/CMakeFiles/02_Merge_Sort_Advance.dir/main.cpp.obj"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")


text:
package com.model;

/**
 * 審查委員
 */
public class Administrator extends A {
	String uid = "";
	String name = "";
	String email = "";
	String phone = "";
	String unit = "";
	String title = "";
	String remark = "";

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUnit() {
		return unit;
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public static void main(String[] args) {

	}

}


text:
package org.advanze.springframework.security.web.access.expression;

import org.springframework.expression.Expression;
import org.springframework.security.access.SecurityConfig;

public class WebExpressionSecurityConfig extends SecurityConfig {

    private final Expression authorizeExpression;

    public WebExpressionSecurityConfig(String attribute, Expression authorizeExpression) {
        super(attribute);
        this.authorizeExpression = authorizeExpression;
    }

    Expression getAuthorizeExpression() {
        return authorizeExpression;
    }

    @Override
    public String toString() {
        return "AuthorizeExpression: " + authorizeExpression.getExpressionString() + ", Attribute: " + super.toString();
    }
}


text:
<?php

class ehough_epilog_processor_UidProcessorTest extends ehough_epilog_TestCase
{
    /**
     * @covers ehough_epilog_processor_UidProcessor::__invoke
     */
    public function testProcessor()
    {
        $processor = new ehough_epilog_processor_UidProcessor();
        $record = call_user_func(array($processor, '__invoke'), $this->getRecord());
        $this->assertArrayHasKey('uid', $record['extra']);
    }
}


text:
package com.intellij.openapi.roots.ui.configuration.projectRoot;

import com.intellij.facet.Facet;
import com.intellij.ide.CommonActionsManager;
import com.intellij.ide.TreeExpander;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.*;
import com.intellij.openapi.ui.MasterDetailsComponent;
import com.intellij.openapi.ui.MasterDetailsState;
import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.navigation.Place;
import com.intellij.util.Icons;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.*;
import java.util.List;

public abstract class BaseStructureConfigurable extends MasterDetailsComponent implements SearchableConfigurable, Disposable, Place.Navigator {

  protected StructureConfigurableContext myContext;

  protected final Project myProject;

  protected boolean myUiDisposed = true;

  private boolean myWasTreeInitialized;

  protected boolean myAutoScrollEnabled = true;

  protected BaseStructureConfigurable(Project project, MasterDetailsState state) {
    super(state);
    myProject = project;
  }

  protected BaseStructureConfigurable(final Project project) {
    myProject = project;
  }

  public void init(StructureConfigurableContext context) {
    myContext = context;
    myContext.getDaemonAnalyzer().addListener(new ProjectStructureDaemonAnalyzerListener() {
      public void usagesCollected(@NotNull ProjectStructureElement containingElement) {
        updateTree();
      }

      public void problemsChanged(@NotNull ProjectStructureElement element) {
        updateTree();
      }

      public void allProblemsChanged() {
        updateTree();
      }

      private void updateTree() {
        if (!myTree.isShowing()) return;

        myTree.revalidate();
        myTree.repaint();
      }
    });
  }

  public ActionCallback navigateTo(@Nullable final Place place, final boolean requestFocus) {
    if (place == null) return new ActionCallback.Done();

    final Object object = place.getPath(TREE_OBJECT);
    final String byName = (String)place.getPath(TREE_NAME);

    if (object == null && byName == null) return new ActionCallback.Done();

    final MyNode node = object == null ? null : findNodeByObject(myRoot, object);
    final MyNode nodeByName = byName == null ? null : findNodeByName(myRoot, byName);

    if (node == null && nodeByName == null) return new ActionCallback.Done();

    final NamedConfigurable config;
    if (node != null) {
      config = node.getConfigurable();
    } else {
      config = nodeByName.getConfigurable();
    }

    final ActionCallback result = new ActionCallback().doWhenDone(new Runnable() {
      public void run() {
        myAutoScrollEnabled = true;
      }
    });

    myAutoScrollEnabled = false;
    myAutoScrollHandler.cancelAllRequests();
    final MyNode nodeToSelect = node != null ? node : nodeByName;
    selectNodeInTree(nodeToSelect, requestFocus).doWhenDone(new Runnable() {
      public void run() {
        setSelectedNode(nodeToSelect);
        Place.goFurther(config, place, requestFocus).notifyWhenDone(result);
      }
    });

    return result;
  }

  public void queryPlace(@NotNull final Place place) {
    if (myCurrentConfigurable != null) {
      place.putPath(TREE_OBJECT, myCurrentConfigurable.getEditableObject());
      Place.queryFurther(myCurrentConfigurable, place);
    }
  }

  protected void initTree() {
    if (myWasTreeInitialized) return;
    myWasTreeInitialized = true;

    super.initTree();
    new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
      public String convert(final TreePath treePath) {
        return ((MyNode)treePath.getLastPathComponent()).getDisplayName();
      }
    }, true);
    ToolTipManager.sharedInstance().registerComponent(myTree);
    myTree.setCellRenderer(new ColoredTreeCellRenderer(){
      public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        if (value instanceof MyNode) {
          final MyNode node = (MyNode)value;

          final NamedConfigurable namedConfigurable = node.getConfigurable();
          if (namedConfigurable == null) {
            return;
          }

          final String displayName = node.getDisplayName();
          final Icon icon = namedConfigurable.getIcon(expanded);
          setIcon(icon);
          setToolTipText(null);
          setFont(UIUtil.getTreeFont());

          SimpleTextAttributes textAttributes =
            selected && hasFocus ? SimpleTextAttributes.SELECTED_SIMPLE_CELL_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES;
          if (node.isDisplayInBold()) {
            textAttributes = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES;
          } else if (namedConfigurable instanceof ProjectStructureElementConfigurable) {
            final ProjectStructureElement projectStructureElement =
              ((ProjectStructureElementConfigurable)namedConfigurable).getProjectStructureElement();
            if (projectStructureElement != null) {
              final ProjectStructureDaemonAnalyzer daemonAnalyzer = myContext.getDaemonAnalyzer();
              final boolean unused = daemonAnalyzer.isUnused(projectStructureElement);
              final ProjectStructureProblemsHolderImpl problemsHolder = daemonAnalyzer.getProblemsHolder(projectStructureElement);
              if (problemsHolder == null) {
                daemonAnalyzer.queueUpdate(projectStructureElement, true, false);
              }
              final ProjectStructureProblemDescription.Severity level = problemsHolder != null ? problemsHolder.getSeverity() : null;
              final boolean invalid = level != null;
              if (unused || invalid) {
                Color fg = unused
                           ? UIUtil.getInactiveTextColor()
                           : selected && hasFocus ? UIUtil.getTreeSelectionForeground() : UIUtil.getTreeForeground();
                textAttributes = new SimpleTextAttributes(invalid ? SimpleTextAttributes.STYLE_WAVED : SimpleTextAttributes.STYLE_PLAIN, fg,
                                                          level == ProjectStructureProblemDescription.Severity.ERROR ? Color.RED : Color.GRAY);
                String text = problemsHolder != null ? problemsHolder.composeTooltipMessage() : "";
                if (unused) {
                  text += ProjectBundle.message("project.roots.tooltip.unused", displayName);
                }
                setToolTipText(text);
              }
            }
          }
          append(displayName, textAttributes);
        }
      }
    });

  }

  public void disposeUIResources() {
    if (myUiDisposed) return;

    super.disposeUIResources();

    myUiDisposed = true;

    myAutoScrollHandler.cancelAllRequests();

    myContext.getDaemonAnalyzer().clear();

    Disposer.dispose(this);
  }

  protected void addCollapseExpandActions(final List<AnAction> result) {
    final TreeExpander expander = new TreeExpander() {
      public void expandAll() {
        TreeUtil.expandAll(myTree);
      }

      public boolean canExpand() {
        return true;
      }

      public void collapseAll() {
        TreeUtil.collapseAll(myTree, 0);
      }

      public boolean canCollapse() {
        return true;
      }
    };
    final CommonActionsManager actionsManager = CommonActionsManager.getInstance();
    result.add(actionsManager.createExpandAllAction(expander, myTree));
    result.add(actionsManager.createCollapseAllAction(expander, myTree));
  }

  @Nullable
  public ProjectStructureElement getSelectedElement() {
    final TreePath selectionPath = myTree.getSelectionPath();
    if (selectionPath != null && selectionPath.getLastPathComponent() instanceof MyNode) {
      MyNode node = (MyNode)selectionPath.getLastPathComponent();
      final NamedConfigurable configurable = node.getConfigurable();
      if (configurable instanceof ProjectStructureElementConfigurable) {
        return ((ProjectStructureElementConfigurable)configurable).getProjectStructureElement();
      }
    }
    return null;
  }

  private class MyFindUsagesAction extends FindUsagesInProjectStructureActionBase {

    public MyFindUsagesAction(JComponent parentComponent) {
      super(parentComponent, myProject);
    }

    protected boolean isEnabled() {
      final TreePath selectionPath = myTree.getSelectionPath();
      if (selectionPath != null){
        final MyNode node = (MyNode)selectionPath.getLastPathComponent();
        return !node.isDisplayInBold();
      } else {
        return false;
      }
    }

    protected StructureConfigurableContext getContext() {
      return myContext;
    }

    protected ProjectStructureElement getSelectedElement() {
      return BaseStructureConfigurable.this.getSelectedElement();
    }

    protected RelativePoint getPointToShowResults() {
      final int selectedRow = myTree.getSelectionRows()[0];
      final Rectangle rowBounds = myTree.getRowBounds(selectedRow);
      final Point location = rowBounds.getLocation();
      location.x += rowBounds.width;
      return new RelativePoint(myTree, location);
    }
  }

  public void reset() {
    myUiDisposed = false;

    if (!myWasTreeInitialized) {
      initTree();
      myTree.setShowsRootHandles(false);
      loadTree();
    } else {
      super.disposeUIResources();
      myTree.setShowsRootHandles(false);
      loadTree();
    }
    for (ProjectStructureElement element : getProjectStructureElements()) {
      myContext.getDaemonAnalyzer().queueUpdate(element, false, true);
    }

    super.reset();
  }

  @NotNull
  protected Collection<? extends ProjectStructureElement> getProjectStructureElements() {
    return Collections.emptyList();
  }

  protected abstract void loadTree();

  @NotNull
  protected ArrayList<AnAction> createActions(final boolean fromPopup) {
    final ArrayList<AnAction> result = new ArrayList<AnAction>();
    AbstractAddGroup addAction = createAddAction();
    if (addAction != null) {
      result.add(addAction);
    }
    result.add(new MyRemoveAction());

    final AnAction copyAction = createCopyAction();
    if (copyAction != null) {
      result.add(copyAction);
    }
    result.add(Separator.getInstance());

    result.add(new MyFindUsagesAction(myTree));

    return result;
  }

  @Nullable
  protected AnAction createCopyAction() {
    return null;
  }

  public void onStructureUnselected() {
  }

  public void onStructureSelected() {
  }

  @Nullable
  protected abstract AbstractAddGroup createAddAction();

  protected class MyRemoveAction extends MyDeleteAction {
    public MyRemoveAction() {
      super(new Condition<Object>() {
        public boolean value(final Object object) {
          if (object instanceof MyNode) {
            final NamedConfigurable namedConfigurable = ((MyNode)object).getConfigurable();
            if (namedConfigurable != null) {
              final Object editableObject = namedConfigurable.getEditableObject();
              if (editableObject instanceof Sdk || editableObject instanceof Module || editableObject instanceof Facet || editableObject instanceof Artifact) return true;
              if (editableObject instanceof Library) {
                final LibraryTable table = ((Library)editableObject).getTable();
                return table == null || table.isEditable();
              }
            }
          }
          return false;
        }
      });
    }

    public void actionPerformed(AnActionEvent e) {
      final TreePath[] paths = myTree.getSelectionPaths();
      if (paths == null) return;

      final Set<TreePath> pathsToRemove = new HashSet<TreePath>();
      for (TreePath path : paths) {
        if (removeFromModel(path)) {
          pathsToRemove.add(path);
        }
      }
      removePaths(pathsToRemove.toArray(new TreePath[pathsToRemove.size()]));
    }

    private boolean removeFromModel(final TreePath selectionPath) {
      final Object last = selectionPath.getLastPathComponent();

      if (!(last instanceof MyNode)) return false;

      final MyNode node = (MyNode)last;
      final NamedConfigurable configurable = node.getConfigurable();
      final Object editableObject = configurable.getEditableObject();
      if (editableObject instanceof Sdk) {
        removeJdk((Sdk)editableObject);
      }
      else if (editableObject instanceof Module) {
        if (!removeModule((Module)editableObject)) return false;
      }
      else if (editableObject instanceof Facet) {
        if (removeFacet((Facet)editableObject).isEmpty()) return false;
      }
      else if (editableObject instanceof Library) {
        if (!removeLibrary((Library)editableObject)) return false;
      }
      else if (editableObject instanceof Artifact) {
        removeArtifact((Artifact)editableObject);
      }
      return true;
    }
  }

  protected void removeArtifact(Artifact artifact) {
  }

  protected boolean removeLibrary(Library library) {
    return false;
  }

  protected void removeFacetNodes(@NotNull List<Facet> facets) {
    for (Facet facet : facets) {
      MyNode node = findNodeByObject(myRoot, facet);
      if (node != null) {
        removePaths(TreeUtil.getPathFromRoot(node));
      }
    }
  }

  protected List<Facet> removeFacet(final Facet facet) {
    return myContext.myModulesConfigurator.getFacetsConfigurator().removeFacet(facet);
  }

  protected boolean removeModule(final Module module) {
    return true;
  }

  protected void removeJdk(final Sdk editableObject) {
  }

  protected abstract static class AbstractAddGroup extends ActionGroup implements ActionGroupWithPreselection {

    protected AbstractAddGroup(String text, Icon icon) {
      super(text, true);

      final Presentation presentation = getTemplatePresentation();
      presentation.setIcon(icon);

      final Keymap active = KeymapManager.getInstance().getActiveKeymap();
      if (active != null) {
        final Shortcut[] shortcuts = active.getShortcuts("NewElement");
        setShortcutSet(new CustomShortcutSet(shortcuts));
      }
    }

    public AbstractAddGroup(String text) {
      this(text, Icons.ADD_ICON);
    }

    public ActionGroup getActionGroup() {
      return this;
    }

    public int getDefaultIndex() {
        return 0;
      }
  }

}


text:
/* Generated by Font Squirrel (http://www.fontsquirrel.com) on August 26, 2015 */
@font-face {
    font-family: 'robotobold';
    src: url('./roboto-bold-webfont.eot');
    src: url('./roboto-bold-webfont.eot?#iefix') format('embedded-opentype'),
         url('./roboto-bold-webfont.woff2') format('woff2'),
         url('./roboto-bold-webfont.woff') format('woff'),
         url('./roboto-bold-webfont.ttf') format('truetype'),
         url('./roboto-bold-webfont.svg#robotobold') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'robotolight';
    src: url('./roboto-light-webfont.eot');
    src: url('./roboto-light-webfont.eot?#iefix') format('embedded-opentype'),
         url('./roboto-light-webfont.woff2') format('woff2'),
         url('./roboto-light-webfont.woff') format('woff'),
         url('./roboto-light-webfont.ttf') format('truetype'),
         url('./roboto-light-webfont.svg#robotolight') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'robotomedium';
    src: url('./roboto-medium-webfont.eot');
    src: url('./roboto-medium-webfont.eot?#iefix') format('embedded-opentype'),
         url('./roboto-medium-webfont.woff2') format('woff2'),
         url('./roboto-medium-webfont.woff') format('woff'),
         url('./roboto-medium-webfont.ttf') format('truetype'),
         url('./roboto-medium-webfont.svg#robotomedium') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'robotoregular';
    src: url('./roboto-regular-webfont.eot');
    src: url('./roboto-regular-webfont.eot?#iefix') format('embedded-opentype'),
         url('./roboto-regular-webfont.woff2') format('woff2'),
         url('./roboto-regular-webfont.woff') format('woff'),
         url('./roboto-regular-webfont.ttf') format('truetype'),
         url('./roboto-regular-webfont.svg#robotoregular') format('svg');
    font-weight: normal;
    font-style: normal;

}


text:
/**
 * External dependencies
 */
import { useCallback } from '@googleforcreators/react';

/**
 * Internal dependencies
 */
import useApi from '../../../../../api/useApi';

const cachedPrimaryOptions = {};

/**
 * Hook used for taxonomy filters logic.
 * Initializes the taxonomy filters data.
 *
 * @return {Object} initializeTaxonomyFilters taxonomies and a function to shape the taxonoimes filter data.
 */

function useTaxonomyFilters() {
  const { getTaxonomies, getTaxonomyTerms } = useApi(
    ({
      actions: {
        taxonomyApi: { getTaxonomies, getTaxonomyTerms },
      },
    }) => ({
      getTaxonomies,
      getTaxonomyTerms,
    })
  );

  /**
   * Query individual taxonomy data.
   * This is needed to initialize the primaryOptions and needed to search and set queriedOptions.
   *
   * @param {Object} taxonomy object holding taxonomy data,
   * including restBase and restPath used to fetch individual taxonomy terms
   * @param {string} search string use to query taxonomy by name
   * @return {Array} taxonomy terms
   */
  const queryTaxonomyTerms = useCallback(
    async (taxonomy, search) => {
      const { restBase, restPath } = taxonomy;
      const terms = await getTaxonomyTerms(restPath, { search, per_page: -1 });
      return terms.map((t) => ({
        ...t,
        restBase,
        restPath,
      }));
    },
    [getTaxonomyTerms]
  );

  /**
   * Get taxonomy terms for a given taxonomy. Cache for later use.
   * This is needed to initialize the primaryOptions.
   * See design-system/src/component/datalist
   *
   * @see queryTaxonomyTerms
   * @param {Object} taxonomy object holding taxonomy data,
   * including restBase and restPath used to fetch individual taxonomy terms
   * @return {Promise<Array>} cached taxonomy terms
   */
  const getPrimaryOptions = useCallback(
    async (taxonomy) => {
      const { restBase } = taxonomy;
      if (!cachedPrimaryOptions[restBase]) {
        cachedPrimaryOptions[restBase] = await queryTaxonomyTerms(taxonomy);
      }
      return cachedPrimaryOptions[restBase];
    },
    [queryTaxonomyTerms]
  );

  /**
   * Query all the taxonomies.
   * Sets up the shape of the taxonomy filters data
   *
   * @return {Promise<Array>} taxonomies filter data
   */
  const initializeTaxonomyFilters = useCallback(async () => {
    const taxonomies = await getTaxonomies({
      hierarchical: true,
      show_ui: true,
    });
    return taxonomies.map((taxonomy) => ({
      key: taxonomy.restBase,
      restPath: taxonomy.restPath,
      placeholder: taxonomy.labels.allItems,
      ariaLabel: taxonomy.labels.filterByItem,
      noMatchesFoundLabel: taxonomy.labels.notFound,
      searchPlaceholder: taxonomy.labels.searchItems,
      query: (search) => queryTaxonomyTerms(taxonomy, search),
      getPrimaryOptions: () => getPrimaryOptions(taxonomy),
    }));
  }, [queryTaxonomyTerms, getPrimaryOptions, getTaxonomies]);

  return initializeTaxonomyFilters;
}

export default useTaxonomyFilters;


text:
"""
Misc utilities.
"""

from fractions import Fraction
from typing import Union

def ord_(dta):
    if isinstance(dta, str):
        return ord(dta)
    return dta

def make_string(seq: Union[bytes, list]) -> str:
    """
    Don't throw an exception when given an out of range character.
    """
    string = ''
    for char in seq:
        # Screen out non-printing characters
        try:
            if 32 <= char < 256:
                string += chr(char)
        except TypeError:
            pass

    # If no printing chars
    if not string:
        if isinstance(seq, list):
            string = ''.join(map(str, seq))
            # Some UserComment lists only contain null bytes, nothing valuable to return
            if set(string) == {'0'}:
                return ''
        else:
            string = str(seq)

    # Clean undesirable characters on any end
    return string.strip(' \x00')

def make_string_uc(seq) -> str:
    """
    Special version to deal with the code in the first 8 bytes of a user comment.
    First 8 bytes gives coding system e.g. ASCII vs. JIS vs Unicode.
    """
    if not isinstance(seq, str):
        # Remove code from sequence only if it is valid
        if make_string(seq[:8]).upper() in ('ASCII', 'UNICODE', 'JIS', ''):
            seq = seq[8:]
    # Of course, this is only correct if ASCII, and the standard explicitly
    # allows JIS and Unicode.
    return make_string(seq)

def get_gps_coords(tags: dict) -> tuple:

    lng_ref_tag_name = 'GPS GPSLongitudeRef'
    lng_tag_name = 'GPS GPSLongitude'
    lat_ref_tag_name = 'GPS GPSLatitudeRef'
    lat_tag_name = 'GPS GPSLatitude'

    # Check if these tags are present
    gps_tags = [lng_ref_tag_name, lng_tag_name, lat_tag_name, lat_tag_name]
    for tag in gps_tags:
        if not tag in tags.keys():
            return ()

    lng_ref_val = tags[lng_ref_tag_name].values
    lng_coord_val = [c.decimal() for c in tags[lng_tag_name].values]

    lat_ref_val = tags[lat_ref_tag_name].values
    lat_coord_val = [c.decimal() for c in tags[lat_tag_name].values]

    lng_coord = sum([c/60**i for i, c in enumerate(lng_coord_val)])
    lng_coord *= (-1) ** (lng_ref_val == 'W')

    lat_coord = sum([c/60**i for i, c in enumerate(lat_coord_val)])
    lat_coord *= (-1) ** (lat_ref_val == 'S')

    return (lat_coord, lng_coord)

class Ratio(Fraction):
    """
    Ratio object that eventually will be able to reduce itself to lowest
    common denominator for printing.
    """

    # We're immutable, so use __new__ not __init__
    def __new__(cls, numerator=0, denominator=None):
        try:
            self = super(Ratio, cls).__new__(cls, numerator, denominator)
        except ZeroDivisionError:
            self = super(Ratio, cls).__new__(cls)
            self._numerator = numerator
            self._denominator = denominator
        return self

    def __repr__(self) -> str:
        return str(self)

    @property
    def num(self):
        return self.numerator

    @property
    def den(self):
        return self.denominator

    def decimal(self) -> float:
        return float(self)


text:
> Convenience task to generate a styleguide using [grunt-dss](https://github.com/darcyclarke/grunt-dss) and [grunt-contrib-compass](https://github.com/gruntjs/grunt-contrib-compass/).

## Getting Started
This plugin requires Grunt `~0.4.1`

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

```shell
$ npm install grunt-styleguide --save-dev
```

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-styleguide');
```

## The "styleguide" task

This is a convenience task to simplify adding grunt-dss to a project that uses grunt-contrib-compass.

### Before

```js
grunt.initConfig({
  compass: {
    options: {
      config: 'source/styles/config.rb',
    },
    dev: {},
    dist: {
      options: {
        outputStyle: 'compressed',
        cssDir: 'public/css/compressed',
        force: true,
      }
    },
    docs: {
      options: {
        sassDir: '<%= dss.docs.options.template =>assets/source',
        cssDir: '<%= dss.docs.options.template =>assets/css',
      }
    }
  },
  dss: {
    docs: {
      options: {
        template: 'source/dssTemplate/',
      },
      files: {
        'docs/dssDocs/': ['test/fixtures/*.{css,scss,sass,less,styl}'],
      },
    },
  },
})
```

### After

```js
grunt.initConfig({
  compass: {
    options: {
      config: 'source/styles/config.rb',
    },
    dev: {},
    dist: {
      options: {
        outputStyle: 'compressed',
        cssDir: 'public/css/compressed',
        force: true,
      }
    },
  },
  styleguide: {
    docs: {
      dssTemplate: 'source/dssTemplate/',
      dssTarget: 'docs/dssDocs/',
      dssFiles: ['test/fixtures/*.{css,scss,sass,less,styl}'],
    },
  },
})
```

### Options

#### options.taskTarget
Type: `String`
Default value: `styledocs`

Name for the target value of the new tasks. Use if you have conflicting compass or dss target already in your Gruntfile;

#### options.compass
Type: `Object`
Default value: `{config: 'config.rb',}`

Object that will be used to configure the [grunt-contrib-compass](https://github.com/gruntjs/grunt-contrib-compass) task for compiling the SASS files for the [grunt-dss template](https://github.com/darcyclarke/grunt-dss#optionstemplate).

[Explation of grunt-contrib-compass options](https://github.com/gruntjs/grunt-contrib-compass?source=c#options)

#### options.compassSourceTarget
Type: `Boolean`
Default value: `false`

By default the Compass `css_dir` and `sass_dir` will be set relative to the `dssTemplate` value, as `[dssTemplate]assets/source` and  `[dssTemplate]assets/css`. Set this to `true` to repect the `options.compass.cssDir` and `options.compass.sassDir` settings instead.

#### options.dssTemplate _Required_
Type: `String`
Default value: `dssTemplate/`

Path to the template you want to use with [grunt-dss](https://github.com/darcyclarke/grunt-dss) to document.

#### options.dssTarget _Required_
Type: `String`
Default value: `styledocs/`

Folder where [grunt-dss](https://github.com/darcyclarke/grunt-dss) outputs.

#### options.dssFiles _Required_
Type: `Array`
Default value: `[]`

Files array of the css files you want [grunt-dss](https://github.com/darcyclarke/grunt-dss) to document.

#### options.dssParsers
Type: `Object`
Default value: `{}`

Custom [DSS](https://github.com/darcyclarke/DSS) parsers. This task already has a few.

### Usage Examples

#### Default Options
Requrired Config

```js
grunt.initConfig({
  styleguide: {
    dev: {
      dssTemplate: 'source/dssTemplate/',
      dssTarget: 'docs/dssDocs/',
      dssFiles: ['test/fixtures/*.{css,scss,sass,less,styl}'],
    },
  },
})
```

#### Custom Options

```js
grunt.initConfig({
  styleguide: {
    options: {
      taskTarget: 'dssDocs',
      dssTemplate: 'source/dssTemplate/',
      dssTarget: 'docs/dssDocs/',
      dssFiles: ['test/fixtures/*.{css,scss,sass,less,styl}'],
    },
    dev: {},
    dist: {
      options: {
        compass: {
          config: 'config.rb'
          outputStyle: 'compact',
          noLineComments: true,
          force: true,
        },
      },
    },
  },
})
```

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Release History

_Planned_      0.1.0

Generated style docs contain documented styles, and custom styles for the docs.


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ValidEntityTypes
 *
 * @author KottkeDP
 */
class ValidEntityTypes {
    const TAB = 'containers';
    const SOURCE = 'widgets';
    const METADATA = 'metadata';
    //const METADATA = 'metadata_fields';
}

?>


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

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
QueryElevationParams (Solr 4.2.1 API)
</TITLE>

<META NAME="date" CONTENT="2013-03-26">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.solr.common.params

Interface QueryElevationParams

public interface QueryElevationParams

Parameters used with the QueryElevationComponent

Field Summary

static String
EDITORIAL_MARKER_FIELD_NAME

          The name of the field that editorial results will be written out as when using the QueryElevationComponent, which
 automatically configures the EditorialMarkerFactory.

static String
ENABLE

static String
EXCLUDE_MARKER_FIELD_NAME

          The name of the field that excluded editorial results will be written out as when using the QueryElevationComponent, which
 automatically configures the EditorialMarkerFactory.

static String
EXCLUSIVE

static String
FORCE_ELEVATION

static String
MARK_EXCLUDES

          Instead of removing excluded items from the results, passing in this parameter allows you to get back the excluded items, but to mark them
 as excluded.

Field Detail

ENABLE

static final String ENABLE

See Also:
Constant Field Values

EXCLUSIVE

static final String EXCLUSIVE

See Also:
Constant Field Values

FORCE_ELEVATION

static final String FORCE_ELEVATION

See Also:
Constant Field Values

EDITORIAL_MARKER_FIELD_NAME

static final String EDITORIAL_MARKER_FIELD_NAME

The name of the field that editorial results will be written out as when using the QueryElevationComponent, which
 automatically configures the EditorialMarkerFactory.  The default name is "elevated"

 See http://wiki.apache.org/solr/DocTransformers

See Also:
Constant Field Values

EXCLUDE_MARKER_FIELD_NAME

static final String EXCLUDE_MARKER_FIELD_NAME

The name of the field that excluded editorial results will be written out as when using the QueryElevationComponent, which
 automatically configures the EditorialMarkerFactory.  The default name is "excluded".  This is only used
 when MARK_EXCLUDES is set to true at query time.

 See http://wiki.apache.org/solr/DocTransformers

See Also:
Constant Field Values

MARK_EXCLUDES

static final String MARK_EXCLUDES

Instead of removing excluded items from the results, passing in this parameter allows you to get back the excluded items, but to mark them
 as excluded.

See Also:
Constant Field Values

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

          Copyright © 2000-2013 Apache Software Foundation.  All Rights Reserved.


text:
package procfs

import (
	"github.com/blacklightops/libbeat/common"
	"github.com/blacklightops/libbeat/logp"
	"github.com/blacklightops/turnbeat/inputs"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"time"
)

const procfsdir = "/proc"

type ProcfsInput struct {
	Config         inputs.MothershipConfig
	Tick_interval  int
	Minor_interval int
	Major_interval int
}

func (l *ProcfsInput) InputType() string {
	return "ProcfsInput"
}

func (l *ProcfsInput) InputVersion() string {
	return "0.0.1"
}

func (l *ProcfsInput) Init(config inputs.MothershipConfig) error {

	l.Config = config

	l.Tick_interval = config.Tick_interval

	logp.Info("[ProcfsInput] Initialized, using tick interval " + strconv.Itoa(l.Tick_interval))

	return nil
}

func (l *ProcfsInput) GetConfig() inputs.MothershipConfig {
	return l.Config
}

type Process struct {
	PID     int
	Cmdline string
	Cwd     string
	Root    string
	Status  string
	// Fds
	// Threads
}

func getProcDetail(PID string) *Process {
	pdir := path.Join(procfsdir, PID)

	p := new(Process)
	p.PID, _ = strconv.Atoi(PID)

	cl, _ := ioutil.ReadFile(path.Join(pdir, "cmdline"))
	p.Cwd, _ = os.Readlink(path.Join(pdir, "cwd"))
	p.Root, _ = os.Readlink(path.Join(pdir, "root"))
	status, _ := ioutil.ReadFile(path.Join(pdir, "status"))

	p.Cmdline = byteTransform(cl)
	p.Status = byteTransform(status)

	return p
}

func getCmdline(PID string) string {
	pdir := path.Join(procfsdir, PID)

	cl, _ := ioutil.ReadFile(path.Join(pdir, "cmdline"))
	cmdline := byteTransform(cl)
	return cmdline
}

func scanProcs(output chan common.MapStr) {
	now := func() time.Time {
		t := time.Now()
		return t
	}

	if !pathExists(procfsdir) {
		return
	}
	ds, err := ioutil.ReadDir(procfsdir)
	if err != nil {
		return
	}

	event := common.MapStr{}
	processes := common.MapStr{}
	proc_detail := common.MapStr{}

	// get all numeric entries
	for _, d := range ds {
		n := d.Name()
		if isNumeric(n) {
			processes[n] = getCmdline(n)
			proc_detail[n] = getProcDetail(n)
		}
	}

	text := "process report"
	event["message"] = &text
	event["data"] = processes
	event["data_detail"] = proc_detail
	event["type"] = "report"

	event.EnsureTimestampField(now)
	event.EnsureCountField()
	output <- event
}

func (l *ProcfsInput) periodic(output chan common.MapStr) {
	logp.Debug("[procfsinput]", "Running..")

	scanProcs(output)
}

func runTick(output chan common.MapStr) {
	logp.Debug("[procfsinput]", "Performing Tick tasks..")
	// nothing for now
}

func runMinor(output chan common.MapStr) {
	logp.Debug("[procfsinput]", "Performing Minor tasks..")

	scanProcs(output)
}

func runMajor(output chan common.MapStr) {
	logp.Debug("[procfsinput]", "Performing Tick..")
	// nothing for now
}

func (l *ProcfsInput) Run(output chan common.MapStr) error {
	logp.Debug("[procfsinput]", "Starting up Procfs Input")

	go inputs.PeriodicTaskRunner(l, output, runTick, runMinor, runMajor)

	return nil
}


text:
RAPID is a http server minimal implementation, works in process model and runs only one thread.

I'm going to use in the following scene:
* a monitor for embedded system
* a http debugging server for native application on smartphone

# Build Status

[![Build Status](https://travis-ci.org/yagihiro/rapid.svg?branch=master)](https://travis-ci.org/yagihiro/rapid)

# Getting Started

You can get easy way about the HTTP GET request / response handler to the following examples.
```C++
#include <cstdlib>
#include <iostream>
#include <rapid/rapid.h>
#include <signal.h>
#include <thread>

static sig_atomic_t _received_sigint = 0;

// Ctrl-C
static void on_sigint(int sig) { _received_sigint = 1; }

int main(int argc, char *argv[]) {
  if (signal(SIGINT, on_sigint) == SIG_ERR) {
    return EXIT_FAILURE;
  }

  rapid::Server server;
  server.set_port(8080);
  server.get("/", [](const rapid::Request &req) -> rapid::ResponsePtr {
    rapid::Response response;

    response.set_status_code(200);
    response.set_headers({{"Content-Type", "application/json"}});
    response.set_body("{'key':'value'}");

    return std::make_shared<rapid::Response>(response);
  });
  server.run();

  do {
    std::this_thread::sleep_for(std::chrono::milliseconds(32));
  } while (_received_sigint == 0);

  return EXIT_SUCCESS;
}
```

# Dependencies

## Mac OS X

Depends on openssl library, you should install it by HomeBrew.
```
% brew install openssl
```

## Linux

Required over GCC 4.9 and CMake. If you build this library, you can refer to the following commands:
```
cmake -DCMAKE_CXX_COMPILER=g++-4.9 . && make
```

# License

MIT License


text:
from abaqusGui import *
from abaqusConstants import ALL, CARTESIAN, SCALAR, INTEGRATION_POINT, CENTROID, ELEMENT_NODAL
from version import version as __version__
# Required to ensure the CSYS list is up to date
from kernelAccess import session

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

class PyvXRAY_plugin(AFXForm):

    def __init__(self, owner):

        # Construct the base class
        AFXForm.__init__(self, owner)

        self.odb          = None
        self.csysList     = None
        self.stepList     = None
        self.elementSets  = None
        self.scalarList   = None
        self.imageFormats = ['bmp','jpeg','png']
        self.suppLocs     = [INTEGRATION_POINT, CENTROID, ELEMENT_NODAL]

        # Keyword definitions
        self.cmd                 = AFXGuiCommand(mode=self, method='createVirtualXrays',objectName='virtualXrays', registerQuery=False)
        self.odbNameKw           = AFXStringKeyword(self.cmd, 'odbName', True, '')
        self.bSetNameKw          = AFXStringKeyword(self.cmd, 'bRegionSetName', True, '')
        self.BMDfonameKw         = AFXStringKeyword(self.cmd, 'BMDfoname', True, '')
        self.showImplantKw       = AFXBoolKeyword(self.cmd,   'showImplant', AFXBoolKeyword.TRUE_FALSE, True, False)
        self.iSetNameKw          = AFXStringKeyword(self.cmd, 'iRegionSetName', True, '')
        self.iDensityKw          = AFXFloatKeyword(self.cmd,  'iDensity', True, 4500)
        self.stepListKw          = AFXStringKeyword(self.cmd, 'stepList', True, '')
        self.csysNameKw          = AFXStringKeyword(self.cmd, 'csysName', True, '')
        self.resGridKw           = AFXFloatKeyword(self.cmd,  'resGrid', True, 2)
        self.imageNameBaseKw     = AFXStringKeyword(self.cmd, 'imageNameBase', True, 'vxray')
        self.preferredXraySizeKw = AFXIntKeyword(self.cmd,    'preferredXraySize', True, 800)
        self.imageFormatKw       = AFXStringKeyword(self.cmd, 'imageFormat', True, self.imageFormats[-1])
        self.smoothKw            = AFXBoolKeyword(self.cmd,   'smooth', AFXBoolKeyword.TRUE_FALSE, True, True)
        self.manualScalingKw     = AFXBoolKeyword(self.cmd,   'manualImageScaling', AFXBoolKeyword.TRUE_FALSE, True, False)

    def getOdbList(self):
        """Get a list of all available odbs in session"""
        self.odbList = session.odbs.keys()

    def getFirstOdb(self):
        """Set first odb in first Dialog Box"""
        if self.odbList==None or len(self.odbList)==0: return
        self.setOdb(self.odbList[0])

    def setOdb(self,odbName):
        """Set odb from name"""
        if odbName=='': return
        self.odb = session.odbs[odbName]

    def getElementSetList(self):
        """Get list of all element sets in the current odb"""
        self.elementSets=[]
        if self.odb==None: return
        # Check part instances
        for instName,inst in self.odb.rootAssembly.instances.items():
            self.elementSets.append('.'.join([instName,'ALL']))
            for setName in inst.elementSets.keys():
                self.elementSets.append('.'.join([instName,setName]))
        # Check assembly
        for setName in self.odb.rootAssembly.elementSets.keys():
            self.elementSets.append(setName)
        self.elementSets.sort()

    def getCsyses(self):
        """Get list of all available csyses"""
        # Check scratch odb csyses
        self.csysList = {'Session':[], 'ODB':[]}
        for k,v in session.scratchOdbs.items():
            for csysName,csys in v.rootAssembly.datumCsyses.items():
                if csys.type==CARTESIAN:
                    self.csysList['Session'].append(csysName)
        # Check odb csyses if an odb is open in the current viewport
        if self.odb != None:
            for csysName,csys in self.odb.rootAssembly.datumCsyses.items():
                if csys.type==CARTESIAN:
                    self.csysList['ODB'].append(csysName)

    def getSteps(self):
        """Get list of all available steps"""
        self.stepList=[]
        if self.odb==None: return
        for stepName in self.odb.steps.keys():
            stepNumber = stepName.split('-')[-1]
            self.stepList.append(stepNumber)
        return

    def getScalarList(self):
        """Get list of available scalars. Check last frame in all steps"""
        self.scalarList=[]
        if self.odb==None: return
        includeList={}; excludeList={}
        for step in self.odb.steps.values():
            frame = step.frames[-1]
            for k in frame.fieldOutputs.keys():
                if excludeList.has_key(k) or includeList.has_key(k): continue
                v   = frame.fieldOutputs[k]
                loc = [True for loc in v.locations if loc.position in self.suppLocs]
                if any(loc) and v.type==SCALAR: includeList[k]=1
                else: excludeList[k]=1
        self.scalarList = includeList.keys()
        self.scalarList.sort()

    def getFirstDialog(self):
        """Create the dialog box"""
        # Get odb information to populate the dialog box
        self.getOdbList()
        self.getFirstOdb()
        self.getElementSetList()
        self.getCsyses()
        self.getSteps()
        self.getScalarList()
        # Create dialog box
        import pyvXRAYDB
        return pyvXRAYDB.PyvXRAYDB(self)

    def doCustomChecks(self):
        """Define empty class function doCustomChecks to check user inputs"""

        # Check that odb exists
        self.getOdbList()
        if self.odbNameKw.getValue() not in self.odbList:
            showAFXErrorDialog(self.getCurrentDialog(), 'Error: Odb %s does not exist' % self.modelNameKw.getValue())
            return False

        # Check that bone region exists in model
        self.getElementSetList()
        if self.bSetNameKw.getValue() not in self.elementSets:
            showAFXErrorDialog(self.getCurrentDialog(), 'Error: Bone region %s does not exist' % self.bSetNameKw.getValue())
            return False

        # If implant is requested, check implant inputs
        if self.showImplantKw.getValue():
            # Check implant region
            self.getElementSetList()
            if self.iSetNameKw.getValue() not in self.elementSets:
                showAFXErrorDialog(self.getCurrentDialog(), 'Error: Implant region %s does not exist' % self.iSetNameKw.getValue())
                return False
            # Check input density
            iDensity  = self.iDensityKw.getValue()
            try: float(iDensity)
            except:
                showAFXErrorDialog(self.getCurrentDialog(), 'Error: Implant density value is not a valid number')
                return False
            if iDensity<0:
                showAFXErrorDialog(self.getCurrentDialog(), 'Error: Implant density must be greater than 0')
                return False

        # Check that values in stepList are valid
        stepList = self.stepListKw.getValue()
        try:
            stepList = [int(s) for s in stepList.replace(',',' ').split()]
        except:
            showAFXErrorDialog(self.getCurrentDialog(), 'Error: Cannot convert step list values to integers')
            return False
        stepList.sort()

        # Check that all steps in step list exist and that density variable exists in all steps (last frame)
        BMDfoname = self.BMDfonameKw.getValue()
        stepInfo  = {}
        for stepName,step in self.odb.steps.items():
            stepNumber = int(stepName.split('-')[-1])
            stepInfo[stepNumber] = step.frames[-1].fieldOutputs.keys()
        for stepNumber in stepList:
            if stepNumber not in stepInfo:
                showAFXErrorDialog(self.getCurrentDialog(), 'Error: Step number %i is not available in odb' % stepNumber)
                return False
            if BMDfoname not in stepInfo[stepNumber]:
                showAFXErrorDialog(self.getCurrentDialog(), 'Error: Density variable %s is not available in Step number %i' % (BMDfoname,stepNumber))
                return False

        # Check mapping resolution, resGrid
        resGrid = self.resGridKw.getValue()
        try: resGrid = float(resGrid)
        except:
            showAFXErrorDialog(self.getCurrentDialog(), 'Error: "Inputs: Mapping resolution" value not valid')
            return False

        # Check preferred size of images
        preferredXraySize = self.preferredXraySizeKw.getValue()
        try: preferredXraySize = int(preferredXraySize)
        except:
            showAFXErrorDialog(self.getCurrentDialog(), 'Error: "X-ray Settings: Approx size of x-ray" value not valid')
            return False
        minXraySize = 100
        if preferredXraySize < minXraySize:
            showAFXErrorDialog(self.getCurrentDialog(), 'Error: Minimum virtual x-ray image size is %i pixels' % minXraySize)
            return False

        # Check for Abaqus version >= 6.11
        majorNumber, minorNumber, updateNumber = getAFXApp().getVersionNumbers()
        if majorNumber==6 and minorNumber < 11:
            showAFXErrorDialog( self.getCurrentDialog(), 'Error: ABAQUS 6.11 and above is required' )
            return False

        return True

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Register the plug-in

desc = 'An ABAQUS plugin used to generate a time series of virtual x-rays from the output of a bone remodelling analysis.\n\n'                  + \
       'The resulting images can be used to analyse the change in bone density over time in a number of regions of interest or "Gruen Zones", ' + \
       'typically due to changes in loading following insertion of an orthopaedic implant. Associated tool BMDanalyse, available on PyPi, was ' + \
       'created for this sole purpose.\n\nRequires an odb file to be open within the current viewport which has a fieldoutput representing '    + \
       'bone density. Works by mapping the bone density fieldoutput onto a regular 3D grid and then projecting the values onto the three '      + \
       'orthogonal planes. Currently only models with C3D4 or C3D10 elements are supported.'

toolset = getAFXApp().getAFXMainWindow().getPluginToolset()
toolset.registerGuiMenuButton(
    buttonText='pyvXRAY|Create virtual x-rays',
    object=PyvXRAY_plugin(toolset),
    messageId=AFXMode.ID_ACTIVATE,
    icon=None,
    kernelInitString='import virtualXrays',
    applicableModules=ALL,
    version=__version__,
    author='Michael Hogg',
    description=desc,
    helpUrl='https://github.com/mhogg/pyvxray'
)


text:
package base

import database.helper.DatabaseTables
import slick.jdbc.JdbcProfile

abstract class PostgresDbSpec extends DatabaseSpec with DatabaseTables {
  override implicit val profile: JdbcProfile = _root_.slick.jdbc.PostgresProfile

  import profile.api._

  protected def dependencies: DBIOAction[Unit, NoStream, Effect.Write]

  override protected def beforeAll(): Unit = {
    super.beforeAll()

    createSchemas()
  }

  override protected def afterAll(): Unit = {
    super.afterAll()

    dropSchemas()
    db.close()
  }

  protected def createSchemas(): Unit = runAsyncSequence(createAction(), dependencies)

  protected def dropSchemas(): Unit = runAsyncSequence(dropAction())

  protected def clearTables(): Unit = runAsyncSequence(tables.reverseMap(_.delete): _*)
}


text:
class Location < ActiveRecord::Base

# == Constants ============================================================
  enum location_type: [:camp, :meeting_hall]

# == Relationships ========================================================
  has_many :events
  has_many :lodgings, dependent: :destroy

# == Validations ==========================================================
  validates :city, presence: true
  validates :name, presence: true

# == Scopes ===============================================================
  scope :by_name, -> { order(:name) }

end


text:
import sys
import xml.etree.cElementTree as et
import os
import re
#import pyltp as ltp
import time
import csv

reload(sys)
sys.setdefaultencoding('utf-8')

import logging
logging.basicConfig(level=logging.INFO,
    format='[%(asctime)s %(msecs)03d][%(name)-10.10s:%(lineno)03d][%(funcName)-15.15s][%(levelname)s] %(message)s',
    datefmt = '%F %T')

#返回类型
class Rules(object):
  def __init__(self):
    self.rules = {}
  def Load(self, fname):
    with open(fname, 'rb') as rf:
      try:
        reader = csv.reader(rf, delimiter = ' ', quotechar = ' ')
        for row in reader:
          self.rules[row[0]] = row[1]
      except:
        return None
#    for key in self.rules.keys():
#      print key, self.rules[key]
    return self.rules

  def GetValue(self, key):
    if self.rules.has_key(key):
      return self.rules[key]
    return None
class ParamRules(Rules):
  def __init__(self):
    Rules.__init__(self)

class ReturnRules(Rules):
  def __init__(self):
    Rules.__init__(self)
    self.default_key = 'default'
  def GetReturnType(self, sentence):
    for key in self.rules.keys():
      if key in sentence:
        return self.rules[key]
    return self.rules[self.default_key]

class Row(object):
  def __init__(self, row):
    self.row = row

    #参数表
    self.parameter = {}

    #
    self.array = filter(lambda x:len(x.strip()) > 0, re.split('{|}', self.row))
    self.return_type = None

    self.sentence = self.array[0].strip()
    param = self.array[1]
    for a in param.split(','):
      try:
        key = a.split('=')[1].strip()
        value = a.split('=')[0].strip()
        self.parameter[key] = value
      except:
        #参数列表有空的:{}
        print '参数列表为空:%s'%(row)
        #返回类型为第二个
        self.return_type = self.array[1].strip()
        break
    if self.return_type is None:
      self.return_type = self.array[2].strip()
    #参数列表处理,取一个
    if '/' in self.return_type or ']' in self.return_type:
     # print self.return_type
      arr = filter(lambda x:len(x.strip()) > 0, re.split('\[|\]|/', self.return_type))
      if len(arr) > 0:
        self.return_type = arr[-1]
     #   print self.return_type
#        time.sleep(2)
  def GetSentence(self):
    return self.sentence

  def ParamKeys(self):
    return self.parameter.keys()

  def ParamValue(self, key):
    try:
      return self.parameter[key]
    except:
      return None
  def GetRetureType(self):
    return self.return_type


text: A minimalism hugo theme. Demo: https://blog.wxh.me.