text:
"""
This module contains useful Javascript utility methods for base_case.py
These helper methods SHOULD NOT be called directly from tests.
"""
import re
import requests
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from seleniumbase import config as sb_config
from seleniumbase.config import settings
from seleniumbase.fixtures import constants

def wait_for_ready_state_complete(driver, timeout=settings.LARGE_TIMEOUT):
    """
    The DOM (Document Object Model) has a property called "readyState".
    When the value of this becomes "complete", page resources are considered
      fully loaded (although AJAX and other loads might still be happening).
    This method will wait until document.readyState == "complete".
    This may be redundant, as methods already wait for page elements to load.
    If the timeout is exceeded, the test will still continue
      because readyState == "interactive" may be good enough.
    (Previously, tests would fail immediately if exceeding the timeout.)
    """
    if hasattr(settings, "SKIP_JS_WAITS") and settings.SKIP_JS_WAITS:
        return
    if sb_config.time_limit and not sb_config.recorder_mode:
        from seleniumbase.fixtures import shared_utils

    start_ms = time.time() * 1000.0
    stop_ms = start_ms + (timeout * 1000.0)
    for x in range(int(timeout * 10)):
        if sb_config.time_limit and not sb_config.recorder_mode:
            shared_utils.check_if_time_limit_exceeded()
        try:
            ready_state = driver.execute_script("return document.readyState;")
        except WebDriverException:
            # Bug fix for: [Permission denied to access property "document"]
            time.sleep(0.03)
            return True
        if ready_state == "complete":
            time.sleep(0.01)  # Better be sure everything is done loading
            return True
        else:
            now_ms = time.time() * 1000.0
            if now_ms >= stop_ms:
                break
            time.sleep(0.1)
    return False  # readyState stayed "interactive" (Not "complete")

def execute_async_script(driver, script, timeout=settings.EXTREME_TIMEOUT):
    driver.set_script_timeout(timeout)
    return driver.execute_async_script(script)

def wait_for_angularjs(driver, timeout=settings.LARGE_TIMEOUT, **kwargs):
    if hasattr(settings, "SKIP_JS_WAITS") and settings.SKIP_JS_WAITS:
        return
    if not settings.WAIT_FOR_ANGULARJS:
        return

    NG_WRAPPER = (
        "%(prefix)s"
        "var $elm=document.querySelector("
        "'[data-ng-app],[ng-app],.ng-scope')||document;"
        "if(window.angular && angular.getTestability){"
        "angular.getTestability($elm).whenStable(%(handler)s)"
        "}else{"
        "var $inj;try{$inj=angular.element($elm).injector()||"
        "angular.injector(['ng'])}catch(ex){"
        "$inj=angular.injector(['ng'])};$inj.get=$inj.get||"
        "$inj;$inj.get('$browser')."
        "notifyWhenNoOutstandingRequests(%(handler)s)}"
        "%(suffix)s"
    )
    def_pre = "var cb=arguments[arguments.length-1];if(window.angular){"
    prefix = kwargs.pop("prefix", def_pre)
    handler = kwargs.pop("handler", "function(){cb(true)}")
    suffix = kwargs.pop("suffix", "}else{cb(false)}")
    script = NG_WRAPPER % {
        "prefix": prefix,
        "handler": handler,
        "suffix": suffix,
    }
    try:
        # This closes any pop-up alerts (otherwise the next part fails)
        driver.execute_script("")
    except Exception:
        pass
    try:
        execute_async_script(driver, script, timeout=timeout)
    except Exception:
        time.sleep(0.05)

def is_html_inspector_activated(driver):
    try:
        driver.execute_script("HTMLInspector")  # Fails if not defined
        return True
    except Exception:
        return False

def is_jquery_activated(driver):
    try:
        driver.execute_script("jQuery('html')")  # Fails if jq is not defined
        return True
    except Exception:
        return False

def wait_for_jquery_active(driver, timeout=None):
    if not timeout:
        timeout = 22
    else:
        timeout = int(timeout * 10.0)
    for x in range(timeout):
        # jQuery needs a small amount of time to activate.
        try:
            driver.execute_script("jQuery('html')")
            wait_for_ready_state_complete(driver)
            wait_for_angularjs(driver)
            return
        except Exception:
            time.sleep(0.1)

def raise_unable_to_load_jquery_exception(driver):
    has_csp_error = False
    csp_violation = "violates the following Content Security Policy directive"
    browser_logs = []
    try:
        browser_logs = driver.get_log("browser")
    except (ValueError, WebDriverException):
        pass
    for entry in browser_logs:
        if entry["level"] == "SEVERE":
            if csp_violation in entry["message"]:
                has_csp_error = True
    if has_csp_error:
        raise Exception(
            """Unable to load jQuery on "%s" due to a violation """
            """of the website's Content Security Policy directive. """
            """To override this policy, add "--disable-csp" on the """
            """command-line when running your tests.""" % driver.current_url
        )
    else:
        raise Exception(
            """Unable to load jQuery on "%s" because this website may be """
            """restricting external JavaScript resources from loading."""
            % driver.current_url
        )

def activate_jquery(driver):
    """
    If "jQuery is not defined" on a website, use this method to activate it.
    This method is needed because jQuery is not always defined on web sites.
    """
    try:
        # Let's first find out if jQuery is already defined.
        driver.execute_script("jQuery('html');")
        # Since that command worked, jQuery is defined. Let's return.
        return
    except Exception:
        # jQuery is not currently defined. Let's proceed by defining it.
        pass
    jquery_js = constants.JQuery.MIN_JS
    add_js_link(driver, jquery_js)
    for x in range(27):
        # jQuery needs a small amount of time to activate.
        try:
            driver.execute_script("jQuery('html');")
            return
        except Exception:
            if x == 15:
                add_js_link(driver, jquery_js)
            time.sleep(0.1)
    # Since jQuery still isn't activating, give up and raise an exception
    raise_unable_to_load_jquery_exception(driver)

def are_quotes_escaped(string):
    if string.count("\\'") != string.count("'") or (
        string.count('\\"') != string.count('"')
    ):
        return True
    return False

def escape_quotes_if_needed(string):
    """
    re.escape() works differently in Python 3.7.0 than earlier versions:

    Python 3.6.5:
    >>> import re
    >>> re.escape('"')
    '\\"'

    Python 3.7.0:
    >>> import re
    >>> re.escape('"')
    '"'

    SeleniumBase needs quotes to be properly escaped for Javascript calls.
    """
    if are_quotes_escaped(string):
        if string.count("'") != string.count("\\'"):
            string = string.replace("'", "\\'")
        if string.count('"') != string.count('\\"'):
            string = string.replace('"', '\\"')
    return string

def is_in_frame(driver):
    """
    Returns True if the driver has switched to a frame.
    Returns False if the driver was on default content.
    """
    in_basic_frame = driver.execute_script(
        """
        var frame = window.frameElement;
        if (frame) {
            return true;
        }
        else {
            return false;
        }
        """
    )
    location_href = driver.execute_script("""return window.location.href;""")
    in_external_frame = False
    if driver.current_url != location_href:
        in_external_frame = True
    if in_basic_frame or in_external_frame:
        return True
    return False

def safe_execute_script(driver, script):
    """When executing a script that contains a jQuery command,
    it's important that the jQuery library has been loaded first.
    This method will load jQuery if it wasn't already loaded."""
    try:
        driver.execute_script(script)
    except Exception:
        # The likely reason this fails is because: "jQuery is not defined"
        activate_jquery(driver)  # It's a good thing we can define it here
        driver.execute_script(script)

def remove_extra_slashes(selector):
    if selector.count('\\"') > 0:
        if selector.count('\\"') == selector.count('"'):
            selector = selector.replace('\\"', '"')
        elif selector.count('\\"') == selector[1:-1].count('"') and (
            "'" not in selector[1:-1]
        ):
            selector = "'" + selector[1:-1].replace('\\"', '"') + "'"
        else:
            pass
    if selector.count("\\'") > 0:
        if selector.count("\\'") == selector.count("'"):
            selector = selector.replace("\\'", "'")
        elif selector.count("\\'") == selector[1:-1].count("'") and (
            '"' not in selector[1:-1]
        ):
            selector = '"' + selector[1:-1].replace("\\'", "'") + '"'
        else:
            pass
    return selector

def optimize_selector(selector):
    if (len(selector) > 2 and selector[0] == "'") and (
        selector[-1] == "'" and '"' not in selector[1:-1]
    ):
        selector = '"' + selector[1:-1] + '"'
    if (
        selector.count('"') == 0
        and selector.count("'") >= 2
        and selector.count("'") % 2 == 0
        and "='" in selector
        and "']" in selector
    ):
        swap_char = "*_SWAP_CHAR_*"
        selector = selector.replace("'", swap_char)
        selector = selector.replace('"', "'")
        selector = selector.replace(swap_char, '"')
    return selector

def wait_for_css_query_selector(
    driver, selector, timeout=settings.LARGE_TIMEOUT
):
    element = None
    selector = escape_quotes_if_needed(selector)
    selector = remove_extra_slashes(selector)
    selector = optimize_selector(selector)
    script = """return document.querySelector('%s');""" % selector
    start_ms = time.time() * 1000.0
    stop_ms = start_ms + (timeout * 1000.0)
    for x in range(int(timeout * 10)):
        try:
            element = driver.execute_script(script)
            if element:
                return element
        except Exception:
            element = None
        if not element:
            now_ms = time.time() * 1000.0
            if now_ms >= stop_ms:
                break
            time.sleep(0.1)
    raise NoSuchElementException(
        "Element {%s} was not present after %s seconds!" % (selector, timeout)
    )

