text:
class CouponUsageHistoryEntity < Grape::Entity
  expose :id, documentation: {required: true, type: "Integer", desc: "coupon id"}
  expose :url, documentation: {required: true, type: "String", desc: "coupon web page url"} do |instance, options|
    instance.coupon.information.url
  end
  expose :status, documentation: {required: true, type: "String", desc: "coupon status, [used|expired]"}
end


text:
warning: 'This file is auto generated by `npm run web:inject`, do not edit by hand'
examples:
  - >-
    function test_in_array (array, p_val) {for(var i = 0, l = array.length; i <
    l; i++) {if (array[i] === p_val) return true} return false}

    var $funcs = get_defined_functions()

    var $found = test_in_array($funcs, 'get_defined_functions')

    var $result = $found
estarget: es5
returns:
  - 'true'
dependencies: []
authors:
  original by:
    - 'Brett Zamir (https://brett-zamir.me)'
  improved by:
    - 'Brett Zamir (https://brett-zamir.me)'
notes:
  - |-
    Test case 1: If get_defined_functions can find
    itself in the defined functions, it worked :)
type: function
layout: function
title: PHP's get_defined_functions in JavaScript
description: >-
  Here's what our current JavaScript equivalent to PHP's
  get_defined_functions looks like.
function: get_defined_functions
category: funchand
language: php
permalink: php/funchand/get_defined_functions/
alias:
  - /functions/php/get_defined_functions/
  - /functions/funchand/get_defined_functions/
  - /php/get_defined_functions/
  - /functions/get_defined_functions/
---
{% codeblock lang:javascript %}module.exports = function get_defined_functions () { // eslint-disable-line camelcase
  //  discuss at: https://locutus.io/php/get_defined_functions/
  // original by: Brett Zamir (https://brett-zamir.me)
  // improved by: Brett Zamir (https://brett-zamir.me)
  //      note 1: Test case 1: If get_defined_functions can find
  //      note 1: itself in the defined functions, it worked :)
  //   example 1: function test_in_array (array, p_val) {for(var i = 0, l = array.length; i < l; i++) {if (array[i] === p_val) return true} return false}
  //   example 1: var $funcs = get_defined_functions()
  //   example 1: var $found = test_in_array($funcs, 'get_defined_functions')
  //   example 1: var $result = $found
  //   returns 1: true
  //        test: skip-1

  var $global = (typeof window !== 'undefined' ? window : global)
  $global.$locutus = $global.$locutus || {}
  var $locutus = $global.$locutus
  $locutus.php = $locutus.php || {}

  var i = ''
  var arr = []
  var already = {}

  for (i in $global) {
    try {
      if (typeof $global[i] === 'function') {
        if (!already[i]) {
          already[i] = 1
          arr.push(i)
        }
      } else if (typeof $global[i] === 'object') {
        for (var j in $global[i]) {
          if (typeof $global[j] === 'function' && $global[j] && !already[j]) {
            already[j] = 1
            arr.push(j)
          }
        }
      }
    } catch (e) {
      // Some objects in Firefox throw exceptions when their
      // properties are accessed (e.g., sessionStorage)
    }
  }

  return arr
}
{% endcodeblock %}

redpajama_set_name: RedPajamaGithub


text:
var parameterTest = module.exports = require('../../..').table();

parameterTest.autoIncrement = true;
parameterTest.read(function (context) {
    // read operations expect to return an array... this could be improved
    return [mapParameters(context)];
});
parameterTest.insert(mapParameters);
parameterTest.update(mapParameters);
parameterTest.delete(mapParameters);

