text:
package org.isisaddons.module.publishing.webapp;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.isis.applib.AppManifest;
import org.apache.isis.applib.fixturescripts.FixtureScript;

import org.isisaddons.module.publishing.PublishingModule;
import org.isisaddons.module.publishing.fixture.dom.PublishingFixtureDomModule;

public class PublishingAppManifest implements AppManifest {
    @Override
    public List<Class<?>> getModules() {
        return Arrays.asList(
                PublishingModule.class,
                PublishingFixtureDomModule.class,
                PublishingAppModule.class
        );
    }
    @Override
    public List<Class<?>> getAdditionalServices() { return null; }
    @Override
    public String getAuthenticationMechanism() { return null; }
    @Override
    public String getAuthorizationMechanism() { return null; }
    @Override
    public List<Class<? extends FixtureScript>> getFixtures() { return null; }
    @Override
    public Map<String, String> getConfigurationProperties() { return null; }

}


text:
import logging

import cStringIO as StringIO

from spitfire.compiler import ast

class CodegenError(Exception):
    pass

class CodeNode(object):

    def __init__(self, src_line=None, input_pos=None):
        self.src_line = src_line
        self.input_pos = input_pos
        self.child_nodes = []

    def append_line(self, line):
        self.append(CodeNode(line))

    def append(self, code_node):
        self.child_nodes.append(code_node)

    def insert(self, index, code_node):
        self.child_nodes.insert(index, code_node)

    def extend(self, code_nodes):
        try:
            self.child_nodes.extend(code_nodes)
        except TypeError:
            raise CodegenError("can't add %s" % code_nodes)

    def __repr__(self):
        return '%s:%s' % (self.__class__.__name__, self.src_line)

