text:
var app = angular.module("testapp", []);

app.controller("GreetingsController", ["$http", function($http) {

	this.greetings = [];

	this.message = "";
	this.author = "";

	var that = this;

	$http.get("/_ah/api/helloworld/v1/hellogreeting").success(function(data) {
		that.greetings = data["items"];
	});

	this.generateJwtString = function(message, author) {
		var jwt_header = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
		var encoded_message = btoa(JSON.stringify({"message": message, "name": author}))
		var hash = CryptoJS.HmacSHA256(jwt_header + '.' + encoded_message, "secret");
  		var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
  		var jwt_string = jwt_header + '.' + encoded_message + '.' + hashInBase64;
  		return jwt_string;
	};

	this.addAuthedGreeting = function() {
		var jwt_string = this.generateJwtString(this.message, this.author);
		$http({
			method: "POST",
			url: "/_ah/api/helloworld/v1/hellogreeting/authed",
			headers: {"Authorization": "Bearer " + jwt_string}
		}).success(that.callback);
	};

	this.callback = function(data) {
		if (!that.greetings) that.greetings = [];
		that.greetings.push(data);
		that.message = "";
		that.author = "";
	};

}]);


text:
---
title: Background Property
localeTitle: Фоновая собственность
---
## Фоновая собственность

Свойство фона CSS позволяет объявить все восемь свойств фона сразу, используя это краткое объявление 1 .

Свойство background задается как один или несколько фоновых слоев, разделенных запятыми для следующих свойств 2 :

*   фоновый цвет
*   изображение на заднем плане
*   фон положение
*   фон-размер
*   фон-повторить
*   фон-происхождения
*   фон-клип
*   фон-вложение

Синтаксис 1 :

```css
body {
  /* Using a <background-color> */
  background: green;
 }

 .error {
  /* Using a <bg-image> and <repeat-style> */
  background: url("test.jpg") repeat-y;
 }

 header {
  /* Using a <box> and <background-color> */
  background: border-box red;
 }

 .topbanner {
  /* A single image, centered and scaled */
  background: no-repeat center/80% url("../img/image.png");
 }
```

### источники