function mapParameters(context) {
    var id = parseInt(context.id || context.req.query.id || '1');
    return {
        id: id,
        parameters: JSON.stringify(context.req.query)
    };
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:shape="oval">
            <solid
                android:color="@color/button_flashlight_circle_on"/>
            <size
                android:width="44dp"
                android:height="44dp"/>
        </shape>
    </item>
    <item
        android:drawable="@drawable/ic_flash_on"
        android:top="4dp"
        android:left="4dp"
        android:width="36dp"
        android:height="36dp"/>
</layer-list>


text:
import collections
import json
import os
import string
import threading
import time

from typing import Dict, Iterable, List, Optional, Union  # noqa

import sublime
import sublime_plugin

from .scripts import files
from .scripts import html_css
from .scripts import load
from .scripts import randomize
from .scripts import scopes
from .scripts import utilities

IDLE = 0

RUNNING = 1

TEMPLATE = """

            {body}

"""

def extra_style() -> str:
    result = []
    suffixes = ("style", "weight", "color", "background")
    data = {
        "con": "",
        "flo": "flow",
        "mod": "modifier",
        "sto": "storage",
        "lan": "language",
    }
    aux = {
        "pun": "delimiter",
        "key": "key",
        "equ": "equals",
        "num": "numeric",
        "wor": "keyword",
        "com": "comma",
        "par": "parameter",
    }

    for tag, pre in data.items():
        for suf in suffixes:
            for opt in ("", "slash"):
                result.append(
                    "--%s%scontrol-sequence-%s: {%s_%s};" % (
                        opt + "-" if opt else "",
                        pre + "-" if pre else "",
                        suf,
                        "s{:.2}".format(tag) if opt else tag,
                        suf,
                    )
                )

    for tag, pre in aux.items():
        for suf in suffixes:
            result.append("--%s-%s: {%s_%s};" % (pre, suf, tag, suf))

    return "html {{%s}}" % "\n".join(result)

EXTRA_STYLE = extra_style()

def try_jump_to_def(view: sublime.View, command: str) -> None:
    threading.Thread(target=lambda: try_jump_to_def_aux(view, command)).start()

def try_jump_to_def_aux(view: sublime.View, name: str) -> None:
    start_time = time.time()
    while view.is_loading():
        time.sleep(0.01)
        if time.time() - start_time > 1:
            return
    symbols = {strip_prefix(text): pos for (pos, text) in view.symbols()}
    if name in symbols:
        region = symbols[name]
        view.run_command(
            "simple_context_show_selection",
            {"regions": [(region.a, region.b)]},
        )

class VirtualCommandDict:
    def __init__(
        self,
        dir_: str,
        max_size: int = 100,
        local_size: int = 10,
        cmds: str = "_commands.json",
    ) -> None:
        self.dir = dir_
        self.missing = sorted(f for f in os.listdir(dir_) if f != cmds)
        with open(os.path.join(dir_, cmds), encoding="utf-8") as f:
            self.cmds = collections.OrderedDict()
            for text in sorted(json.load(f), key=lambda s: s.split(":", 1)[1]):
                parity, ctrl = text.split(":", 1)
                self.cmds[ctrl] = int(parity)
        self.local_size = local_size
        self.cache = utilities.FuzzyOrderedDict(max_size=max_size)

    def __setitem__(self, key, value) -> None:
        self.cache.add_left(key, value)

    def __getitem__(self, key) -> None:
        if key in self:
            if key in self.cache:
                return self.cache[key]
            name = min(f for f in self.missing if key <= f)
            with open(os.path.join(self.dir, name), encoding="utf-8") as f:
                data = json.load(f)

            sample = [
                (k, data[k])
                for k in randomize.safe_random_sample(
                    list(data), self.local_size,
                )
            ]
            self.cache.fuzzy_add_right(sample)

            result = data[key]
            self[key] = result
            return result
        else:
            raise KeyError

    def __len__(self) -> int:
        return len(self.cache)

    def __contains__(self, key) -> bool:
        return key in self.cmds

def strip_prefix(text: str) -> str:
    return "".join(text.split()[-1:])

class SimpleContextMacroSignatureEventListener(
    utilities.BaseSettings, sublime_plugin.ViewEventListener,
):
    cache = {}
    html_cache = {}
    lock = threading.Lock()
    loader = load.InterfaceLoader()
    state = IDLE
    file_min = 20000
    param_char = string.ascii_letters  # + string.whitespace
    extensions = (".mkix", ".mkxi", ".mkiv", ".mkvi", ".tex", ".mkii")
    auto_complete_cmd_key = None
    attempts = 0

    def is_visible(self) -> bool:
        return self.is_visible_alt()

    def reload_settings(self) -> None:
        super().reload_settings()
        self.pop_ups = {
            k.split("/")[-1]: self.get_setting("pop_ups/{}".format(k))
            for k in {
                "line_break",
                "match_indentation",
                "hang_indentation",
                "methods/on_hover",
                "methods/on_modified",
                "show_copy_pop_up",
                "show_source_files",
            }
        }
        self.name = files.file_as_slug(self.context_path)
        self.size = self.view.size()
        if (
            self.state == IDLE and
            self.is_visible() and
            self.name not in self.cache
        ):
            if self.get_setting("pop_ups/try_generate_on_demand"):
                self.state = RUNNING
                threading.Thread(target=self.reload_settings_aux).start()
            else:
                self.try_load_commands()

    def reload_settings_aux(self) -> None:
        self.view.window().run_command(
            "simple_context_regenerate_interface_files",
            {
                "do_all": False,
                "paths": [self.context_path],
                "overwrite": False,
            },
        )
        self.try_load_commands()
        self.state = IDLE

    def try_load_commands(self) -> None:
        self.attempts += 1
        if self.attempts < 10:
            self.load_commands(
                os.path.join(
                    sublime.packages_path(),
                    "simple_ConTeXt",
                    "interface",
                    self.name,
                )
            )

    def load_css(self) -> None:
        self.style = html_css.strip_css_comments(
            sublime.load_resource(
                "Packages/simple_ConTeXt/css/pop_up.css"
            )
        )

    def load_commands(self, path: str) -> None:
        try:
            self.cache[self.name] = \
                VirtualCommandDict(path, max_size=500, local_size=25)
            self.html_cache[self.name] = \
                utilities.LeastRecentlyUsedCache(max_size=500)
        except OSError:
            pass

    def on_query_completions(
        self, prefix: str, locations: List[int],
    ) -> Optional[List[List[str]]]:
        self.reload_settings()
        if self.state != IDLE or not self.is_visible():
            return None

        cmd = self.auto_complete_cmd_key
        if cmd is not None:
            self.auto_complete_cmd_key = None
            return self.complete_key(cmd)

        if self.name in self.cache:
            return self.complete_command(self.cache[self.name], locations)

        return None

    def complete_command(
        self, cache: VirtualCommandDict, locations: List[int],
    ) -> Optional[List[List[str]]]:
        for location in locations:
            if scopes.enclosing_block(
                self.view,
                location - 1,
                scopes.FULL_CONTROL_SEQ,
                end=self.size,
            ):
                result = []
                for ctrl, parity in cache.cmds.items():
                    if parity > 0:
                        entry = ["\\{}\t({}) command".format(ctrl, parity)]
                    else:
                        entry = ["\\{}\tcommand".format(ctrl)]
                    entry.append("\\{}$0".format(ctrl))
                    result.append(entry)
                return result
        return None

    # Crude, does a decent job though.
    def complete_key(self, cmd: str, limit: int = 2):
        return self.complete_key_aux(cmd, intermediate=False, limit=limit)

    # For now, just handle the possibility of multiple variations by
    # merging them all. Watch out for infinite recursion.
    def complete_key_aux(
        self, cmd: str, intermediate: bool = False, limit: int = 3,
    ):
        result = {}  # type: Dict[str, List[str]]
        for var in cmd:
            if not isinstance(var, dict):
                continue
            content = var.get("con")
            if isinstance(content, dict):
                content = [content]
            if not isinstance(content, list) or not content:
                continue
            for arg in content:
                if not isinstance(arg, dict):
                    continue
                con = arg.get("con")
                if isinstance(con, dict):
                    for k in con:
                        if k.isalpha():
                            result[k] = [
                                "{}\t{}".format(k, "option"),
                                "{}=$1, $0".format(k),
                            ]
                inh_orig = arg.get("inh")
                if inh_orig is None:
                    continue
                inhs = [inh_orig] if isinstance(inh_orig, str) else inh_orig
                for inh in inhs:
                    if (
                        limit > 0 and
                        self.name in self.cache and
                        inh in self.cache.get(self.name, {})
                    ):
                        inh_cmd = self.cache[self.name][inh]
                        result.update(
                            self.complete_key_aux(
                                inh_cmd, intermediate=True, limit=limit - 1,
                            )
                        )

        if intermediate:
            return result
        return sorted(result.values()) if result else None

    def on_hover(self, point: int, hover_zone: int) -> None:
        if not self.is_visible() or hover_zone != sublime.HOVER_TEXT:
            return

        self.reload_settings()
        if (
            self.state != IDLE or
            not self.get_setting("pop_ups/methods/on_hover") or
            not self.is_visible()
        ):
            self.view.hide_popup()
            return

        ctrl = scopes.enclosing_block(
            self.view, point, scopes.CONTROL_WORD, end=self.size,
        )
        if not ctrl:
            return
        name = self.view.substr(sublime.Region(*ctrl))
        if name in self.cache.get(self.name, {}):
            self.view.show_popup(
                self.get_popup_text(name),
                location=ctrl[0] - 1,
                max_width=600,
                flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY,
                on_navigate=lambda href: self.on_navigate(href, name),
            )
        else:
            self.view.hide_popup()

    def on_modified_async(self) -> None:
        self.reload_settings()
        if self.state != IDLE or not self.is_visible():
            self.view.hide_popup()
            return

        selection = self.view.sel()
        if not selection:
            return
        sel = selection[0]
        end = sel.end()
        end_ = end - 1 if end < self.size else end

        if self.get_setting("pop_ups/methods/on_modified"):
            ctrl = scopes.left_enclosing_block(
                self.view, end_, scopes.CONTROL_SEQ, end=self.size
            )
            if ctrl:
                name = self.view.substr(sublime.Region(*ctrl))
                if name in self.cache.get(self.name, {}):
                    self.view.show_popup(
                        self.get_popup_text(name),
                        location=ctrl[0] - 1,
                        max_width=600,
                        flags=sublime.COOPERATE_WITH_AUTO_COMPLETE,
                        on_navigate=lambda href: self.on_navigate(href, name),
                    )
                    return

        if self.get_setting("option_completions/on"):
            ctrl = scopes.last_block_in_region(
                self.view,
                0,
                scopes.CONTROL_SEQ,
                end=end_,
                skip=scopes.SKIP_ARGS_AND_SPACES,
            )
            if (
                ctrl and
                self.view.substr(end - 1) in string.ascii_letters and
                self.view.match_selector(end - 1, scopes.BRACKETS_NOT_VALUE)
            ):
                name = self.view.substr(sublime.Region(*ctrl))
                if name in self.cache.get(self.name, {}):
                    self.auto_complete_cmd_key = self.cache[self.name][name]
                    self.view.run_command(
                        "auto_complete",
                        {
                            "disable_auto_insert": True,
                            "api_completions_only": True,
                        },
                    )
                    return

        self.view.hide_popup()

    def get_popup_text(self, name: str) -> str:
        new_pop_up_state = json.dumps(self.pop_ups, sort_keys=True)
        if not hasattr(self, "prev_pop_up_state"):
            self.prev_pop_up_state = None
        if new_pop_up_state != self.prev_pop_up_state:
            self.html_cache[self.name].clear()
        if name not in self.html_cache[self.name]:
            cmd = self.cache[self.name][name]
            self.html_cache[self.name][name] = self.loader.load(
                name, cmd, protect_space=True, **self.pop_ups
            )
        self.prev_pop_up_state = new_pop_up_state
        self.popup_name = name

        self.load_css()
        return TEMPLATE.format(
            body="

".join(
                s for s in self.html_cache[self.name][name] if s
            ),
            style=self.style,
            extra_style=self.get_extra_style(),
        )

    def get_extra_style(self) -> str:
        con, sco = self.styles_for_scope("support.function")
        flo, sfl = self.styles_for_scope("keyword.control")
        mod, smo = self.styles_for_scope("storage.modifier")
        sto, sst = self.styles_for_scope("storage.type")
        lan, sla = self.styles_for_scope("constant.language")

        pun = self.view.style_for_scope("punctuation.section")
        key = self.view.style_for_scope("variable.parameter")
        equ = self.view.style_for_scope("keyword.operator.assignment")
        num = self.view.style_for_scope("constant.numeric")
        wor = self.view.style_for_scope("keyword.other")
        com = self.view.style_for_scope("punctuation.separator.comma")
        par = self.view.style_for_scope("variable.parameter")

        styles = {
            "con": con, "sco": sco, "flo": flo, "sfl": sfl, "mod": mod,
            "smo": smo, "sto": sto, "sst": sst, "lan": lan, "sla": sla,
            "pun": pun, "key": key, "equ": equ, "num": num, "com": com,
            "par": par, "wor": wor,
        }
        opts = {}
        for s, d in styles.items():
            opts["{}_style".format(s)] = "italic" if d.get("italic") else ""
            opts["{}_weight".format(s)] = "bold" if d.get("bold") else ""
            opts["{}_color".format(s)] = d.get("foreground")
            opts["{}_background".format(s)] = \
                d.get("background", "--background")

        return EXTRA_STYLE.format(**opts)

    def style_for_scope_punc(self, text: str) -> str:
        return self.view.style_for_scope(
            "{} punctuation.definition.backslash".format(text)
        )

    def styles_for_scope(self, text: str) -> List[str]:
        return [
            self.view.style_for_scope(text), self.style_for_scope_punc(text),
        ]

    def on_navigate(self, href: str, name: str) -> None:
        type_, content = href[:4], href[5:]
        if type_ == "file":
            self.on_navigate_file(content, name)
        elif type_ == "copy":
            text = "