def highlight_with_js(driver, selector, loops=4, o_bs=""):
    try:
        # This closes any pop-up alerts
        driver.execute_script("")
    except Exception:
        pass
    if selector == "html":
        selector = "body"
    selector_no_spaces = selector.replace(" ", "")
    early_exit = False
    if '[style=\\"' in selector_no_spaces:
        if "box\\-shadow:" in selector:
            early_exit = True  # Changing the box-shadow changes the selector
        elif '[style=\\"' in selector:
            selector = selector.replace('[style=\\"', '[style\\*=\\"')
        else:
            early_exit = True  # Changing the box-shadow changes the selector
        if early_exit:
            return
    script = (
        """document.querySelector('%s').style.boxShadow =
        '0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    for n in range(loops):
        script = (
            """document.querySelector('%s').style.boxShadow =
            '0px 0px 6px 6px rgba(255, 0, 0, 1)';"""
            % selector
        )
        try:
            driver.execute_script(script)
        except Exception:
            return
        time.sleep(0.0181)
        script = (
            """document.querySelector('%s').style.boxShadow =
            '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""
            % selector
        )
        try:
            driver.execute_script(script)
        except Exception:
            return
        time.sleep(0.0181)
        script = (
            """document.querySelector('%s').style.boxShadow =
            '0px 0px 6px 6px rgba(0, 0, 255, 1)';"""
            % selector
        )
        try:
            driver.execute_script(script)
        except Exception:
            return
        time.sleep(0.0181)
        script = (
            """document.querySelector('%s').style.boxShadow =
            '0px 0px 6px 6px rgba(0, 255, 0, 1)';"""
            % selector
        )
        try:
            driver.execute_script(script)
        except Exception:
            return
        time.sleep(0.0181)
        script = (
            """document.querySelector('%s').style.boxShadow =
            '0px 0px 6px 6px rgba(128, 128, 0, 1)';"""
            % selector
        )
        try:
            driver.execute_script(script)
        except Exception:
            return
        time.sleep(0.0181)
        script = (
            """document.querySelector('%s').style.boxShadow =
            '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""
            % selector
        )
        try:
            driver.execute_script(script)
        except Exception:
            return
        time.sleep(0.0181)
    script = """document.querySelector('%s').style.boxShadow =
        '%s';""" % (
        selector,
        o_bs,
    )
    try:
        driver.execute_script(script)
    except Exception:
        return

def highlight_with_jquery(driver, selector, loops=4, o_bs=""):
    try:
        # This closes any pop-up alerts
        driver.execute_script("")
    except Exception:
        pass
    if selector == "html":
        selector = "body"
    selector_no_spaces = selector.replace(" ", "")
    early_exit = False
    if '[style=\\"' in selector_no_spaces:
        if "box\\-shadow:" in selector:
            early_exit = True  # Changing the box-shadow changes the selector
        elif '[style=\\"' in selector:
            selector = selector.replace('[style=\\"', '[style\\*=\\"')
        else:
            early_exit = True  # Changing the box-shadow changes the selector
        if early_exit:
            return
    script = (
        """jQuery('%s').css('box-shadow',
        '0px 0px 6px 6px rgba(128, 128, 128, 0.5)');"""
        % selector
    )
    safe_execute_script(driver, script)
    for n in range(loops):
        script = (
            """jQuery('%s').css('box-shadow',
            '0px 0px 6px 6px rgba(255, 0, 0, 1)');"""
            % selector
        )
        driver.execute_script(script)
        time.sleep(0.0181)
        script = (
            """jQuery('%s').css('box-shadow',
            '0px 0px 6px 6px rgba(128, 0, 128, 1)');"""
            % selector
        )
        driver.execute_script(script)
        time.sleep(0.0181)
        script = (
            """jQuery('%s').css('box-shadow',
            '0px 0px 6px 6px rgba(0, 0, 255, 1)');"""
            % selector
        )
        driver.execute_script(script)
        time.sleep(0.0181)
        script = (
            """jQuery('%s').css('box-shadow',
            '0px 0px 6px 6px rgba(0, 255, 0, 1)');"""
            % selector
        )
        driver.execute_script(script)
        time.sleep(0.0181)
        script = (
            """jQuery('%s').css('box-shadow',
            '0px 0px 6px 6px rgba(128, 128, 0, 1)');"""
            % selector
        )
        driver.execute_script(script)
        time.sleep(0.0181)
        script = (
            """jQuery('%s').css('box-shadow',
            '0px 0px 6px 6px rgba(128, 0, 128, 1)');"""
            % selector
        )
        driver.execute_script(script)
        time.sleep(0.0181)
    script = """jQuery('%s').css('box-shadow', '%s');""" % (selector, o_bs)
    driver.execute_script(script)

def add_css_link(driver, css_link):
    script_to_add_css = """function injectCSS(css) {
          var head_tag=document.getElementsByTagName("head")[0];
          var link_tag=document.createElement("link");
          link_tag.rel="stylesheet";
          link_tag.type="text/css";
          link_tag.href=css;
          link_tag.crossorigin="anonymous";
          head_tag.appendChild(link_tag);
       }
       injectCSS("%s");"""
    css_link = escape_quotes_if_needed(css_link)
    driver.execute_script(script_to_add_css % css_link)

def add_js_link(driver, js_link):
    script_to_add_js = """function injectJS(link) {
          var body_tag=document.getElementsByTagName("body")[0];
          var script_tag=document.createElement("script");
          script_tag.src=link;
          script_tag.type="text/javascript";
          script_tag.crossorigin="anonymous";
          script_tag.defer;
          script_tag.onload=function() { null };
          body_tag.appendChild(script_tag);
       }
       injectJS("%s");"""
    js_link = escape_quotes_if_needed(js_link)
    driver.execute_script(script_to_add_js % js_link)

def add_css_style(driver, css_style):
    add_css_style_script = """function injectStyle(css) {
          var head_tag=document.getElementsByTagName("head")[0];
          var style_tag=document.createElement("style");
          style_tag.type="text/css";
          style_tag.appendChild(document.createTextNode(css));
          head_tag.appendChild(style_tag);
       }
       injectStyle("%s");"""
    css_style = css_style.replace("\n", "")
    css_style = escape_quotes_if_needed(css_style)
    driver.execute_script(add_css_style_script % css_style)

def add_js_code_from_link(driver, js_link):
    if js_link.startswith("//"):
        js_link = "http:" + js_link
    js_code = requests.get(js_link).text
    add_js_code_script = (
        """var body_tag=document.getElementsByTagName('body').item(0);"""
        """var script_tag=document.createElement("script");"""
        """script_tag.type="text/javascript";"""
        """script_tag.onload=function() { null };"""
        """script_tag.appendChild(document.createTextNode("%s"));"""
        """body_tag.appendChild(script_tag);"""
    )
    js_code = js_code.replace("\n", " ")
    js_code = escape_quotes_if_needed(js_code)
    driver.execute_script(add_js_code_script % js_code)

def add_js_code(driver, js_code):
    add_js_code_script = (
        """var body_tag=document.getElementsByTagName('body').item(0);"""
        """var script_tag=document.createElement("script");"""
        """script_tag.type="text/javascript";"""
        """script_tag.onload=function() { null };"""
        """script_tag.appendChild(document.createTextNode("%s"));"""
        """body_tag.appendChild(script_tag);"""
    )
    js_code = js_code.replace("\n", " ")
    js_code = escape_quotes_if_needed(js_code)
    driver.execute_script(add_js_code_script % js_code)

def add_meta_tag(driver, http_equiv=None, content=None):
    if http_equiv is None:
        http_equiv = "Content-Security-Policy"
    if content is None:
        content = (
            "default-src *; style-src 'self' 'unsafe-inline'; "
            "script-src: 'self' 'unsafe-inline' 'unsafe-eval'"
        )
    script_to_add_meta = """function injectMeta() {
           var meta_tag=document.createElement('meta');
           meta_tag.httpEquiv="%s";
           meta_tag.content="%s";
           document.getElementsByTagName('head')[0].appendChild(meta_tag);
        }
        injectMeta();""" % (
        http_equiv,
        content,
    )
    driver.execute_script(script_to_add_meta)

def is_jquery_confirm_activated(driver):
    try:
        driver.execute_script("jconfirm")  # Fails if jq_confirm is not defined
        return True
    except Exception:
        return False

def activate_jquery_confirm(driver):
    jquery_js = constants.JQuery.MIN_JS
    jq_confirm_css = constants.JqueryConfirm.MIN_CSS
    jq_confirm_js = constants.JqueryConfirm.MIN_JS

    if not is_jquery_activated(driver):
        add_js_link(driver, jquery_js)
        wait_for_jquery_active(driver, timeout=1.2)
    add_css_link(driver, jq_confirm_css)
    add_js_link(driver, jq_confirm_js)

    for x in range(25):
        # jQuery-Confirm needs a small amount of time to load & activate.
        try:
            driver.execute_script("jconfirm")
            wait_for_ready_state_complete(driver)
            wait_for_angularjs(driver)
            return
        except Exception:
            time.sleep(0.1)

def activate_html_inspector(driver):
    jquery_js = constants.JQuery.MIN_JS
    html_inspector_js = constants.HtmlInspector.MIN_JS

    if is_html_inspector_activated(driver):
        return
    if not is_jquery_activated(driver):
        add_js_link(driver, jquery_js)
        wait_for_jquery_active(driver, timeout=1.2)
        wait_for_ready_state_complete(driver)
        wait_for_angularjs(driver)
    add_js_link(driver, html_inspector_js)
    wait_for_ready_state_complete(driver)
    wait_for_angularjs(driver)

    for x in range(25):
        # HTML-Inspector needs a small amount of time to load & activate.
        try:
            driver.execute_script("HTMLInspector")
            wait_for_ready_state_complete(driver)
            wait_for_angularjs(driver)
            return
        except Exception:
            time.sleep(0.1)
    wait_for_ready_state_complete(driver)
    wait_for_angularjs(driver)

def activate_messenger(driver):
    from seleniumbase.core.style_sheet import get_messenger_style

    jquery_js = constants.JQuery.MIN_JS
    messenger_css = constants.Messenger.MIN_CSS
    messenger_js = constants.Messenger.MIN_JS
    msgr_theme_flat_js = constants.Messenger.THEME_FLAT_JS
    msgr_theme_future_js = constants.Messenger.THEME_FUTURE_JS
    msgr_theme_flat_css = constants.Messenger.THEME_FLAT_CSS
    msgr_theme_future_css = constants.Messenger.THEME_FUTURE_CSS
    msgr_theme_block_css = constants.Messenger.THEME_BLOCK_CSS
    msgr_theme_air_css = constants.Messenger.THEME_AIR_CSS
    msgr_theme_ice_css = constants.Messenger.THEME_ICE_CSS
    spinner_css = constants.Messenger.SPINNER_CSS
    underscore_js = constants.Underscore.MIN_JS

    msg_style = (
        "Messenger.options = {'maxMessages': 8, "
        "extraClasses: 'messenger-fixed "
        "messenger-on-bottom messenger-on-right', "
        "theme: 'flat'}"
    )

    if not is_jquery_activated(driver):
        add_js_link(driver, jquery_js)
        wait_for_jquery_active(driver, timeout=1)
    add_css_link(driver, messenger_css)
    add_css_link(driver, msgr_theme_flat_css)
    add_css_link(driver, msgr_theme_future_css)
    add_css_link(driver, msgr_theme_block_css)
    add_css_link(driver, msgr_theme_air_css)
    add_css_link(driver, msgr_theme_ice_css)
    add_js_link(driver, underscore_js)
    add_css_link(driver, spinner_css)
    add_js_link(driver, messenger_js)
    add_css_style(driver, get_messenger_style())

    for x in range(10):
        # Messenger needs a small amount of time to load & activate.
        try:
            result = driver.execute_script(
                """ if (typeof Messenger === 'undefined') { return "U"; } """
            )
            if result == "U":
                time.sleep(0.022)
                continue
            else:
                break
        except Exception:
            time.sleep(0.02)
    try:
        driver.execute_script(msg_style)
        add_js_link(driver, msgr_theme_flat_js)
        add_js_link(driver, msgr_theme_future_js)
        wait_for_ready_state_complete(driver)
        wait_for_angularjs(driver)
        return
    except Exception:
        time.sleep(0.1)

def set_messenger_theme(
    driver, theme="default", location="default", max_messages="default"
):
    if theme == "default":
        theme = "flat"
    if location == "default":
        location = "bottom_right"
        if hasattr(sb_config, "mobile_emulator") and sb_config.mobile_emulator:
            location = "top_center"
    if max_messages == "default":
        max_messages = "8"

    valid_themes = ["flat", "future", "block", "air", "ice"]
    if theme not in valid_themes:
        raise Exception("Theme: %s is not in %s!" % (theme, valid_themes))
    valid_locations = [
        "top_left",
        "top_center",
        "top_right",
        "bottom_left",
        "bottom_center",
        "bottom_right",
    ]
    if location not in valid_locations:
        raise Exception(
            "Location: %s is not in %s!" % (location, valid_locations)
        )

    if location == "top_left":
        messenger_location = "messenger-on-top messenger-on-left"
    elif location == "top_center":
        messenger_location = "messenger-on-top"
    elif location == "top_right":
        messenger_location = "messenger-on-top messenger-on-right"
    elif location == "bottom_left":
        messenger_location = "messenger-on-bottom messenger-on-left"
    elif location == "bottom_center":
        messenger_location = "messenger-on-bottom"
    elif location == "bottom_right":
        messenger_location = "messenger-on-bottom messenger-on-right"

    msg_style = (
        "Messenger.options = {'maxMessages': %s, "
        "extraClasses: 'messenger-fixed %s', theme: '%s'}"
        % (max_messages, messenger_location, theme)
    )
    try:
        driver.execute_script(msg_style)
    except Exception:
        time.sleep(0.05)
        activate_messenger(driver)
        time.sleep(0.05)
        try:
            driver.execute_script(msg_style)
        except Exception:
            pass
    time.sleep(0.1)

def post_message(driver, message, msg_dur, style="info"):
    """A helper method to post a message on the screen with Messenger.
    (Should only be called from post_message() in base_case.py)"""
    if not msg_dur:
        msg_dur = settings.DEFAULT_MESSAGE_DURATION
    msg_dur = float(msg_dur)
    message = re.escape(message)
    message = escape_quotes_if_needed(message)
    messenger_script = (
        """Messenger().post({message: "%s", type: "%s", """
        """hideAfter: %s, hideOnNavigate: true});"""
        % (message, style, msg_dur)
    )
    try:
        driver.execute_script(messenger_script)
    except Exception:
        activate_messenger(driver)
        set_messenger_theme(driver)
        try:
            driver.execute_script(messenger_script)
        except Exception:
            time.sleep(0.2)
            activate_messenger(driver)
            time.sleep(0.2)
            set_messenger_theme(driver)
            time.sleep(0.3)
            driver.execute_script(messenger_script)

def post_messenger_success_message(driver, message, msg_dur):
    if not msg_dur:
        msg_dur = settings.DEFAULT_MESSAGE_DURATION
    msg_dur = float(msg_dur)
    try:
        theme = "flat"
        location = "bottom_right"
        if hasattr(sb_config, "mobile_emulator") and sb_config.mobile_emulator:
            location = "top_center"
        set_messenger_theme(driver, theme=theme, location=location)
        post_message(driver, message, msg_dur, style="success")
        time.sleep(msg_dur + 0.07)
    except Exception:
        pass

def post_messenger_error_message(driver, message, msg_dur):
    if not msg_dur:
        msg_dur = settings.DEFAULT_MESSAGE_DURATION
    msg_dur = float(msg_dur)
    try:
        set_messenger_theme(driver, theme="block", location="top_center")
        post_message(driver, message, msg_dur, style="error")
        time.sleep(msg_dur + 0.07)
    except Exception:
        pass

def highlight_with_js_2(driver, message, selector, o_bs, msg_dur):
    try:
        # This closes any pop-up alerts
        driver.execute_script("")
    except Exception:
        pass
    if selector == "html":
        selector = "body"
    selector_no_spaces = selector.replace(" ", "")
    early_exit = False
    if '[style=\\"' in selector_no_spaces:
        if "box\\-shadow:" in selector:
            early_exit = True  # Changing the box-shadow changes the selector
        elif '[style=\\"' in selector:
            selector = selector.replace('[style=\\"', '[style\\*=\\"')
        else:
            early_exit = True  # Changing the box-shadow changes the selector
        if early_exit:
            try:
                activate_jquery(driver)
                post_messenger_success_message(driver, message, msg_dur)
            except Exception:
                pass
            return
    script = (
        """document.querySelector('%s').style.boxShadow =
        '0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """document.querySelector('%s').style.boxShadow =
        '0px 0px 6px 6px rgba(205, 30, 0, 1)';"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """document.querySelector('%s').style.boxShadow =
        '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """document.querySelector('%s').style.boxShadow =
        '0px 0px 6px 6px rgba(50, 50, 128, 1)';"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """document.querySelector('%s').style.boxShadow =
        '0px 0px 6px 6px rgba(50, 205, 50, 1)';"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)

    try:
        activate_jquery(driver)
        post_messenger_success_message(driver, message, msg_dur)
    except Exception:
        pass

    script = """document.querySelector('%s').style.boxShadow = '%s';""" % (
        selector,
        o_bs,
    )
    try:
        driver.execute_script(script)
    except Exception:
        return

def highlight_with_jquery_2(driver, message, selector, o_bs, msg_dur):
    if selector == "html":
        selector = "body"
    selector_no_spaces = selector.replace(" ", "")
    early_exit = False
    if '[style=\\"' in selector_no_spaces:
        if "box\\-shadow:" in selector:
            early_exit = True  # Changing the box-shadow changes the selector
        elif '[style=\\"' in selector:
            selector = selector.replace('[style=\\"', '[style\\*=\\"')
        else:
            early_exit = True  # Changing the box-shadow changes the selector
        if early_exit:
            try:
                activate_jquery(driver)
                post_messenger_success_message(driver, message, msg_dur)
            except Exception:
                pass
            return
    script = (
        """jQuery('%s').css('box-shadow',
        '0px 0px 6px 6px rgba(128, 128, 128, 0.5)');"""
        % selector
    )
    try:
        safe_execute_script(driver, script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """jQuery('%s').css('box-shadow',
        '0px 0px 6px 6px rgba(205, 30, 0, 1)');"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """jQuery('%s').css('box-shadow',
        '0px 0px 6px 6px rgba(128, 0, 128, 1)');"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """jQuery('%s').css('box-shadow',
        '0px 0px 6px 6px rgba(50, 50, 200, 1)');"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)
    script = (
        """jQuery('%s').css('box-shadow',
        '0px 0px 6px 6px rgba(50, 205, 50, 1)');"""
        % selector
    )
    try:
        driver.execute_script(script)
    except Exception:
        return
    time.sleep(0.0181)

    try:
        activate_jquery(driver)
        post_messenger_success_message(driver, message, msg_dur)
    except Exception:
        pass

    script = """jQuery('%s').css('box-shadow', '%s');""" % (selector, o_bs)
    try:
        driver.execute_script(script)
    except Exception:
        return

def get_scroll_distance_to_element(driver, element):
    try:
        scroll_position = driver.execute_script("return window.scrollY;")
        element_location = None
        element_location = element.location["y"]
        element_location = element_location - constants.Scroll.Y_OFFSET
        if element_location < 0:
            element_location = 0
        distance = element_location - scroll_position
        return distance
    except Exception:
        return 0

def scroll_to_element(driver, element):
    element_location_y = None
    element_location_x = None
    element_width = 0
    screen_width = 0
    try:
        element_location_y = element.location["y"]
    except Exception:
        return False
    try:
        element_location_x = element.location["x"]
        element_width = element.size["width"]
        screen_width = driver.get_window_size()["width"]
    except Exception:
        element_location_x = 0
    element_location_y = element_location_y - constants.Scroll.Y_OFFSET
    if element_location_y < 0:
        element_location_y = 0
    element_location_x_fix = element_location_x - 400
    if element_location_x_fix < 0:
        element_location_x_fix = 0
    if element_location_x + element_width <= screen_width:
        element_location_x_fix = 0
    scroll_script = "window.scrollTo(%s, %s);" % (
        element_location_x_fix, element_location_y
    )
    # The old jQuery scroll_script required by=By.CSS_SELECTOR
    # scroll_script = "jQuery('%s')[0].scrollIntoView()" % selector
    try:
        driver.execute_script(scroll_script)
        return True
    except Exception:
        return False

def slow_scroll_to_element(driver, element, browser):
    if browser == "ie":
        # IE breaks on slow-scrolling. Do a fast scroll instead.
        scroll_to_element(driver, element)
        return
    scroll_position = driver.execute_script("return window.scrollY;")
    element_location_y = None
    try:
        element_location_y = element.location["y"]
    except Exception:
        element.location_once_scrolled_into_view
        return
    try:
        element_location_x = element.location["x"]
        element_width = element.size["width"]
        screen_width = driver.get_window_size()["width"]
    except Exception:
        element_location_x = 0
    element_location_y = element_location_y - constants.Scroll.Y_OFFSET
    if element_location_y < 0:
        element_location_y = 0
    element_location_x_fix = element_location_x - 400
    if element_location_x_fix < 0:
        element_location_x_fix = 0
    if element_location_x + element_width <= screen_width:
        element_location_x_fix = 0
    distance = element_location_y - scroll_position
    if distance != 0:
        total_steps = int(abs(distance) / 50.0) + 2.0
        step_value = float(distance) / total_steps
        new_position = scroll_position
        for y in range(int(total_steps)):
            time.sleep(0.011)
            new_position += step_value
            scroll_script = "window.scrollTo(0, %s);" % new_position
            driver.execute_script(scroll_script)
    time.sleep(0.01)
    scroll_script = "window.scrollTo(%s, %s);" % (
        element_location_x_fix, element_location_y
    )
    driver.execute_script(scroll_script)
    time.sleep(0.01)
    if distance > 430 or distance < -300:
        # Add small recovery time for long-distance slow-scrolling
        time.sleep(0.162)
    else:
        time.sleep(0.045)

def get_drag_and_drop_script():
    # This script uses jQuery to perform a Drag-and-Drop action.
    # (Requires the Drag-selector and the Drop-selector to work)
    script = r"""(function( $ ) {
        $.fn.simulateDragDrop = function(options) {
                return this.each(function() {
                        new $.simulateDragDrop(this, options);
                });
        };
        $.simulateDragDrop = function(elem, options) {
                this.options = options;
                this.simulateEvent(elem, options);
        };
        $.extend($.simulateDragDrop.prototype, {
                simulateEvent: function(elem, options) {
                        /*Simulating drag start*/
                        var type = 'dragstart';
                        var event = this.createEvent(type);
                        this.dispatchEvent(elem, type, event);

                        /*Simulating drop*/
                        type = 'drop';
                        var dropEvent = this.createEvent(type, {});
                        dropEvent.dataTransfer = event.dataTransfer;
                        this.dispatchEvent(
                            $(options.dropTarget)[0], type, dropEvent);

                        /*Simulating drag end*/
                        type = 'dragend';
                        var dragEndEvent = this.createEvent(type, {});
                        dragEndEvent.dataTransfer = event.dataTransfer;
                        this.dispatchEvent(elem, type, dragEndEvent);
                },
                createEvent: function(type) {
                        var event = document.createEvent("CustomEvent");
                        event.initCustomEvent(type, true, true, null);
                        event.dataTransfer = {
                                data: {
                                },
                                setData: function(type, val){
                                        this.data[type] = val;
                                },
                                getData: function(type){
                                        return this.data[type];
                                }
                        };
                        return event;
                },
                dispatchEvent: function(elem, type, event) {
                        if(elem.dispatchEvent) {
                                elem.dispatchEvent(event);
                        }else if( elem.fireEvent ) {
                                elem.fireEvent("on"+type, event);
                        }
                }
        });
        })(jQuery);"""
    return script

def get_js_drag_and_drop_script():
    # HTML5 Drag-and-Drop script (Requires extra parameters to work)
    # param1 (WebElement): Source element to drag
    # param2 (WebElement): Target element for the drop (Optional)
    # param3 (int): Optional - Drop offset x relative to the target
    # param4 (int): Optional - Drop offset y relative to the target
    # param4 (int): Optional - Delay in milliseconds (default = 1ms)
    # param5 (string): Optional - Key pressed (ALT or CTRL or SHIFT)
    script = """var t=arguments,e=t[0],n=t[1],i=t[2]||0,o=t[3]||0,r=t[4]||1,
        a=t[5]||'',s='alt'===a||'\ue00a'===a,l='ctrl'===a||'\ue009'===a,
        c='shift'===a||'\ue008'===a,u=e.ownerDocument,
        f=e.getBoundingClientRect(),g=n?n.getBoundingClientRect():f,
        p=f.left+f.width/2,d=f.top+f.height/2,h=g.left+(i||g.width/2),
        m=g.top+(o||g.height/2),v=u.elementFromPoint(p,d),
        y=u.elementFromPoint(h,m);if(!v||!y){
        var E=new Error('source or target element is not interactable');
        throw E.code=15,E}var _={constructor:DataTransfer,effectAllowed:null,
        dropEffect:null,types:[],files:Object.setPrototypeOf([],null),
        _items:Object.setPrototypeOf([],{add:function(t,e){
        this[this.length]={_data:''+t,kind:'string',
        type:e,getAsFile:function(){},getAsString:function(t){t(this._data)}},
        _.types.push(e)},remove:function(t){
        Array.prototype.splice.call(this,65535&t,1),_.types.splice(65535&t,1)},
        clear:function(t,e){this.length=0,_.types.length=0}}),
        setData:function(t,e){this.clearData(t),this._items.add(e,t)},
        getData:function(t){for(var e=this._items.length;
        e--&&this._items[e].type!==t;);return e>=0?this._items[e]._data:null},
        clearData:function(t){for(var e=this._items.length;
        e--&&this._items[e].type!==t;);this._items.remove(e)},
        setDragImage:function(t){}};function w(t,e,n,i){
        for(var o=0;o<e.length;++o){var r=u.createEvent('MouseEvent');
        r.initMouseEvent(e[o],!0,!0,u.defaultView,0,0,0,p,d,l,s,c,!1,0,null),
        t.dispatchEvent(r)}i&&setTimeout(i,n)}function D(t,e,n,i){
        var o=u.createEvent('DragEvent');o.initMouseEvent(
        e,!0,!0,u.defaultView,0,0,0,p,d,l,s,c,!1,0,null),Object.setPrototypeOf(
        o,null),o.dataTransfer=_,Object.setPrototypeOf(o,DragEvent.prototype),
        t.dispatchEvent(o),i&&setTimeout(i,n)}
        'items'in DataTransfer.prototype&&(_.items=_._items),
        w(v,['pointerdown','mousedown'],1,function(){
        for(var t=v;t&&!t.draggable;)t=t.parentElement;if(t&&t.contains(v)){
        var e=y.getBoundingClientRect();D(v,'dragstart',r,function(){
        var t=y.getBoundingClientRect();p=t.left+h-e.left,d=t.top+m-e.top,D(
        y,'dragenter',1,function(){D(y,'dragover',r,
        function(){D(u.elementFromPoint(p,d),'drop',1,function(){D(v,'dragend',
        1,function(){w(u.elementFromPoint(p,d),
        ['mouseup','pointerup'])})})})})})}})"""
    return script

def get_drag_and_drop_with_offset_script(selector, x, y):
    # This script uses pure JS (No jQuery)
    script_a = """
        var source = document.querySelector("%s");
        var offsetX = %f;
        var offsetY = %f;
        """ % (
        selector,
        x,
        y,
    )
    script_b = r"""
        var rect = source.getBoundingClientRect();
        var dragPt = {x: rect.left + (rect.width >> 1),
                      y: rect.top + (rect.height >> 1)};
        var dropPt = {x: dragPt.x + offsetX, y: dragPt.y + offsetY};
        var target = document.elementFromPoint(dropPt.x, dropPt.y);
        var dataTransfer = {
          dropEffect: '',
          effectAllowed: 'all',
          files: [],
          items: {},
          types: [],
          setData: function (format, data) {
            this.items[format] = data;
            this.types.push(format);
          },
          getData: function (format) {
            return this.items[format];
          },
          clearData: function (format) { }
        };
        var emit = function (event, target, pt) {
          var evt = document.createEvent('MouseEvent');
          evt.initMouseEvent(event, true, true, window, 0, 0, 0, pt.x, pt.y,
                             false, false, false, false, 0, null);
          evt.dataTransfer = dataTransfer;
          target.dispatchEvent(evt);
        };
        emit('mousedown', source, dragPt);
        emit('mousemove', source, dragPt);
        emit('mousemove', source, dropPt);
        emit('mouseup',   source, dropPt);"""
    script = script_a + script_b
    return script

def clear_out_console_logs(driver):
    try:
        # Clear out the current page log before navigating to a new page
        # (To make sure that assert_no_js_errors() uses current results)
        driver.get_log("browser")
    except Exception:
        pass

def _jq_format(code):
    """
    DEPRECATED - Use re.escape() instead, which performs the intended action.
    Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
    Selectors with quotes inside of quotes would otherwise break jQuery.
    If you just want to escape quotes, there's escape_quotes_if_needed().
    This is similar to "json.dumps(value)", but with one less layer of quotes.
    """
    code = code.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n")
    code = code.replace('"', '\\"').replace("'", "\\'")
    code = code.replace("\v", "\\v").replace("\a", "\\a").replace("\f", "\\f")
    code = code.replace("\b", "\\b").replace(r"\u", "\\u").replace("\r", "\\r")
    return code


text:
import * as Mapbox from './mapbox';

export { Mapbox };

redpajama_set_name: RedPajamaGithub


text:
package tested.ds;

import leap.lang.Threads;
import leap.lang.jdbc.StatementAdapter;

import java.sql.SQLException;

public class MockStatement extends StatementAdapter {

    private final MockDataSource ds;
    private final MockConnection conn;

    public MockStatement(MockDataSource ds, MockConnection conn) {
        this.ds = ds;
        this.conn = conn;
    }

    @Override
    public boolean execute(String sql) throws SQLException {
        Threads.sleep(ds.getStatementDurationMs());
        return true;
    }

}


text:
import filter from './filter'

/**
 * @name compact
 * @category Collection
 * @description
 * Removes all falsy values from a list. For objects, dissociates all
 * properties with falsy values.
 *
 * @example
 * compact([null, undefined, 0, true, false]) // => [true]
 * compact({ a: false, b: null, c: true })    // => { c: true }
 */
export default function compact (xs) {
  return filter(Boolean, xs)
}


text:
require 'spec_helper'
require 'shared-examples'
manifest = 'roles/cinder.pp'

# FIXME: neut_vlan.cinder-block-device.compute.yaml ubuntu
# RUN: neut_vxlan_dvr.murano.sahara-cinder.yaml ubuntu
# SKIP_HIERA: neut_vlan.cinder-block-device.compute

describe manifest do

  before(:each) do
    Noop.puppet_function_load :is_pkg_installed
    MockFunction.new(:is_pkg_installed) do |function|
      allow(function).to receive(:call).and_return false
    end
  end

  shared_examples 'catalog' do

  storage_hash = Noop.hiera_hash 'storage'
  ceilometer_hash = Noop.hiera_hash 'ceilometer', { 'enabled' => false }
  use_ceph = Noop.hiera 'use_ceph'
  volume_backend_name = storage_hash['volume_backend_names']
  kombu_compression = Noop.hiera 'kombu_compression', ''

  database_vip = Noop.hiera('database_vip')
  cinder_db_password = Noop.hiera_structure 'cinder/db_password', 'cinder'
  cinder_db_user = Noop.hiera_structure 'cinder/db_user', 'cinder'
  cinder_db_name = Noop.hiera_structure 'cinder/db_name', 'cinder'
  cinder = Noop.puppet_function 'roles_include', 'cinder'

  let(:manage_volumes) do
    if cinder and storage_hash['volumes_lvm']
      'iscsi'
    elsif storage_hash['volumes_ceph']
      'ceph'
    else
      false
    end
  end

  it 'should configure the database connection string' do
    if facts[:os_package_type] == 'debian'
      extra_params = '?charset=utf8&read_timeout=60'
    else
      extra_params = '?charset=utf8'
    end
    should contain_class('cinder').with(
      :database_connection => "mysql://#{cinder_db_user}:#{cinder_db_password}@#{database_vip}/#{cinder_db_name}#{extra_params}"
    )
  end

  if use_ceph and !(storage_hash['volumes_lvm']) and !(member($roles, 'cinder-vmware'))
      it { should contain_class('ceph') }
  end

  it { should contain_package('python-amqp') }

  if Noop.hiera_structure('use_ssl')
    glance_protocol = 'https'
    glance_internal_address = Noop.hiera_structure('use_ssl/glance_internal_hostname')
  else
    glance_protocol = 'http'
    glance_internal_address = Noop.hiera('management_vip')
  end
  glance_api_servers = "#{glance_protocol}://#{glance_internal_address}:9292"

  it 'should contain correct glance api servers addresses' do
    should contain_class('cinder::glance').with(
      'glance_api_servers' => glance_api_servers
    )
  end

  it 'should disable use_stderr option' do
    should contain_cinder_config('DEFAULT/use_stderr').with(:value => 'false')
  end

  if storage_hash['volumes_block_device']
    disks_metadata = Noop.hiera('node_volumes')

    let (:disks_list) do
      disks_list = Noop.puppet_function('get_disks_list_by_role', disks_metadata, 'cinder-block-device')
    end

    let (:iscsi_bind_host) do
      iscsi_bind_host = Noop.puppet_function('get_network_role_property', 'cinder/iscsi', 'ipaddr')
    end

    it 'should contain proper config file for cinder' do
      should contain_cinder_config('DEFAULT/iscsi_helper').with(:value => 'fake')
      should contain_cinder_config('DEFAULT/iscsi_protocol').with(:value => 'iscsi')
      should contain_cinder_config('DEFAULT/volume_driver').with(:value => 'cinder.volume.drivers.block_device.BlockDeviceDriver')
      should contain_cinder_config('DEFAULT/iscsi_ip_address').with(:value => iscsi_bind_host)
      should contain_cinder_config('DEFAULT/volume_group').with(:value => 'cinder')
      should contain_cinder_config('DEFAULT/volume_dir').with(:value => '/var/lib/cinder/volumes')
      should contain_cinder_config('DEFAULT/volume_clear').with(:value => 'zero')
      should contain_cinder_config('DEFAULT/available_devices').with(:value => disks_list)
    end
  end

  it 'ensures that cinder have proper volume_backend_name' do
    if cinder and storage_hash['volumes_lvm']
      should contain_cinder__backend__iscsi('DEFAULT').with(
        'volume_backend_name' => volume_backend_name['volumes_lvm']
      )
    elsif storage_hash['volumes_ceph']
      should contain_cinder__backend__rbd('DEFAULT').with(
       'volume_backend_name' => volume_backend_name['volumes_ceph']
      )
    else
      should_not contain_cinder_config('DEFAULT/volume_backend_name')
    end
  end

  let :ceilometer_hash do
    Noop.hiera_hash 'ceilometer', { 'enabled' => false }
  end

  if ceilometer_hash['enabled']
    it 'should contain notification_driver option' do
      should contain_cinder_config('DEFAULT/notification_driver').with(:value => ceilometer_hash['notification_driver'])
    end
  end

  it 'should check stuff that openstack cinder did' do
    is_expected.to contain_class('cinder')
    if manage_volumes
      is_expected.to contain_class('cinder::volume')
    else
      is_expected.to_not contain_class('cinder::volume')
    end
  end

  if ['gzip', 'bz2'].include?(kombu_compression)
    it 'should configure kombu compression' do
      should contain_cinder_config('oslo_messaging_rabbit/kombu_compression').with(:value => kombu_compression)
    end
  end

  end # end of shared_examples
  test_ubuntu_and_centos manifest
end


text:
	×

{{singlePost.title}}

BY: {{singlePost.author}} | {{singlePost.datePublished | date:'MM-dd-yyyy'}}

        <blogger-comments post-instance="singlePost"></blogger-comments>


text:
namespace Synology.FileStation.Favorite.Results
{
    /// <summary>
    /// Favorite owner result.
    /// </summary>
    public interface IFavoriteOwnerResult
    {
        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <value>The user.</value>
        string User { get; }
        /// <summary>
        /// Gets the group.
        /// </summary>
        /// <value>The group.</value>
        string Group { get; }
        /// <summary>
        /// Gets the uid.
        /// </summary>
        /// <value>The uid.</value>
        int Uid { get; }
        /// <summary>
        /// Gets the gid.
        /// </summary>
        /// <value>The gid.</value>
        int Gid { get; }
    }
}


text:
@implementation PFUserExt

#pragma mark - Overrided methods

+ (instancetype)logInWithUsername:(NSString *)username
                         password:(NSString *)password
                            error:(NSError **)error
{
    return
    [self
     extLogInWithUsername:username
     password:password
     error:error];
}

+ (void)logOut
{
    [self extLogOut];
}

@end


text:
require 'rails/generators'

module Pavlov
  class InstallGenerator < Rails::Generators::Base
    def self.source_root
      @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
    end

    def copy_backend_directory
      directory 'backend', 'app/backend', recursive: true
    end

    def add_backend_to_autoload_paths
      application "config.autoload_paths += %W(\#{config.root}/app/backend)"
    end
  end
end


text:
/**
 * Spring Data JPA repositories.
 */
package com.in100gram.repository;


text:
#!/usr/bin/env python3

import os.path
import os
import json
import gmafile
import re
from functools import partial
from fnmatch import fnmatch

class GModAddon:
    """Represents a Garry's mod addon based on the addon.json data
    """
    def __init__(self, data, path, addonFile = 'addon.json'):
        self.data = data
        self.file = os.path.join(path, addonFile)
        self.path = path

    def has_workshop_id(self):
        """Whether this addon has a workshop id (and thus exists on the workshop)"""
        return u'workshopid' in self.data

    def getworkshopid(self):
        return u'workshopid' in self.data and self.data[u'workshopid'] or 0

    def getdefault_changelog(self):
        """The default changelog of the addon.

            Used when the changelog is omitted from the command line.
        """
        return u'default_changelog' in self.data and self.data[u'default_changelog'] or ''

    def gettitle(self):
        """Get the title (name) of the addon"""
        return 'title' in self.data and self.data['title'] or "No title"

    def getignored(self):
        """Get the list of files to be ignored in this addon
        Always returns a list, even if the addon does not provide a list of ignored files
        """
        if u'ignore' not in self.data:
            return []
        return self.data[u'ignore']

    def getsteamid(self):
        """Unused. Get the SteamID64 of the addon as an int."""
        return 'steamid64' in self.data and self.data['steamid64'] or 0

    def get_description_json(self):
        """The "description" of this addon (includes description, type and tags)
        This description is used in the GMA file.
        """
        a_description = u'description' in self.data and self.data['description'] or u'Description'
        a_type = self.data['type'].lower()
        a_tags = self.data['tags']
        return json.dumps({'description': a_description, 'type': a_type, 'tags': a_tags})

    def getdescription(self):
        """Get the description of the addon"""
        return u'description' in self.data and self.data[u'description'] or u'Description'

    def gettype(self):
        """Get the type of the addon"""
        return u'type' in self.data and self.data[u'type'] or u'type'

    def gettags(self):
        """Get the tags of the addon"""
        return u'tags' in self.data and self.data[u'tags'] or []

    def getlogo(self):
        """Get the logo of the addon"""
        return u'logo' in self.data and self.data[u'logo'] or ''

    def getauthor(self):
        """The author of the addon"""
        return 'author' in self.data and self.data['author'] or "Author Name"

    def getversion(self):
        """The addon version. This field is not used and will always return 1."""
        return 1

    def set_workshopid(self, id):
        """Set the workshop ID of the addon to id and store in addon.json"""
        self.data['workshopid'] = id
        self.save_changes()

    def save_changes(self):
        """Store the current state of the GModAddon to addon.json"""
        serialized = json.dumps(self.data, indent = 4, sort_keys = True)
        with open(self.file, 'w') as f:
            f.write(serialized)

    def getfiles(self):
        """Return a list of files in the addon
        all files are relative to the addon path
        """
        ignore = ['*' + os.path.relpath(self.file, self.path)] # Always add the addon.json file
        ignore += self.getignored()

        file_list = []

        for dir, _, files in os.walk(self.path):
            rel = os.path.relpath(dir, self.path)
            file_list += list(map(partial(os.path.join, rel), files))

        # Remove './' at the start of some paths
        file_list = sorted(list(map(partial(re.sub, r'^\.[/\\]', ''), file_list)))
        # Replace backslashes with forward slashes (Windows)
        file_list = list(map(partial(re.sub, r'\\', '/'), file_list))
        return list(filter(partial(self._file_nomatch, ignore), file_list))

    def getpath(self):
        """The path of the addon folder"""
        return self.path

    def setfile(self, file):
        self.file = file
        self.path = os.path.dirname(file)

    def _file_nomatch(self, ignore, f):
        """Whether a given file is not in the blacklist
        >>> addon_info_from_path("test")._file_nomatch(['*.psd'], 'a/b/c.psd')
        False
        >>> addon_info_from_path("test")._file_nomatch(['*.psd', '*.svn*'], 'a/b/c.lua')
        True
        """
        for pattern in ignore:
            if fnmatch(f, pattern):
                return False

        return True

    def verify_files(self):
        """Check if all files in the path are allowed in a GMA file.
        >>> addon_info_from_path("test").verify_files()
        (True, [])
        """
        file_list = self.getfiles()
        disallowed = list(filter(partial(self._file_nomatch, addon_whitelist), file_list))
        return not disallowed, disallowed

    def compress(self, output):
        """Compress the contents of a folder into a .gma file"""
        allowed, illegal_files = self.verify_files()
        if not allowed:
            return False, illegal_files

        gmafile.write(self, output)

        return True, []

class AddonNotFoundError(Exception):
    def __init__(self, path):
        self.value = path

    def __str__(self):
        return "No GMod addon found in " + os.path.abspath(self.value)

def find_addon(location, addonFile = 'addon.json'):
    """Try to find an addon.json file at location or any of the parents
        e.g. find_addon("a/b/c/") will try to find the following files in order:
         - a/b/c/addon.json
         - a/b/addon.json
         - a/addon.json
         - /addon.json

        An exception will be thrown if the addon.json is not found.
        >>> find_addon("test")
        'test/addon.json'

        >>> find_addon("/etc/")
        Traceback (most recent call last):
        ...
        AddonNotFoundError: No GMod addon found in /etc
    """
    curLocation = location

    # Try at most 10 levels up
    for k in range(1, 10):
        filename = os.path.join(curLocation, addonFile)

        if os.path.isfile(filename):
            return filename

        curLocation = os.path.dirname(curLocation)
    else:
        raise AddonNotFoundError(location)

def get_addon_info(addon_info_path):
    """Get the contents of addon.json in a dictionary
    >>> isinstance(addon_info_from_path('test'), GModAddon)
    True

    >>> get_addon_info('WrongPath')
    """
    if not os.path.isfile(addon_info_path):
        return

    with open(addon_info_path, 'r') as f:
        data = json.load(f)

    return GModAddon(data, os.path.dirname(addon_info_path), addon_info_path)

def addon_info_from_path(path, addonFile = 'addon.json'):
    """Get the addon info from a folder path."""
    return get_addon_info(find_addon(path, addonFile))

addon_whitelist = [
            "maps/*.bsp",
            "maps/*.png",
            "maps/*.nav",
            "maps/*.ain",
            "sound/*.wav",
            "sound/*.mp3",
            "sound/*.ogg",
            "lua/*.lua",
            "materials/*.vmt",
            "materials/*.vtf",
            "materials/*.png",
            "materials/*.jpeg",
            "materials/*.jpg",
            "models/*.mdl",
            "models/*.vtx",
            "models/*.phy",
            "models/*.ani",
            "models/*.vvd",
            "gamemodes/*.txt",
            "gamemodes/*/gamemode/*.lua",
            "gamemodes/*/entities/effects/*.lua",
            "gamemodes/*/entities/entities/*.lua",
            "gamemodes/*/entities/weapons/*.lua",
            "gamemodes/*/backgrounds/*.jpeg",
            "gamemodes/*/backgrounds/*.png",
            "gamemodes/*/*.fgd",
            "gamemodes/*/content/models/*.mdl",
            "gamemodes/*/content/models/*.vtx",
            "gamemodes/*/content/models/*.phy",
            "gamemodes/*/content/models/*.ani",
            "gamemodes/*/content/models/*.vvd",
            "gamemodes/*/content/materials/*.vmt",
            "gamemodes/*/content/materials/*.vtf",
            "gamemodes/*/content/materials/*.png",
            "gamemodes/*/content/materials/*.jpg",
            "gamemodes/*/content/materials/*.jpeg",
            "gamemodes/*/content/scenes/*.vcd",
            "gamemodes/*/content/particles/*.pcf",
            "gamemodes/*/content/resource/fonts/*.ttf",
            "gamemodes/*/content/scripts/vehicles/*.txt",
            "gamemodes/*/content/resource/localization/*/*.properties",
            "gamemodes/*/content/maps/*.bsp",
            "gamemodes/*/content/maps/*.nav",
            "gamemodes/*/content/maps/*.ain",
            "gamemodes/*/content/maps/thumb/*.png",
            "gamemodes/*/content/sound/*.wav",
            "gamemodes/*/content/sound/*.mp3",
            "gamemodes/*/content/sound/*.ogg",
            "scenes/*.vcd",
            "particles/*.pcf",
            "gamemodes/*/backgrounds/*.jpg",
            "gamemodes/*/icon24.png",
            "gamemodes/*/logo.png",
            "scripts/vehicles/*.txt",
            "resource/localization/*/*.properties",
            "resource/fonts/*.ttf"
            ]

if __name__ == '__main__':
    import doctest
    doctest.testmod()


text:
package org.openestate.io.openimmo.xml;

import java.io.Serializable;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.CopyStrategy2;
import org.jvnet.jaxb2_commons.lang.CopyTo2;
import org.jvnet.jaxb2_commons.lang.Equals2;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy2;
import org.jvnet.jaxb2_commons.lang.JAXBCopyStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString2;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy2;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;

/**
 * Java class for <erschliessung_umfang> element.
 *
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "erschliessung_umfang")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
public class ErschliessungUmfang implements Serializable, Cloneable, CopyTo2, Equals2, ToString2
{

    @XmlAttribute(name = "erschl_attr")
    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    protected ErschliessungUmfang.ErschlAttr erschlAttr;

    /**
     * Gets the value of the erschlAttr property.
     *
     * @return
     *     possible object is
     *     {@link ErschliessungUmfang.ErschlAttr }
     *
     */
    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public ErschliessungUmfang.ErschlAttr getErschlAttr() {
        return erschlAttr;
    }

    /**
     * Sets the value of the erschlAttr property.
     *
     * @param value
     *     allowed object is
     *     {@link ErschliessungUmfang.ErschlAttr }
     *
     */
    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public void setErschlAttr(ErschliessungUmfang.ErschlAttr value) {
        this.erschlAttr = value;
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public String toString() {
        final ToStringStrategy2 strategy = JAXBToStringStrategy.INSTANCE2;
        final StringBuilder buffer = new StringBuilder();
        append(null, buffer, strategy);
        return buffer.toString();
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) {
        strategy.appendStart(locator, this, buffer);
        appendFields(locator, buffer, strategy);
        strategy.appendEnd(locator, this, buffer);
        return buffer;
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) {
        {
            ErschliessungUmfang.ErschlAttr theErschlAttr;
            theErschlAttr = this.getErschlAttr();
            strategy.appendField(locator, this, "erschlAttr", buffer, theErschlAttr, (this.erschlAttr!= null));
        }
        return buffer;
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public Object clone() {
        return copyTo(createNewInstance());
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public Object copyTo(Object target) {
        final CopyStrategy2 strategy = JAXBCopyStrategy.INSTANCE2;
        return copyTo(null, target, strategy);
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public Object copyTo(ObjectLocator locator, Object target, CopyStrategy2 strategy) {
        final Object draftCopy = ((target == null)?createNewInstance():target);
        if (draftCopy instanceof ErschliessungUmfang) {
            final ErschliessungUmfang copy = ((ErschliessungUmfang) draftCopy);
            {
                Boolean erschlAttrShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.erschlAttr!= null));
                if (erschlAttrShouldBeCopiedAndSet == Boolean.TRUE) {
                    ErschliessungUmfang.ErschlAttr sourceErschlAttr;
                    sourceErschlAttr = this.getErschlAttr();
                    ErschliessungUmfang.ErschlAttr copyErschlAttr = ((ErschliessungUmfang.ErschlAttr) strategy.copy(LocatorUtils.property(locator, "erschlAttr", sourceErschlAttr), sourceErschlAttr, (this.erschlAttr!= null)));
                    copy.setErschlAttr(copyErschlAttr);
                } else {
                    if (erschlAttrShouldBeCopiedAndSet == Boolean.FALSE) {
                        copy.erschlAttr = null;
                    }
                }
            }
        }
        return draftCopy;
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public Object createNewInstance() {
        return new ErschliessungUmfang();
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) {
        if ((object == null)||(this.getClass()!= object.getClass())) {
            return false;
        }
        if (this == object) {
            return true;
        }
        final ErschliessungUmfang that = ((ErschliessungUmfang) object);
        {
            ErschliessungUmfang.ErschlAttr lhsErschlAttr;
            lhsErschlAttr = this.getErschlAttr();
            ErschliessungUmfang.ErschlAttr rhsErschlAttr;
            rhsErschlAttr = that.getErschlAttr();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "erschlAttr", lhsErschlAttr), LocatorUtils.property(thatLocator, "erschlAttr", rhsErschlAttr), lhsErschlAttr, rhsErschlAttr, (this.erschlAttr!= null), (that.erschlAttr!= null))) {
                return false;
            }
        }
        return true;
    }

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public boolean equals(Object object) {
        final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE2;
        return equals(null, null, object, strategy);
    }

    /**
     *
     *                     Java enum for erschl_attr attribute in <erschliessung_umfang> elements.
     *
     *
Java class for null.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *

     *

     * <simpleType>
     *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
     *     <enumeration value="GAS"/>
     *     <enumeration value="WASSER"/>
     *     <enumeration value="STROM"/>
     *     <enumeration value="TK"/>
     *   </restriction>
     * </simpleType>
     *

     *
     */
    @XmlType(name = "")
    @XmlEnum
    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T06:31:15+02:00", comments = "JAXB RI v2.3.0")
    public enum ErschlAttr {

        GAS,
        WASSER,
        STROM,
        TK;

        public String value() {
            return name();
        }

        public static ErschliessungUmfang.ErschlAttr fromValue(String v) {
            return valueOf(v);
        }

    }

}


text:
#include "stdafx.h"
#include "DeviceFlt.h"

#include <DriverMgr\DriverMgr.h>

namespace MBox
{
    namespace DeviceFlt
    {
        //
        // Private struct & enum
        //

        enum class PnpDeviceState : UINT32
        {
            Removed,
            Removing,

            Attached,
            Attaching,

            Stopped,
            Stopping,

            Started,
            Starting,
        };

        struct DeviceContext
        {
            IO_REMOVE_LOCK		m_RemoveLock{};
            PnpDeviceState		m_PnpState = PnpDeviceState::Removed;
            PnpDeviceState		m_BeforePnpState = PnpDeviceState::Removed;

            DEVICE_OBJECT*		m_PhysicalDeviceObject = nullptr;
            DEVICE_OBJECT*		m_NextDeviceObject = nullptr;

            DeviceContext();

            NTSTATUS AcquireRemoveLock(IRP* aIrp);
            void ReleaseRemoveLock(IRP* aIrp);
            void ReleaseRemoveLockAndWait(IRP* aIrp);

            void SetCurrentPnpState(PnpDeviceState aPnpState);
        };

        DeviceContext::DeviceContext()
        {
            IoInitializeRemoveLock(
                &m_RemoveLock,
                KTL$CompileTime$ByteSwap32$Macro('MBox'),
                0,
                0);
        }

        NTSTATUS DeviceContext::AcquireRemoveLock(IRP* aIrp)
        {
            return IoAcquireRemoveLock(&m_RemoveLock, aIrp);
        }

        void DeviceContext::ReleaseRemoveLock(IRP* aIrp)
        {
            return IoReleaseRemoveLock(&m_RemoveLock, aIrp);
        }

        void DeviceContext::ReleaseRemoveLockAndWait(IRP * aIrp)
        {
            return IoReleaseRemoveLockAndWait(&m_RemoveLock, aIrp);
        }

        void DeviceContext::SetCurrentPnpState(PnpDeviceState aPnpState)
        {
            InterlockedExchange((volatile long*)&m_BeforePnpState, (long)m_PnpState);
            InterlockedExchange((volatile long*)&m_PnpState, (long)aPnpState);
        }

        //////////////////////////////////////////////////////////////////////////

        //
        // Global static member
        //

        static volatile long    s_IsStartedFilter   = false;
        HANDLE                  s_GroupHandle       = nullptr;

        //////////////////////////////////////////////////////////////////////////

        //
        // Static private function & helper function
        //

        static void FltUnload(DRIVER_OBJECT* /*aDriverObject*/)
        {
            Uninitialize();
        }

        static NTSTATUS FltAddDevice(
            DRIVER_OBJECT* /*aDriverObject*/,
            DEVICE_OBJECT* aPhysicalDeviceObject)
        {
            NTSTATUS vStatus = STATUS_SUCCESS;

            DEVICE_OBJECT* vDeviceObject = nullptr;

            for (;;)
            {
                DEVICE_TYPE    vDeviceType = 0;

                DEVICE_OBJECT* vTopDeviceObject = IoGetAttachedDeviceReference(aPhysicalDeviceObject);
                vDeviceType = vTopDeviceObject->DeviceType;
                ObDereferenceObject(vTopDeviceObject);
                vTopDeviceObject = nullptr;

                vStatus = DriverMgr::CreateDeviceObject(
                    s_GroupHandle,
                    sizeof(DeviceContext),
                    nullptr,
                    vDeviceType,
                    FILE_DEVICE_SECURE_OPEN,
                    FALSE,
                    &vDeviceObject);
                if (!NT_SUCCESS(vStatus))
                {
                    break;
                }

                DeviceContext* vDeviceContext = new(vDeviceObject->DeviceExtension) DeviceContext;
                if (nullptr == vDeviceContext)
                {
                    // Only to eliminate the warning..

                    vStatus = STATUS_INSUFFICIENT_RESOURCES;
                    break;
                }

                vDeviceContext->m_PhysicalDeviceObject = aPhysicalDeviceObject;

                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Attaching);
                vDeviceContext->m_NextDeviceObject = IoAttachDeviceToDeviceStack(vDeviceObject, aPhysicalDeviceObject);
                if (nullptr == vDeviceContext->m_NextDeviceObject)
                {
                    vStatus = STATUS_DEVICE_REMOVED;
                    break;
                }
                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Attached);

                vDeviceObject->Flags = (vDeviceContext->m_NextDeviceObject->Flags
                    & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE));

                vDeviceObject->DeviceType = vDeviceContext->m_NextDeviceObject->DeviceType;
                vDeviceObject->Characteristics = vDeviceContext->m_NextDeviceObject->Characteristics;

                vDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING);
                break;
            }

            if (!NT_SUCCESS(vStatus))
            {
                if (vDeviceObject)
                {
                    DriverMgr::DeleteDeviceObject(s_GroupHandle, vDeviceObject);
                }
            }

            return vStatus;
        }

        static NTSTATUS FltIoCompletion(
            PDEVICE_OBJECT /*aDeviceObject*/,
            PIRP           aIrp,
            PVOID          aContext)
        {
            if (aIrp->PendingReturned)
            {
                KeSetEvent(PKEVENT(aContext), IO_NO_INCREMENT, FALSE);
            }
            return STATUS_MORE_PROCESSING_REQUIRED;
        }

        static NTSTATUS FltIoOperation(
            DEVICE_OBJECT *aDeviceObject,
            IRP *aIrp)
        {
            NTSTATUS vStatus = STATUS_SUCCESS;

            KEVENT vCompletionEvent{};
            KeInitializeEvent(&vCompletionEvent, NotificationEvent, FALSE);
            IoCopyCurrentIrpStackLocationToNext(aIrp);

            IoSetCompletionRoutine(
                aIrp,
                FltIoCompletion,
                &vCompletionEvent,
                TRUE,
                TRUE,
                TRUE);

            vStatus = IoCallDriver(aDeviceObject, aIrp);
            if (STATUS_PENDING == vStatus)
            {
                KeWaitForSingleObject(&vCompletionEvent, Executive, KernelMode, FALSE, nullptr);
                vStatus = aIrp->IoStatus.Status;
            }

            return vStatus;
        }

        _Dispatch_type_(IRP_MJ_PNP)
        static NTSTATUS FltPnpDispatch(
            DEVICE_OBJECT *aDeviceObject,
            IRP *aIrp)
        {
            NTSTATUS vStatus = STATUS_SUCCESS;

            IO_STACK_LOCATION* vIrp = IoGetCurrentIrpStackLocation(aIrp);
            auto vDeviceContext = static_cast<DeviceContext*>(aDeviceObject->DeviceExtension);
            vStatus = vDeviceContext->AcquireRemoveLock(aIrp);
            if (!NT_SUCCESS(vStatus))
            {
                aIrp->IoStatus.Status = vStatus;
                IoCompleteRequest(aIrp, IO_NO_INCREMENT);
                return vStatus;
            }

            bool vIsNeedCompleteRequest = false;
            auto vMinorFunctionIndex = vIrp->MinorFunction;
            switch (vMinorFunctionIndex)
            {
            default:
            {
                IoSkipCurrentIrpStackLocation(aIrp);
                vStatus = IoCallDriver(vDeviceContext->m_NextDeviceObject, aIrp);
                break;
            }

            case IRP_MN_START_DEVICE:
            {
                vIsNeedCompleteRequest = true;

                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Starting);

                vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);
                if (!NT_SUCCESS(vStatus))
                {
                    vDeviceContext->SetCurrentPnpState(vDeviceContext->m_BeforePnpState);
                    break;
                }

                Vol::Device::DeviceClasses vDeviceType = Vol::Device::GetDeviceClasses(vDeviceContext->m_PhysicalDeviceObject);
                vStatus = InstanceSetupCallback(aDeviceObject, vDeviceType);
                aIrp->IoStatus.Status = vStatus;

                if (!NT_SUCCESS(vStatus))
                {
                    vDeviceContext->SetCurrentPnpState(vDeviceContext->m_BeforePnpState);
                }
                else
                {
                    vDeviceContext->SetCurrentPnpState(PnpDeviceState::Started);
                }

                break;
            }

            case IRP_MN_QUERY_STOP_DEVICE:
            {
                vStatus = InstanceQueryTeardownCallback(aDeviceObject);
                if (!NT_SUCCESS(vStatus))
                {
                    aIrp->IoStatus.Status = vStatus;
                    IoCompleteRequest(aIrp, IO_NO_INCREMENT);
                    break;
                }

                aIrp->IoStatus.Status = STATUS_SUCCESS;
                IoSkipCurrentIrpStackLocation(aIrp);
                vStatus = IoCallDriver(vDeviceContext->m_NextDeviceObject, aIrp);
                break;
            }

            case IRP_MN_STOP_DEVICE:
            {
                vIsNeedCompleteRequest = true;

                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Stopping);

                //
                // Pre-Stop
                //

                InstanceTeardownStartCallback(aDeviceObject);

                //
                // Stop
                //

                vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);
                if (!NT_SUCCESS(vStatus))
                {
                    vDeviceContext->SetCurrentPnpState(vDeviceContext->m_BeforePnpState);
                    break;
                }

                //
                // Post-Stop
                //

                InstanceTeardownCompleteCallback(aDeviceObject);

                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Stopped);
                break;
            }

            case IRP_MN_CANCEL_STOP_DEVICE:
            {
                if (PnpDeviceState::Stopping == vDeviceContext->m_PnpState)
                {
                    vIsNeedCompleteRequest = true;

                    vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);
                    if (!NT_SUCCESS(vStatus))
                    {
                        break;
                    }

                    vDeviceContext->SetCurrentPnpState(vDeviceContext->m_BeforePnpState);
                    break;
                }

                aIrp->IoStatus.Status = STATUS_SUCCESS;
                IoSkipCurrentIrpStackLocation(aIrp);
                vStatus = IoCallDriver(vDeviceContext->m_NextDeviceObject, aIrp);
                break;
            }

            case IRP_MN_QUERY_REMOVE_DEVICE:
            {
                if (PnpDeviceState::Stopped != vDeviceContext->m_PnpState)
                {
                    vStatus = InstanceQueryTeardownCallback(aDeviceObject);
                    if (!NT_SUCCESS(vStatus))
                    {
                        aIrp->IoStatus.Status = vStatus;
                        IoCompleteRequest(aIrp, IO_NO_INCREMENT);
                        break;
                    }
                }

                aIrp->IoStatus.Status = STATUS_SUCCESS;
                IoSkipCurrentIrpStackLocation(aIrp);
                vStatus = IoCallDriver(vDeviceContext->m_NextDeviceObject, aIrp);
                break;
            }

            case IRP_MN_REMOVE_DEVICE:
            {
                vIsNeedCompleteRequest = true;
                bool vNeedCleanupContext = false;

                if (PnpDeviceState::Stopped != vDeviceContext->m_PnpState
                    && PnpDeviceState::Stopping != vDeviceContext->m_BeforePnpState)
                {
                    vNeedCleanupContext = true;
                }

                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Removing);
                vDeviceContext->ReleaseRemoveLockAndWait(aIrp);

                if (vNeedCleanupContext)
                {
                    //
                    // Pre-Stop
                    //

                    InstanceTeardownStartCallback(aDeviceObject);
                }

                //
                // Stop & Remove
                //

                vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);
                if (!NT_SUCCESS(vStatus))
                {
                    break;
                }
                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Removed);

                if (vNeedCleanupContext)
                {
                    //
                    // Post-Stop
                    //

                    InstanceTeardownCompleteCallback(aDeviceObject);
                }

                IoDetachDevice(vDeviceContext->m_NextDeviceObject);
                DriverMgr::DeleteDeviceObject(s_GroupHandle, aDeviceObject);
                break;
            }

            case IRP_MN_CANCEL_REMOVE_DEVICE:
            {
                if (PnpDeviceState::Removing == vDeviceContext->m_PnpState)
                {
                    vIsNeedCompleteRequest = true;

                    vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);
                    if (!NT_SUCCESS(vStatus))
                    {
                        break;
                    }

                    vDeviceContext->SetCurrentPnpState(vDeviceContext->m_BeforePnpState);
                    break;
                }

                aIrp->IoStatus.Status = STATUS_SUCCESS;
                IoSkipCurrentIrpStackLocation(aIrp);
                vStatus = IoCallDriver(vDeviceContext->m_NextDeviceObject, aIrp);
                break;
            }

            case IRP_MN_SURPRISE_REMOVAL:
            {
                vIsNeedCompleteRequest = true;

                vDeviceContext->SetCurrentPnpState(PnpDeviceState::Removed);

                vDeviceContext->ReleaseRemoveLockAndWait(aIrp);

                //
                // Pre-Stop
                //

                InstanceTeardownStartCallback(aDeviceObject);

                //
                // Stop
                //

                vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);
                if (!NT_SUCCESS(vStatus))
                {
                    break;
                }

                //
                // Post-Stop
                //

                InstanceTeardownCompleteCallback(aDeviceObject);

                //
                // Detach & Delete device
                //

                IoDetachDevice(vDeviceContext->m_NextDeviceObject);
                DriverMgr::DeleteDeviceObject(s_GroupHandle, aDeviceObject);

                break;
            }

            case IRP_MN_DEVICE_USAGE_NOTIFICATION:
            {
                vIsNeedCompleteRequest = true;

#pragma prefast(disable: 28175, "The DeviceObject->Flags need to be the same.")
                if (aDeviceObject->AttachedDevice == nullptr
                    || aDeviceObject->AttachedDevice->Flags & DO_POWER_PAGABLE)
                {
                    aDeviceObject->Flags |= DO_POWER_PAGABLE;
                }

                vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);

                if (!(vDeviceContext->m_NextDeviceObject->Flags & DO_POWER_PAGABLE))
                {
                    aDeviceObject->Flags &= (~DO_POWER_PAGABLE);
                }