1.  [Посетите страницу справочной системы MDN для получения дополнительной информации.](https://developer.mozilla.org/en-US/docs/Web/CSS/background)
2.  [Посетите страницу свойств веб-сайта CSS W3School для получения дополнительной информации.](https://www.w3schools.com/cssref/css3_pr_background.asp)

redpajama_set_name: RedPajamaGithub


text:
import { background, brand, contrast, font } from "../../variables";
import { TextBox } from "./textbox";
/*

DISCLAIMER:
Do not change this file because it is core styling.
Customizing core files will make updating Atlas much more difficult in the future.
To customize any core styling, copy the part you want to customize to styles/native/app/ so the core styling is overwritten.

==========================================================================
    Segmented Controls

    Default Class For Mendix Segmented Controls Widget
========================================================================== */
export const com_mendix_widget_native_togglebuttons_ToggleButtons = {
    container: {
        // All ViewStyle properties are allowed
        backgroundColor: background.secondary,
        borderRadius: 16,
        alignSelf: "stretch"
    },
    containerDisabled: {
        opacity: 0.6,
        alignSelf: "stretch"
    },
    button: {
        // All ViewStyle properties are allowed
        backgroundColor: "transparent",
        borderColor: "transparent",
        borderRadius: 16
    },
    text: {
        // All TextStyle properties are allowed
        color: contrast.low,
        fontSize: font.size,
        fontFamily: font.family
    },
    activeButton: {
        // All ViewStyle properties are allowed
        backgroundColor: brand.primary,
        borderColor: brand.primary,
        borderRadius: 16
    },
    activeButtonText: {
        // All TextStyle properties are allowed
        color: "#FFF",
        fontSize: font.size,
        fontFamily: font.family
    },
    validationMessage: {
        // All TextStyle properties are allowed
        ...TextBox.validationMessage
    }
};


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="48"
    android:viewportHeight="48"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M12.8,33.2H35.2V29.35H12.8ZM5.95,38V10H42.05V38Z"/>
</vector>


text:
require 'json'

module BugherdClient
  module Resources
    module V2

      class Base

        DEFAULT_HEADER_ATTRS = {
          :content_type => :json,
          :accept => :json
        }.freeze

        #
        # Return a list of available methods in a Resource
        #
        def api_methods
          self.class.instance_methods(false)
        end

        # store a reference to the HTTP connection
        attr_accessor :connection

        attr_accessor :options

        def initialize(conn, opts={})
          @connection, @options = conn, opts
        end

        def send_request(method='GET', path='', params={}, headers={})
          headers = DEFAULT_HEADER_ATTRS.merge(headers)
          params.merge!(headers)
          method_name = method.to_s.downcase
          self.connection[path].__send__(method_name, params)
        rescue RestClient::Exception => e
          raise(BugherdClient::Errors::HttpRequestError.new(e.message, e.http_code))
        end

        [:get, :post, :put, :patch, :delete].each do |method_name|
          define_method("#{method_name}_request") do |path, params={}|
            send_request(method_name, path, params)
          end
        end

        def converter(body)
          case body
          when Hash
            ::Hashie::Mash.new(body)
          when Array
            body.map { |item| item.is_a?(Hash) ? converter(item) : item }
          else
            body
          end
        end

        def parse_response(response, root_element=nil)
          parsed = if root_element
            p = JSON.parse(response)
            p.key?(root_element.to_s) ? p[root_element.to_s] : p
          else
            JSON.parse(response)
          end
          converter(parsed)
        end

      end

    end
  end
end


text:
{% extends "base.xml" %}
{% from "macros.xml" import request_xml %}

{% block content %}
<requests count="{{ requests|count }}" total-payouts="{{ total_payouts.currency() }}">
  {% for srp_request in requests %}
    {{ request_xml(srp_request) }}
  {% endfor %}
</requests>
{% if prev is defined %}
<prev>{{ prev }}</prev>
{% endif %}
{% if next is defined %}
<next>{{ next }}</next>
{% endif %}
{% endblock content %}


text:
package com.tagmycode.plugin;

import com.tagmycode.plugin.exception.TagMyCodeGuiException;
import com.tagmycode.plugin.exception.TagMyCodeStorageException;
import com.tagmycode.plugin.gui.IDocumentInsertText;
import com.tagmycode.plugin.gui.IOnErrorCallback;
import com.tagmycode.plugin.gui.WindowType;
import com.tagmycode.plugin.gui.form.*;
import com.tagmycode.sdk.Client;
import com.tagmycode.sdk.SaveFilePath;
import com.tagmycode.sdk.TagMyCode;
import com.tagmycode.sdk.authentication.TagMyCodeApi;
import com.tagmycode.sdk.crash.CrashClient;
import com.tagmycode.sdk.exception.TagMyCodeException;
import com.tagmycode.sdk.exception.TagMyCodeUnauthorizedException;
import com.tagmycode.sdk.model.LanguagesCollection;
import com.tagmycode.sdk.model.Snippet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

public class Framework implements IOnErrorCallback {
    public static final Logger LOGGER = LogManager.getLogger(Framework.class);

    public static final String USER_SETTINGS_PROPERTIES = "user_settings.properties";

    private final TagMyCode tagMyCode;
    private final Frame parentFrame;
    private final IMessageManager messageManager;
    private final AbstractTaskFactory taskFactory;
    private final SnippetsUpdatePollingProcess pollingProcess;
    private final AbstractVersion version;
    private final Data data;
    private final IBrowser browser;
    private final MainWindow mainWindow;
    private final QuickSearchDialog quickSearchDialog;
    private final AboutDialog aboutDialog;
    private final CrashService crashService;
    private final SyntaxSnippetEditorFactory syntaxSnippetEditorFactory;
    private final UserPreferences userPreferences;
    private final SaveFilePath saveFilePath;

    public Framework(TagMyCodeApi tagMyCodeApi, FrameworkConfig frameworkConfig, AbstractSecret secret) throws SQLException {
        WindowType.setDefaultType(WindowType.Type.JDIALOG);
        saveFilePath = frameworkConfig.getSaveFilePath();
        this.browser = frameworkConfig.getBrowser();
        Client client = new Client(tagMyCodeApi, secret.getConsumerId(), secret.getConsumerSecret(), new Wallet(frameworkConfig.getPasswordKeyChain()));
        tagMyCode = new TagMyCode(client);
        this.messageManager = frameworkConfig.getMessageManager();
        this.parentFrame = frameworkConfig.getParentFrame();
        this.taskFactory = frameworkConfig.getTask();
        userPreferences = new UserPreferences(new File(saveFilePath.getPathWith(USER_SETTINGS_PROPERTIES)));
        userPreferences.load();
        StorageEngine storageEngine = new StorageEngine(frameworkConfig.getDbService());
        this.data = new Data(storageEngine);
        syntaxSnippetEditorFactory = new SyntaxSnippetEditorFactory(loadThemeFile(storageEngine), storageEngine.loadEditorFontSize());
        quickSearchDialog = new QuickSearchDialog(this, getParentFrame());
        pollingProcess = new SnippetsUpdatePollingProcess(this);
        version = frameworkConfig.getVersionObject();
        aboutDialog = new AboutDialog(this, getParentFrame());
        this.mainWindow = new MainWindow(this);
        crashService = new CrashService(new CrashClient(client), data, tagMyCode, version, secret.getConsumerId());
    }

    private String loadThemeFile(StorageEngine storageEngine) {
        String themeFile = "";
        try {
            themeFile = storageEngine.loadEditorTheme();
        } catch (TagMyCodeStorageException ignored) {
        }
        return themeFile;
    }

    public SyntaxSnippetEditorFactory getSyntaxSnippetEditorFactory() {
        return syntaxSnippetEditorFactory;
    }

    public void start() throws TagMyCodeException {
        restoreData();

        boolean initialized = isInitialized();
        mainWindow.setLoggedIn(initialized);
        if (initialized) {
            mainWindow.getSnippetsPanel().setNetworkingEnabled(isNetworkingEnabled());
        }
    }

    public void syncSnippets() {
        pollingProcess.forceScheduleUpdate();
    }

    public LoginDialog showLoginDialog() {
        LoginDialog loginDialog = new LoginDialog(this, getParentFrame());
        loginDialog.display();
        return loginDialog;
    }

    public SnippetDialog showSnippetDialog(Snippet snippet) {
        // TODO check if can operate
        SnippetDialog snippetDialog = new SnippetDialog(this, getParentFrame());
        snippetDialog.setSnippet(snippet);
        snippetDialog.display();
        return snippetDialog;
    }

    public void showSettingsDialog() {
        new SettingsForm(this, getParentFrame())
                .display();
    }

    public QuickSearchDialog showSearchDialog(IDocumentInsertText documentInsertText) {
        // TODO check if can operate

        quickSearchDialog.display();
        quickSearchDialog.setDocumentInsertText(documentInsertText);
        return quickSearchDialog;
    }

    public MainWindow getMainWindow() {
        return mainWindow;
    }

    public void setLanguageCollection(LanguagesCollection languageCollection) throws TagMyCodeStorageException {
        getStorageEngine().saveLanguageCollection(languageCollection);
    }

    public AbstractTaskFactory getTaskFactory() {
        return taskFactory;
    }

    public IMessageManager getMessageManager() {
        return messageManager;
    }

    public void fetchAndStoreAllData() throws TagMyCodeException {
        fetchBasicData();
        saveData();
    }

    protected void fetchBasicData() throws TagMyCodeException {
        data.setAccount(tagMyCode.fetchAccount());
        data.setLanguages(tagMyCode.fetchLanguages());
    }

    protected void loadData() throws TagMyCodeStorageException {
        data.loadAll();
        tagMyCode.setLastSnippetsUpdate(data.getLastSnippetsUpdate());
    }

    public void logout() {
        getMainWindow().setLoggedIn(false);
        pollingProcess.terminate();
        try {
            reset();
        } catch (TagMyCodeException e) {
            manageTagMyCodeExceptions(e);
        }
    }

    void reset() throws TagMyCodeException {
        data.clearDataAndStorage();
        resetLastSnippetsUpdate();
        tagMyCode.revokeAccessToken();
        snippetsDataChanged();
    }

    public void resetLastSnippetsUpdate() {
        tagMyCode.setLastSnippetsUpdate(null);
        data.setLastSnippetsUpdate(null);
    }

    public boolean isInitialized() {
        return tagMyCode.isAuthenticated() && data.getAccount() != null && data.getLanguages() != null;
    }

    public Frame getParentFrame() {
        return parentFrame;
    }

    public void showErrorDialog(final String message) {
        new GuiThread().execute(new Runnable() {
            @Override
            public void run() {
                messageManager.errorDialog(message);
            }
        });
    }

    public void writeErrorLog(final String message) {
        new GuiThread().execute(new Runnable() {
            @Override
            public void run() {
                messageManager.errorLog(message);
            }
        });
    }

    public void manageTagMyCodeExceptions(Throwable e) {
        logError(e);
        if (e instanceof TagMyCodeUnauthorizedException) {
            showErrorDialog(e.getMessage());
            logoutAndAuthenticateAgain();
        } else if (e instanceof TagMyCodeGuiException) {
            showErrorDialog(e.getMessage());
        } else {
            writeErrorLog(e.getMessage());
        }
    }

    public void logError(Throwable e) {
        LOGGER.error("TagMyCode Error", e);
        crashService.send(e);
    }

    public void logoutAndAuthenticateAgain() {
        logout();
        showLoginDialog();
    }

    public boolean canOperate() {
        if (!isInitialized()) {
            showLoginDialog();
        }
        return isInitialized();
    }

    public void restoreData() throws TagMyCodeStorageException {
        try {
            tagMyCode.loadOauthToken();
            loadData();
            snippetsDataChanged();
        } catch (TagMyCodeStorageException e) {
            data.clearDataAndStorage();
            logError(e);
        } catch (TagMyCodeException e) {
            manageTagMyCodeExceptions(e);
        }
    }

    public void initialize(final String verificationCode) throws TagMyCodeException {
        tagMyCode.authenticate(verificationCode);

        try {
            mainWindow.setLoggedIn(true);
            fetchAndStoreAllData();
            saveAndTellThatSnippetsDataAreChanged();
            if (isNetworkingEnabled()) {
                pollingProcess.start();
            }
        } catch (TagMyCodeException ex) {
            manageTagMyCodeExceptions(ex);
            logout();
        }
    }

    public TagMyCode getTagMyCode() {
        return tagMyCode;
    }

    public Data getData() {
        return data;
    }

    public StorageEngine getStorageEngine() {
        return data.getStorageEngine();
    }

    public void saveAndTellThatSnippetsDataAreChanged() {
        saveData();
        snippetsDataChanged();
    }

    public void snippetsDataChanged() {
        getData().setLastSnippetsUpdate(tagMyCode.getLastSnippetsUpdate());
        getMainWindow().getSnippetsPanel().fireSnippetsChanged();
    }

    protected synchronized void saveData() {
        try {
            getData().saveAll();
        } catch (TagMyCodeStorageException e) {
            manageTagMyCodeExceptions(e);
        }
    }

    public JComponent getMainFrame() {
        return mainWindow.getMainComponent();
    }

    @Override
    public void onError(TagMyCodeException e) {
        manageTagMyCodeExceptions(e);
    }

    public void showAboutDialog() {
        aboutDialog.display();
    }

    public AbstractVersion getVersion() {
        return version;
    }

    public boolean isNetworkingEnabled() {
        return data.isNetworkingEnabled();
    }

    public synchronized void setNetworkingEnabled(boolean flag) {
        data.setNetworkingEnabled(flag);
        if (flag) {
            pollingProcess.start();
        } else {
            pollingProcess.terminate();
        }
    }

    public void closeFramework() throws TagMyCodeStorageException {
        // TODO wait for all pending tasks
        if (isInitialized()) {
            data.saveAll();
        }

        try {
            userPreferences.store();
        } catch (IOException e) {
            e.printStackTrace();
        }
        getStorageEngine().close();
        LOGGER.info("Exiting TagMyCode");
    }

    public void openUrlInBrowser(String url) {
        boolean urlOpened = browser.openUrl(url);
        if (!urlOpened) {
            logError(new TagMyCodeException("Unable to open link in browser, please open it manually: " + url));
        }
    }

    public SnippetsUpdatePollingProcess getPollingProcess() {
        return pollingProcess;
    }

    public UserPreferences getUserPreferences() {
        return userPreferences;
    }

    public SaveFilePath getSaveFilePath() {
        return saveFilePath;
    }
}


text:
/**
 * @fileoverview Rule to enforce line breaks after each array element
 * @author Jan Peer Stöcklmair <https://github.com/JPeer264>
 */

"use strict";

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        type: "layout",

        docs: {
            description: "enforce line breaks after each array element",
            category: "Stylistic Issues",
            recommended: false,
            url: "https://eslint.org/docs/rules/array-element-newline"
        },

        fixable: "whitespace",

        schema: [
            {
                oneOf: [
                    {
                        enum: ["always", "never", "consistent"]
                    },
                    {
                        type: "object",
                        properties: {
                            multiline: {
                                type: "boolean"
                            },
                            minItems: {
                                type: ["integer", "null"],
                                minimum: 0
                            }
                        },
                        additionalProperties: false
                    }
                ]
            }
        ],

        messages: {
            unexpectedLineBreak: "There should be no linebreak here.",
            missingLineBreak: "There should be a linebreak after this element."
        }
    },

    create(context) {
        const sourceCode = context.getSourceCode();

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------

        /**
         * Normalizes a given option value.
         *
         * @param {string|Object|undefined} providedOption - An option value to parse.
         * @returns {{multiline: boolean, minItems: number}} Normalized option object.
         */
        function normalizeOptionValue(providedOption) {
            let consistent = false;
            let multiline = false;
            let minItems;

            const option = providedOption || "always";

            if (!option || option === "always" || option.minItems === 0) {
                minItems = 0;
            } else if (option === "never") {
                minItems = Number.POSITIVE_INFINITY;
            } else if (option === "consistent") {
                consistent = true;
                minItems = Number.POSITIVE_INFINITY;
            } else {
                multiline = Boolean(option.multiline);
                minItems = option.minItems || Number.POSITIVE_INFINITY;
            }

            return { consistent, multiline, minItems };
        }

        /**
         * Normalizes a given option value.
         *
         * @param {string|Object|undefined} options - An option value to parse.
         * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object.
         */
        function normalizeOptions(options) {
            const value = normalizeOptionValue(options);

            return { ArrayExpression: value, ArrayPattern: value };
        }

        /**
         * Reports that there shouldn't be a line break after the first token
         * @param {Token} token - The token to use for the report.
         * @returns {void}
         */
        function reportNoLineBreak(token) {
            const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true });

            context.report({
                loc: {
                    start: tokenBefore.loc.end,
                    end: token.loc.start
                },
                messageId: "unexpectedLineBreak",
                fix(fixer) {
                    if (astUtils.isCommentToken(tokenBefore)) {
                        return null;
                    }

                    if (!astUtils.isTokenOnSameLine(tokenBefore, token)) {
                        return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " ");
                    }

                    /*
                     * This will check if the comma is on the same line as the next element
                     * Following array:
                     * [
                     *     1
                     *     , 2
                     *     , 3
                     * ]
                     *
                     * will be fixed to:
                     * [
                     *     1, 2, 3
                     * ]
                     */
                    const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, { includeComments: true });

                    if (astUtils.isCommentToken(twoTokensBefore)) {
                        return null;
                    }

                    return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], "");

                }
            });
        }

        /**
         * Reports that there should be a line break after the first token
         * @param {Token} token - The token to use for the report.
         * @returns {void}
         */
        function reportRequiredLineBreak(token) {
            const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true });

            context.report({
                loc: {
                    start: tokenBefore.loc.end,
                    end: token.loc.start
                },
                messageId: "missingLineBreak",
                fix(fixer) {
                    return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n");
                }
            });
        }

        /**
         * Reports a given node if it violated this rule.
         *
         * @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node.
         * @returns {void}
         */
        function check(node) {
            const elements = node.elements;
            const normalizedOptions = normalizeOptions(context.options[0]);
            const options = normalizedOptions[node.type];

            let elementBreak = false;

            /*
             * MULTILINE: true
             * loop through every element and check
             * if at least one element has linebreaks inside
             * this ensures that following is not valid (due to elements are on the same line):
             *
             * [
             *      1,
             *      2,
             *      3
             * ]
             */
            if (options.multiline) {
                elementBreak = elements
                    .filter(element => element !== null)
                    .some(element => element.loc.start.line !== element.loc.end.line);
            }

            const linebreaksCount = node.elements.map((element, i) => {
                const previousElement = elements[i - 1];

                if (i === 0 || element === null || previousElement === null) {
                    return false;
                }

                const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken);
                const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken);
                const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken);

                return !astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement);
            }).filter(isBreak => isBreak === true).length;

            const needsLinebreaks = (
                elements.length >= options.minItems ||
                (
                    options.multiline &&
                    elementBreak
                ) ||
                (
                    options.consistent &&
                    linebreaksCount > 0 &&
                    linebreaksCount < node.elements.length
                )
            );

            elements.forEach((element, i) => {
                const previousElement = elements[i - 1];

                if (i === 0 || element === null || previousElement === null) {
                    return;
                }

                const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken);
                const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken);
                const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken);

                if (needsLinebreaks) {
                    if (astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) {
                        reportRequiredLineBreak(firstTokenOfCurrentElement);
                    }
                } else {
                    if (!astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) {
                        reportNoLineBreak(firstTokenOfCurrentElement);
                    }
                }
            });
        }

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        return {
            ArrayPattern: check,
            ArrayExpression: check
        };
    }
};