# perform an in-order traversal of the AST and call the generate methods
# in this case, we are generating python source code that should be somewhat
# human-readable
class CodeGenerator(object):
    indent_str = '  '
    indent_level = 0

    # options - an AnalyzerOptions object
    def __init__(self, ast_root, compiler, options=None):
        self.ast_root = ast_root
        # Compiler - an instance of Compiler defined in util.
        self.compiler = compiler
        # This stack of FunctionNodes represents the functions we are
        # currently inside. When we enter a function node, we push that
        # onto the stack and when we leave that function, we pop it from
        # the stack.
        self.function_stack = []
        self.options = options
        self.output = StringIO.StringIO()
        self.template = None
        self.baked_mode = False

    def get_code(self):
        code_root = self.build_code(self.ast_root)[0]
        self.write_python(code_root, indent_level=-1)
        return self.output.getvalue().encode(self.ast_root.encoding)

    def generate_python(self, code_node):
        try:
            return code_node.src_line
        except AttributeError, e:
            self.compiler.error(CodegenError("can't write code_node: %s\n\t%s" %
                                             (code_node, e)))

    def write_python(self, code_node, indent_level):
        try:
            if code_node.src_line is not None:
                if code_node.src_line:
                    self.output.write(self.indent_str * indent_level)
                    self.output.write(code_node.src_line)
                    if (self.options.include_sourcemap and
                            code_node.input_pos and self.compiler.src_line_map):
                        self.output.write(
                            ' # L%s' %
                            self.compiler.src_line_map[code_node.input_pos])
                self.output.write('\n')
        except AttributeError:
            self.compiler.error(CodegenError("can't write code_node: %s" %
                                             code_node))

        for cn in code_node.child_nodes:
            self.write_python(cn, indent_level + 1)

    def build_code(self, ast_node):
        method_name = 'codegenAST%s' % ast_node.__class__.__name__
        method = getattr(self, method_name, self.codegenDefault)
        return method(ast_node)

    def codegenASTTemplateNode(self, node):
        self.template = node.copy(copy_children=False)

        module_code = CodeNode()
        module_code.append_line('#!/usr/bin/env python')
        module_code.append_line('# -*- coding: %s -*-' % node.encoding)
        if node.baked:
            module_code.append_line('# Baked Mode')
            self.baked_mode = True
        module_code.append_line('')
        if node.import_nodes:
            module_code.append_line('# template imports')
            for n in node.import_nodes:
                module_code.extend(self.build_code(n))
            module_code.append_line('')
        if node.from_nodes:
            module_code.append_line('# template from imports')
            for n in node.from_nodes:
                module_code.extend(self.build_code(n))
            module_code.append_line('')

        classname = node.classname

        module_code.append_line('import spitfire.runtime')
        module_code.append_line('import spitfire.runtime.template')

        if self.options and self.options.cheetah_cheats:
            module_code.append_line(
                'from Cheetah.NameMapper import valueFromSearchList '
                'as resolve_placeholder')
            module_code.append_line(
                'from Cheetah.NameMapper import valueForKey as resolve_udn')
        else:
            module_code.append_line(
                'from spitfire.runtime.udn import resolve_placeholder')
            module_code.append_line('from spitfire.runtime.udn '
                                    'import resolve_placeholder_with_locals')
            module_code.append_line(
                'from spitfire.runtime.udn import resolve_udn')

        module_code.append_line(
            'from spitfire.runtime.baked import SanitizedPlaceholder')
        module_code.append_line(
            'from spitfire.runtime.baked import runtime_mark_as_sanitized')
        module_code.append_line(
            'from spitfire.runtime.baked import mark_as_sanitized')
        module_code.append_line(
            'from spitfire.runtime.template import template_method')
        module_code.append_line('')

        if node.cached_identifiers:
            module_code.append_line('# cached identifiers')
            for cached_ph in node.cached_identifiers:
                module_code.append_line('%s = None' % cached_ph.name)
            module_code.append_line('')

        if not node.library:
            extends = []
            for n in node.extends_nodes:
                extends.append(self.generate_python(self.build_code(n)[0]))
            if not extends:
                extends = [self.options.base_template_full_import_path]
                if (self.options.base_template_full_import_path !=
                    (self.options.DEFAULT_BASE_TEMPLATE_FULL_IMPORT_PATH)):
                    # If we are not using the default base template class, we
                    # need to import the module for the custom template class.
                    # The module for the default base template class is already
                    # imported below and is required regardless of which base
                    # template is being used.
                    base_template_module_bits = (
                        self.options.base_template_full_import_path.split(
                            '.')[:-1])
                    # If the full import path is a.b.ClassName, we want to
                    # import the module a.b.
                    base_template_module = '.'.join(base_template_module_bits)
                    module_code.append_line('import %s' % base_template_module)

            extends_clause = ', '.join(extends)
            class_code = CodeNode('class %(classname)s(%(extends_clause)s):' %
                                  vars())

            module_code.append(class_code)
            for n in node.attr_nodes:
                class_code.extend(self.build_code(n))
                class_code.append_line('')
            def_parent_code = class_code
        else:
            # Library functions are written to the module directly.
            module_code.append_line('')
            def_parent_code = module_code

        for n in node.child_nodes:
            def_parent_code.extend(self.build_code(n))
            def_parent_code.append_line('')

        # if we aren't extending a template, build out the main function
        if not node.library and (not node.extends_nodes or node.implements):
            def_parent_code.extend(self.build_code(node.main_function))

        # NOTE(msolo): originally, i thought this would be helpful in case a bit
        # of human error - however, a more robust check is necessary here to
        # make the warning less spurious
        # else:
        #   from spitfire.compiler.visitor import flatten_tree
        #   logging.warning(throwing away defined main function because "
        #                   "it is not a base class %s %s",
        #                   self.ast_root.source_path)
        #   logging.warning("%s", flatten_tree(node.main_function))

        module_code.append_line(run_tmpl % vars(node))

        return [module_code]

    def codegenASTExtendsNode(self, node):
        return [CodeNode('.'.join([
            self.generate_python(self.build_code(n)[
                0]) for n in node.module_name_list
        ]))]

    def codegenASTImportNode(self, node):
        return [CodeNode('import %s' % '.'.join([
            self.generate_python(self.build_code(n)[
                0]) for n in node.module_name_list
        ]))]

    def codegenASTFromNode(self, node):
        from_clause = '.'.join([
            self.generate_python(self.build_code(n)[
                0]) for n in node.module_name_list
        ])
        import_clause = self.generate_python(self.build_code(node.identifier)[
            0])

        if node.alias:
            alias_clause = self.generate_python(self.build_code(node.alias)[0])
            return [CodeNode('from %(from_clause)s '
                             'import %(import_clause)s '
                             'as %(alias_clause)s' % vars())]
        else:
            return [CodeNode('from %(from_clause)s '
                             'import %(import_clause)s' % vars())]

    def codegenASTPlaceholderSubstitutionNode(self, node):
        placeholder = self.generate_python(self.build_code(node.expression)[0])
        return [CodeNode(ASTPlaceholderSubstitutionNode_tmpl[0] % vars(),
                         input_pos=node.pos)]

    def codegenASTDoNode(self, node):
        return [CodeNode(
            self.generate_python(self.build_code(node.expression)[0]),
            input_pos=node.pos)]

    def codegenASTCallFunctionNode(self, node):
        expression = self.generate_python(self.build_code(node.expression)[0])
        if expression == '_self_filter_function':
            self.function_stack[-1].uses_filter_function = True
        if expression == '_self_private_filter_function':
            self.function_stack[-1].uses_private_filter_function = True
        if node.arg_list:
            arg_list = self.generate_python(self.build_code(node.arg_list)[0])
        else:
            arg_list = ''
        call = ASTCallFunctionNode_tmpl[0] % vars()
        if self.baked_mode:
            sanitization_state = node.sanitization_state
            # For SANITIZED_STRING we could use SanitizedPlaceholder(), but the
            # mark_as_sanitized() function is faster so we use that instead.
            if (sanitization_state == ast.SanitizedState.SANITIZED_STRING or
                    sanitization_state == ast.SanitizedState.SANITIZED):
                return [CodeNode('mark_as_sanitized(%s)' % call,
                                 input_pos=node.pos)]
            elif (sanitization_state == ast.SanitizedState.UNSANITIZED or
                  sanitization_state == ast.SanitizedState.NOT_OUTPUTTED or
                  sanitization_state ==
                  ast.SanitizedState.OUTPUTTED_IMMEDIATELY):
                return [CodeNode(call, input_pos=node.pos)]
            elif sanitization_state == ast.SanitizedState.UNKNOWN:
                return [CodeNode(
                    'runtime_mark_as_sanitized(%(call)s, %(expression)s)' %
                    vars(),
                    input_pos=node.pos)]
        return [CodeNode(call, input_pos=node.pos)]

    def codegenASTForNode(self, node):
        target_list = self.generate_python(self.build_code(node.target_list)[0])
        expression_list = self.generate_python(self.build_code(
            node.expression_list)[0])
        code_node = CodeNode(ASTForNode_tmpl[0] % vars(), input_pos=node.pos)
        for n in node.child_nodes:
            code_node.extend(self.build_code(n))
        return [code_node]

    def codegenASTIfNode(self, node):
        test_expression = self.generate_python(self.build_code(
            node.test_expression)[0])
        if_code_node = CodeNode("if %(test_expression)s:" % vars(),
                                input_pos=node.pos)
        for n in node.child_nodes:
            if_code_node.extend(self.build_code(n))
        code_nodes = [if_code_node]
        if node.else_.child_nodes:
            else_code_node = CodeNode('else:')
            for n in node.else_.child_nodes:
                else_code_node.extend(self.build_code(n))
            code_nodes.append(else_code_node)
        return code_nodes

    def codegenASTTargetListNode(self, node):
        if len(node.child_nodes) == 1:
            return self.build_code(node.child_nodes[0])
        else:
            return [CodeNode('(%s)' % ', '.join([self.generate_python(
                self.build_code(n)[0]) for n in node.child_nodes]))]

    codegenASTExpressionListNode = codegenASTTargetListNode

    def codegenASTLiteralNode(self, node):
        if (self.options and not self.options.generate_unicode and
                isinstance(node.value, basestring)):
            # If the node is the empty string, we should mark it as sanitized by
            # default. Eventually, all string literals should be marked as
            # sanitized.
            if self.baked_mode and node.value == '':
                return [CodeNode("mark_as_sanitized('')", input_pos=node.pos)]

            return [CodeNode(
                repr(node.value.encode(self.ast_root.encoding)),
                input_pos=node.pos)]
        else:
            # generate unicode by default
            return [CodeNode('%(value)r' % vars(node), input_pos=node.pos)]

    def codegenASTListLiteralNode(self, node):
        return [CodeNode('[%s]' % ', '.join([
            self.generate_python(self.build_code(n)[
                0]) for n in node.child_nodes
        ]),
                         input_pos=node.pos)]

    def codegenASTTupleLiteralNode(self, node):
        return [CodeNode('(%s)' % ', '.join([
            self.generate_python(self.build_code(n)[
                0]) for n in node.child_nodes
        ]),
                         input_pos=node.pos)]

    def codegenASTDictLiteralNode(self, node):
        return [
            CodeNode('{%s}' % ', '.join([
                '%s: %s' % (self.generate_python(self.build_code(kn)[
                    0]), self.generate_python(self.build_code(vn)[0])
                           ) for kn, vn in node.child_nodes
            ]))
        ]

    def codegenASTParameterNode(self, node):
        if node.default:
            return [CodeNode('%s=%s' % (
                node.name,
                self.generate_python(self.build_code(node.default)[0])))]
        else:
            return [CodeNode('%s' % node.name)]

    def codegenASTAttributeNode(self, node):
        return [CodeNode('%s = %s' % (
            node.name, self.generate_python(self.build_code(node.default)[0])),
                         input_pos=node.pos)]

    def codegenASTFilterAttributeNode(self, node):
        return [CodeNode('%s = staticmethod(%s)' % (
            node.name, self.generate_python(self.build_code(node.default)[0])))]

    def codegenASTParameterListNode(self, node):
        if len(node.child_nodes) == 1:
            return self.build_code(node.child_nodes[0])
        else:
            return [CodeNode('%s' % ', '.join([self.generate_python(
                self.build_code(n)[0]) for n in node.child_nodes]))]

    codegenASTArgListNode = codegenASTParameterListNode

    def codegenASTGetUDNNode(self, node):
        #print ' '.join("codegenASTGetUDNNode", id(node), "name", node.name,
        #               "expr", node.expression)
        expression = self.generate_python(self.build_code(node.expression)[0])
        name = node.name
        if (self.options and self.options.default_to_strict_resolution and
                self.template and not self.template.use_loose_resolution):
            return [CodeNode("%(expression)s.%(name)s" % vars())]
        if self.options and self.options.raise_udn_exceptions:
            return [CodeNode(
                "resolve_udn(%(expression)s, '%(name)s', raise_exception=True)"
                % vars(),
                input_pos=node.pos)]
        else:
            return [CodeNode("resolve_udn(%(expression)s, '%(name)s')" % vars(),
                             input_pos=node.pos)]

    def codegenASTPlaceholderNode(self, node):
        name = node.name
        if name in ('has_var', 'get_var'):
            return [CodeNode("self.%(name)s" % vars())]
        elif self.options and self.options.cheetah_cheats:
            return [CodeNode("resolve_placeholder([locals()] + "
                             "_self_search_list, '%(name)s')" % vars(),
                             input_pos=node.pos)]
        elif self.options and self.options.omit_local_scope_search:
            self.function_stack[-1].uses_globals = True
            return [CodeNode("resolve_placeholder('%(name)s', self, _globals)" %
                             vars(),
                             input_pos=node.pos)]
        else:
            self.function_stack[-1].uses_globals = True
            return [CodeNode("resolve_placeholder_with_locals('%(name)s', "
                             "self, locals(), _globals)" % vars(),
                             input_pos=node.pos)]

    def codegenASTReturnNode(self, node):
        expression = self.generate_python(self.build_code(node.expression)[0])
        return [CodeNode("return %(expression)s" % vars(), input_pos=node.pos)]

    def codegenASTOptionalWhitespaceNode(self, node):
        #if self.ignore_optional_whitespace:
        #  return []
        return [CodeNode(ASTOptionalWhitespaceNode_tmpl[0] % vars(node),
                         input_pos=node.pos)]

    def codegenASTSliceNode(self, node):
        expression = self.generate_python(self.build_code(node.expression)[0])
        slice_expression = self.generate_python(self.build_code(
            node.slice_expression)[0])
        return [CodeNode("%(expression)s[%(slice_expression)s]" % vars())]

    def codegenASTBinOpExpressionNode(self, node):
        left = self.generate_python(self.build_code(node.left)[0])
        right = self.generate_python(self.build_code(node.right)[0])
        operator = node.operator
        return [CodeNode('(%(left)s %(operator)s %(right)s)' % vars(),
                         input_pos=node.pos)]

    def codegenASTBinOpNode(self, node):
        left = self.generate_python(self.build_code(node.left)[0])
        right = self.generate_python(self.build_code(node.right)[0])
        operator = node.operator
        return [CodeNode('%(left)s %(operator)s %(right)s' % vars(),
                         input_pos=node.pos)]

    codegenASTAssignNode = codegenASTBinOpNode

    def codegenASTUnaryOpNode(self, node):
        expression = self.generate_python(self.build_code(node.expression)[0])
        operator = node.operator
        return [CodeNode('(%(operator)s %(expression)s)' % vars(),
                         input_pos=node.pos)]

    def codegenASTGetAttrNode(self, node):
        expression = self.generate_python(self.build_code(node.expression)[0])
        name = node.name
        return [CodeNode("%(expression)s.%(name)s" % vars(),
                         input_pos=node.pos)]

    def codegenASTFunctionNode(self, node):
        name = node.name
        node.uses_globals = False
        node.uses_filter_function = False
        node.uses_private_filter_function = False
        node.uses_buffer_write = False
        node.uses_buffer_extend = False
        self.function_stack.append(node)
        if node.parameter_list:
            parameter_list = self.generate_python(self.build_code(
                node.parameter_list)[0])
        else:
            parameter_list = ''

        decorator_node = CodeNode('@template_method')
        # NOTE: for Cheetah compatibility, we have to handle the case where
        # Cheetah tries to pass a 'transaction' object through. hopefully this
        # doesn't have some other baggage coming with it.
        if self.options and self.options.cheetah_compatibility:
            if parameter_list:
                code_node = CodeNode(
                    'def %(name)s(%(parameter_list)s, **kargs):' % vars(),
                    input_pos=node.pos)
            else:
                code_node = CodeNode('def %(name)s(**kargs):' % vars(),
                                     input_pos=node.pos)
        else:
            code_node = CodeNode('def %(name)s(%(parameter_list)s):' % vars(),
                                 input_pos=node.pos)

        needs_globals_added = True
        child_nodes = node.child_nodes

        if self.options and self.options.cheetah_compatibility:
            if_cheetah = CodeNode("if 'trans' in kargs:")
            code_node.append(if_cheetah)
            if_cheetah.append(CodeNode("_buffer = kargs['trans'].response()"))
            else_spitfire = CodeNode('else:')
            else_spitfire.append(CodeNode('_buffer = self.new_buffer()'))
            code_node.append(else_spitfire)
        else:
            # If the first node is an if statement with no else AND there's no
            # other statements, generate the if code first.  That way, we can
            # avoid doing extra work when the condition is false.  ie, avoid the
            # overhead of creating a new list setting up useless local variables
            # and joining all to get an empty string. Disable this in baked mode
            # until I figure out how to handle this. TODO: Do not perform
            # sanitization inside of a test_expression. Then we can remove this
            # baked_mode check.
            if child_nodes and len(child_nodes) == 1 and not self.baked_mode:
                if_node = child_nodes[0]
                if isinstance(if_node,
                              ast.IfNode) and not if_node.else_.child_nodes:
                    child_nodes = if_node.child_nodes
                    # Insert code that does:
                    #   if not ($test_expression):
                    #     return ''
                    new_if_condition = ast.IfNode(ast.UnaryOpNode(
                        'not', if_node.test_expression))
                    new_if_condition.append(ast.ReturnNode(ast.LiteralNode('')))
                    new_code = self.build_code(new_if_condition)
                    if node.uses_globals:
                        needs_globals_added = False
                        code_node.append(CodeNode('_globals = globals()'))
                    code_node.extend(new_code)

            code_node.append(CodeNode('_buffer = self.new_buffer()'))

        # Save the point where _globals and self_filter_funtion will go if used.
        # We don't append these here because we have to determine if these two
        # functions are used in the scope of the current ast.FunctionNode.
        insertion_point = len(code_node.child_nodes)

        if self.options and self.options.cheetah_cheats:
            node.uses_globals = True
            if_cheetah = CodeNode('if self.search_list:')
            if_cheetah.append(CodeNode(
                '_self_search_list = self.search_list + [_globals]'))
            else_cheetah = CodeNode('else:')
            else_cheetah.append(CodeNode('_self_search_list = [_globals]'))
            code_node.append(if_cheetah)
            code_node.append(else_cheetah)

        for n in child_nodes:
            code_child_nodes = self.build_code(n)
            code_node.extend(code_child_nodes)

        if node.uses_globals and needs_globals_added:
            code_node.insert(insertion_point, CodeNode('_globals = globals()'))
            insertion_point += 1
        if node.uses_filter_function:
            code_node.insert(
                insertion_point,
                CodeNode('_self_filter_function = self.filter_function'))
            insertion_point += 1
        if node.uses_private_filter_function:
            code_node.insert(insertion_point, CodeNode(
                '_self_private_filter_function = self._filter_function'))
            insertion_point += 1
        if node.uses_buffer_write:
            code_node.insert(insertion_point,
                             CodeNode('_buffer_write = _buffer.write'))
            insertion_point += 1
        if node.uses_buffer_extend:
            code_node.insert(insertion_point,
                             CodeNode('_buffer_extend = _buffer.extend'))
        if self.options.cheetah_compatibility:
            if_cheetah = CodeNode("if 'trans' not in kargs:")
            if_cheetah.append(CodeNode('return _buffer.getvalue()'))
            code_node.append(if_cheetah)
        else:
            code_node.append(CodeNode('return _buffer.getvalue()'))
        self.function_stack.pop()
        return [decorator_node, code_node]

    # fixme: don't know if i still need this - a 'template function'
    # has an implicit return of the buffer built in - might be simpler
    # to code that rather than adding a return node during the analyze
    #def codegenASTReturnNode(self, node):
    #  code_node = self.codegenDefault(node)

    def codegenASTBufferWrite(self, node):
        self.function_stack[-1].uses_buffer_write = True
        expression = self.generate_python(self.build_code(node.expression)[0])
        code_node = CodeNode('_buffer_write(%(expression)s)' % vars(),
                             input_pos=node.pos)
        return [code_node]

    def codegenASTBufferExtend(self, node):
        self.function_stack[-1].uses_buffer_extend = True
        expression = self.generate_python(self.build_code(node.expression)[0])
        code_node = CodeNode('_buffer_extend(%(expression)s)' % vars(),
                             input_pos=node.pos)
        return [code_node]

    def codegenASTEchoNode(self, node):
        self.function_stack[-1].uses_buffer_write = True
        node_list = []

        true_expression = self.generate_python(self.build_code(
            node.true_expression)[0])
        true_code = CodeNode('_buffer_write(%(true_expression)s)' % vars())
        if node.test_expression:
            test_expression = self.generate_python(self.build_code(
                node.test_expression)[0])
            if_code = CodeNode('if %(test_expression)s:' % vars())
            if_code.append(true_code)
            node_list.append(if_code)
        else:
            node_list.append(true_code)

        if node.false_expression:
            false_expression = self.generate_python(self.build_code(
                node.false_expression)[0])
            else_code = CodeNode('else:' % vars())
            else_code.append(CodeNode('_buffer_write(%(false_expression)s)' %
                                      vars()))
            node_list.append(else_code)
        return node_list

    def codegenASTCacheNode(self, node):
        self.function_stack[-1].uses_globals = True
        cached_name = node.name
        expression = self.generate_python(self.build_code(node.expression)[0])
        # use dictionary syntax to get around coalescing 'global' statements
        #globalize_var = CodeNode('global %(cached_name)s' % vars())
        if_code = CodeNode("if %(cached_name)s is None:" % vars(),
                           input_pos=node.pos)
        if_code.append(
            CodeNode("_globals['%(cached_name)s'] = %(expression)s" % vars(),
                     input_pos=node.pos))
        return [if_code]

    def codegenASTFilterNode(self, node):
        expression = self.generate_python(self.build_code(node.expression)[0])
        if node.filter_function_node == ast.DefaultFilterFunction:
            # In baked mode, we must always call into _self_filter_function.
            # This is because this is the function that will contain the logic
            # for deciding whether or not to filter a SanitizedPlaceholder.
            if isinstance(node.expression,
                          ast.CallFunctionNode) or self.baked_mode:
                self.function_stack[-1].uses_filter_function = True
                filter_expression = '_self_filter_function'
            else:
                # Since there is no second argument to filter_function, there
                # will be a call to _filter_function. This optimization skips
                # the check and calls directly to _filter_function.
                self.function_stack[-1].uses_private_filter_function = True
                filter_expression = '_self_private_filter_function'
        elif node.filter_function_node:
            filter_expression = self.generate_python(self.build_code(
                node.filter_function_node)[0])
        else:
            filter_expression = None

        if isinstance(node.expression, ast.CallFunctionNode):
            # need the placeholder function expression to make sure that we
            # don't double escape the output of template functions
            # fixme: this is suboptimal if this expression is expensive -
            # should the optimizer fix this, or should we generate speedy code?
            placeholder_function_expression = self.generate_python(
                self.build_code(node.expression.expression)[0])
            if node.filter_function_node == ast.DefaultFilterFunction:
                code_node = CodeNode('%(filter_expression)s(%(expression)s, '
                                     '%(placeholder_function_expression)s)' %
                                     vars(),
                                     input_pos=node.pos)
            elif node.filter_function_node:
                code_node = CodeNode(
                    '%(filter_expression)s(self, '
                    '%(expression)s, %(placeholder_function_expression)s)' %
                    vars(),
                    input_pos=node.pos)
            else:
                code_node = CodeNode('%(expression)s' % vars(),
                                     input_pos=node.pos)
        else:
            if node.filter_function_node == ast.DefaultFilterFunction:
                code_node = CodeNode('%(filter_expression)s(%(expression)s)' %
                                     vars(),
                                     input_pos=node.pos)
            elif node.filter_function_node:
                code_node = CodeNode('%(filter_expression)s(%(expression)s)' %
                                     vars(),
                                     input_pos=node.pos)
            else:
                code_node = CodeNode('%(expression)s' % vars(),
                                     input_pos=node.pos)
        return [code_node]

    def codegenDefault(self, node):
        v = globals()
        try:
            return [CodeNode(line % vars(node))
                    for line in v['AST%s_tmpl' % node.__class__.__name__]]
        except KeyError, e:
            self.compiler.error(CodegenError("no codegen for %s %s" % (type(
                node), vars(node))))

    def codegen(self, node):
        return self.codegenDefault(node)[0]