#pragma prefast(pop)

                break;
            }

            }

            if (vIsNeedCompleteRequest)
            {
                aIrp->IoStatus.Status = vStatus;
                IoCompleteRequest(aIrp, IO_NO_INCREMENT);
            }

            if (IRP_MN_REMOVE_DEVICE != vMinorFunctionIndex
                && IRP_MN_SURPRISE_REMOVAL != vMinorFunctionIndex)
            {
                vDeviceContext->ReleaseRemoveLock(aIrp);
            }

            return vStatus;
        }

        _Dispatch_type_(IRP_MJ_POWER)
        static NTSTATUS FltPowerDispatch(
            DEVICE_OBJECT *aDeviceObject,
            IRP *aIrp)
        {
            NTSTATUS vStatus = STATUS_SUCCESS;

            auto vDeviceContext = static_cast<DeviceContext*>(aDeviceObject->DeviceExtension);
            vStatus = vDeviceContext->AcquireRemoveLock(aIrp);
            if (!NT_SUCCESS(vStatus))
            {
                aIrp->IoStatus.Status = vStatus;
                IoCompleteRequest(aIrp, IO_NO_INCREMENT);
                return vStatus;
            }

            for (;;)
            {
                PoStartNextPowerIrp(aIrp);
                IoSkipCurrentIrpStackLocation(aIrp);
                vStatus = PoCallDriver(vDeviceContext->m_NextDeviceObject, aIrp);

                break;
            }

            vDeviceContext->ReleaseRemoveLock(aIrp);
            return vStatus;
        }

        _Dispatch_type_(IRP_MJ_OTHER)
        static NTSTATUS FltDispatch(
            DEVICE_OBJECT *aDeviceObject,
            IRP *aIrp)
        {
            NTSTATUS vStatus = STATUS_SUCCESS;

            auto vDeviceContext = static_cast<DeviceContext*>(aDeviceObject->DeviceExtension);
            vStatus = vDeviceContext->AcquireRemoveLock(aIrp);
            if (!NT_SUCCESS(vStatus))
            {
                //
                // STATUS_DELETE_PENDING
                //

                aIrp->IoStatus.Status = vStatus;
                IoCompleteRequest(aIrp, IO_NO_INCREMENT);
                return vStatus;
            }

            for (;;)
            {
                //
                // Pre-operation
                //

                PreOperationCallbackStatus vPreCallbackStatus = PreOperationCallbackStatus::SuccessWithCallback;
                vPreCallbackStatus = PreOperationCallback(aDeviceObject, aIrp, nullptr);
                if (PreOperationCallbackStatus::Complete == vPreCallbackStatus)
                {
                    vStatus = aIrp->IoStatus.Status;
                    break;
                }

                //
                // Operation
                //

                vStatus = FltIoOperation(vDeviceContext->m_NextDeviceObject, aIrp);
                if (!NT_SUCCESS(vStatus))
                {
                    break;
                }

                //
                // Post-operation
                //

                PostOperationCallbackStatus vPostCallbackStatus = PostOperationCallbackStatus::FinishedProcessing;
                vPostCallbackStatus = PostOperationCallback(aDeviceObject, aIrp, nullptr);

                vStatus = aIrp->IoStatus.Status;
                break;
            }

            aIrp->IoStatus.Status = vStatus;
            IoCompleteRequest(aIrp, IO_NO_INCREMENT);

            vDeviceContext->ReleaseRemoveLock(aIrp);
            return vStatus;
        }

        //////////////////////////////////////////////////////////////////////////

        //
        // Public function
        //

        NTSTATUS Initialize()
        {
            NTSTATUS vStatus = STATUS_SUCCESS;

            for (;;)
            {
                vStatus = GetContextManager()->Initialize();
                if (!NT_SUCCESS(vStatus))
                {
                    break;
                }

                vStatus = GetCallbackPacketManager()->Initialize();
                if (!NT_SUCCESS(vStatus))
                {
                    break;
                }

                break;
            }

            if (!NT_SUCCESS(vStatus))
            {
                Uninitialize();
            }

            return vStatus;
        }

        void Uninitialize()
        {
            GetContextManager()->Uninitialize();
            GetCallbackPacketManager()->Uninitialize();
        }

        NTSTATUS RegisterFilter()
        {
            NTSTATUS vStatus = STATUS_SUCCESS;

            for (;;)
            {
                auto vDispatchPacket = new DriverMgr::DispatchCallbackPacket;
                if (nullptr == vDispatchPacket)
                {
                    vStatus = STATUS_INSUFFICIENT_RESOURCES;
                    break;
                }

                for (ktl::u32 i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; ++i)
                {
                    vDispatchPacket->m_MajorCallback[i] = FltDispatch;
                }

                vDispatchPacket->m_AddDeviceCallback    = FltAddDevice;
                vDispatchPacket->m_UnloadCallback       = FltUnload;

                vDispatchPacket->m_MajorCallback[IRP_MJ_PNP]    = FltPnpDispatch;
                vDispatchPacket->m_MajorCallback[IRP_MJ_POWER]  = FltPowerDispatch;

                vStatus = DriverMgr::RegisterDeviceGroup(
                    &s_GroupHandle,
                    vDispatchPacket,
                    [](DriverMgr::DispatchCallbackPacket* aDispatchPacket)->void { delete aDispatchPacket; });
                if (!NT_SUCCESS(vStatus))
                {
                    delete vDispatchPacket;
                    vDispatchPacket = nullptr;
                    break;
                }

                break;
            }

            return vStatus;
        }

        NTSTATUS StartFilter()
        {
            InterlockedExchange(&s_IsStartedFilter, TRUE);
            return STATUS_SUCCESS;
        }

        NTSTATUS StopFilter()
        {
            InterlockedExchange(&s_IsStartedFilter, FALSE);
            return STATUS_SUCCESS;
        }

        BOOLEAN IsStartedFilter()
        {
            return BOOLEAN(s_IsStartedFilter);
        }

    }
}