text: b9PrintString("Hello World!");


text:
Enables built in tools in [crystal](http://crystal-lang.org) compiler to be used from atom.

_Note: requires crystal >= 0.7.7._

Supported tools

* **context**: displays available context variables at a specific location
* **implementations**: over a method call, search for all possible definition of the method. Even across macro expansions.

![screenshot](https://cloud.githubusercontent.com/assets/459923/9243080/36701a0a-4162-11e5-95d0-80da85d9287f.png)


text:
namespace rocksdb {

inline size_t TruncateToPageBoundary(size_t page_size, size_t s) {
  s -= (s & (page_size - 1));
  assert((s % page_size) == 0);
  return s;
}

inline size_t Roundup(size_t x, size_t y) {
  return ((x + y - 1) / y) * y;
}

// This class is to manage an aligned user
// allocated buffer for direct I/O purposes
// though can be used for any purpose.
class AlignedBuffer {
  size_t alignment_;
  std::unique_ptr<char[]> buf_;
  size_t capacity_;
  size_t cursize_;
  char* bufstart_;

public:
  AlignedBuffer()
    : alignment_(),
      capacity_(0),
      cursize_(0),
      bufstart_(nullptr) {
  }

  AlignedBuffer(AlignedBuffer&& o) ROCKSDB_NOEXCEPT {
    *this = std::move(o);
  }

  AlignedBuffer& operator=(AlignedBuffer&& o) ROCKSDB_NOEXCEPT {
    alignment_ = std::move(o.alignment_);
    buf_ = std::move(o.buf_);
    capacity_ = std::move(o.capacity_);
    cursize_ = std::move(o.cursize_);
    bufstart_ = std::move(o.bufstart_);
    return *this;
  }

  AlignedBuffer(const AlignedBuffer&) = delete;

  AlignedBuffer& operator=(const AlignedBuffer&) = delete;

  static bool isAligned(const void* ptr, size_t alignment) {
    return reinterpret_cast<uintptr_t>(ptr) % alignment == 0;
  }

  static bool isAligned(size_t n, size_t alignment) {
    return n % alignment == 0;
  }

  size_t Alignment() const {
    return alignment_;
  }

  size_t Capacity() const {
    return capacity_;
  }

  size_t CurrentSize() const {
    return cursize_;
  }

  const char* BufferStart() const {
    return bufstart_;
  }

  char* BufferStart() { return bufstart_; }

  void Clear() {
    cursize_ = 0;
  }

  void Alignment(size_t alignment) {
    assert(alignment > 0);
    assert((alignment & (alignment - 1)) == 0);
    alignment_ = alignment;
  }

  // Allocates a new buffer and sets bufstart_ to the aligned first byte
  void AllocateNewBuffer(size_t requested_capacity, bool copy_data = false) {
    assert(alignment_ > 0);
    assert((alignment_ & (alignment_ - 1)) == 0);

    if (copy_data && requested_capacity < cursize_) {
      // If we are downsizing to a capacity that is smaller than the current
      // data in the buffer. Ignore the request.
      return;
    }

    size_t new_capacity = Roundup(requested_capacity, alignment_);
    char* new_buf = new char[new_capacity + alignment_];
    char* new_bufstart = reinterpret_cast<char*>(
        (reinterpret_cast<uintptr_t>(new_buf) + (alignment_ - 1)) &
        ~static_cast<uintptr_t>(alignment_ - 1));

    if (copy_data) {
      memcpy(new_bufstart, bufstart_, cursize_);
    } else {
      cursize_ = 0;
    }

    bufstart_ = new_bufstart;
    capacity_ = new_capacity;
    buf_.reset(new_buf);
  }
  // Used for write
  // Returns the number of bytes appended
  size_t Append(const char* src, size_t append_size) {
    size_t buffer_remaining = capacity_ - cursize_;
    size_t to_copy = std::min(append_size, buffer_remaining);

    if (to_copy > 0) {
      memcpy(bufstart_ + cursize_, src, to_copy);
      cursize_ += to_copy;
    }
    return to_copy;
  }

  size_t Read(char* dest, size_t offset, size_t read_size) const {
    assert(offset < cursize_);

    size_t to_read = 0;
    if(offset < cursize_) {
      to_read = std::min(cursize_ - offset, read_size);
    }
    if (to_read > 0) {
      memcpy(dest, bufstart_ + offset, to_read);
    }
    return to_read;
  }

  /// Pad to alignment
  void PadToAlignmentWith(int padding) {
    size_t total_size = Roundup(cursize_, alignment_);
    size_t pad_size = total_size - cursize_;

    if (pad_size > 0) {
      assert((pad_size + cursize_) <= capacity_);
      memset(bufstart_ + cursize_, padding, pad_size);
      cursize_ += pad_size;
    }
  }

  // After a partial flush move the tail to the beginning of the buffer
  void RefitTail(size_t tail_offset, size_t tail_size) {
    if (tail_size > 0) {
      memmove(bufstart_, bufstart_ + tail_offset, tail_size);
    }
    cursize_ = tail_size;
  }

  // Returns place to start writing
  char* Destination() {
    return bufstart_ + cursize_;
  }

  void Size(size_t cursize) {
    cursize_ = cursize;
  }
};
}


text:
#include <target-utils/OS/os_config.h>
#include <target-utils/OS/os.h>
#include "os_int.h"
#include "os_log.h"

AIM_LOG_STRUCT_DEFINE(
                      OS_CONFIG_LOG_OPTIONS_DEFAULT,
                      OS_CONFIG_LOG_BITS_DEFAULT,
                      NULL, /* custom map */
                      OS_CONFIG_LOG_CUSTOM_BITS_DEFAULT
                      );


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

<title>Result (rulebook API)</title>
<meta name="date" content="2018-12-04">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.deliveredtechnologies.rulebook

Class Result<T>

java.lang.Object

com.deliveredtechnologies.rulebook.Result<T>

All Implemented Interfaces:

Referable<T>

public class Result<T>
extends java.lang.Object
implements Referable<T>

This is a wrapper class for the actual result.
 This is needed to ensure that an instance is available and that a reference is maintained to the actual that
 can be manipulated in the then BiFunction.
 The Result object can then contain a pointer to any instance, which can be shared with lamda calls
 and across other objects (i.e. DecisionBook and Decision objects)

Constructor Summary

Constructors

Constructor and Description

Result()

Result(T value)

Creates an instance of Result with a default value.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

T
getValue()

The method getValue() returns the object contained in the Result object.

void
reset()

Resets the value of the Result to its default value.

void
setValue(T value)

The method setValue() sets the object to be contained in the Result object.

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Result

public Result()

Result

public Result(T value)

Creates an instance of Result with a default value.

Parameters:

value - the default value.

Method Detail

reset

public void reset()

Resets the value of the Result to its default value.

getValue

public T getValue()

The method getValue() returns the object contained in the Result object.

Specified by:

getValue in interface Referable<T>

Returns:

the object stored in the Result object

setValue

public void setValue(T value)

The method setValue() sets the object to be contained in the Result object.

Specified by:

setValue in interface Referable<T>

Parameters:

value - the object to be stored in the Result object

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package ru.besttuts.stockwidget.io;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ru.besttuts.stockwidget.io.model.Result;
import ru.besttuts.stockwidget.util.LogUtils;

import static ru.besttuts.stockwidget.util.LogUtils.LOGE;

public class ResultHandler {

    private static final String TAG = LogUtils.makeLogTag(ResultHandler.class);

    // map from room ID to Room model object
    private List<Result> mResults = new ArrayList<>();

    public ResultHandler() {
        //
    }

    public List<Result> getResults() {
        return mResults;
    }

    private void process(JSONObject o) throws JSONException, IOException {
        Result result = new Result();
        result.symbol = o.getString("symbol");
        result.name = o.getString("name");
        result.exch = o.getString("exch");
        result.type = o.getString("type");
        result.exchDisp = o.getString("exchDisp");
        result.typeDisp = o.getString("typeDisp");

        mResults.add(result);
    }

    public void readAndParseJSON(String in) {
        try {
            JSONObject reader = new JSONObject(in);

            if (reader.isNull("ResultSet") || reader.getJSONObject("ResultSet").isNull("Result")) {
                return;
            }

            Object oResults = reader.getJSONObject("ResultSet").get("Result");

            if (oResults instanceof JSONArray) {
                JSONArray results = (JSONArray) oResults;

                for (int i = 0; i < results.length(); i++) {
                    process(results.getJSONObject(i));
                }

            } else {
                process((JSONObject) oResults);
            }

        } catch (JSONException jsone) {
            LOGE(TAG, jsone.getMessage());
            jsone.printStackTrace();
        } catch (IOException ioe) {
            LOGE(TAG, ioe.getMessage());
            ioe.printStackTrace();
        }

    }

}


text:
/*
!!! XXX DOES NOT USE BUILT-IN DETECTION FUNCTIONS XXX !!!

Note there are three rules in here that all largely share the same structs -- references, most options, metadata, etc.  Also, there are three flowbits in addition to the download flowbit for keeping track of things.  The code has been written to reuse as many structures as possible and all three rules are evaluated using the same detection function that determines which content match succeeded and sets up the rest of the algorithm appropriately.

alert tcp $EXTERNAL_NET 554 -> $HOME_NET any (msg:"MULTIMEDIA Windows Media Player malicious playlist buffer overflow attempt"; flow:to_client,established; flowbits:isset,file.wmp_playlist; content:"kQfct7epzxGO5gDADCBT"; content:"QJ5p+E1bzxGo/QCAX1xE"; fast_pattern; distance:12; within:20; metadata:policy security-ips drop, policy balanced-ips drop; reference:cve,2008-2253; reference:url,technet.microsoft.com/en-us/security/bulletin/MS08-054; classtype:attempted-user; sid:14252; rev:1;)

alert tcp $EXTERNAL_NET 554 -> $HOME_NET any (msg:"MULTIMEDIA Windows Media Player malicious playlist buffer overflow attempt"; flow:to_client,established; flowbits:isset,file.wmp_playlist; content:"B9y3t6nPEY7mAMAMIFNl"; content:"nmn4TVvPEaj9AIBfXEQr"; fast_pattern; distance:12; within:20; metadata:policy security-ips drop, policy balanced-ips drop; reference:cve,2008-2253; reference:url,technet.microsoft.com/en-us/security/bulletin/MS08-054; classtype:attempted-user; sid:14253; rev:1;)

alert tcp $EXTERNAL_NET 554 -> $HOME_NET any (msg:"MULTIMEDIA Windows Media Player malicious playlist buffer overflow attempt"; flow:to_client,established; flowbits:isset,file.wmp_playlist; content:"3Le3qc8RjuYAwAwg"; content:"afhNW88RqP0AgF9c"; fast_pattern; distance:16; within:16; metadata:policy security-ips drop, policy balanced-ips drop; reference:cve,2008-2253; reference:url,technet.microsoft.com/en-us/security/bulletin/MS08-054; classtype:attempted-user; sid:14254; rev:1;)
*/
/*
 * Use at your own risk.
 *
 * Copyright (C) 2005-2008 Sourcefire, Inc.
 *
 * This file is autogenerated via rules2c, by Brian Caswell <bmc@sourcefire.com>
 */

#include <string.h>

#include "sf_snort_plugin_api.h"
#include "sf_snort_packet.h"

#include "so-util.h"
#include "so-util_base64-decode.h"

//#define DEBUG
#ifdef DEBUG
#define DEBUG_SO(code) code
#else
#define DEBUG_SO(code)
#endif

typedef struct _SampleRate {
    uint32_t samplerate;
    uint16_t bitrate;
} SampleRate;

/* declare detection functions */
static int rule14252eval(void *);
static int rule14253eval(void *);
static int rule14254eval(void *);
static int checkPrereqs(void *);
static int ruleCVE_2008_2253Eval(void *, uint8_t);

/* declare rule data structures */
/* precompile the stuff that needs pre-compiled */
/* flow:established, to_client; */
static FlowFlags ruleCVE_2008_2253flow0 =
{
    FLOW_ESTABLISHED|FLOW_TO_CLIENT
};

static RuleOption ruleCVE_2008_2253option0 =
{
    OPTION_TYPE_FLOWFLAGS,
    {
        &ruleCVE_2008_2253flow0
    }
};
/* flowbits:isset "file.wmp_playlist"; */
static FlowBitsInfo ruleCVE_2008_2253flowbits1 =
{
    "file.wmp_playlist",
    FLOWBIT_ISSET,
    0,
};

static RuleOption ruleCVE_2008_2253option1 =
{
    OPTION_TYPE_FLOWBIT,
    {
        &ruleCVE_2008_2253flowbits1
    }
};

// content:"kQfct7epzxGO5gDADCBT", depth 0;
static ContentInfo rule14252content2 =
{
    (uint8_t *) "kQfct7epzxGO5gDADCBT", /* pattern (now in snort content format) */
    0, /* depth */
    0, /* offset */
    CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule14252option2 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule14252content2
    }
};
// content:"QJ5p+E1bzxGo/QCAX1xE", offset 12, depth 20, relative, fast_pattern;
static ContentInfo rule14252content3 =
{
    (uint8_t *) "QJ5p+E1bzxGo/QCAX1xE", /* pattern (now in snort content format) */
    20, /* depth */
    12, /* offset */
    CONTENT_RELATIVE|CONTENT_FAST_PATTERN|CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule14252option3 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule14252content3
    }
};