run_tmpl = """

if __name__ == '__main__':
  import spitfire.runtime.runner
  spitfire.runtime.runner.run_template(%(classname)s)
"""

ASTFunctionNode_tmpl = ['def %(name)s(%(parameter_list)s):']

ASTCallFunctionNode_tmpl = ['%(expression)s(%(arg_list)s)']

ASTForNode_tmpl = ['for %(target_list)s in %(expression_list)s:']

ASTTargetNode_tmpl = ['%(name)s']

ASTIdentifierNode_tmpl = ['%(name)s']
ASTTemplateMethodIdentifierNode_tmpl = ['self.%(name)s']

ASTLiteralNode_tmpl = ['%(value)r']

ASTBreakNode_tmpl = ['break']

ASTContinueNode_tmpl = ['continue']

redpajama_set_name: RedPajamaGithub


text:
package service

import (
	"github.com/docker/cli/cli"
	"github.com/docker/cli/cli/command"
	"github.com/docker/cli/cli/command/completion"
	"github.com/docker/docker/api/types"
	"github.com/spf13/cobra"
)

// NewServiceCommand returns a cobra command for `service` subcommands
func NewServiceCommand(dockerCli command.Cli) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "service",
		Short: "Manage Swarm services",
		Args:  cli.NoArgs,
		RunE:  command.ShowHelp(dockerCli.Err()),
		Annotations: map[string]string{
			"version": "1.24",
			"swarm":   "manager",
		},
	}
	cmd.AddCommand(
		newCreateCommand(dockerCli),
		newInspectCommand(dockerCli),
		newPsCommand(dockerCli),
		newListCommand(dockerCli),
		newRemoveCommand(dockerCli),
		newScaleCommand(dockerCli),
		newUpdateCommand(dockerCli),
		newLogsCommand(dockerCli),
		newRollbackCommand(dockerCli),
	)
	return cmd
}