text:
<?php

namespace Omines\Semver\Collections;

use Omines\Semver\Version;

/**
 * VersionMapIterator.
 *
 * @author Niels Keurentjes <niels.keurentjes@omines.com>
 */
class VersionMapIterator extends AbstractVersionIterator
{
    /**
     * {@inheritdoc}
     */
    public function current()
    {
        $item = current($this->data);
        return $item[1];
    }

    /**
     * @return Version
     */
    public function key()
    {
        $item = current($this->data);
        return $item[0];
    }
}


text:
object P07 {
  def flatten(items: List[Any]): List[Any] = items flatMap {
    case list: List[_] => flatten(list)
    case e => List(e)
  }
}


text:
class KeyboardSocket: public Socket
{
public:
  typedef std::shared_ptr<KeyboardSocket> Ptr;

public:
  KeyboardSocket();
  virtual ~KeyboardSocket();
};

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Peronospora euphorbiae-thymifoliae Sawada

### Remarks
null


text:
package uk.co.optimisticpanda.gtest.dto;

import java.util.List;

import uk.co.optimisticpanda.gtest.dto.rule.Edit;
import uk.co.optimisticpanda.gtest.dto.util.FunctionUtils;
import uk.co.optimisticpanda.gtest.dto.util.MapOfLists;