RuleOption *rule14252options[] =
{
    &ruleCVE_2008_2253option0,
    &ruleCVE_2008_2253option1,
    &rule14252option2,
    &rule14252option3,
    NULL
};

/* references for sid 14252 */
/* reference: cve "2008-2253"; */
static RuleReference ruleCVE_2008_2253ref1 =
{
    "cve", /* type */
    "2008-2253" /* value */
};

/* reference: url "technet.microsoft.com/en-us/security/bulletin/MS08-054"; */
static RuleReference ruleCVE_2008_2253ref2 =
{
    "url", /* type */
    "technet.microsoft.com/en-us/security/bulletin/MS08-054" /* value */
};

static RuleReference *ruleCVE_2008_2253refs[] =
{
    &ruleCVE_2008_2253ref1,
    &ruleCVE_2008_2253ref2,
    NULL
};

/* metadata for sid 14252 */
static RuleMetaData rule14252policy1 =
{
   "policy max-detect-ips drop"
};

static RuleMetaData *rule14252metadata[] =
{
   &rule14252policy1,
   NULL
};

/* metadata:policy max-detect-ips drop; */
static RuleMetaData ruleCVE_2008_2253policy1 =
{
    "policy max-detect-ips drop"
};

static RuleMetaData *ruleCVE_2008_2253metadata[] =
{
    &ruleCVE_2008_2253policy1,
    NULL
};

Rule rule14252 = {

   /* rule header, akin to => tcp any any -> any any               */{
       IPPROTO_TCP, /* proto */
       "$EXTERNAL_NET", /* SRCIP     */
       "554", /* SRCPORT   */
       0, /* DIRECTION */
       "$HOME_NET", /* DSTIP     */
       "any", /* DSTPORT   */
   },
   /* metadata */
   {
       3,  /* genid (HARDCODED!!!) */
       14252, /* sigid */
       17, /* revision */

       "attempted-user", /* classification */
       0,  /* hardcoded priority XXX NOT PROVIDED BY GRAMMAR YET! */
       "FILE-MULTIMEDIA Windows Media Player malicious playlist buffer overflow attempt",     /* message */
       ruleCVE_2008_2253refs /* ptr to references */
       ,rule14252metadata
   },
   rule14252options, /* ptr to rule options */
   rule14252eval, /* DO NOT use the built in detection function */
   0 /* am I initialized yet? */
};

// content:"B9y3t6nPEY7mAMAMIFNl", depth 0;
static ContentInfo rule14253content2 =
{
    (uint8_t *) "B9y3t6nPEY7mAMAMIFNl", /* pattern (now in snort content format) */
    0, /* depth */
    0, /* offset */
    CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule14253option2 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule14253content2
    }
};
// content:"nmn4TVvPEaj9AIBfXEQr", offset 12, depth 20, relative, fast_pattern;
static ContentInfo rule14253content3 =
{
    (uint8_t *) "nmn4TVvPEaj9AIBfXEQr", /* pattern (now in snort content format) */
    20, /* depth */
    12, /* offset */
    CONTENT_RELATIVE|CONTENT_FAST_PATTERN|CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule14253option3 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule14253content3
    }
};

RuleOption *rule14253options[] =
{
    &ruleCVE_2008_2253option0,
    &ruleCVE_2008_2253option1,
    &rule14253option2,
    &rule14253option3,
    NULL
};

Rule rule14253 = {

   /* rule header, akin to => tcp any any -> any any               */{
       IPPROTO_TCP, /* proto */
       "$EXTERNAL_NET", /* SRCIP     */
       "554", /* SRCPORT   */
       0, /* DIRECTION */
       "$HOME_NET", /* DSTIP     */
       "any", /* DSTPORT   */
   },
   /* metadata */
   {
       3,  /* genid (HARDCODED!!!) */
       14253, /* sigid */
       17, /* revision */

       "attempted-user", /* classification */
       0,  /* hardcoded priority XXX NOT PROVIDED BY GRAMMAR YET! */
       "FILE-MULTIMEDIA Windows Media Player malicious playlist buffer overflow attempt",     /* message */
       ruleCVE_2008_2253refs /* ptr to references */
       ,ruleCVE_2008_2253metadata
   },
   rule14253options, /* ptr to rule options */
   rule14253eval, /* DO NOT use the built in detection function */
   0 /* am I initialized yet? */
};

// content:"3Le3qc8RjuYAwAwg", depth 0;
static ContentInfo rule14254content2 =
{
    (uint8_t *) "3Le3qc8RjuYAwAwg", /* pattern (now in snort content format) */
    0, /* depth */
    0, /* offset */
    CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule14254option2 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule14254content2
    }
};
// content:"afhNW88RqP0AgF9c", offset 16, depth 16, relative, fast_pattern;
static ContentInfo rule14254content3 =
{
    (uint8_t *) "afhNW88RqP0AgF9c", /* pattern (now in snort content format) */
    16, /* depth */
    16, /* offset */
    CONTENT_RELATIVE|CONTENT_FAST_PATTERN|CONTENT_BUF_NORMALIZED, /* flags */
    NULL, /* holder for boyer/moore PTR */
    NULL, /* more holder info - byteform */
    0, /* byteform length */
    0 /* increment length*/
};

static RuleOption rule14254option3 =
{
    OPTION_TYPE_CONTENT,
    {
        &rule14254content3
    }
};

RuleOption *rule14254options[] =
{
    &ruleCVE_2008_2253option0,
    &ruleCVE_2008_2253option1,
    &rule14254option2,
    &rule14254option3,
    NULL
};

Rule rule14254 = {

   /* rule header, akin to => tcp any any -> any any               */{
       IPPROTO_TCP, /* proto */
       "$EXTERNAL_NET", /* SRCIP     */
       "554", /* SRCPORT   */
       0, /* DIRECTION */
       "$HOME_NET", /* DSTIP     */
       "any", /* DSTPORT   */
   },
   /* metadata */
   {
       3,  /* genid (HARDCODED!!!) */
       14254, /* sigid */
       17, /* revision */

       "attempted-user", /* classification */
       0,  /* hardcoded priority XXX NOT PROVIDED BY GRAMMAR YET! */
       "FILE-MULTIMEDIA Windows Media Player malicious playlist buffer overflow attempt",     /* message */
       ruleCVE_2008_2253refs /* ptr to references */
       ,ruleCVE_2008_2253metadata
   },
   rule14254options, /* ptr to rule options */
   rule14254eval, /* DO NOT use the built in detection function */
   0 /* am I initialized yet? */
};

/* detection functions */
static int rule14252eval(void *p)
{
    if (checkPrereqs(p) != 0)
        return RULE_NOMATCH;

    return ruleCVE_2008_2253Eval(p, 1);
}