// CompletionFn offers completion for swarm services
func CompletionFn(dockerCli command.Cli) completion.ValidArgsFn {
	return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		list, err := dockerCli.Client().ServiceList(cmd.Context(), types.ServiceListOptions{})
		if err != nil {
			return nil, cobra.ShellCompDirectiveError
		}
		var names []string
		for _, service := range list {
			names = append(names, service.ID)
		}
		return names, cobra.ShellCompDirectiveNoFileComp
	}
}


text:
/**
 *
 * @param params
 * @returns {*}
 * @private
 */
jDoc.engines.ODF.prototype._parseTextDocumentTableRowNode = function (params) {
    var row = {
            cells: [],
            css: {},
            dimensionCSSRules: {}
        },
        j,
        c,
        cell,
        ccNodes,
        lllength,
        styleRules = {},
        cNodes = jDoc.DOM.children(params.node),
        length = cNodes.length;

    for (j = 0; j < length; j++) {
        if (cNodes[j].localName === "table-cell") {
            if (cNodes[j].attributes['table:style-name'] && cNodes[j].attributes['table:style-name'].value) {
                styleRules  = this._getStyleRules({
                    documentData: params.documentData,
                    styles: params.styles,
                    styleName: cNodes[j].attributes['table:style-name'].value,
                    elements: ['tableCell']
                });
            }

            cell = jDoc.deepMerge({
                elements: [],
                options: {}
            }, params.styles, styleRules.tableCell);
            ccNodes = jDoc.DOM.children(cNodes[j]);
            lllength = ccNodes.length;

            for (c = 0; c < lllength; c++) {
                if (ccNodes[c].localName === "p") {
                    cell.elements.push(this._parseTextDocumentParagraphNode({
                        node: ccNodes[c],
                        styles: params.styles,
                        documentData: params.documentData
                    }));
                }
            }
            row.cells.push(cell);
        }
    }

    return row;
};


text:
package com.socrata.geospace.lib.regioncache

import org.geoscript.geometry.{builder => build}
import org.geoscript.layer._

trait RegionCodingPerfTester {
  // Generates numPoints random points within the bounding box of layer, and times the georegion coding
  def benchmark(layer: Layer, numPoints: Int): Long = {
    val bbox = layer.getBounds

    println("Generating random points...")
    val points = Array.fill(numPoints)(build.Point(bbox.getMinX + util.Random.nextDouble * bbox.getWidth,
                                                   bbox.getMinY + util.Random.nextDouble * bbox.getHeight))

    println("Timing geo-region-coding...")
    val coder = SpatialIndex(layer)
    val startTime = System.currentTimeMillis
    var matches = 0
    for (i <- 0 until numPoints) {
      val regions = coder.firstContains(points(i))
      matches += regions.size
    }
    val endTime = System.currentTimeMillis

    println(s"$matches matches out of $numPoints")
    endTime - startTime
  }
}

/**
 * Benchmark geo region coding using a layer based on Shapefiles on disk.
 * This turns out to be really slow:
 *  - 49% of the time is mostly spent opening up .dbfs, loading and initializing the quadtree index
 *    for each point
 *  - 38% of the time is spent just seeking features on disk
 *  - 10% of the time is spent parsing the CQL query
 */
object RegionCodingPerfShapefileTest extends App with RegionCodingPerfTester {

  val shapefile = if (args.length > 0) args(0) else "data/chicago_wards/Wards.shp"
  val NumPoints = 50000

  println("Loading shapefile $shapefile...")
  val layer = Shapefile(shapefile)

  val millis = benchmark(layer, NumPoints)
  println(s"Coding $NumPoints points with shapefile $shapefile took $millis millis")
  println(s"Geo-region-coding speed: ${NumPoints / (millis / 1000.0)} points/sec/core")
}


text:
template<typename ...T> constexpr auto sum(T ...t) { return (... + t); }
template<typename ...T> constexpr auto product(T ...t) { return (t * ...); }
template<typename ...T> constexpr auto all(T ...t) { return (true && ... && t); }
template<typename ...T> constexpr auto all2(T ...t) { return (t && ... && true); }

int k1 = (1 + ... + 2); // expected-error {{does not contain any unexpanded parameter packs}}
int k2 = (1 + ...); // expected-error {{does not contain any unexpanded parameter packs}}
int k3 = (... + 2); // expected-error {{does not contain any unexpanded parameter packs}}

template<int ...N> void bad1() { (N + ... + N); } // expected-error {{unexpanded parameter packs in both operands}}
// FIXME: it would be reasonable to support this as an extension.
template<int ...N> void bad2() { (2 * N + ... + 1); } // expected-error {{expression not permitted as operand}}
template<int ...N> void bad3() { (2 + N * ... * 1); } // expected-error {{expression not permitted as operand}}
template<int ...N, int ...M> void bad4(int (&...x)[N]) { (N + M * ... * 1); } // expected-error {{expression not permitted as operand}}
template<int ...N, int ...M> void fixed4(int (&...x)[N]) { ((N + M) * ... * 1); }

// Parens are mandatory.
template<int ...N> void bad5() { N + ...; } // expected-error {{expected expression}} expected-error +{{}}
template<int ...N> void bad6() { ... + N; } // expected-error {{expected expression}}
template<int ...N> void bad7() { N + ... + N; } // expected-error {{expected expression}} expected-error +{{}}

// Must have a fold-operator in the relevant places.
template<int ...N> int bad8() { return (N + ... * 3); } // expected-error {{operators in fold expression must be the same}}
template<int ...N> int bad9() { return (3 + ... * N); } // expected-error {{operators in fold expression must be the same}}
template<int ...N> int bad10() { return (3 ? ... : N); } // expected-error +{{}} expected-note {{to match}}
template<int ...N> int bad11() { return (N + ... 0); } // expected-error {{expected a foldable binary operator}} expected-error {{expected expression}}
template<int ...N> int bad12() { return (... N); } // expected-error {{expected expression}}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.mybusinessaccountmanagement.v1.model;