/**
 * A {@link IDataEditor} that can be used to edit multiple types of dto. Rules
 * are keyed on the class of the dto that its is applicable for.
 *
 * @author Andy Lee
 */
public class MappedClassDataEditor implements IDataEditor<Object> {

	MapOfLists<Class<?>, Edit<? extends Object>> map = new MapOfLists<Class<?>, Edit<? extends Object>>();

	/**
	 * Create a new MappedClassDataEditor
	 */
	public MappedClassDataEditor() {
		//do nothing apart from instantiation
	}

	/**
	 * see {@link IDataEditor#edit(List)}
	 *
	 * @param testData
	 *            the collection of dtos to apply the rules to.
	 */
	public void edit(List<Object> testData) {
		testData.stream()
					.map(FunctionUtils.indexed())
					.forEach(i -> edit(i.index, i.item));
	}

	/**
	 * see {@link IDataEditor#edit(int, Object)}
	 *
	 * @param index
	 *            the current index of the dto in the list
	 * @param dataItem
	 *            the dto to apply the rule to.
	 */
	@SuppressWarnings("unchecked")
	public Object edit(int index, Object dataItem) {
		List<Edit<? extends Object>> rules = getEdits(dataItem);
		rules.stream()
			.map(r -> ((Edit<Object>) r))
			.filter(r -> r.isValid(index, dataItem))
			.forEach(r-> r.edit(index, dataItem));
		return dataItem;
	}