static int rule14253eval(void *p)
{
    if (checkPrereqs(p) != 0)
        return RULE_NOMATCH;

    return ruleCVE_2008_2253Eval(p, 0);
}

static int rule14254eval(void *p)
{
    if (checkPrereqs(p) != 0)
        return RULE_NOMATCH;

    return ruleCVE_2008_2253Eval(p, 2);
}

static int checkPrereqs(void *p)
{
    SFSnortPacket *sp = (SFSnortPacket *)p;

    if ((sp == NULL) || (sp->payload == NULL) || (sp->stream_session_ptr == NULL))
        return -1;

    // flow:established, to_client;
    if(checkFlow(p, rule14252options[0]->option_u.flowFlags) <= 0 )
        return -1;

    // flowbits:isset "file.wmp_playlist";
    if(processFlowbits(p, rule14252options[1]->option_u.flowBit) <= 0)
        return -1;

    return 0;
}

static int ruleCVE_2008_2253Eval(void *p, uint8_t alignment)
{
   const uint8_t *cursor_normal=0, *end_of_payload;
   SFSnortPacket *sp = (SFSnortPacket *)p;

   // for base64 decoder
   uint8_t  outbuf[16], *p_outbuf;
   uint32_t bytes_written;
   int ret;

   // to store or retrieve sample per second value
   SampleRate      *samplerate2compare;
   RuleInformation *ruleinfo;

   // for extracting the sample per second
   uint32_t samplerate;
   // for extracting the bits per sample
   uint16_t bitrate;

   DEBUG_SO(printf("ruleCVE_2008_2253eval (malicious WMP playlist) enter\n"));

   if(getBuffer(sp, CONTENT_BUF_NORMALIZED, &cursor_normal, &end_of_payload) <= 0)
      return RULE_NOMATCH;

   switch (alignment)
   {
       case 0:
           if (contentMatch(p, rule14253options[2]->option_u.content, &cursor_normal) <= 0)
               return RULE_NOMATCH;
           if (contentMatch(p, rule14253options[3]->option_u.content, &cursor_normal) <= 0)
               return RULE_NOMATCH;
           ruleinfo = &(rule14253.info);
           break;
       case 1:
           if (contentMatch(p, rule14252options[2]->option_u.content, &cursor_normal) <= 0)
               return RULE_NOMATCH;
           if (contentMatch(p, rule14252options[3]->option_u.content, &cursor_normal) <= 0)
               return RULE_NOMATCH;
           ruleinfo = &(rule14252.info);
           break;
       case 2:
           if (contentMatch(p, rule14254options[2]->option_u.content, &cursor_normal) <= 0)
               return RULE_NOMATCH;
           if (contentMatch(p, rule14254options[3]->option_u.content, &cursor_normal) <= 0)
               return RULE_NOMATCH;
           ruleinfo = &(rule14254.info);
           break;
       default:
           return RULE_NOMATCH;
   }

   if(cursor_normal + 76 > end_of_payload)
      return RULE_NOMATCH;

   ret = base64decode(cursor_normal + 56, 20, outbuf, 16, &bytes_written);
   DEBUG_SO(printf("bytes_written = %d\n", bytes_written);)

   if(ret != 0 || bytes_written != 15)  // error
      return RULE_NOMATCH;

   p_outbuf = outbuf + alignment;
   samplerate = read_little_32(p_outbuf);
   p_outbuf += 10;
   bitrate    = read_little_16(p_outbuf);

   DEBUG_SO(printf("decoded value: \n");)
   DEBUG_SO(printf("|%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x|", outbuf[0],  outbuf[1],  outbuf[2],  outbuf[3],  outbuf[4], outbuf[5],  outbuf[6],  outbuf[7],  outbuf[8],  outbuf[9], outbuf[10], outbuf[11], outbuf[12], outbuf[13], outbuf[14]);)
   DEBUG_SO(printf("samplerate=0x%08x    bitrate=0x%04x\n", samplerate, bitrate);)

#ifndef BEFORE_2091300
   getRuleData(sp, ruleinfo, (void*)(&samplerate2compare), NULL);
#else
   samplerate2compare = (SampleRate *)getRuleData(sp, (uint32_t)ruleinfo->sigID);
#endif

   if (samplerate2compare == NULL)
   {
       DEBUG_SO(printf("ruleCVE_2008_2253Eval is allocatin memory\n");)
       samplerate2compare = (SampleRate *)allocRuleData(sizeof(SampleRate));
       if (samplerate2compare == NULL)
           return RULE_NOMATCH;

       samplerate2compare->samplerate = samplerate;
       samplerate2compare->bitrate    = bitrate;

#ifndef BEFORE_2091300
       if (storeRuleData(sp, ruleinfo, samplerate2compare, NULL) < 0)
#else
       if (storeRuleData(sp, samplerate2compare, ruleinfo->sigID, &freeRuleData) < 0)
#endif
           freeRuleData(samplerate2compare);

       return RULE_NOMATCH;
   }

   DEBUG_SO(printf("stored samplerate = 0x%08x\n", samplerate2compare->samplerate);)

   // malicious condition
   if ((samplerate2compare->samplerate < samplerate)  && (samplerate2compare->bitrate == bitrate))
       return RULE_MATCH;

   // in order to check next consecutive audio files
   samplerate2compare->samplerate = samplerate;
   samplerate2compare->bitrate    = bitrate;

#ifndef BEFORE_2091300
   if (storeRuleData(sp, ruleinfo, samplerate2compare, NULL) < 0)
#else
   if (storeRuleData(sp, samplerate2compare, ruleinfo->sigID, &freeRuleData) < 0)
#endif
       freeRuleData(samplerate2compare);

   return RULE_NOMATCH;
}

/*
Rule *rules[] = {
    &rule14252,
    &rule14253,
    &rule14254,
    NULL
};
*/


text:
"""
Management of NFS exports
===============================================

.. versionadded:: 2018.3.0

To ensure an NFS export exists:

.. code-block:: yaml

    add_simple_export:
      nfs_export.present:
        - name:     '/srv/nfs'
        - hosts:    '10.0.2.0/24'
        - options:
          - 'rw'

This creates the following in /etc/exports:

.. code-block:: bash

    /srv/nfs 10.0.2.0/24(rw)

For more complex exports with multiple groups of hosts, use 'clients':

.. code-block:: yaml

    add_complex_export:
      nfs_export.present:
        - name: '/srv/nfs'
        - clients:
          # First export, same as simple one above
          - hosts: '10.0.2.0/24'
            options:
              - 'rw'
          # Second export
          - hosts: '*.example.com'
            options:
              - 'ro'
              - 'subtree_check'

This creates the following in /etc/exports:

.. code-block:: bash

    /srv/nfs 10.0.2.0/24(rw) 192.168.0.0/24,172.19.0.0/16(ro,subtree_check)

Any export of the given path will be modified to match the one specified.

To ensure an NFS export is absent:

.. code-block:: yaml

    delete_export:
      nfs_export.absent:
        - name: '/srv/nfs'

"""

import salt.utils.path

def __virtual__():
    """
    Only work with nfs tools installed
    """
    cmd = "exportfs"
    if salt.utils.path.which(cmd):
        return bool(cmd)

    return (
        False,
        "The nfs_exports state module failed to load: "
        "the exportfs binary is not in the path",
    )

def present(name, clients=None, hosts=None, options=None, exports="/etc/exports"):
    """
    Ensure that the named export is present with the given options

    name
        The export path to configure

    clients
        A list of hosts and the options applied to them.
        This option may not be used in combination with
        the 'hosts' or 'options' shortcuts.

    .. code-block:: yaml

        - clients:
          # First export
          - hosts: '10.0.2.0/24'
            options:
              - 'rw'
          # Second export
          - hosts: '*.example.com'
            options:
              - 'ro'
              - 'subtree_check'

    hosts
        A string matching a number of hosts, for example:

    .. code-block:: yaml

        hosts: '10.0.2.123'

        hosts: '10.0.2.0/24'

        hosts: 'minion1.example.com'

        hosts: '*.example.com'

        hosts: '*'

    options
        A list of NFS options, for example:

    .. code-block:: yaml

        options:
          - 'rw'
          - 'subtree_check'

    """
    path = name
    ret = {"name": name, "changes": {}, "result": None, "comment": ""}

    if not clients:
        if not hosts:
            ret["result"] = False
            ret["comment"] = "Either 'clients' or 'hosts' must be defined"
            return ret
        # options being None is handled by add_export()
        clients = [{"hosts": hosts, "options": options}]

    old = __salt__["nfs3.list_exports"](exports)
    if path in old:
        if old[path] == clients:
            ret["result"] = True
            ret["comment"] = "Export {} already configured".format(path)
            return ret

        ret["changes"]["new"] = clients
        ret["changes"]["old"] = old[path]
        if __opts__["test"]:
            ret["result"] = None
            ret["comment"] = "Export {} would be changed".format(path)
            return ret

        __salt__["nfs3.del_export"](exports, path)

    else:
        ret["changes"]["old"] = None
        ret["changes"]["new"] = clients
        if __opts__["test"]:
            ret["result"] = None
            ret["comment"] = "Export {} would be added".format(path)
            return ret

    add_export = __salt__["nfs3.add_export"]
    for exp in clients:
        add_export(exports, path, exp["hosts"], exp["options"])

    ret["changes"]["new"] = clients

    try_reload = __salt__["nfs3.reload_exports"]()
    ret["comment"] = try_reload["stderr"]
    ret["result"] = try_reload["result"]
    return ret

def absent(name, exports="/etc/exports"):
    """
    Ensure that the named path is not exported

    name
        The export path to remove
    """

    path = name
    ret = {"name": name, "changes": {}, "result": None, "comment": ""}

    old = __salt__["nfs3.list_exports"](exports)
    if path in old:
        if __opts__["test"]:
            ret["comment"] = "Export {} would be removed".format(path)
            ret["changes"][path] = old[path]
            ret["result"] = None
            return ret

        __salt__["nfs3.del_export"](exports, path)
        try_reload = __salt__["nfs3.reload_exports"]()
        if not try_reload["result"]:
            ret["comment"] = try_reload["stderr"]
        else:
            ret["comment"] = "Export {} removed".format(path)

        ret["result"] = try_reload["result"]
        ret["changes"][path] = old[path]
    else:
        ret["comment"] = "Export {} already absent".format(path)
        ret["result"] = True

    return ret