/**
 * Additional information stored for an organization.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the My Business Account Management API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class OrganizationInfo extends com.google.api.client.json.GenericJson {

  /**
   * Output only. The postal address for the account.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private PostalAddress address;

  /**
   * Output only. The contact number for the organization.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String phoneNumber;

  /**
   * Output only. The registered domain for the account.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String registeredDomain;

  /**
   * Output only. The postal address for the account.
   * @return value or {@code null} for none
   */
  public PostalAddress getAddress() {
    return address;
  }

  /**
   * Output only. The postal address for the account.
   * @param address address or {@code null} for none
   */
  public OrganizationInfo setAddress(PostalAddress address) {
    this.address = address;
    return this;
  }

  /**
   * Output only. The contact number for the organization.
   * @return value or {@code null} for none
   */
  public java.lang.String getPhoneNumber() {
    return phoneNumber;
  }

  /**
   * Output only. The contact number for the organization.
   * @param phoneNumber phoneNumber or {@code null} for none
   */
  public OrganizationInfo setPhoneNumber(java.lang.String phoneNumber) {
    this.phoneNumber = phoneNumber;
    return this;
  }

  /**
   * Output only. The registered domain for the account.
   * @return value or {@code null} for none
   */
  public java.lang.String getRegisteredDomain() {
    return registeredDomain;
  }

  /**
   * Output only. The registered domain for the account.
   * @param registeredDomain registeredDomain or {@code null} for none
   */
  public OrganizationInfo setRegisteredDomain(java.lang.String registeredDomain) {
    this.registeredDomain = registeredDomain;
    return this;
  }

  @Override
  public OrganizationInfo set(String fieldName, Object value) {
    return (OrganizationInfo) super.set(fieldName, value);
  }

  @Override
  public OrganizationInfo clone() {
    return (OrganizationInfo) super.clone();
  }

}


text:
> version 2.0.0

This repo consists in the development of the second version of my personal portfolio

## Development environment

To setup the development environment, it is necessary to install:
- Ruby
- Jekyll 3.x
- jekyll-sitemap
- gemoji
- jekyll-pagination
- jekyll-paginate
- jekyll-frontmatter-jsonify

## Production ready
Run `JEKYLL_ENV=production bundle exec jekyll serve` in order to serve as a production environment. This has a major effect in the `site.url`.

## License
The project is licensed under **The MIT License (MIT)**, see the LICENSE file for more details.


text:
INSERT INTO authorised_system (host, description, version)
    SELECT host, description, version
    FROM (SELECT @ip as host, @description as description, 1 as version) t
    WHERE NOT EXISTS (SELECT 1 FROM authorised_system a WHERE a.host = t.host);


text:
@implementation NewsModel

//+(instancetype)newsWithDict:(NSDictionary *)dict{
//
//    id obj = [[self alloc]init];
//
//    // 手动遍历需要的数据
//    NSArray *propertis = [self loadList];
//    for (NSString *key in propertis) {
//        if (dict[key] != nil) {
//            [obj setValue:dict[key] forKeyPath:key];
//        }
//    }
//    //    [obj setValuesForKeysWithDictionary:dict];
//    return obj;
//}

// 数据完整显示
-(NSString *)description{
    NSArray *propertis = [self.class loadList];
    NSDictionary *dict = [self dictionaryWithValuesForKeys:propertis];

    return [NSString stringWithFormat:@"%@,%p,%@",self.class,self,dict];
}

//统一调用这个方法遍历模型数据
// 利用关联对象,给类添加属性,OC中的类,本身就是一个特殊对象
//const char *kPropertyKey = "PropertyKey";
//+(NSArray *)loadList{
//
//   NSArray *arrayKey = objc_getAssociatedObject(self, kPropertyKey);
//    if (arrayKey != nil) {
//        return arrayKey;
//    }
//
//    unsigned int count = 0;
//
//   objc_property_t *list = class_copyPropertyList([self class], &count);
//
//    //遍历数组,动态获取属性名称
//    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:count];
//
//    for (unsigned int i = 0; i < count; ++i) {
//
//        objc_property_t pry = list[i];
//
//        const char *cName = property_getName(pry);
//
//        [arrayM addObject:[NSString stringWithUTF8String:cName]];
//    }
//    NSLog(@"%@",arrayM);
//
//    free(list);
//
//    objc_setAssociatedObject(self, kPropertyKey, arrayM, OBJC_ASSOCIATION_COPY_NONATOMIC);
//
//    return objc_getAssociatedObject(self, kPropertyKey);
//}

//网络数据接口
+(void)loadNewsListWithUrlString:(NSString *)urlString finished:(void (^)(NSArray *))finished{

    NSAssert(finished != nil, @"断言:必须传入完成回调");

    [[ANetworkTools sharedNetworkTools] GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {

        //keyEnumerator 这个属性可以拿到字典中的第一个 Key
//        NSLog(@"%@",responseObject.keyEnumerator.nextObject);

        NSArray *array = responseObject[responseObject.keyEnumerator.nextObject];
        NSLog(@"删选后的数据%@",array);

        // 字典转模型
        NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];

        for (NSDictionary *obj in array) {
            [arrayM addObject:[self objWithDict:obj]];

        }
//        NSLog(@"字典转模型%@", arrayM);
        finished (arrayM.copy);

//        NSLog(@"成功回调:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"失败:%@",error);
    }];

}

@end


text:
import React, { Component } from 'react';
import Clipboard from 'clipboard';

class GeneratedIpsum extends Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonText: 'Click to Copy'
    }
  }
  render() {
    const { speech, paragraphs} = this.props;
    const ipsumChunks = [];
    const clipboard = new Clipboard('.copy-btn');

    clipboard.on('success', (e) => {
      this.setState({
        buttonText: 'Copied!'
      })
    });

    for(var i = 0; i < paragraphs; i++) {
      let index = 0;
      let length = speech.length

      if ( i < length) {
        index = i;

      } else {
        let remainder = i % length;
        index = remainder;
      }

      let paragraph =
{speech[index]}

      ipsumChunks.push(paragraph);
    }

    return(

3. Copy Pasta

          { this.state.buttonText }

          { ipsumChunks }

    );
  }
}

export default GeneratedIpsum;


text:
package org.ldp4j.application.data;

import java.io.Serializable;
import java.net.URI;
import java.util.List;

import com.google.common.collect.Lists;

final class DataSetHelperImpl extends DataSetHelper {

	private final class IndividualRenamer implements TripleConsumer {

		private final Individual<?, ?> from;
		private final Individual<?, ?> to;

		private IndividualRenamer(final Individual<?, ?> from, final Individual<?, ?> to) {
			this.from = from;
			this.to = to;
		}

		@Override
		public void consume(final Individual<?, ?> subject, final URI predicate, final Literal<?> object) {
			if(subject==this.from) {
				this.to.addValue(predicate,object);
			}
		}

		@Override
		public void consume(final Individual<?, ?> subject, final URI predicate, final Individual<?, ?> object) {
			if(subject==this.from) {
				Value value=object;
				if(value==this.from) {
					value=this.to;
				}
				this.to.addValue(predicate,value);
			} else if(subject!=this.to && object==this.from) {
				subject.removeValue(predicate, object);
				subject.addValue(predicate,this.to);
			}
		}
	}

	private static class DataSetIterator{

		private static final class TripleConsumerAdapter implements ValueVisitor {
			private final Individual<?, ?> individual;
			private final DataSetHelperImpl.TripleConsumer consumer;
			private final URI predicate;

			private TripleConsumerAdapter(final Property property, final Individual<?, ?> individual, final DataSetHelperImpl.TripleConsumer consumer) {
				this.predicate  = property.predicate();
				this.individual = individual;
				this.consumer   = consumer;
			}

			@Override
			public void visitLiteral(final Literal<?> value) {
				this.consumer.consume(this.individual,this.predicate,value);
			}

			@Override
			public void visitIndividual(final Individual<?, ?> value) {
				this.consumer.consume(this.individual,this.predicate,value);
			}

		}

		private final DataSet dataSet;

		private DataSetIterator(final DataSet dataSet) {
			this.dataSet = dataSet;
		}

		void iterate(final DataSetHelperImpl.TripleConsumer processor) {
			for(final Individual<?,?> individual:this.dataSet) {
				for(final Property property:individual) {
					final DataSetIterator.TripleConsumerAdapter visitor = new TripleConsumerAdapter(property,individual, processor);
					for(final Value value:property) {
						value.accept(visitor);
					}
				}
			}
		}

	}

	private static final class NewIndividualIdCollector implements IndividualVisitor {

		private final List<URI> newIds=Lists.newArrayList();
		private final ManagedIndividualId id;

		private boolean hasSelf=false;
		private boolean idInUse=false;

		private NewIndividualIdCollector(final ManagedIndividualId id) {
			this.id = id;
		}

		@Override
		public void visitManagedIndividual(final ManagedIndividual individual) {
			this.idInUse=this.id.equals(individual.id());
		}

		@Override
		public void visitRelativeIndividual(final RelativeIndividual individual) {
			// Nothing to do
		}

		@Override
		public void visitLocalIndividual(final LocalIndividual individual) {
			// Nothing to do
		}

		@Override
		public void visitExternalIndividual(final ExternalIndividual individual) {
			// Nothing to do
		}