	/**
	 * This is protected to enable the use of other strategies when retrieving
	 * rules. For instance a strategy for dealing with proxied objects.
	 *
	 * @param dataItem
	 *            the dto that the returned rules will be applicable for.
	 * @return The applicable rules for this dto.
	 * */
	protected List<Edit<? extends Object>> getEdits(Object dataItem) {
		return map.get(dataItem.getClass());
	}

	/**
	 * @param <D>
	 *            the type of the data item this rule will be stored against.
	 * @param clazz
	 *            the clazz of the dto.
	 * @param edit
	 *            the rule to store against this type of dto.
	 */
	public <D> void addEditForClass(Class<D> clazz, Edit<D> edit) {
		map.putA(clazz, edit);
	}
}


text:
define(["Tone/core/Tone", "Tone/component/FeedbackCombFilter", "Tone/effect/StereoEffect", "Tone/signal/Scale"],
function(Tone){

	"use strict";

	/**
	 *  an array of the comb filter delay time values
	 *  @private
	 *  @static
	 *  @type {Array}
	 */
	var combFilterDelayTimes = [1687 / 25000, 1601 / 25000, 2053 / 25000, 2251 / 25000];

	/**
	 *  the resonances of each of the comb filters
	 *  @private
	 *  @static
	 *  @type {Array}
	 */
	var combFilterResonances = [0.773, 0.802, 0.753, 0.733];

	/**
	 *  the allpass filter frequencies
	 *  @private
	 *  @static
	 *  @type {Array}
	 */
	var allpassFilterFreqs = [347, 113, 37];

	/**
	 *  @class Tone.JCReverb is a simple [Schroeder Reverberator](https://ccrma.stanford.edu/~jos/pasp/Schroeder_Reverberators.html)
	 *         tuned by John Chowning in 1970.
	 *         It is made up of three allpass filters and four Tone.FeedbackCombFilter.
	 *
	 *
	 *  @extends {Tone.Effect}
	 *  @constructor
	 *  @param {NormalRange|Object} [roomSize] Coorelates to the decay time.
	 *  @example
	 * var reverb = new Tone.JCReverb(0.4).connect(Tone.Master);
	 * var delay = new Tone.FeedbackDelay(0.5);
	 * //connecting the synth to reverb through delay
	 * var synth = new Tone.DuoSynth().chain(delay, reverb);
	 * synth.triggerAttackRelease("A4","8n");
	 */
	Tone.JCReverb = function(){

		var options = this.optionsObject(arguments, ["roomSize"], Tone.JCReverb.defaults);
		Tone.StereoEffect.call(this, options);

		/**
		 *  room size control values between [0,1]
		 *  @type {NormalRange}
		 *  @signal
		 */
		this.roomSize = new Tone.Signal(options.roomSize, Tone.Type.NormalRange);

		/**
		 *  scale the room size
		 *  @type {Tone.Scale}
		 *  @private
		 */
		this._scaleRoomSize = new Tone.Scale(-0.733, 0.197);

		/**
		 *  a series of allpass filters
		 *  @type {Array}
		 *  @private
		 */
		this._allpassFilters = [];

		/**
		 *  parallel feedback comb filters
		 *  @type {Array}
		 *  @private
		 */
		this._feedbackCombFilters = [];

		//make the allpass filters
		for (var af = 0; af < allpassFilterFreqs.length; af++) {
			var allpass = this.context.createBiquadFilter();
			allpass.type = "allpass";
			allpass.frequency.value = allpassFilterFreqs[af];
			this._allpassFilters.push(allpass);
		}

		//and the comb filters
		for (var cf = 0; cf < combFilterDelayTimes.length; cf++) {
			var fbcf = new Tone.FeedbackCombFilter(combFilterDelayTimes[cf], 0.1);
			this._scaleRoomSize.connect(fbcf.resonance);
			fbcf.resonance.value = combFilterResonances[cf];
			this._allpassFilters[this._allpassFilters.length - 1].connect(fbcf);
			if (cf < combFilterDelayTimes.length / 2){
				fbcf.connect(this.effectReturnL);
			} else {
				fbcf.connect(this.effectReturnR);
			}
			this._feedbackCombFilters.push(fbcf);
		}

		//chain the allpass filters together
		this.roomSize.connect(this._scaleRoomSize);
		this.connectSeries.apply(this, this._allpassFilters);
		this.effectSendL.connect(this._allpassFilters[0]);
		this.effectSendR.connect(this._allpassFilters[0]);
		this._readOnly(["roomSize"]);
	};

	Tone.extend(Tone.JCReverb, Tone.StereoEffect);

	/**
	 *  the default values
	 *  @static
	 *  @const
	 *  @type {Object}
	 */
	Tone.JCReverb.defaults = {
		"roomSize" : 0.5
	};

	/**
	 *  Clean up.
	 *  @returns {Tone.JCReverb} this
	 */
	Tone.JCReverb.prototype.dispose = function(){
		Tone.StereoEffect.prototype.dispose.call(this);
		for (var apf = 0; apf < this._allpassFilters.length; apf++) {
			this._allpassFilters[apf].disconnect();
			this._allpassFilters[apf] = null;
		}
		this._allpassFilters = null;
		for (var fbcf = 0; fbcf < this._feedbackCombFilters.length; fbcf++) {
			this._feedbackCombFilters[fbcf].dispose();
			this._feedbackCombFilters[fbcf] = null;
		}
		this._feedbackCombFilters = null;
		this._writable(["roomSize"]);
		this.roomSize.dispose();
		this.roomSize = null;
		this._scaleRoomSize.dispose();
		this._scaleRoomSize = null;
		return this;
	};

	return Tone.JCReverb;
});


text:
<?php

namespace School\Controller;

use School\Form;
use School\Model;

class ScheludeController extends \Account\Controller\EntityController
{
    protected $_formName = '\School\Form\ScheludeForm';

    protected $_mapperName = '\School\Model\ScheludeMapper';

    protected $_tableName = '\School\Model\ScheludeTable';

    protected $_listHeaders = array(
        'subject'     => 'Предмет',
        'class'       => 'Класс',
        'teacher'     => 'Учитель',
        'description' => 'День недели',
        'leeson'      => 'Урок'
    );
}


text:
package net.johnewart.gearman.server.persistence;

import net.johnewart.gearman.common.Job;
import net.johnewart.gearman.server.core.QueuedJob;

import java.util.Collection;

public interface PersistenceEngine {
    public String getIdentifier();
	public void write(Job job);
	public void delete(Job job);
    public void delete(String functionName, String uniqueID);
	public void deleteAll();
    public Job findJob(String functionName, String uniqueID);
	public Collection<QueuedJob> readAll();
    public Collection<QueuedJob> getAllForFunction(String functionName);
    public Job findJobByHandle(String jobHandle);
}