text:
<?php
/**
 * @Author: Leandro Henrique Reis <emtudo@gmail.com>
 * @Date:   2016-05-05 08:50:22
 * @Last Modified by:   Leandro Henrique Reis
 * @Last Modified time: 2016-06-04 19:52:15
 */

namespace Domain\Student\Http\Requests;

use Domain\Http\Requests\Request;

class StoreRequest extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:45',
            'sex' => 'required|in:male,female',

            'father' => 'max:45',
            'mother' => 'max:45',
            'responsible' => 'required|max:45',
            'cpf_responsible' => 'cpf',
            'phone_father' => 'max:11|phone_br',
            'phone_mother' => 'max:11|phone_br',
            'phone_responsible' => 'required|max:11|phone_br',

            'postcode' => 'required|max:8|regex:/[0-9]/',
            'street' => 'required|max:60',
            'number' => 'required|max:10',
            'district' => 'required|max:60',
            'city' => 'required|max:60',
            'state' => 'required|max:2',
            'phone' => 'required|max:10|phone_br',
            'cellphone' => 'required|max:11|cellphone_br',
            'complement' => 'max:30',

            'monthly_payment' => 'required|numeric|positive',
            'day_of_payment' => 'required|integer|min:1|max:31',
            'installments' => 'integer',

            'user' => 'required|array',
            'user.password' => 'required|min:6|max:255',
            'user.username' => 'required|max:30|unique:users,username,NULL,id,owner_type,Domain\Student\Student',
            'user.email' => 'required|max:255|email|unique:users,email,NULL,id,owner_type,Domain\Student\Student',

            'status' => 'boolean',
        ];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Knx.ObjectModel.Meta
{
    public class AttributeSplitExtractor : AttributeExtractor
    {
        public string Mark { get; set; }
        public bool UntilMark { get; set; }
        public override void Extract(Filtering.FilteredResult fr, ref KnxPort meta)
        {
            base.Extract(fr, ref meta);
            var result = meta.MetaData[AttributeName];
            if (!string.IsNullOrWhiteSpace(result))
            {
                var idx = result.IndexOf(Mark, StringComparison.InvariantCultureIgnoreCase);
                if (idx >= 0)
                {
                    if (UntilMark)
                        meta.MetaData[AttributeName] = result.Substring(0, idx);
                    else if (result.Length > idx + Mark.Length)
                        meta.MetaData[AttributeName] = result.Substring(idx + Mark.Length);
                }
            }
        }
    }
}


text:
package org.micromanager.plugins.magellan.mmcloneclasses.utils;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;

import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import org.micromanager.plugins.magellan.misc.Log;
import org.micromanager.plugins.magellan.propsandcovariants.DeviceControlTableModel;
import org.micromanager.plugins.magellan.propsandcovariants.SinglePropertyOrGroup;

/**
 * Cell editing using either JTextField or JComboBox depending on whether the
 * property enforces a set of allowed values.
 */
public class PropertyValueCellEditor extends AbstractCellEditor implements TableCellEditor {

   private static final long serialVersionUID = 1L;
   // This is the component that will handle the editing of the cell value
   JTextField text_ = new JTextField();
   JComboBox combo_ = new JComboBox();
   SliderPanel slider_ = new SliderPanel();
   SinglePropertyOrGroup item_;

   public PropertyValueCellEditor() {
      super();

      // end editing on selection change
      combo_.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            fireEditingStopped();
         }
      });

      slider_.addEditActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            fireEditingStopped();
         }
      });

      slider_.addSliderMouseListener(new MouseAdapter() {

         @Override
         public void mouseReleased(MouseEvent e) {
            fireEditingStopped();
         }
      });

      text_.addKeyListener(new KeyAdapter() {

         @Override
         public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
               fireEditingStopped();
            }
         }
      });

      text_.addFocusListener(new FocusAdapter() {

         @Override
         public void focusLost(FocusEvent e) {
            // fireEditingStopped();
         }
      });
   }

   // This method is called when a cell value is edited by the user.
   @Override
   public Component getTableCellEditorComponent(JTable table, Object value,
           boolean isSelected, int rowIndex, int colIndex) {

      // https://stackoverflow.com/a/3055930
      if (value == null) {
         return null;
      }

      DeviceControlTableModel data = (DeviceControlTableModel) table.getModel();
      item_ = data.getPropertyItem(rowIndex);

      // Configure the component with the specified value:
      if (item_.allowed.length == 0) {
         if (item_.hasRange) {
            if (item_.isInteger()) {
               slider_.setLimits((int) item_.lowerLimit, (int) item_.upperLimit);
            } else {
               slider_.setLimits(item_.lowerLimit, item_.upperLimit);
            }
            try {
               slider_.setText((String) value);
            } catch (ParseException ex) {
               Log.log(ex);
            }
            return slider_;
         } else {
            text_.setText((String) value);
            return text_;
         }
      } else {
         ActionListener[] l = combo_.getActionListeners();
         for (int i = 0; i < l.length; i++) {
            combo_.removeActionListener(l[i]);
         }
         combo_.removeAllItems();
         for (int i = 0; i < item_.allowed.length; i++) {
            combo_.addItem(item_.allowed[i]);
         }
         combo_.setSelectedItem(item_.value);

         // end editing on selection change
         combo_.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
               fireEditingStopped();
            }
         });

         return combo_;
      }

   }

   // This method is called when editing is completed.
   // It must return the new value to be stored in the cell.
   @Override
   public Object getCellEditorValue() {
      if (item_.allowed.length == 0) {
         if (item_.hasRange) {
            return slider_.getText();
         } else {
            return text_.getText();
         }
      } else {
         return combo_.getSelectedItem();
      }
   }
}


text:
#ifndef WAYMO_OPEN_DATASET_METRICS_METRICS_UTILS_H_
#define WAYMO_OPEN_DATASET_METRICS_METRICS_UTILS_H_

// Some internal helper functions to implement detection and tracking metrics.
// Refer to detection_metrics.h and tracking_metrics.h for public APIs.

#include <vector>

#include "waymo_open_dataset/label.pb.h"
#include "waymo_open_dataset/metrics/matcher.h"
#include "waymo_open_dataset/protos/breakdown.pb.h"
#include "waymo_open_dataset/protos/metrics.pb.h"

namespace waymo {
namespace open_dataset {
namespace internal {

// Returns true if the i-th entry in the pd_matches is a true positive.
// Requires: i >= 0, i < pd_matches.size().
bool IsTP(const std::vector<int>& pd_matches, int i);

// Returns true if the i-th entry in the pd_matches is a false positive.
// 'matcher' is needed to examine whether the prediction overlaps any NLZs.
// Requires: pd_matches is a valid matching result from 'matcher'
// Requires: i >= 0, i < pd_matches.size().
bool IsFP(const Matcher& matcher, const std::vector<int>& pd_matches, int i);

// Returns true if the i-th entry in the gt_matches is a false positive for
// detection at the given difficulty level.
// Detection and tracking are considered differently as they have a different
// definition of difficulty.
// Requires: gt_matches is a valid matching result from 'matcher'.
// Requires: i >= 0, i < gt_matches.size().
bool IsDetectionFN(const Matcher& matcher, const std::vector<int>& gt_matches,
                   int i, Label::DifficultyLevel level);

// Returns true if the i-th entry in the gt_matches is a false positive for
// tracking at the given difficulty level.
// Detection and tracking are considered differently as they have different
// definition of difficulty.
// Requires: gt_matches is a valid matching result from 'matcher'.
// Requires: i >= 0, i < gt_matches.size().
bool IsTrackingFN(const Matcher& matcher, const std::vector<int>& gt_matches,
                  int i, Label::DifficultyLevel level);

// Returns the heading accuracy for the given prediction and ground truth.
// The heading accuracy is within [0.0, 1.0]. The higher, the better.
// Requires: prediction_index and ground_truth_index are valid indices from
// 'matcher'.
float ComputeHeadingAccuracy(const Matcher& matcher, int prediction_index,
                             int ground_truth_index);

// A convenient struct that wraps object subsets for all score cutoffs.
// It is used to provide inputs for Matcher::Set{Prediction,GroundTruth}Subset.
struct BreakdownShardSubset {
  // The subsets ordered the same as scores in the config.
  // The size of this is set to 1 if the struct is used for ground truths as all
  // score cutoffs share the ground truth same subset.
  std::vector<std::vector<int>> indices;

  // The breakdown ID index of Config::breakdown_generator_ids associated with
  // this subset. This is provided as downstream consumers of this struct need
  // to compute metrics for different difficulty levels which is specified per
  // breakdown generator.
  int breakdown_generator_id_index = -1;
  // The breakdown shard this subset is computed for.
  int breakdown_shard = -1;
};

// Builds all breakdown subsets for the given objects (either prediction or
// ground truths) based on the config.
// Set is_gt if 'objects' are ground truths.
// Set is_detection if this function is called when computing detection metrics.
// Output ordering:
// [{generator_i_shard_j}].
// i \in [0, num_breakdown_generators).
// j \in [0, num_shards for the i-th breakdown generator).
std::vector<BreakdownShardSubset> BuildSubsets(
    const Config& config, const std::vector<Object>& objects, bool is_gt,
    bool is_detection);

// Returns a vector of difficulty levels for the given breakdown generator ID
// index of Config::breakdown_generator_ids based on the config.
std::vector<Label::DifficultyLevel> GetDifficultyLevels(
    const Config& config, int breakdown_generator_id_index);

// Decides score cutoffs that evenly distributes scores into
// `num_desired_cutoffs` buckets.
// Requires: scores are sorted in ascending order. Every element in scores is
//   within [0.0, 1.0].
std::vector<float> DecideScoreCutoffs(const std::vector<float>& scores,
                                      int num_desired_cutoffs);

// Computes mean average precision from pairs of precision and recalls.
// Notes about the implementation details:
// 1. We follow COCO by updating p(r) to be p(r) = max_{r' >= r}p(r').
// 2. If the gap between consecutive recalls are bigger than a desired threshold
//    (e.g. 0.05), p/r points are explicitly added with conservative precisions.
//    Example: p(r): p(0) = 1.0, p(1) = 0.0, delta = 0.05. We add p(0.95) = 0.0,
//    p(0.90) = 0.0, ..., p(0.05) = 0.0. The mAP = 0.05 after this augmentation.
//    This avoids producing an over-estimated mAP with very sparse p/r curve
//    sampling.
//    To disable this, set recall_delta to 1.0.
// Note: the precisions and recalls passed here are not necessarily to be sorted
// but need to have 1:1 correspondence.
float ComputeMeanAveragePrecision(const std::vector<float>& precisions,
                                  const std::vector<float>& recalls,
                                  float max_recall_delta);

// Estimates predicted object speed by looking for the nearest groundtruth
// object.
std::vector<Object> EstimateObjectSpeed(const std::vector<Object>& pds,
                                        const std::vector<Object>& gts);

// Similar as above but takes multiple frames prediction as input.
std::vector<std::vector<Object>> EstimateObjectSpeed(
    const std::vector<std::vector<Object>>& pds,
    const std::vector<std::vector<Object>>& gts);

// Returns true if velocity breakdown is enabled.
bool HasVelocityBreakdown(const Config& config);

// Finds the ground truth that has the largest IoU with the given prediction
// represented by its subset ID within the given matcher.
int FindGTWithLargestIoU(const Matcher& matcher, int pd_subset_id,
                         double iou_threshold);

// Returns true if the object is in the given breakdown.
bool IsInBreakdown(const Object& object, const Breakdown& breakdown);

// Returns true if the breakdown is a ground truth only breakdown.
bool IsGroundTruthOnlyBreakdown(const Breakdown& breakdown);

}  // namespace internal
}  // namespace open_dataset
}  // namespace waymo