		@Override
		public void visitNewIndividual(final NewIndividual individual) {
			final URI path=individual.path();
			this.hasSelf=this.hasSelf || path.equals(SELF);
			this.newIds.add(path);
		}

		List<URI> getCollectedIds() throws DataSetModificationException {
			if(!this.hasSelf) {
				throw new DataSetModificationException("No default new individual defined");
			}
			return this.newIds;
		}

		void collect(final Individual<?, ?> individual) throws DataSetModificationException {
			individual.accept(this);
			if(this.idInUse) {
				throw new DataSetModificationException("The data set already has an individual identified as '"+this.id+"'");
			}
		}

	}

	private final DataSet dataSet;

	DataSetHelperImpl(final DataSet dataSet) {
		this.dataSet = dataSet;
	}

	private void rename(final Individual<?,?> from, final Individual<?,?> to) {
		final DataSetIterator iterator = new DataSetIterator(this.dataSet);
		final TripleConsumer consumer = new IndividualRenamer(from, to);
		iterator.iterate(consumer);
		this.dataSet.remove(from);
	}

	private List<URI> getNewIds(final ManagedIndividualId id) throws DataSetModificationException {
		final NewIndividualIdCollector collector=new NewIndividualIdCollector(id);
		for(final Individual<?,?> individual:this.dataSet) {
			collector.collect(individual);
		}
		return collector.getCollectedIds();
	}

	@Override
	public <T extends Serializable, S extends Individual<T, S>>  S replace(final Serializable from, final T to, final Class<? extends S> clazz) {
		S target=null;
		final Individual<?, ?> src=this.dataSet.individualOfId(from);
		if(src!=null) {
			target=this.dataSet.individual(to, clazz);
			rename(src,target);
		}
		return target;

	}