".join(
                s for s in self.html_cache[self.name][self.popup_name][:-1]
                if s
            )
            self.copy(html_css.raw_print(text))
            # if content == "html":
            #     self.copy(html_css.pretty_print(text))
            # elif content == "plain":
            #     self.copy(html_css.raw_print(text))

    def on_navigate_file(self, name: str, command: str) -> None:
        threading.Thread(
            target=lambda: self.on_navigate_file_aux(name, command)
        ).start()

    def on_navigate_file_aux(self, name: str, command: str) -> None:
        main = files.locate(
            self.context_path, name, flags=self.flags, shell=self.shell,
        )
        if main and os.path.exists(main):
            view = self.view.window().open_file(main)
            try_jump_to_def(view, command)
            return

        other = files.fuzzy_locate(
            self.context_path,
            name,
            extensions=self.extensions,
            flags=self.flags,
            shell=self.shell,
        )
        if other and os.path.exists(other):
            view = self.view.window().open_file(other)
            try_jump_to_def(view, command)
            return

        sublime.message_dialog('Falied to locate file "{}".'.format(name))

    def copy(self, text: str) -> None:
        self.view.hide_popup()
        sublime.set_clipboard(text)
        sublime.status_message("Pop-up content copied to clipboard")


text:
package org.wildfly.build.plugin;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.filtering.MavenFilteringException;
import org.apache.maven.shared.filtering.MavenResourcesExecution;
import org.apache.maven.shared.filtering.MavenResourcesFiltering;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.RemoteRepository;
import org.wildfly.build.AetherArtifactFileResolver;
import org.wildfly.build.Locations;
import org.wildfly.build.featurepack.FeaturePackBuilder;
import org.wildfly.build.featurepack.model.FeaturePackBuild;
import org.wildfly.build.featurepack.model.FeaturePackBuildModelParser;
import org.wildfly.build.util.FileUtils;
import org.wildfly.build.util.MapPropertyResolver;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * The maven plugin that builds a Wildfly feature pack
 *
 * @author Stuart Douglas
 * @author Eduardo Martins
 * @author James R. Perkins
 */