#endif  // WAYMO_OPEN_DATASET_METRICS_METRICS_UTILS_H_


text:
/*******************************************************
*   Refraction©
*
*   This file may be used under under the license as
*   stated below. For more information about License
*   types see the included LICENSE file. If you did
*   not recive a copy of that file contact the author.
*
*   @author  YNOP (ynop@acm.org)
*   @version beta
*   @date    Feb 5 2000
*   @license Refraction Core Code
*******************************************************/
#ifndef _TOOL_TIP_H
#define _TOOL_TIP_H

#include "ToolTipWindow.h"

struct tip_entry{
   BView *v;
   const char *tip;
};

class ToolTip{
public:
   ToolTip();
   ~ToolTip();
   status_t AddTip(BView *v,const char *tip = NULL);
   const char* GetTip(BView*);
private:
   static int32 _ToolTip_Thread_(void *data){
      return ((ToolTip*)(data))->Tool_Thread();
   }
   int32 Tool_Thread();
   BView* FindView(BPoint);
private:
   thread_id ttThread;
   ToolTipWindow *ttWin;
   BList *tips;
};
#endif


text:
namespace ReMi.Plugin.ZenDesk
{
    public enum Types
    {
        problem,
        incident,
        question,
        task
    }
}


text:
import sys
import click
import pytest

@click.group()
def cli():
    pass

@cli.command()
def test():
    """Run tests"""
    print("RUN TESTS")
    sys.exit(pytest.main(["backend/tests/", "-v", "--tb", "short", "-m", "dev", "--disable-warnings"]))

@cli.command()
def test_cov():
    """Run tests with coverage"""
    print("RUN TESTS WITH COVERAGE")
    sys.exit(pytest.main(["backend/tests/", "-v", "--tb", "short", "--cov-report", "term:skip-covered", "--cov=backend", "--disable-warnings"]))

@cli.command()
def test_cov_html():
    """Run tests"""
    print("RUN TESTS WITH COVERAGE ON HTML INTERFACE")
    sys.exit(pytest.main(["backend/tests/", "-v", "--tb", "short", "--cov-report", "html:cov_html", "--cov=backend"]))

if __name__ == "__main__":
    cli()


text:
package fr.paris.lutece.util.pool.service;

import java.sql.Connection;
import java.sql.SQLException;

import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.sql.DataSource;

import org.apache.logging.log4j.Logger;

/**
 * This class provides a ConnectionService based on Tomcat
 */
public class TomcatConnectionService implements ConnectionService
{
    private DataSource _ds;
    private String _strPoolName;
    private Logger _logger;