	@Override
	public ManagedIndividual manage(final ManagedIndividualId id) throws DataSetModificationException {
		final List<URI> newIds=getNewIds(id);
		newIds.remove(SELF);
		final ManagedIndividual self=replace(SELF,id,ManagedIndividual.class);
		for(final URI newId:newIds) {
			final RelativeIndividualId relativeId=RelativeIndividualId.createId(id, newId);
			replace(newId,relativeId,RelativeIndividual.class);
		}
		return self;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends Individual<URI,T>> T self() {
		return (T)relative(SELF);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends Individual<URI,T>> T relative(final URI path) {
		return (T)this.dataSet.individualOfId(path);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IndividualHelper managedIndividual(final Name<?> name, final String managerId) {
		final ManagedIndividualId individualId = ManagedIndividualId.createId(name,managerId);
		final ManagedIndividual individual = this.dataSet.individual(individualId, ManagedIndividual.class);
		return new IndividualHelperImpl(individual);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IndividualHelper relativeIndividual(final Name<?> name, final String managerId, final URI path) {
		final ManagedIndividualId parentId = ManagedIndividualId.createId(name,managerId);
		final RelativeIndividualId individualId=RelativeIndividualId.createId(parentId, path);
		final RelativeIndividual individual = this.dataSet.individual(individualId, RelativeIndividual.class);
		return new IndividualHelperImpl(individual);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IndividualHelper localIndividual(final Name<?> name) {
		@SuppressWarnings("rawtypes")
		final
		LocalIndividual individual = this.dataSet.individual((Name)name, LocalIndividual.class);
		return new IndividualHelperImpl(individual);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IndividualHelper externalIndividual(final URI uri) {
		Individual<?, ?> individual=null;
		if(uri.isAbsolute()) {
			individual=this.dataSet.individual(uri, ExternalIndividual.class);
		} else {
			individual=this.dataSet.individual(uri, NewIndividual.class);
		}
		return new IndividualHelperImpl(individual);
	}

}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends MX_Controller {

	function __construct() {
		parent::__construct();
		/* !!!!!! Warning !!!!!!!11
		 *  admin panel initialization
		 *  do not over-right or remove auth_panel/auth_panel_ini/auth_ini
		 */
		$this->load->helper('aul');
		modules::run('auth_panel/auth_panel_ini/auth_ini');
		$this->load->library('form_validation', 'uploads');
		$this->load->model("backend_user");
		$this->load->model("counter_model");
	}

	public function index() {
		$user_data = $this->session->userdata('active_user_data');
		$view_data['roles'] = $user_data->roles;
		$view_data['total_user'] = $this->counter_model->counter_total_users();
		$view_data['total_user_today'] = $this->counter_model->counter_total_users_today();

		$view_data['total_listed_cars'] = $this->counter_model->counter_total_listed_cars();
		$view_data['total_listed_cars_today'] = $this->counter_model->counter_total_listed_cars_today();

		$view_data['total_rental_request'] = $this->counter_model->counter_total_rental_requests();
		$view_data['total_rental_requests_today'] = $this->counter_model->counter_total_rental_requests_today();

		$view_data['total_booking'] = $this->counter_model->counter_total_booking();
		$view_data['total_booking_today'] = $this->counter_model->counter_total_booking_today();

		$data['page_data'] = $this->load->view('admin/WELCOME_PAGE_' . $user_data->roles, $view_data, TRUE);
		$data['page_title'] = "welcome page";
		echo modules::run('auth_panel/template/call_default_template', $data);
	}

	public function user_list() {
		$data['page_title'] = "user list";
		$data['page_data'] = $this->load->view('admin/user_list/user_list', '', TRUE);
		echo modules::run(AUTH_DEFAULT_TEMPLATE, $data);
	}

	public function create_backend_user() {

		if ($this->input->post()) {
			$this->form_validation->set_rules('username', 'User Name', 'required|trim|is_unique[backend_user.username]');
			$this->form_validation->set_rules('password', 'Password', 'required|trim');
			$this->form_validation->set_rules('email', 'Email', 'required|trim|is_unique[backend_user.email]');
			$this->form_validation->set_rules('role', 'Role', 'required|trim');
			if ($this->form_validation->run() == False) {

			} else {
				$username = $this->input->post('username');
				$password = $this->input->post('password');
				$email = $this->input->post('email');
				$role = $this->input->post('role');
				$insert_array = array(
					'username' => $username,
					'email' => $email,
					'password' => md5($password),
					'roles' => $role,
					'creation_time' => time()
				);
				$insetData = $this->backend_user->create_backend_user($insert_array);
				if ($insetData == true) {
					$this->session->set_flashdata('success_message', 'User has been created succssfully');
				} else {
					$this->session->set_flashdata('error_message', 'User not created');
				}
			}
		}
		$view_data = array();
		$data['page_data'] = $this->load->view('admin/backend_user/create_new_backend_user', $view_data, TRUE);
		echo modules::run(AUTH_DEFAULT_TEMPLATE, $data);
	}

	public function backend_user_list() {

		$data['page_title'] = "Backend User List";
		$data['page_data'] = $this->load->view('admin/backend_user/backend_user_list', '', TRUE);
		echo modules::run(AUTH_DEFAULT_TEMPLATE, $data);
	}

	public function ajax_backend_user_list() {
		// storing  request (ie, get/post) global array to a variable
		$requestData = $_REQUEST;

		$columns = array(
			// datatable column index  => database column name
			0 => 'username',
			1 => 'email',
			2 => 'roles',
			3 => 'user_state'
		);

		$query = "SELECT count(id) as total
								FROM urend_backend_user where status != 2
								";
		$query = $this->db->query($query);
		$query = $query->row_array();
		$totalData = (count($query) > 0) ? $query['total'] : 0;
		$totalFiltered = $totalData;

		$sql = "SELECT * ,
											case status
											when '0' then 'Active'
											when '1' then 'Blocked'
											end as user_state
								FROM urend_backend_user   where status != 2 ";

		// getting records as per search parameters
		if (!empty($requestData['columns'][0]['search']['value'])) {   //name
			$sql.=" AND username LIKE '" . $requestData['columns'][0]['search']['value'] . "%' ";
		}
		if (!empty($requestData['columns'][1]['search']['value'])) {  //salary
			$sql.=" AND email LIKE '" . $requestData['columns'][1]['search']['value'] . "%' ";
		}
		if (!empty($requestData['columns'][2]['search']['value'])) {  //salary
			$sql.=" AND roles LIKE '" . $requestData['columns'][2]['search']['value'] . "%' ";
		}
		if (!empty($requestData['columns'][3]['search']['value'])) {  //salary
			$sql.=" having user_state LIKE '" . $requestData['columns'][3]['search']['value'] . "%' ";
		}

		$query = $this->db->query($sql)->result();

		$totalFiltered = count($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.

		$sql.=" ORDER BY " . $columns[$requestData['order'][0]['column']] . "   " . $requestData['order'][0]['dir'] . "   LIMIT " . $requestData['start'] . " ," . $requestData['length'] . "   ";  // adding length

		$result = $this->db->query($sql)->result();
		$data = array();
		foreach ($result as $r) {  // preparing an array
			$nestedData = array();

			$nestedData[] = $r->username;
			$nestedData[] = $r->email;
			$nestedData[] = $r->roles;
			$nestedData[] = $r->user_state;
			$action = "id . "'>Edit "
				. "id . "'>Delete ";
			if ($r->user_state == 'Active') {
				$action .= "id . "/1'>Block";
			} else {
				$action .= "id . "/0'>Unblock";
			}
			$nestedData[] = $action;

			$data[] = $nestedData;
		}

		$json_data = array(
			"draw" => intval($requestData['draw']), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
			"recordsTotal" => intval($totalData), // total number of records
			"recordsFiltered" => intval($totalFiltered), // total number of records after searching, if there is no searching then totalFiltered = totalData
			"data" => $data   // total data array
		);

		echo json_encode($json_data);  // send data as json format
	}

	public function edit_backend_user($id = null) {
		if (!$this->input->post()) {
			if($this->input->get('password_change')){

				$data['page_toast'] = 'Password changed successfully.';
				$data['page_toast_type'] = 'success';
				$data['page_toast_title'] = 'Action performed.';
			}
			$view_data['user_data'] = $this->backend_user->get_user_data($id);
			$data['page_data'] = $this->load->view('admin/backend_user/edit_backend_user', $view_data, TRUE);
			echo modules::run(AUTH_DEFAULT_TEMPLATE, $data);
		} else {
			if ($this->input->post()) {
				$this->form_validation->set_rules('username', 'User Name', 'required|trim');
				$this->form_validation->set_rules('email', 'Email', 'required|trim');
				$this->form_validation->set_rules('role', 'Role', 'required|trim');
				if ($this->form_validation->run() == False) {

				} else {
					$id = $this->input->post('id');
					$username = $this->input->post('username');
					$email = $this->input->post('email');
					$role = $this->input->post('role');
					$update_array = array(
						'username' => $username,
						'email' => $email,
						'roles' => $role,
						'updated_time' => time()
					);
					$update_data = $this->backend_user->update_backend_user($update_array, $id);
					if ($update_data == true) {
						$this->session->set_flashdata('success_message', 'User has been Updated succssfully');
					} else {
						$this->session->set_flashdata('error_message', 'User not Updated');
					}
					redirect(AUTH_PANEL_URL . 'admin/backend_user_list');
				}
			}
		}
	}

	public function delete_backend_user($id) {
		$delete_user = $this->backend_user->delete_backend_user($id);
		if ($update_data == true) {
			$this->session->set_flashdata('success_message', 'User has been Deleted succssfully');
		} else {
			$this->session->set_flashdata('error_message', 'User not Deleted');
		}
		redirect(AUTH_PANEL_URL . 'admin/backend_user_list');
	}

	public function block_backend_user($id, $status) {
		$delete_user = $this->backend_user->block_backend_user($id, $status);
		if ($update_data == true) {
			$this->session->set_flashdata('success_message', 'User has been Deleted succssfully');
		} else {
			$this->session->set_flashdata('error_message', 'User not Deleted');
		}
		redirect(AUTH_PANEL_URL . 'admin/backend_user_list');
	}

	public function change_password_backend_user(){
		$id= $this->input->post('id');
		if($this->input->post('new_password') != ''){
			$update_data = $this->backend_user->change_password_backend_user($this->input->post());
		}
		redirect(AUTH_PANEL_URL . "admin/edit_backend_user/$id?password_change=true");
	}

}


text:
module Day4.TheIdealStockingStuffer
    ( mineAdventCoin
    ) where

import           Data.Digest.Pure.MD5 (md5)
import qualified Data.ByteString.Lazy.Char8 as B

mineAdventCoin :: Int -> String -> Int
mineAdventCoin prefix secret = head $ filter (isValid . calcMD5Hash secret) [1..]
  where isValid dig = take prefix dig == replicate prefix '0'

calcMD5Hash :: String -> Int -> String
calcMD5Hash secret i = show . md5 . B.pack $ secret ++ show i


text:
package com.bitdubai.fermat_p2p_plugin.layer.ws.communications.cloud.server.developer.bitdubai.version_1.structure.processors;

import com.bitdubai.fermat_api.layer.all_definition.components.interfaces.DiscoveryQueryParameters;
import com.bitdubai.fermat_api.layer.all_definition.components.interfaces.PlatformComponentProfile;
import com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.AsymmectricCryptography;
import com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.ECCKeyPair;
import com.bitdubai.fermat_api.layer.all_definition.network_service.enums.NetworkServiceType;
import com.bitdubai.fermat_api.layer.all_definition.components.enums.PlatformComponentType;
import com.bitdubai.fermat_p2p_api.layer.all_definition.communication.commons.components.DiscoveryQueryParametersCommunication;
import com.bitdubai.fermat_p2p_api.layer.all_definition.communication.commons.components.PlatformComponentProfileCommunication;
import com.bitdubai.fermat_p2p_api.layer.all_definition.communication.commons.contents.FermatPacketCommunicationFactory;
import com.bitdubai.fermat_p2p_api.layer.all_definition.communication.commons.contents.FermatPacketEncoder;
import com.bitdubai.fermat_p2p_api.layer.p2p_communication.commons.contents.FermatPacket;
import com.bitdubai.fermat_p2p_api.layer.p2p_communication.commons.enums.FermatPacketType;
import com.bitdubai.fermat_p2p_api.layer.p2p_communication.commons.enums.JsonAttNamesConstants;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.java_websocket.WebSocket;

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

/**
 * The Class com.bitdubai.fermat_p2p_plugin.layer.ws.communications.cloud.server.developer.bitdubai.version_1.structure.processors.RequestListComponentRegisterPacketProcessor implement
 * the logic to process the packet when a packet type com.bitdubai.fermat_p2p_api.layer.p2p_communication.commons.enums.FermatPacketType.REQUEST_LIST_COMPONENT_REGISTERED is receive by the server.
 *

 * Created by Roberto Requena - (rart3001@gmail.com) on 06/09/15.
 *
 * @version 1.0
 * @since Java JDK 1.7
 */
public class RequestListComponentRegisterPacketProcessor extends FermatPacketProcessor {

    /**
     * (no-javadoc)
     * @see FermatPacketProcessor#processingPackage(WebSocket, FermatPacket, ECCKeyPair)
     */
    @Override
    public void processingPackage(WebSocket clientConnection, FermatPacket receiveFermatPacket, ECCKeyPair serverIdentity) {

        System.out.println(" --------------------------------------------------------------------- ");
        System.out.println("RequestListComponentRegisterPacketProcessor - Starting processingPackage");

        /*
         * Get the filters from the message content and decrypt
         */
        String messageContentJsonStringRepresentation = AsymmectricCryptography.decryptMessagePrivateKey(receiveFermatPacket.getMessageContent(), serverIdentity.getPrivateKey());

        /*
         * Construct the json object
         */
        Gson gson = new Gson();
        DiscoveryQueryParameters discoveryQueryParameters = new DiscoveryQueryParametersCommunication().fromJson(messageContentJsonStringRepresentation);

        /*
         * hold the result list
         */
        List<PlatformComponentProfile> resultList = null;

        if (discoveryQueryParameters.getFromOtherPlatformComponentType() == null &&
                discoveryQueryParameters.getFromOtherNetworkServiceType() == null){

            resultList = applyDiscoveryQueryParameters(discoveryQueryParameters, receiveFermatPacket);

        }else{

            resultList = applyDiscoveryQueryParametersFromOtherComponent(discoveryQueryParameters, receiveFermatPacket);

        }

        System.out.println("RequestListComponentRegisterPacketProcessor - filteredLis.size() ="+resultList.size());

        /*
         * Convert the list to json representation
         */
        String jsonListRepresentation = gson.toJson(resultList, new TypeToken<List<PlatformComponentProfileCommunication>>(){ }.getType());

        /*
         * Create the respond
         */
        JsonObject jsonObjectRespond = new JsonObject();
        jsonObjectRespond.addProperty(JsonAttNamesConstants.JSON_ATT_NAME_COMPONENT_TYPE,       discoveryQueryParameters.getPlatformComponentType().toString());
        jsonObjectRespond.addProperty(JsonAttNamesConstants.JSON_ATT_NAME_NETWORK_SERVICE_TYPE, discoveryQueryParameters.getNetworkServiceType().toString());
        jsonObjectRespond.addProperty(JsonAttNamesConstants.JSON_ATT_NAME_RESULT_LIST,          jsonListRepresentation);

         /*
         * Construct a fermat packet whit the list
         */
        FermatPacket fermatPacketRespond = FermatPacketCommunicationFactory.constructFermatPacketEncryptedAndSinged(receiveFermatPacket.getSender(),                    //Destination
                                                                                serverIdentity.getPublicKey(),                      //Sender
                                                                                gson.toJson(jsonObjectRespond),                     //Message Content
                                                                                FermatPacketType.REQUEST_LIST_COMPONENT_REGISTERED, //Packet type
                                                                                serverIdentity.getPrivateKey());                    //Sender private key
        /*
        * Send the encode packet to the server
        */
        clientConnection.send(FermatPacketEncoder.encode(fermatPacketRespond));
    }

    /**
     * Return the primary list from the cache filtered by the platformComponentType or
     * networkServiceType
     *
     * @param platformComponentType
     * @param networkServiceType
     * @return List<PlatformComponentProfile>
     */
    public List<PlatformComponentProfile> getPrimaryFilteredListFromCache(PlatformComponentType platformComponentType, NetworkServiceType networkServiceType, FermatPacket receiveFermatPacket){

        /*
         * Get the list
         */
        List<PlatformComponentProfile> list = null;

         /*
         * Switch between platform component type
         */
        switch (platformComponentType.getCode()){

            //COMMUNICATION_CLOUD_SERVER_COMPONENT;
            case "COM_CLD_SER_COMP" :
                list = new ArrayList<>(getWsCommunicationCloudServer().getRegisteredCommunicationsCloudServerCache().values());
                break;

            //COMMUNICATION_CLOUD_CLIENT_COMPONENT
            case "COM_CLD_CLI_COMP" :
                list = new ArrayList<>(getWsCommunicationCloudServer().getRegisteredCommunicationsCloudClientCache().values());
                break;

            //NETWORK_SERVICE_COMPONENT
            case "NS_COMP" :
                list = new ArrayList<>(getWsCommunicationCloudServer().getRegisteredNetworkServicesCache().get(networkServiceType));
                break;

            //Others
            default :
                list = getWsCommunicationCloudServer().getRegisteredPlatformComponentProfileCache().get(platformComponentType);
                break;

        }

        /*
         * Remove the requester from the list
         */
        for (PlatformComponentProfile platformComponentProfileRegistered: list) {
            if(platformComponentProfileRegistered.getCommunicationCloudClientIdentity().equals(receiveFermatPacket.getSender())){
                list.remove(platformComponentProfileRegistered);
                break;
            }
        }

        return list;
    }

    /**
     * Filter the PlatformComponentProfile that match with the discoveryQueryParameters
     *
     * @param discoveryQueryParameters
     * @param receiveFermatPacket
     * @return List<PlatformComponentProfile>
     */
    private  List<PlatformComponentProfile> applyDiscoveryQueryParameters(DiscoveryQueryParameters discoveryQueryParameters, FermatPacket receiveFermatPacket){

        int totalFilterToApply = countFilers(discoveryQueryParameters);
        int filterMatched = 0;

        List<PlatformComponentProfile>  list = getPrimaryFilteredListFromCache(discoveryQueryParameters.getPlatformComponentType(), discoveryQueryParameters.getNetworkServiceType(), receiveFermatPacket);
        List<PlatformComponentProfile>  filteredLis = new ArrayList<>();

        System.out.println("RequestListComponentRegisterPacketProcessor - totalFilterToApply    = "+totalFilterToApply);

        if (totalFilterToApply > 0){

            /*
             * Apply the basic filter
             */
            for (PlatformComponentProfile platformComponentProfile: list) {

                if (discoveryQueryParameters.getIdentityPublicKey() != null && discoveryQueryParameters.getIdentityPublicKey() != ""){
                    if (platformComponentProfile.getIdentityPublicKey() == discoveryQueryParameters.getIdentityPublicKey()){
                        filterMatched += 1;
                    }
                }

                if (discoveryQueryParameters.getAlias() != null && discoveryQueryParameters.getAlias() != ""){
                    if (platformComponentProfile.getAlias() == discoveryQueryParameters.getAlias()){
                        filterMatched += 1;
                    }
                }

                if (discoveryQueryParameters.getName() != null && discoveryQueryParameters.getName() != ""){
                    if (platformComponentProfile.getName() == discoveryQueryParameters.getName()){
                        filterMatched += 1;
                    }
                }

                if (discoveryQueryParameters.getExtraData() != null && discoveryQueryParameters.getExtraData() != ""){
                    if (platformComponentProfile.getExtraData() == discoveryQueryParameters.getExtraData()){
                        filterMatched += 1;
                    }
                }

                //if all filter matched
                if (totalFilterToApply == filterMatched){
                    //Add to the list
                    filteredLis.add(platformComponentProfile);
                }

            }

        }else {

            filteredLis = list;
        }

        /*
         * Apply geo location filter
         */
        if (discoveryQueryParameters.getLocation() != null &&
                discoveryQueryParameters.getLocation().getLatitude() != 0 &&
                    discoveryQueryParameters.getLocation().getLongitude() != 0){

        }

        if ((discoveryQueryParameters.getNumberRegister() != 0) && (discoveryQueryParameters.firstRecord() != 0)){

            /*
             * Apply pagination
             */
            if (filteredLis.size() > discoveryQueryParameters.getNumberRegister() &&
                    filteredLis.size() > discoveryQueryParameters.firstRecord()){
                filteredLis =  filteredLis.subList(discoveryQueryParameters.firstRecord(), discoveryQueryParameters.getNumberRegister());
            }else if (filteredLis.size() > 100) {
                filteredLis = filteredLis.subList(discoveryQueryParameters.firstRecord(), 100);
            }

        }else if (filteredLis.size() > 100) {
            filteredLis = filteredLis.subList(0, 100);
        }

        return filteredLis;

    }

    /**
     * Filter the PlatformComponentProfiles that match with the discoveryQueryParameters that get from other component
     *
     * @param discoveryQueryParameters
     * @param receiveFermatPacket
     * @return List<PlatformComponentProfile>
     */
    private  List<PlatformComponentProfile> applyDiscoveryQueryParametersFromOtherComponent(DiscoveryQueryParameters discoveryQueryParameters, FermatPacket receiveFermatPacket){

        List<PlatformComponentProfile>  filteredListFromOtherComponentType = new ArrayList<>();
        List<PlatformComponentProfile>  finalFilteredList = new ArrayList<>();

        /*
         * Get the list from the cache that match with the other componet
         */
        List<PlatformComponentProfile>  list = getPrimaryFilteredListFromCache(discoveryQueryParameters.getFromOtherPlatformComponentType(), discoveryQueryParameters.getFromOtherNetworkServiceType(), receiveFermatPacket);

        /*
         * Find the other component that match with the identity
         */
        for (PlatformComponentProfile platformComponentProfile: list) {

            if (discoveryQueryParameters.getIdentityPublicKey() != null && discoveryQueryParameters.getIdentityPublicKey() != ""){
                if (platformComponentProfile.getIdentityPublicKey() == discoveryQueryParameters.getIdentityPublicKey()){
                    filteredListFromOtherComponentType.add(platformComponentProfile);
                }
            }

        }

         /*
         * Get the list from the cache that match with the componet that made the request, to find his same type
         */
         list = getPrimaryFilteredListFromCache(discoveryQueryParameters.getPlatformComponentType(), discoveryQueryParameters.getNetworkServiceType(), receiveFermatPacket);

        for (PlatformComponentProfile otherPlatformComponentProfile: filteredListFromOtherComponentType) {

            for (PlatformComponentProfile platformComponentProfile : list) {

                /*
                 * The component that have the same CommunicationCloudClientIdentity, they are register for the same CommunicationCloudClientIdentity and
                 * this indicate the are from the same device
                 */
                if (platformComponentProfile.getCommunicationCloudClientIdentity().equals(otherPlatformComponentProfile.getCommunicationCloudClientIdentity())) {
                    finalFilteredList.add(platformComponentProfile);
                }

            }
        }

        return finalFilteredList;

    }

    /**
     * Count the number of filter to apply
     *
     * @param discoveryQueryParameters
     * @return int
     */
    private int countFilers(DiscoveryQueryParameters discoveryQueryParameters){

        int total = 0;

        if (discoveryQueryParameters.getIdentityPublicKey() != null && discoveryQueryParameters.getIdentityPublicKey() != ""){
            total += 1;
        }

        if (discoveryQueryParameters.getAlias() != null && discoveryQueryParameters.getAlias() != ""){
            total += 1;
        }

        if (discoveryQueryParameters.getName() != null && discoveryQueryParameters.getName() != ""){
            total += 1;
        }

        if (discoveryQueryParameters.getExtraData() != null && discoveryQueryParameters.getExtraData() != ""){
            total += 1;
        }

        return  total;
    }

    /**
     * (no-javadoc)
     * @see FermatPacketProcessor#getFermatPacketType()
     */
    @Override
    public FermatPacketType getFermatPacketType() {
        return FermatPacketType.REQUEST_LIST_COMPONENT_REGISTERED;
    }
}


text:
opencards

mit license


text:
module Thredded
  module RenderPreview
    protected

    def render_preview
      if request.xhr?
        render layout: false
      else
        @preview_content = render_to_string(layout: false)
        render template: 'thredded/shared/preview'
      end
    end
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Ruschia incumbens L.Bolus

### Remarks
null