@SuppressWarnings("InstanceVariableMayNotBeInitialized")
@Mojo(name = "build", requiresDependencyResolution = ResolutionScope.RUNTIME, defaultPhase = LifecyclePhase.COMPILE)
public class FeaturePackBuildMojo extends AbstractMojo {
    private static final boolean OS_WINDOWS = System.getProperty("os.name").contains("indows");

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    protected MavenProject project;

    /**
     * The configuration file used for feature pack.
     */
    @Parameter(alias = "config-file", defaultValue = "feature-pack-build.xml", property = "wildfly.feature.pack.configFile")
    private String configFile;

    /**
     * The directory the configuration file is located in.
     */
    @Parameter(alias = "config-dir", defaultValue = "${basedir}", property = "wildfly.feature.pack.configDir")
    private File configDir;

    /**
     * A path relative to {@link #configDir} that represents the directory under which of resources such as
     * {@code configuration/standalone/subsystems.xml}, {modules}, {subsystem-templates}, etc.
     */
    @Parameter(alias = "resources-dir", defaultValue = "src/main/resources", property = "wildfly.feature.pack.resourcesDir", required = true)
    private String resourcesDir;

    /**
     * The name of the server.
     */
    @Parameter(alias = "server-name", defaultValue = "${project.build.finalName}", property = "wildfly.feature.pack.serverName")
    private String serverName;