    /**
     * {@inheritDoc}
     */
    @Override
    public Connection getConnection( )
    {
        Connection conn = null;

        try
        {
            if ( _ds != null )
            {
                conn = _ds.getConnection( );
                _logger.debug( "The connexion is get" );

            }
        }
        catch( Exception e )
        {
            _logger.error( "Erreur when getting the connexion with the pool : {}", getPoolName( ), e );
        }

        return conn;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void freeConnection( Connection conn )
    {
        try
        {
            conn.close( );
        }
        catch( SQLException e )
        {
            _logger.error( "SQL error when releasing the connexion with the pool : {}", getPoolName( ), e );
        }
        catch( Exception e )
        {
            _logger.error( "Error while releasing the connexion with the pool : {}", getPoolName( ), e );
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void init( Map<String, String> htParamsConnectionPool )
    {
        try
        {
            String strDs = htParamsConnectionPool.get( getPoolName( ) + ".ds" );
            Context ctx = new InitialContext( );

            _ds = (DataSource) ctx.lookup( "java:comp/env/" + strDs );
        }
        catch( Exception e )
        {
            _logger.error( "Error while initializing the pool {}", getPoolName( ), e );
        }

        _logger.info( "Initialization of the pool {}", getPoolName( ) );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setPoolName( String strPoolName )
    {
        _strPoolName = strPoolName;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getPoolName( )
    {
        return _strPoolName;
    }

    /**
     * Sets the logger
     *
     * @param logger
     *            The logger
     */
    @Override
    public void setLogger( Logger logger )
    {
        _logger = logger;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Logger getLogger( )
    {
        return _logger;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void release( )
    {
        // Nothing to do
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getCurrentConnections( )
    {
        return ConnectionService.INFO_NOT_AVAILABLE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getMaxConnections( )
    {
        return ConnectionService.INFO_NOT_AVAILABLE;
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public String getPoolProvider( )
    {
        return "Tomcat";
    }

    /**
     * {@inheritDoc }
     */
    @Override
    public DataSource getDataSource( )
    {
        return _ds;
    }
}


text:
<?php

namespace app\controllers;

/**
* This is the class for controller "UserrController".
*/
class UserrController extends \app\controllers\base\UserrController
{

}


text:
import { TEXT } from 'config/types';
import { escapeHtml } from 'utils/html';
import detach from './shared/detach';

var Text = function ( options ) {
	this.type = TEXT;
	this.text = options.template;
};

Text.prototype = {
	detach: detach,

	firstNode () {
		return this.node;
	},

	render () {
		if ( !this.node ) {
			this.node = document.createTextNode( this.text );
		}

		return this.node;
	},

	toString ( escape ) {
		return escape ? escapeHtml( this.text ) : this.text;
	},

	unrender ( shouldDestroy ) {
		if ( shouldDestroy ) {
			return this.detach();
		}
	}
};

export default Text;


text:
var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './rio/assets/index'
  ],
  output: {
    path: path.join(__dirname, 'rio/static/dashboard'),
    filename: 'bundle.js',
    publicPath: '/static/dashboard'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: [ 'babel' ],
        exclude: /node_modules/,
        include: __dirname
      },
      {
        test: /\.css?$/,
        loaders: [ 'style', 'raw' ],
        include: __dirname
      }
    ]
  }
}


text:
var chai = require('chai');
var chaiFs = require('chai-fs');
var path = require('path');
var sass = require('dart-sass');

chai.use(chaiFs);
var assert = chai.assert;
var should = chai.should();

var Path = {
  INPUT: path.join(__dirname, 'testdata/a.scss'),
  EXPECTED_OUTPUT: path.join(__dirname, 'testdata/a.min.css')
};

describe('ak-breakpoint', function() {
  it('a.scss should compile to a.min.css', function(done) {
    sass.render({
      file: Path.INPUT,
      outputStyle: 'expanded'
    }, function(err, result) {
      should.not.exist(err);
      assert.fileContent(Path.EXPECTED_OUTPUT, result.css.toString());
      done();
    });
  });
});


text:
#ifndef InspectorClient_h
#define InspectorClient_h

#include "InspectorForwarding.h"
#include <wtf/Forward.h>
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>

namespace WebCore {

class InspectorController;
class Frame;
class Page;

class InspectorClient {
public:
    virtual ~InspectorClient() { }

    virtual void inspectorDestroyed() = 0;

    virtual InspectorFrontendChannel* openInspectorFrontend(InspectorController*) = 0;
    virtual void closeInspectorFrontend() = 0;
    virtual void bringFrontendToFront() = 0;
    virtual void didResizeMainFrame(Frame*) { }

    virtual void highlight() = 0;
    virtual void hideHighlight() = 0;

    virtual void showInspectorIndication() { }
    virtual void hideInspectorIndication() { }

    virtual bool canClearBrowserCache() { return false; }
    virtual void clearBrowserCache() { }
    virtual bool canClearBrowserCookies() { return false; }
    virtual void clearBrowserCookies() { }

    virtual bool overridesShowPaintRects() { return false; }
    virtual void setShowPaintRects(bool) { }

    virtual bool canShowDebugBorders() { return false; }
    virtual void setShowDebugBorders(bool) { }

    virtual bool canShowFPSCounter() { return false; }
    virtual void setShowFPSCounter(bool) { }

    virtual bool canContinuouslyPaint() { return false; }
    virtual void setContinuousPaintingEnabled(bool) { }

    virtual void didSetSearchingForNode(bool) { }

    virtual bool handleJavaScriptDialog(bool, const String*) { return false; }

    static bool doDispatchMessageOnFrontendPage(Page* frontendPage, const String& message);
};

} // namespace WebCore

#endif // !defined(InspectorClient_h)


text:
<?php

require_once 'includes/Upload.class.php';

$type = $_GET['output'] ?? 'json';
$response = (new Core\Response($type));

if (isset($_FILES['files'])) {
    $uploads = Upload::reFiles($_FILES['files']);

    try {
        foreach ($uploads as $upload) {
            $res[] = Upload::uploadFile();
        }
        if (isset($res)) {
            $response->send($res);
        }
    } catch (Exception $e) {
        $response->error($e->getCode(), $e->getMessage());
    }
} else {
    $response->error(400, 'No input file(s)');
}


text: git slides demo


text:
package test.com.qiniu.util;

import static org.junit.jupiter.api.Assertions.assertEquals;
import com.qiniu.util.Crc32;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

public class CrcTest {
    @Test
    @Tag("UnitTest")
    public void testCrc() {
        byte[] data = "Hello, World!".getBytes();
        long result = Crc32.bytes(data);
        assertEquals(3964322768L, result);
    }
}


text:
package com.haulmont.cuba.core;

import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.core.global.LoadContext;
import com.haulmont.cuba.security.entity.Group;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.cuba.testsupport.TestContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import java.util.List;
import java.util.UUID;

import static org.junit.Assert.assertEquals;

@SuppressWarnings("IncorrectCreateEntity")
public class HsqlLikeNullFailTest {

    @ClassRule
    public static TestContainer cont = TestContainer.Common.INSTANCE;

    @Before
    public void setUp() throws Exception {
        DataManager dataManager = AppBeans.get(DataManager.NAME);

        Group group = dataManager.load(new LoadContext<>(Group.class)
                .setId(UUID.fromString("0fa2b1a5-1d68-4d69-9fbd-dff348347f93")));

        User user = new User();
        user.setGroup(group);
        user.setId(UUID.fromString("de0f39d2-e60a-11e1-9b55-3860770d7eaf"));
        user.setName("Test");
        user.setLogin("tEst");
        user.setLoginLowerCase("test");

        dataManager.commit(user);
    }

    @After
    public void tearDown() throws Exception {
        cont.deleteRecord("SEC_USER", UUID.fromString("de0f39d2-e60a-11e1-9b55-3860770d7eaf"));
    }

    @Test
    public void testLoadListCaseInsensitive() {
        LoadContext<User> loadContext = LoadContext.create(User.class);
        loadContext.setQueryString("select u from sec$User u " +
                "where u.name like :custom_searchString or u.login like :custom_searchString")
                .setParameter("custom_searchString", null);

        DataManager dataManager = AppBeans.get(DataManager.NAME);
        List<User> list = dataManager.loadList(loadContext);
        assertEquals(0, list.size());
    }
}


text:
// Define Minimongo collections to match server/publish.js.
Lists = new Meteor.Collection("lists");
Todos = new Meteor.Collection("todos");

// ID of currently selected list
Session.setDefault('list_id', null);

// Name of currently selected tag for filtering
Session.setDefault('tag_filter', null);

// When adding tag to a todo, ID of the todo
Session.setDefault('editing_addtag', null);

// When editing a list name, ID of the list
Session.setDefault('editing_listname', null);

// When editing todo text, ID of the todo
Session.setDefault('editing_itemname', null);

// Subscribe to 'lists' collection on startup.
// Select a list once data has arrived.
var listsHandle = Meteor.subscribe('lists', function () {
  if (!Session.get('list_id')) {
    var list = Lists.findOne({}, {sort: {name: 1}});
    if (list)
      Router.setList(list._id);
  }
});

var todosHandle = null;
// Always be subscribed to the todos for the selected list.
Deps.autorun(function () {
  var list_id = Session.get('list_id');
  if (list_id)
    todosHandle = Meteor.subscribe('todos', list_id);
  else
    todosHandle = null;
});

////////// Helpers for in-place editing //////////

// Returns an event map that handles the "escape" and "return" keys and
// "blur" events on a text input (given by selector) and interprets them
// as "ok" or "cancel".
var okCancelEvents = function (selector, callbacks) {
  var ok = callbacks.ok || function () {};
  var cancel = callbacks.cancel || function () {};

  var events = {};
  events['keyup '+selector+', keydown '+selector+', focusout '+selector] =
    function (evt) {
      if (evt.type === "keydown" && evt.which === 27) {
        // escape = cancel
        cancel.call(this, evt);

      } else if (evt.type === "keyup" && evt.which === 13 ||
                 evt.type === "focusout") {
        // blur/return/enter = ok/submit if non-empty
        var value = String(evt.target.value || "");
        if (value)
          ok.call(this, value, evt);
        else
          cancel.call(this, evt);
      }
    };

  return events;
};

var activateInput = function (input) {
  input.focus();
  input.select();
};

////////// Lists //////////

Template.lists.loading = function () {
  return !listsHandle.ready();
};

Template.lists.lists = function () {
  return Lists.find({}, {sort: {name: 1}});
};

Template.lists.events({
  'mousedown .list': function (evt) { // select list
    Router.setList(this._id);
  },
  'click .list': function (evt) {
    // prevent clicks on <a> from refreshing the page.
    evt.preventDefault();
  },
  'dblclick .list': function (evt, tmpl) { // start editing list name
    Session.set('editing_listname', this._id);
    Deps.flush(); // force DOM redraw, so we can focus the edit field
    activateInput(tmpl.find("#list-name-input"));
  }
});

// Attach events to keydown, keyup, and blur on "New list" input box.
Template.lists.events(okCancelEvents(
  '#new-list',
  {
    ok: function (text, evt) {
      var id = Lists.insert({name: text});
      Router.setList(id);
      evt.target.value = "";
    }
  }));

Template.lists.events(okCancelEvents(
  '#list-name-input',
  {
    ok: function (value) {
      Lists.update(this._id, {$set: {name: value}});
      Session.set('editing_listname', null);
    },
    cancel: function () {
      Session.set('editing_listname', null);
    }
  }));

Template.lists.selected = function () {
  return Session.equals('list_id', this._id) ? 'selected' : '';
};

Template.lists.name_class = function () {
  return this.name ? '' : 'empty';
};

Template.lists.editing = function () {
  return Session.equals('editing_listname', this._id);
};

////////// Todos //////////

Template.todos.loading = function () {
  return todosHandle && !todosHandle.ready();
};

Template.todos.any_list_selected = function () {
  return !Session.equals('list_id', null);
};

Template.todos.events(okCancelEvents(
  '#new-todo',
  {
    ok: function (text, evt) {
      var tag = Session.get('tag_filter');
      Todos.insert({
        text: text,
        list_id: Session.get('list_id'),
        done: false,
        timestamp: (new Date()).getTime(),
        tags: tag ? [tag] : []
      });
      evt.target.value = '';
    }
  }));

Template.todos.todos = function () {
  // Determine which todos to display in main pane,
  // selected based on list_id and tag_filter.

  var list_id = Session.get('list_id');
  if (!list_id)
    return {};

  var sel = {list_id: list_id};
  var tag_filter = Session.get('tag_filter');
  if (tag_filter)
    sel.tags = tag_filter;

  return Todos.find(sel, {sort: {timestamp: 1}});
};

Template.todo_item.tag_objs = function () {
  var todo_id = this._id;
  return _.map(this.tags || [], function (tag) {
    return {todo_id: todo_id, tag: tag};
  });
};

Template.todo_item.done_class = function () {
  return this.done ? 'done' : '';
};

Template.todo_item.editing = function () {
  return Session.equals('editing_itemname', this._id);
};

Template.todo_item.adding_tag = function () {
  return Session.equals('editing_addtag', this._id);
};

Template.todo_item.events({
  'click .check': function () {
    Todos.update(this._id, {$set: {done: !this.done}});
  },

  'click .destroy': function () {
    Todos.remove(this._id);
  },

  'click .addtag': function (evt, tmpl) {
    Session.set('editing_addtag', this._id);
    Deps.flush(); // update DOM before focus
    activateInput(tmpl.find("#edittag-input"));
  },

  'dblclick .display .todo-text': function (evt, tmpl) {
    Session.set('editing_itemname', this._id);
    Deps.flush(); // update DOM before focus
    activateInput(tmpl.find("#todo-input"));
  },

  'click .remove': function (evt) {
    var tag = this.tag;
    var id = this.todo_id;

    evt.target.parentNode.style.opacity = 0;
    // wait for CSS animation to finish
    Meteor.setTimeout(function () {
      Todos.update({_id: id}, {$pull: {tags: tag}});
    }, 300);
  }
});

Template.todo_item.events(okCancelEvents(
  '#todo-input',
  {
    ok: function (value) {
      Todos.update(this._id, {$set: {text: value}});
      Session.set('editing_itemname', null);
    },
    cancel: function () {
      Session.set('editing_itemname', null);
    }
  }));

Template.todo_item.events(okCancelEvents(
  '#edittag-input',
  {
    ok: function (value) {
      Todos.update(this._id, {$addToSet: {tags: value}});
      Session.set('editing_addtag', null);
    },
    cancel: function () {
      Session.set('editing_addtag', null);
    }
  }));

////////// Tag Filter //////////

// Pick out the unique tags from all todos in current list.
Template.tag_filter.tags = function () {
  var tag_infos = [];
  var total_count = 0;

  Todos.find({list_id: Session.get('list_id')}).forEach(function (todo) {
    _.each(todo.tags, function (tag) {
      var tag_info = _.find(tag_infos, function (x) { return x.tag === tag; });
      if (! tag_info)
        tag_infos.push({tag: tag, count: 1});
      else
        tag_info.count++;
    });
    total_count++;
  });

  tag_infos = _.sortBy(tag_infos, function (x) { return x.tag; });
  tag_infos.unshift({tag: null, count: total_count});

  return tag_infos;
};

Template.tag_filter.tag_text = function () {
  return this.tag || "All items";
};

Template.tag_filter.selected = function () {
  return Session.equals('tag_filter', this.tag) ? 'selected' : '';
};

Template.tag_filter.events({
  'mousedown .tag': function () {
    if (Session.equals('tag_filter', this.tag))
      Session.set('tag_filter', null);
    else
      Session.set('tag_filter', this.tag);
  }
});

////////// Tracking selected list in URL //////////

var TodosRouter = Backbone.Router.extend({
  routes: {
    ":list_id": "main"
  },
  main: function (list_id) {
    var oldList = Session.get("list_id");
    if (oldList !== list_id) {
      Session.set("list_id", list_id);
      Session.set("tag_filter", null);
    }
  },
  setList: function (list_id) {
    this.navigate(list_id, true);
  }
});

Router = new TodosRouter;

Meteor.startup(function () {
  Backbone.history.start({pushState: true});
});


text:
SYNONYM

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

#### Published in
Docums Mycol. , mém. hors sér. 21(no. 82): 66 (1991)

#### Original name
Tricholoma ionides var. obscurissima A. Pearson, 1946

### Remarks
null


text:
package microsoft.exchange.webservices.data.misc;

/**
 * The Class Param.
 *
 * @param <T> the generic type
 */
abstract class Param<T> {

  /**
   * The param.
   */
  private T param;

  /**
   * Gets the param.
   *
   * @return the param
   */
  public T getParam() {
    return param;
  }

  /**
   * Sets the param.
   *
   * @param param the new param
   */
  public void setParam(T param) {
    this.param = param;
  }

}


text:
Default

    <m-table-header></m-table-header>

With addBtnLabel

    <m-table-header add-btn-label="Add data"></m-table-header>

With left slot

    <m-table-header>

Content in left slot

    </m-table-header>

With right slot

    <m-table-header>

Content in right slot

    </m-table-header>

With addBtnLabel, left and right slots

    <m-table-header add-btn-label="Add data">

Content in left slot

Content in right slot

    </m-table-header>