    /**
     * The directory for the built artifact.
     */
    @Parameter(defaultValue = "${project.build.directory}", property = "wildfly.feature.pack.buildName")
    private String buildName;

    /**
     * Allows for additional resources or resources to be processed in a different manor. For example resources can be
     * {@linkplain Resource#isFiltering() filtered}.
     */
    @Parameter
    private List<Resource> resources;

    /**
     * The entry point to Aether, i.e. the component doing all the work.
     */
    @Component
    private RepositorySystem repoSystem;

    /**
     * The current repository/network configuration of Maven.
     */
    @Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
    private RepositorySystemSession repoSession;

    /**
     * The project's remote repositories to use for the resolution.
     */
    @Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true)
    private List<RemoteRepository> remoteRepos;

    @Parameter( defaultValue = "${session}", readonly = true )
    private MavenSession session;

    @Component( role = MavenResourcesFiltering.class, hint = "default" )
    private MavenResourcesFiltering mavenResourcesFiltering;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        /* normalize resourcesDir */
        if (!resourcesDir.isEmpty()) {
            switch (resourcesDir.charAt(0)) {
            case '/':
            case '\\':
                break;
            default:
                resourcesDir = "/" + resourcesDir;
                break;
            }
        }

        copyContents();
        try (FileInputStream configStream = new FileInputStream(new File(configDir, configFile))) {
            Properties properties = new Properties();
            properties.putAll(project.getProperties());
            properties.putAll(System.getProperties());
            properties.put("project.version", project.getVersion()); //TODO: figure out the correct way to do this
            final FeaturePackBuild build = new FeaturePackBuildModelParser(new MapPropertyResolver(properties)).parse(configStream);
            File target = new File(buildName, serverName);
            FeaturePackBuilder.build(build, target, new MavenProjectArtifactResolver(project), new AetherArtifactFileResolver(repoSystem, repoSession, remoteRepos));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // Process additional resources
        if (resources != null) {
            try {
                processResources(getOverwriteResources(),true);
                processResources(getNonOverwriteResources(), false);
            } catch (MavenFilteringException e) {
                throw new MojoExecutionException("Failed to process resources.", e);
            }
        }
    }

    /**
     * @throws IOException
     */
    private void copyContents() {
        try {
            File baseDir = new File(buildName, serverName);
            FileUtils.deleteRecursive(baseDir);

            final Path path = Paths.get(baseDir.getAbsolutePath());

            final Path baseFile = Paths.get(configDir.getAbsolutePath() + resourcesDir);
            doCopy(path.resolve(Locations.CONTENT), baseFile.resolve(Locations.CONTENT));
            doCopy(path.resolve(Locations.MODULES), baseFile.resolve(Locations.MODULES));
            doCopy(path.resolve(Locations.CONFIGURATION), baseFile.resolve(Locations.CONFIGURATION));
            doCopy(path.resolve(Locations.SUBSYSTEM_TEMPLATES), baseFile.resolve(Locations.SUBSYSTEM_TEMPLATES));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void doCopy(final Path target, final Path source) throws IOException {
        Files.walkFileTree(source, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                String relative = source.relativize(dir).toString();
                boolean include = true;
                if (include) {
                    Path rel = target.resolve(relative);
                    if (!Files.isDirectory(rel)) {
                        if (!rel.toFile().mkdirs()) {
                            throw new IOException("Could not create directory " + rel.toString());
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
                return FileVisitResult.SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String relative = source.relativize(file).toString();

                Path targetFile = target.resolve(relative);
                FileUtils.copyFile(file.toFile(), targetFile.toFile());
                if (!OS_WINDOWS) {
                    Files.setPosixFilePermissions(targetFile, Files.getPosixFilePermissions(file));
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.TERMINATE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
    }

    private void processResources(final List<org.apache.maven.model.Resource> resources, final boolean overwrite) throws MavenFilteringException {
        final MavenResourcesExecution resourcesExecution = new MavenResourcesExecution(resources, new File(buildName, serverName),
                project, "UTF-8", Collections.emptyList(), Collections.emptyList(), session);
        resourcesExecution.setIncludeEmptyDirs(false);
        resourcesExecution.setEscapeWindowsPaths(true);
        resourcesExecution.setOverwrite(overwrite);
        resourcesExecution.setAddDefaultExcludes(true);
        mavenResourcesFiltering.filterResources(resourcesExecution);
    }

    private List<org.apache.maven.model.Resource> getOverwriteResources() {
        final List<org.apache.maven.model.Resource> result = new ArrayList<>();
        for (Resource resource : resources) {
            if (resource.isOverwrite()) {
                result.add(resource);
            }
        }
        return result;
    }

    private List<org.apache.maven.model.Resource> getNonOverwriteResources() {
        final List<org.apache.maven.model.Resource> result = new ArrayList<>();
        for (Resource resource : resources) {
            if (!resource.isOverwrite()) {
                result.add(resource);
            }
        }
        return result;
    }

}


text:
#include "locale_utils.h"

#include "../error.h"
#include "string_ascii_utils.h"

#include <assert.h>
#include <locale.h>
#include <stddef.h>
#include <string.h>

const char *gmio_lc_numeric()
{
    const char* lcnum = setlocale(LC_NUMERIC, NULL);
    return lcnum != NULL ? lcnum : "";
}

bool gmio_lc_numeric_is_C()
{
    const char* lc = gmio_lc_numeric();
    return (gmio_ascii_stricmp(lc, "C") == 0
            || gmio_ascii_stricmp(lc, "POSIX") == 0);
}

static char global_lcnum[64] = {0};
static const size_t maxlen_global_lcnum = GMIO_ARRAY_SIZE(global_lcnum);

void gmio_lc_numeric_save()
{
    /* Save LC_NUMERIC
     * POSIX specifies that the pointer returned by setlocale(), not just the
     * contents of the pointed-to string, may be invalidated by subsequent calls
     * to setlocale() */
    const char* lcnum = setlocale(LC_NUMERIC, NULL);
    const size_t lcnum_len = strlen(lcnum != NULL ? lcnum : "");
    const size_t lcnum_endpos = lcnum_len > 0 ? lcnum_len + 1 : 0;
    assert(lcnum_endpos < maxlen_global_lcnum);
    if (lcnum_len > 0)
        strncpy(global_lcnum, lcnum, lcnum_len);
    global_lcnum[lcnum_endpos] = '\0';
}

void gmio_lc_numeric_restore()
{
    if (global_lcnum[0] != '\0')
        setlocale(LC_NUMERIC, global_lcnum);
}