text:
#ifndef BADVPN_SECURITY_BENCRYPTION_H
#define BADVPN_SECURITY_BENCRYPTION_H

#include <stdint.h>
#include <string.h>

#ifdef BADVPN_USE_CRYPTODEV
#include <crypto/cryptodev.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#endif

#include <openssl/blowfish.h>
#include <openssl/aes.h>

#include <misc/debug.h>
#include <base/DebugObject.h>

#define BENCRYPTION_MODE_ENCRYPT 1
#define BENCRYPTION_MODE_DECRYPT 2

#define BENCRYPTION_MAX_BLOCK_SIZE 16
#define BENCRYPTION_MAX_KEY_SIZE 16

#define BENCRYPTION_CIPHER_BLOWFISH 1
#define BENCRYPTION_CIPHER_BLOWFISH_BLOCK_SIZE 8
#define BENCRYPTION_CIPHER_BLOWFISH_KEY_SIZE 16

#define BENCRYPTION_CIPHER_AES 2
#define BENCRYPTION_CIPHER_AES_BLOCK_SIZE 16
#define BENCRYPTION_CIPHER_AES_KEY_SIZE 16

// NOTE: update the maximums above when adding a cipher!

/**
 * Block cipher encryption abstraction.
 */
typedef struct {
    DebugObject d_obj;
    int mode;
    int cipher;
    #ifdef BADVPN_USE_CRYPTODEV
    int use_cryptodev;
    #endif
    union {
        BF_KEY blowfish;
        struct {
            AES_KEY encrypt;
            AES_KEY decrypt;
        } aes;
        #ifdef BADVPN_USE_CRYPTODEV
        struct {
            int fd;
            int cfd;
            int cipher;
            uint32_t ses;
        } cryptodev;
        #endif
    };
} BEncryption;

/**
 * Checks if the given cipher number is valid.
 *
 * @param cipher cipher number
 * @return 1 if valid, 0 if not
 */
int BEncryption_cipher_valid (int cipher);

/**
 * Returns the block size of a cipher.
 *
 * @param cipher cipher number. Must be valid.
 * @return block size in bytes
 */
int BEncryption_cipher_block_size (int cipher);

/**
 * Returns the key size of a cipher.
 *
 * @param cipher cipher number. Must be valid.
 * @return key size in bytes
 */
int BEncryption_cipher_key_size (int cipher);

/**
 * Initializes the object.
 * {@link BSecurity_GlobalInitThreadSafe} must have been done if this object
 * will be used from a non-main thread.
 *
 * @param enc the object
 * @param mode whether encryption or decryption is to be done, or both.
 *             Must be a bitwise-OR of at least one of BENCRYPTION_MODE_ENCRYPT
 *             and BENCRYPTION_MODE_DECRYPT.
 * @param cipher cipher number. Must be valid.
 * @param key encryption key
 */
void BEncryption_Init (BEncryption *enc, int mode, int cipher, uint8_t *key);

/**
 * Frees the object.
 *
 * @param enc the object
 */
void BEncryption_Free (BEncryption *enc);

/**
 * Encrypts data.
 * The object must have been initialized with mode including
 * BENCRYPTION_MODE_ENCRYPT.
 *
 * @param enc the object
 * @param in data to encrypt
 * @param out ciphertext output
 * @param len number of bytes to encrypt. Must be >=0 and a multiple of
 *            block size.
 * @param iv initialization vector. Updated such that continuing a previous encryption
 *           starting with the updated IV is equivalent to performing just one encryption.
 */
void BEncryption_Encrypt (BEncryption *enc, uint8_t *in, uint8_t *out, int len, uint8_t *iv);

/**
 * Decrypts data.
 * The object must have been initialized with mode including
 * BENCRYPTION_MODE_DECRYPT.
 *
 * @param enc the object
 * @param in data to decrypt
 * @param out plaintext output
 * @param len number of bytes to decrypt. Must be >=0 and a multiple of
 *            block size.
 * @param iv initialization vector. Updated such that continuing a previous decryption
 *           starting with the updated IV is equivalent to performing just one decryption.
 */
void BEncryption_Decrypt (BEncryption *enc, uint8_t *in, uint8_t *out, int len, uint8_t *iv);

#endif


text:
package com.hyrax.microservice.project.rest.api.converter;

import com.hyrax.microservice.project.rest.api.domain.response.RequestValidationDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.validation.ObjectError;

import java.util.Objects;

@Component
public class ObjectErrorToRequestValidationDetailConverter implements Converter<ObjectError, RequestValidationDetail> {

    @Override
    public RequestValidationDetail convert(final ObjectError objectError) {
        RequestValidationDetail requestValidationDetail = null;

        if (Objects.nonNull(objectError)) {
            requestValidationDetail = RequestValidationDetail.builder()
                    .field(StringUtils.uncapitalize(objectError.getCode()))
                    .message(objectError.getDefaultMessage())
                    .build();
        }

        return requestValidationDetail;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Utility functions and classes used by nose internally.
"""
import inspect
import os
import sys
import types
try:
    # for python 3
    from types import ClassType, TypeType
    class_types = (ClassType, TypeType)
except:
    class_types = (type, )

try:
    #for jython
    from compiler.consts import CO_GENERATOR
except:
    CO_GENERATOR=0x20

PYTHON_VERSION_MAJOR = sys.version_info[0]
PYTHON_VERSION_MINOR = sys.version_info[1]

def cmp_lineno(a, b):
    """Compare functions by their line numbers.
    """
    return cmp(func_lineno(a), func_lineno(b))

def func_lineno(func):
    """Get the line number of a function.
    """
    try:
        return func.compat_co_firstlineno
    except AttributeError:
        try:
            if PYTHON_VERSION_MAJOR == 3:
                return func.__code__.co_firstlineno
            return func.func_code.co_firstlineno
        except AttributeError:
            return -1

def isclass(obj):
    obj_type = type(obj)
    return obj_type in class_types or issubclass(obj_type, type)

def isgenerator(func):
    if PYTHON_VERSION_MAJOR == 3:
        return inspect.isgeneratorfunction(func)
    try:
        return func.func_code.co_flags & CO_GENERATOR != 0
    except AttributeError:
        return False

def resolve_name(name, module=None):
    """Resolve a dotted name to a module and its parts.
    """
    parts = name.split('.')
    parts_copy = parts[:]
    if module is None:
        while parts_copy:
            try:
                module = __import__('.'.join(parts_copy))
                break
            except ImportError:
                del parts_copy[-1]
                if not parts_copy:
                    raise
        parts = parts[1:]
    obj = module
    for part in parts:
        obj = getattr(obj, part)
    return obj

def try_run(obj, names):
    """Given a list of possible method names, try to run them with the
    provided object.
    """
    for name in names:
        func = getattr(obj, name, None)
        if func is not None:
            if type(obj) == types.ModuleType:
                try:
                    args, varargs, varkw, defaults = inspect.getargspec(func)
                except TypeError:
                    if hasattr(func, '__call__'):
                        func = func.__call__
                    try:
                        args, varargs, varkw, defaults = \
                            inspect.getargspec(func)
                        args.pop(0)
                    except TypeError:
                        raise TypeError("Attribute %s of %r is not a python "
                                        "function. Only functions or callables"
                                        " may be used as fixtures." %
                                        (name, obj))
                if len(args):
                    return func(obj)
            return func()

def src(filename):
    """Find the python source file for a .pyc, .pyo
    or $py.class file on jython
    """
    if filename is None:
        return filename
    if sys.platform.startswith('java') and filename.endswith('$py.class'):
        return '.'.join((filename[:-9], 'py'))
    base, ext = os.path.splitext(filename)
    if ext in ('.pyc', '.pyo', '.py'):
        return '.'.join((base, 'py'))
    return filename

def transplant_class(cls, module):
    """
    Make a class appear to reside in `module`, rather than the module in which
    it is actually defined.
    """
    class C(cls):
        pass
    C.__module__ = module
    C.__name__ = cls.__name__
    return C

def transplant_func(func, module = None):
    """
    Make a function imported from module A appear as if it is located
    in module B.
    """

    def newfunc(*arg, **kw):
        return func(*arg, **kw)

    newfunc = make_decorator(func)(newfunc)
    if module is None:
        newfunc.__module__ = inspect.getmodule(func)
    else:
        newfunc.__module__ = module
    return newfunc

def make_decorator(func):
    """
    Wraps a test decorator so as to properly replicate metadata
    of the decorated function.
    """
    def decorate(newfunc):
        if hasattr(func, 'compat_func_name'):
            name = func.compat_func_name
        else:
            name = func.__name__
        newfunc.__dict__ = func.__dict__
        newfunc.__doc__ = func.__doc__
        if not hasattr(newfunc, 'compat_co_firstlineno'):
            if PYTHON_VERSION_MAJOR == 3:
                newfunc.compat_co_firstlineno = func.__code__.co_firstlineno
            else:
                newfunc.compat_co_firstlineno = func.func_code.co_firstlineno
        try:
            newfunc.__name__ = name
        except TypeError:
            newfunc.compat_func_name = name
        return newfunc
    return decorate

# trick for python 3
# The following emulates the behavior (we need) of an 'unbound method' under
# Python 3.x (namely, the ability to have a class associated with a function
# definition so that things can do stuff based on its associated class)

class UnboundMethod:
    def __init__(self, cls, func):
        self.func = func
        self.__self__ = UnboundSelf(cls)

    def address(self):
        cls = self.__self__.cls
        module = cls.__module__
        m = sys.modules[module]
        file = getattr(m, '__file__', None)
        if file is not None:
            file = os.path.abspath(file)
        return (nose.util.src(file), module, "%s.%s" % (cls.__name__, self.func.__name__))

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

    def __getattr__(self, attr):
        return getattr(self.func, attr)

class UnboundSelf:
    def __init__(self, cls):
        self.cls = cls

    # We have to do this hackery because Python won't let us override the
    # __class__ attribute...
    def __getattribute__(self, attr):
        if attr == '__class__':
            return self.cls
        else:
            return object.__getattribute__(self, attr)

def unbound_method(cls, func):
    if inspect.ismethod(func):
        return func
    if not inspect.isfunction(func):
        raise TypeError('%s is not a function' % (repr(func),))
    return UnboundMethod(cls, func)

def ismethod(obj):
    return inspect.ismethod(obj) or isinstance(obj, UnboundMethod)

def isunboundmethod(obj):
    return (inspect.ismethod(obj) and obj.im_self is None) or isinstance(obj, UnboundMethod)


text:
package com.amazonaws.services.lookoutmetrics.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.lookoutmetrics.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * AnomalyDetectorDataQualityMetric JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AnomalyDetectorDataQualityMetricJsonUnmarshaller implements Unmarshaller<AnomalyDetectorDataQualityMetric, JsonUnmarshallerContext> {

    public AnomalyDetectorDataQualityMetric unmarshall(JsonUnmarshallerContext context) throws Exception {
        AnomalyDetectorDataQualityMetric anomalyDetectorDataQualityMetric = new AnomalyDetectorDataQualityMetric();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("StartTimestamp", targetDepth)) {
                    context.nextToken();
                    anomalyDetectorDataQualityMetric.setStartTimestamp(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("MetricSetDataQualityMetricList", targetDepth)) {
                    context.nextToken();
                    anomalyDetectorDataQualityMetric.setMetricSetDataQualityMetricList(new ListUnmarshaller<MetricSetDataQualityMetric>(
                            MetricSetDataQualityMetricJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return anomalyDetectorDataQualityMetric;
    }

    private static AnomalyDetectorDataQualityMetricJsonUnmarshaller instance;

    public static AnomalyDetectorDataQualityMetricJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new AnomalyDetectorDataQualityMetricJsonUnmarshaller();
        return instance;
    }
}


text:
{% extends "html/events/page.html" %}

{% block title %}{% trans %}Upcoming Events{% endtrans %} | {% trans %}Calendar{% endtrans %}{% endblock %}

{% block module_title %}{% trans %}Calendar{% endtrans %}{% endblock %}

{% block class_upcoming %}sidebar-link-active{% endblock %}

{% block sidebar_right %}

{% trans %}Export to{% endtrans %}
    {% if '?' in request.get_full_path() %}<a href="{{ request.get_full_path()|replace('.ajax','').replace('?','.csv?') }}"{% else %}CSV,
    {% if '?' in request.get_full_path() %}<a href="{{ request.get_full_path()|replace('.ajax','').replace('?','.xls?') }}"{% else %}XLS

{% endblock %}

{% block module_content %}
{% if events %}
<form action="" method="post">
{% csrf_token %}

        <input type="hidden" name="massform" value="massform" />
        <input type="checkbox" name="mass-unclassified" value="unclassified" class="group-control" />
         {{ massform.as_ul()|htsafe }}

            <input type="submit" value="{% trans %}Save{% endtrans %}" />

	{{ events_event_list(paginate(events)) }}
    {{ pager(events) }}
</form>
{% else %}
{{ show_hint('events_all') }}
{% endif %}

{% endblock %}


text:
module("Resource interface", {});

test("Check interface", function() {
    stop();
    var frameLoaded = Q.fcall(promiseIFrameLoaded, "scenes/scene-loading.html");

    var test = frameLoaded.then(function (doc) {
        var resource = doc.XML3D.resource;

        ok(resource.registerFormatHandler.call, "registerFormatHandler exists");
        ok(resource.fetch.call, "fetch exists");
        ok(resource.getDocument.call, "getDocument exists");
        ok(resource.onRequest.call, "onRequest exists");
        ok(resource.URI.call, "URI exists");
        ok(resource.URIResolver.call, "URIResolver exists");

        ok(
            resource.FormatHandler.prototype.isFormatSupported &&
            resource.FormatHandler.prototype.getAdapter &&
            resource.FormatHandler.prototype.getFormatData &&
            resource.FormatHandler.prototype.getFragmentData,
            "FormatHandler is exposed properly");
    });

    test.fin(QUnit.start).done();
});

test("Check onRequest hook", function() {
    stop();
    var frameLoaded = Q.fcall(promiseIFrameLoaded, "scenes/scene-loading.html");

    var test = frameLoaded.then(function (doc) {
        var xml3d = doc.XML3D;
        var hookTestDone = false;
        var hook = function(uri, request) {
            if (hookTestDone)
                return;
            ok(true, "Request hook was called");
            ok(uri instanceof xml3d.resource.URI, "URI was provided");
            ok(request.headers !== undefined &&
                request.priority !== undefined &&
                request.abort !== undefined, "Request object contained the expected fields");
            hookTestDone = true;
        };
        xml3d.resource.onRequest(hook);

        var abortHook = function(uri, request) {
            if (uri.fragment == "abortThisRequest") {
                request.abort = true;
            }
        };
        xml3d.resource.onRequest(abortHook);

        xml3d.resource.fetch("json/offsets.json").then(function(response) {
            ok(response !== undefined, "Request was completed");
        });
        xml3d.resource.fetch("json/offsets.json#abortThisRequest").then(function(doc) {
            ok(false, "Request should have been aborted");
        }).catch(function(e) {
            ok(e.name == "RequestAbortedException", "Request was properly aborted");
        });
    });

    test.fin(QUnit.start).done();
});

var TestFormatHandler = function() {
    XML3D.resource.FormatHandler.call(this);
};
XML3D.createClass(TestFormatHandler, XML3D.resource.FormatHandler);

TestFormatHandler.prototype.isFormatSupported = function (response) {
    ok(response, "isFormatSupported was called with response argument");
    return true;
};

TestFormatHandler.prototype.getFormatData = function (response) {
    ok(response, "getFormatData called with response argument");
    return response.json();
};

TestFormatHandler.prototype.getAdapter = function(data, aspect, canvasId) {
    ok(!!data && !!aspect && canvasId === 0, "getAdapter was called with correct arguments");
    return {getXflowNode : function() {return new Xflow.DataNode(false)}};
};

test("Custom format handler", function() {
    stop();
    var frameLoaded = Q.fcall(promiseIFrameLoaded, "scenes/scene-loading.html");

    var test = frameLoaded.then(function (doc) {
        doc.XML3D.resource.registerFormatHandler(new TestFormatHandler());
        var xml3d = doc.getElementById("myXml3d_1");

        var testmesh = doc.createElement("mesh");
        testmesh.setAttribute("src", "json/simpleMesh.testjson"); //bogus file ending to make sure our test format handler is the only one to handle this response
        xml3d.appendChild(testmesh);
        return xml3d;

    }).then(promiseSceneRendered).then(function(xml3d) {
        // The mesh that was added above will not be rendered, will throw an error about missing 'position' data because
        // the test format handler was designed to return just an empty DataNode
        ok(true, "Scene was rendered again");
    });

    test.fin(QUnit.start).done();
});


text:
#pragma once

//#include "PlatformExportMacros.h"

namespace WebCore {

class ScriptExecutionContext;

class ContextDestructionObserver {
public:
    explicit ContextDestructionObserver(ScriptExecutionContext*);
    virtual void contextDestroyed();

    ScriptExecutionContext* scriptExecutionContext() const { return m_scriptExecutionContext; }

protected:
    virtual ~ContextDestructionObserver();
    void observeContext(ScriptExecutionContext*);

    ScriptExecutionContext* m_scriptExecutionContext;
};

} // namespace WebCore


text:
package com.linkedin.datahub.upgrade.impl;

import com.linkedin.datahub.upgrade.UpgradeReport;
import com.linkedin.datahub.upgrade.UpgradeResult;

public class DefaultUpgradeResult implements UpgradeResult {

  private final Result _result;
  private final UpgradeReport _report;

  DefaultUpgradeResult(Result result, UpgradeReport report) {
    _result = result;
    _report = report;
  }

  @Override
  public Result result() {
    return _result;
  }

  @Override
  public UpgradeReport report() {
    return _report;
  }
}


text:
<template name="AdminTeam">
  {{#with team}}
    {{#if Template.subscriptionsReady}}

Admin Home

Teams

{{title}}

{{title}}

Configuration

                Team Title

                {{> EditableTextField dataKey='title' value=title mode='inline' }}

                Team Owner

                  {{#if owner}}

                  {{/if}}

                {{> EditableRecordSelector ownerSelectorContext }}

                Default Project

                  {{#if defaultProjectId}}

                  {{/if}}

                {{> EditableRecordSelector projectSelectorContext dataKey='defaultProjectId' value=defaultProjectId }}

                Default Reporter

                  {{#if reportingContributorId}}

                  {{/if}}

                {{> EditableRecordSelector reporterSelectorContext }}

                Banner Template

                  {{#if bannerTemplate}}
                    {{>AdminDisplayTemplateLink templateName=bannerTemplate}}
                  {{/if}}

                {{> EditableRecordSelector displayTemplateSelectorContext dataKey="bannerTemplate" value=bannerTemplate templateType=DisplayTemplateTypes.banner }}

                Home Template

                  {{#if homeTemplate}}
                    {{>AdminDisplayTemplateLink templateName=homeTemplate}}
                  {{/if}}

                {{> EditableRecordSelector displayTemplateSelectorContext dataKey="homeTemplate" value=homeTemplate templateType=DisplayTemplateTypes.component }}

                Reports

                {{> EditableRecordChecklist displayTemplateSelectorContext dataKey="reports" value=reports templateType=DisplayTemplateTypes.report emptyText="Select Reports"}}

Team Composition

                Name
                Default Role
                Team Roles
                Other Teams

              {{#each contributors}}

                  {{name}}
                  {{renderTeamRole roleId}}

                      {{#each rolesOnTeam ../_id}}
                        {{> AdminTeamContributorRole }}
                      {{/each}}

                      {{#each contributorOtherTeams}}

                          {{title}}

                        {{#each ../rolesOnTeam _id}}
                          {{> AdminTeamContributorRole }}
                        {{/each}}
                      {{/each}}

              {{/each}}

    {{else}}
      {{> AppLoading }}
    {{/if}}
  {{else}}
    {{> NotFound}}
  {{/with}}
</template>


text:
@interface SecondViewController : BaseViewController

@end


text:
package org.codelabor.system.util;

import java.util.Calendar;
import java.util.GregorianCalendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Date 유틸리티 클래스
 *
 * @author Shin Sang-jae
 *
 */
public class DateUtils {
	/**
	 * 로거
	 */
	final static Logger logger = LoggerFactory.getLogger(DateUtils.class);

	/**
	 * 해당 연, 월에 대한 최대 일 수를 가져온다.
	 *
	 * @param year
	 *            연
	 * @param month
	 *            월
	 * @return 최대 일 수
	 */
	static public int getDays(int year, int month) {
		GregorianCalendar calendar = new GregorianCalendar(year, month - 1, 1);
		boolean isLeapYear = calendar.isLeapYear(year);
		int lastDate = calendar.getActualMaximum(Calendar.DATE);

		logger.debug("calendar.getTime(): {}", calendar.getTime());
		logger.debug("isLeapYear: {}", isLeapYear);
		logger.debug("lastDate: {}", lastDate);
		return lastDate;
	}
}


text:
title: Mayor
layout: post
categories:
    - chattanooga
excerpt: |
    The mayor is the chief executive who runs Chattanooga city government.

    He oversees a large administration that provides government services. The structure of this government is mostly determined by the mayor himself. However, he is required by the City Charter to appoint some administrators, including a police chief, fire chief, finance officer and treasurer.

    He is popularly elected in a citywide election every four years. The current mayor, Andy Berke, was first elected in March 2013. Chattanooga's mayor is limited to serving two consecutive terms in office.
ocdid: /country:us/state:tn/place:chattanooga/citywide
---

The mayor is the chief executive who runs Chattanooga city government.

He oversees a large administration that provides government services. The structure of this government is mostly determined by the mayor himself. However, he is required by the City Charter to appoint some administrators, including a police chief, fire chief, finance officer and treasurer.

The mayor is popularly elected in a citywide election every four years. The current mayor, Andy Berke, was first elected in March 2013. Chattanooga's mayor is limited to serving two consecutive terms in office.

The mayor is required to submit an annual budget to the City Council each year. The budget determines which operations and infrastructure projects will be funded in the coming year.

Though he does not sit on the council, or vote on legislation, the mayor's office and administration propose most of the ordinances and resolutions that go before council members.

Chattanooga's mayor also makes appointments to [regulatory boards and commissions](http://www.chattanooga.gov/boards-commissions). He, along with the mayor of Hamilton County, has an automatic seat on the boards of many local and regional organizations.

He often weighs in on decisions that affect the area, such as the recruitment of new industries, long-term planning and regional growth.

He is also the city's spokesman to business leaders and state and federal officials.

## Administration

At the beginning of a term, the mayor determines what the overall structure of city government will be. He creates departments, names administrators to head them, and determines what services they will provide. Four departments are required by the city's charter—police, fire, public works and finance. The remaining departments are up to the mayor to decide.

The mayor's administration has a long list of roles and responsibilities that range from public safety to economic development. The current administration consists of seven departments. Each department is divided into other offices and agencies.

### Police

The Chattanooga Police Department (CPD) is the city's law enforcement agency.

The department enforces laws, preserves the peace, maintains order, combats crime and works to make Chattanooga safe.

The department is divided into three commands: uniform services, investigative services, and administration and support services.

More than 400 sworn officers, as well as civilian staff, work for the CPD.

[Read more](./police.html)

### Fire

The Chattanooga Fire Department (CFD) responds to many emergency situations in the city limits.

The department consists of six divisions: fire suppression and emergency operations, tactical services, fire prevention bureau, logistics, training and administration.

About 400 professional firefighters in the suppression and emergency operations division work from one of 19 fire stations.

[Read more](./fire.html)

### Public Works

The Department of Public Works oversees many of Chattanooga's sanitation and infrastructure systems.

It consists of four main divisions: parks, garbage and recycling, city engineering and water quality, and waste resources.

[Read more](./public-works.html)

### Finance and Administration

The Department of Finance and Administration manages city government's expenditures and revenue.

The department consists of three divisions: finance, treasury and city court clerk.

[Read more](./finance.html)

### Economic and Community Development

The Department of Economic and Community Development oversees federal programs, code enforcement and regional planning.

It is divided into six divisions: comunity developement, land development, neighborhood services, Outdoor Chattanooga, public art and the Regional Planning Agency.

[Read more](./economic-community-development.html)

### Youth and Family Development

The Department of Youth and Family Development manages the staff and programming at community centers.

The department has five focus areas: education, leadership, career development, recreation and social services.

[Read more](./youth-family-development.html)

### Transportation

The Transportation Department manages the city's transportation network and works with other transportation agencies.

It consists of two divisions: traffic engineering and traffic operations.

[Read more](./transportation.html)


text:
package com.google.code.maven_replacer_plugin;

import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.logging.Log;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProxyFileProcessor {
    private File proxyFile;
    private File outputPolicyLoc;
    private File policyLoc;
    private File resourceLoc;
    private File outputResourceLoc;
    private Log log;
    private Set<String> copyCache = new HashSet<String>();

    private void initPaths(String proxyFile, String outputPolicyLoc, String policyLoc, String resourceLoc,
                           String outputResourceLoc, Log log) {
        this.proxyFile = new File(proxyFile);
        this.outputPolicyLoc = new File(outputPolicyLoc);
        this.policyLoc = new File(policyLoc);
        this.resourceLoc = new File(resourceLoc);
        this.outputResourceLoc = new File(outputResourceLoc);
        this.log = log;
    }

    public void process(String proxyFile, String policyLoc, String outputPolicyLoc, String resourceLoc,
                        String outputResourceLoc, Log log) throws IOException {
        int initalSize = copyCache.size();
        initPaths(proxyFile, outputPolicyLoc, policyLoc, resourceLoc, outputResourceLoc, log);
        if (!validatePaths()) {
            return;
        }
        final List<String> polices = getPolicies(FileUtils.readLines(this.proxyFile));
        copyFiles(polices);
        if (copyCache.size() - initalSize > 0) {
            log.info(String.format("Copied %s files referenced by proxy %s.", copyCache.size() - initalSize, proxyFile));
        }
    }

    private void copyFiles(List<String> policies) throws IOException {
        for (String policy : policies) {
            final File policyFile = new File(policyLoc, policy);
            copyPolicyFile(policyFile);
            final ArrayList<String> resourceFiles = processPolicyJSResources(policyFile);
            copyFiles(resourceFiles);
        }
    }

    private void copyFiles(ArrayList<String> resourceFiles) throws IOException {
        for (String resourceFile : resourceFiles) {
            copyResourceFile(resourceFile);
        }
    }

    private void copyResourceFile(String resourceFile) throws IOException {
        final File inFile = new File(resourceLoc, resourceFile);
        if (!inFile.exists()) {
            log.warn(String.format("File %s does not exists.", inFile.getAbsolutePath()));
            return;
        }
        final File outFile = new File(outputResourceLoc, resourceFile);
        if (copyCache.contains(outFile.getCanonicalPath())) {
            return;
        }
        log.debug(String.format("Copying file %s to %s", inFile.getAbsolutePath(), outFile.getAbsolutePath()));
        FileUtils.copyFile(inFile, outFile);
        copyCache.add(outFile.getCanonicalPath());
    }

    private void copyPolicyFile(File srcFile) throws IOException {
        if (!srcFile.exists()) {
            log.warn(String.format("File %s does not exists.", srcFile.getAbsolutePath()));
            return;
        }
        final File outFile = new File(outputPolicyLoc, srcFile.getName());
        if (copyCache.contains(outFile.getCanonicalPath())) {
            return;
        }
        log.debug(String.format("Copying file %s to directory %s", srcFile.getAbsolutePath(), outputPolicyLoc.getAbsolutePath()));
        FileUtils.copyFileToDirectory(srcFile, outputPolicyLoc);
        copyCache.add(outFile.getCanonicalPath());
    }

    private ArrayList<String> processPolicyJSResources(File srcFile) throws IOException {
        if (!srcFile.exists()) {
            return new ArrayList<String>();
        }
        final List<String> lines = FileUtils.readLines(srcFile);
        final ArrayList<String> resourceFiles = new ArrayList<String>();
        for (String line : lines) {
            processJSURLs(resourceFiles, line);
        }
        return resourceFiles;
    }

    private void processJSURLs(ArrayList<String> resourceFiles, String line) {
        String res = getUrl(line, "ResourceURL");
        addResToList(resourceFiles, res);
        res = getUrl(line, "IncludeURL");
        addResToList(resourceFiles, res);
    }

    private void addResToList(ArrayList<String> resourceFiles, String res) {
        if (res != null) {
            resourceFiles.add(res);
        }
    }

    private String getUrl(String line, String urlTag) {
        Pattern pattern = Pattern.compile(String.format("<%1$s>jsc://(.*)</%1$s>", urlTag));
        Matcher matcher = pattern.matcher(line.trim());
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    private List<String> getPolicies(List<String> lines) {
        final ArrayList<String> policies = new ArrayList<String>();
        for (String line : lines) {
            Pattern pattern = Pattern.compile("<Name>(.*)</Name>");
            Matcher matcher = pattern.matcher(line.trim());
            if (matcher.find()) {
                policies.add(matcher.group(1) + ".xml");
            }
        }
        return policies;
    }

    private boolean validatePaths() {
        if (!proxyFile.exists()) {
            return false;
        }
        if (!outputPolicyLoc.exists()) {
            return false;
        }
        if (!policyLoc.exists()) {
            return false;
        }
        return true;
    }
}


text:
package org.adridadou.ethereum.propeller.solidity.converters.decoders;

import org.adridadou.ethereum.propeller.values.EthData;
import org.apache.commons.lang.ArrayUtils;

import java.lang.reflect.Type;

import static org.adridadou.ethereum.propeller.values.EthData.WORD_SIZE;

/**
 * Created by davidroon on 04.04.17.
 * This code is released under Apache 2 license
 */
public class StringDecoder implements SolidityTypeDecoder {
    private final NumberDecoder numberDecoder = new NumberDecoder();

    @Override
    public String decode(Integer index, EthData data, Type resultType) {
        Integer strIndex = numberDecoder.decode(index, data, Integer.class).intValue() / WORD_SIZE;
        Integer len = numberDecoder.decode(strIndex, data, Integer.class).intValue();
        return new String(ArrayUtils.subarray(data.data, (strIndex + 1) * WORD_SIZE, (strIndex + 1) * WORD_SIZE + len));
    }

    @Override
    public boolean canDecode(Class<?> resultCls) {
        return String.class.equals(resultCls);
    }
}


text:
const chalk = require('chalk');
const fs = require('fs-extra');
const nunjucks = require('nunjucks');
const os = require('os');
const path = require('path');
const pathExists = require('path-exists');
const readlineSync = require('readline-sync');
const { FileData } = require('./fileData');

let env = nunjucks.configure({ autoescape: true, noCache: true });
const dateFilter = require('../lib/filters/date');
const customFilters = require('../lib/filters/custom');
env.addFilter('date', dateFilter);
Object.keys(customFilters).forEach(f => env.addFilter(f, customFilters[f]));
if (pathExists.sync(os.homedir() + '/.rename/userFilters.js')) {
  let userFilters = require(os.homedir() + '/.rename/userFilters.js');
  Object.keys(userFilters).forEach(f => env.addFilter(f, userFilters[f]));
}

const CURRENT_DIR = process.cwd() + path.sep;

module.exports.Operation = class Operation {
  constructor(input, options, sequelize) {
    this.options = options;
    this.sequelize = sequelize;
    this.inputFileString = input;
    this.inputFilePath = path.parse(input);
    this.fileData = new FileData(input, options);
    this.outputString = '';
    this.outputFilePath = (path.parse(this.outputString));
    this.outputFileString = '';
    this.conflict = false;
    this.alreadyExists = false;
    this.directoryExists = true;
  }

  async replaceVariables() {
    let data;
    data = await this.fileData.get();
    this.outputString = nunjucks.renderString(this.options.outputPattern, data);
    await this.parseOutputPath();
  }

  async printData() {
    let data;
    if (this.userData) {
      data = await Object.assign(await this.fileData.get(), this.userData);
    } else {
      data = await this.fileData.get();
    }
    console.dir(data);
  }

  async parseOutputPath() {
    this.outputFilePath = path.parse(path.resolve(this.outputString));
    if (!this.outputFilePath.ext && !this.options.noExt && this.inputFilePath.ext) {
      this.outputFilePath.ext = this.inputFilePath.ext;
    }
    if (this.options.noMove) {
      this.outputFilePath.dir = this.inputFilePath.dir;
    }
    let ext = this.outputFilePath.ext || '';
    if (!ext && !this.options.noExt) { ext = this.inputFilePath.ext; }
    this.outputFileString = `${this.outputFilePath.dir}${path.sep}${this.outputFilePath.name}${ext}`;
    if (this.inputFileString.toLowerCase() !== this.outputFileString.toLowerCase()) {
      this.alreadyExists = await fs.pathExists(this.outputFileString);
      this.directoryExists = await fs.pathExists(this.outputFilePath.dir);
    } else { // prevent already exists warning if changing the case of a file name
      this.alreadyExists = false;
      this.directoryExists = true;
    }
  }

  async setIndex(index) {
    if (this.outputString.indexOf('--FILEINDEXHERE--') > -1) {
      this.outputString = this.outputString.replaceAll('--FILEINDEXHERE--', index);
    } else {
      this.outputString = appendToFileName(this.outputString, index);
    }
    await this.parseOutputPath();
  }

  setConflict(conflict) {
    this.conflict = conflict;
  }

  getOperationText() {
    return `${this.inputFileString.replace(CURRENT_DIR, '')} → ${this.outputFileString.replace(CURRENT_DIR, '')}`;
  }

  async run(batchId) {
    if (this.inputFileString.toLowerCase() !== this.outputFileString.toLowerCase()) {
      this.alreadyExists = await fs.pathExists(this.outputFileString);
    }
    if (this.alreadyExists && this.options.keep) {
      let newFileName;
      let appender = 0;
      do {
        appender += 1;
        newFileName = appendToFileName(this.outputString, `-${appender}`);
      } while(pathExists.sync(newFileName));
      this.outputString = newFileName;
      await this.parseOutputPath();
    }
    const operationText = this.getOperationText();
    if (this.options.ignoreDirectories && this.fileData.stats.isDirectory()) {
      if (this.options.verbose) console.log(chalk`{yellow Skipping ${this.inputFileString.replace(CURRENT_DIR, '')} because it is a directory}`);
      return;
    } else if (!this.options.simulate && !this.options.force && this.alreadyExists) {
      console.log(chalk`{red
${operationText}
  WARNING: ${this.outputFileString.replace(CURRENT_DIR, '')} already exists!}`);
      let response = readlineSync.keyInSelect(['Overwrite the file', 'Keep both files'], `What would you like to do?`, { cancel: 'Skip' });
      if (response === 0 && this.options.verbose) {
        console.log(chalk`{yellow Overwriting ${this.outputFileString.replace(CURRENT_DIR, '')}}`);
      } else if (response === 1) { // prompt for new file name
        let ext = this.outputFilePath.ext || '';
        if (!ext && !this.options.noExt) { ext = this.inputFilePath.ext; }
        const defaultInput = `${this.outputFilePath.dir}${path.sep}${this.outputFilePath.name}1${ext}`;
        this.outputString = readlineSync.question('Please input the desired file name (Default: $<defaultInput>): ', { defaultInput: defaultInput.replace(CURRENT_DIR, '') });
        await this.parseOutputPath();
        await this.run();
        return;
      } else if (response === -1) {
        if (this.options.verbose) console.log(`Skipping ${this.outputFileString.replace(CURRENT_DIR, '')}`);
        return;
      }
    } else if (!this.options.simulate && !this.options.force && !this.options.keep && this.conflict) {
      console.log(chalk`{keyword('orange')
${operationText}
  WARNING: This operation conflicts with other operations in this batch!
}`);
      if (!readlineSync.keyInYN(chalk.keyword('orange')('Would you like to proceed with this operation? [y/n]: '), { guide: false })) {
        if (this.options.verbose) console.log(`Skipping ${this.outputFileString.replace(CURRENT_DIR, '')}`);
        return;
      }
    } else if (!this.options.createDirs && !this.directoryExists) {
      console.log(chalk`{keyword('orange')
${operationText}
  WARNING: The directory does not exist!
}`);
      if (!readlineSync.keyInYN(chalk.keyword('orange')('Would you like to create the directory? [y/n]: '), { guide: false })) {
        if (this.options.verbose) console.log(`Skipping ${this.outputFileString.replace(CURRENT_DIR, '')}`);
        return;
      }
    } else if (this.options.verbose || this.options.simulate) {
      console.log(operationText);
    }
    if (this.options.simulate) return; // Don't perform rename
    // If it has made it this far, it's now time to rename
    if (!this.directoryExists) await fs.mkdirp(this.outputFilePath.dir);
    if (await fs.pathExists(this.inputFileString)) {
      const input = this.inputFileString.replace(/\\\[/g, '[').replace(/\\\]/g, ']');
      const output = this.outputFileString.replace(/\\\[/g, '[').replace(/\\\]/g, ']');
      await fs.rename(input, output);
      if (!this.options.noUndo && this.sequelize) { // write operations to database
        await this.sequelize.models.Op.create({
          input: input,
          output: output,
          BatchId: batchId
        });
      }
    } else if (this.options.verbose) {
      console.log(chalk`{yellow Skipping ${this.inputFileString.replace(CURRENT_DIR, '')} because the file no longer exists}`);
    }
  }
};

function appendToFileName(str, append) {
  let pathObj = path.parse(str);
  return `${pathObj.dir}${pathObj.dir !== '' ? path.sep : ''}${pathObj.name}${append}${pathObj.ext}`;
}


text:
package javactor.akka;

import java.util.concurrent.TimeUnit;

import javactor.JavactorContext.SupervisorStrategyInfo;
import javactor.JavactorContext.SupervisorStrategyType;

public class AllForOneTestJavactor extends SupervisorJavactor
{
	public SupervisorStrategyInfo supervisorStrategyInfo() {
		return SupervisorStrategyInfo.builder().type(SupervisorStrategyType.ALL_FOR_ONE)
			.retries(10, 1L, TimeUnit.MINUTES)
			.build();
	}
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\GoodsParamsNameSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'data_type') ?>

    <?= $form->field($model, 'required') ?>

    <?= $form->field($model, 'goods_param_namecol') ?>

    <?php // echo $form->field($model, 'sort') ?>

    <?php // echo $form->field($model, 'goods_type_type') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
var $ = require('gulp-load-plugins')();
var gulp = require('gulp');
var sequence = require('run-sequence');
var panini = require('panini');
var supercollider = require('supercollider');
var rimraf = require('rimraf');
var browser = require('browser-sync');
var foundationDocs = require('foundation-docs');
var octophant = require('octophant');
var inky = require('inky');
var siphon = require('siphon-media-query');
var lazypipe = require('lazypipe');
var fs = require('fs');
var yargs = require('yargs');

// Configuration for the documentation generator
supercollider
  .config({
    template: foundationDocs.componentTemplate,
    marked: foundationDocs.marked,
    handlebars: foundationDocs.handlebars,
    keepFm: true,
    quiet: false,
    pageRoot: 'docs/pages',
    data: {
      repoName: 'foundation-emails',
      editBranch: 'develop'
    }
  })
  .searchConfig({
    sort: ['page', 'component', 'sass variable', 'sass mixin', 'sass function', 'js class', 'js function', 'js plugin option', 'js event'],
    pageTypes: {
      library: function(item) {
        return !!(item.library);
      }
    }
  })
  .adapter('sass')
  .adapter('js');

// Cleans the build folder
gulp.task('clean', function(cb) {
  rimraf('_build', cb);
});

// Copies static documentation assets
gulp.task('copy', function() {
  return gulp.src(['docs/assets/**/*', '!docs/assets/scss/**/*', '!docs/assets/js/**/*'])
    .pipe(gulp.dest('_build/assets'));
  });

// Copies inky-browser
gulp.task('copy-inky', function() {
  return gulp.src(['node_modules/inky/dist/inky-browser.js'])
    .pipe(gulp.dest('_build/assets/js'));
});

// Builds documentation pages
gulp.task('html', function() {
  return gulp.src('docs/pages/**/*')
    .pipe($.cached('docs'))
    .pipe(supercollider.init())
    .pipe(panini({
      root: 'docs/pages/',
      layouts: 'docs/layouts/',
      partials: 'docs/partials/',
      helpers: foundationDocs.handlebarsHelpers
    }))
    .pipe(gulp.dest('_build'))
    .on('finish', function() {
      supercollider.buildSearch('_build/data/search.json', function() {});
    });
});

gulp.task('sass', ['sass:docs', 'sass:foundation']);

// Compiles documentation-specific CSS
gulp.task('sass:docs', function() {
  return gulp.src('docs/assets/scss/docs.scss')
    .pipe($.sass({ includePaths: [process.cwd()] }).on('error', $.sass.logError))
    .pipe($.autoprefixer({
      browsers: ['last 2 versions', 'ie >= 9']
    }))
    .pipe(gulp.dest('_build/assets/css'));
});

// Compiles Foundation-specific CSS
gulp.task('sass:foundation', function() {
  return gulp.src('scss/foundation-emails.scss')
    .pipe($.sass().on('error', $.sass.logError))
    .pipe(gulp.dest('_build/assets/css'));
});

// Compiles documentation JavaScript
gulp.task('javascript:docs', function() {
  return gulp.src(['node_modules/foundation-docs/js/*.js', 'docs/assets/js/**/*.js'])
    .pipe($.concat('docs.js'))
    .pipe(gulp.dest('_build/assets/js'));
});

// Generates a Sass settings file from the current codebase
gulp.task('settings', function() {
  octophant('scss/**/*.scss', {
    title: 'Foundation for Emails Settings',
    output: 'scss/settings/_settings.scss',
    sort: ['global', 'grid', 'block-grid', 'type']
  });
});

// Lints the Sass codebase
gulp.task('lint', function() {
  return gulp.src('scss/**/*.scss')
    .pipe($.sassLint())
    .pipe($.sassLint.format())
    .pipe($.sassLint.failOnError());
});

// Creates a BrowserSync server
gulp.task('server', ['build'], function() {
  browser.init({
    server: './_build',
    port: yargs.argv.port || 3001
  });
});

// Uploads the documentation to the live server
gulp.task('deploy:docs', ['build'], function() {
  return gulp.src('./_build/**')
    .pipe($.prompt.confirm('Make sure everything looks right before you deploy.'))
    .pipe($.rsync({
      root: './_build',
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-emails-march16'
    }));
});

// Runs the entire build process
gulp.task('build', function(cb) {
  sequence('clean', ['copy', 'copy-inky', 'html', 'sass', 'javascript:docs'], cb);
});

// Runs the build process, spins up a server, and watches for file changes
gulp.task('default', ['server'], function() {
  gulp.watch('docs/**/*', ['html', browser.reload]);
  gulp.watch(['docs/assets/scss/**/*', 'node_modules/foundation-docs/scss/**/*'], ['sass:docs', browser.reload]);
  gulp.watch('scss/**/*.scss', ['sass:foundation', browser.reload]);
});

gulp.task('test', ['sass', 'test:compile'], function() {
  browser.init({ server: 'test/visual/_build', directory: true });
  gulp.watch('scss/**/*.scss', ['sass:foundation', browser.reload]);
  gulp.watch('test/visual/pages/*.html', ['test:compile', browser.reload]);
});

gulp.task('test:compile', function() {
  gulp.src('test/visual/pages/*.html')
    .pipe($.wrap({ src: 'test/visual/_template.html' }))
    .pipe(inky())
    .pipe(inliner('_build/assets/css/foundation-emails.css'))
    .pipe(gulp.dest('test/visual/_build'));
});

gulp.task('templates', function() {
  return gulp.src('templates/*.html')
    .pipe($.wrap({ src: 'test/visual/_template.html' }))
    .pipe(inky())
    .pipe($.prettify({ indent_size: 2 }))
    .pipe(gulp.dest('.templates'))
    .pipe($.zip('all-templates.zip'))
    .pipe(gulp.dest('.templates'));
});

gulp.task('download:build:index', function() {
  return gulp.src('test/visual/_template.html', { base: 'test/visual' })
    .pipe($.injectString.replace('<%= contents %>', ''))
    .pipe($.injectString.replace('../assets/', ''))
    .pipe($.rename('index.html'))
    .pipe(gulp.dest('.download'));
});

gulp.task('download:build:templates', ['templates'], function() {
  return gulp.src('.templates/*.html')
    .pipe(gulp.dest('.download/templates'));
});

gulp.task('download:build:css', ['sass:foundation'], function() {
  return gulp.src('_build/assets/css/foundation-emails.css')
    .pipe(gulp.dest('.download/css'));
})

gulp.task('download:build', ['download:build:index', 'download:build:templates', 'download:build:css'], function() {
  return gulp.src('.download/**/*')
    .pipe($.zip('foundation-emails.zip'))
    .pipe(gulp.dest('.'));
});

gulp.task('download', ['download:build'], function(done) {
  return gulp.src('foundation-emails.zip')
    .pipe($.rsync({
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-sites-6-marketing/downloads/'
    }));
});

gulp.task('dist', ['sass:foundation'], function() {
  return gulp.src('_build/assets/css/foundation-emails.css')
    .pipe(gulp.dest('dist'))
    .pipe($.cssnano())
    .pipe($.rename('foundation-emails.min.css'))
    .pipe(gulp.dest('dist'));
});

function inliner(css) {
  var css = fs.readFileSync(css).toString();
  var mqCss = siphon(css);

  var pipe = lazypipe()
    .pipe($.inlineCss, {
      applyStyleTags: false,
      removeStyleTags: false,
      removeLinkTags: false
    })
    .pipe($.injectString.replace, '<!-- <style> -->', '<style>'+mqCss+'</style>')
    .pipe($.htmlmin, {
      collapseWhitespace: false,
      minifyCSS: false,
      maxLineLength: 800
    });

  return pipe();
}


text:
namespace absl {
ABSL_NAMESPACE_BEGIN

namespace flags_internal {
using FlagKindFilter = std::function<bool (absl::string_view)>;
}  // namespace flags_internal

// FlagsUsageConfig
//
// This structure contains the collection of callbacks for changing the behavior
// of the usage reporting routines in Abseil Flags.
struct FlagsUsageConfig {
  // Returns true if flags defined in the given source code file should be
  // reported with --helpshort flag. For example, if the file
  // "path/to/my/code.cc" defines the flag "--my_flag", and
  // contains_helpshort_flags("path/to/my/code.cc") returns true, invoking the
  // program with --helpshort will include information about --my_flag in the
  // program output.
  flags_internal::FlagKindFilter contains_helpshort_flags;

  // Returns true if flags defined in the filename should be reported with
  // --help flag. For example, if the file
  // "path/to/my/code.cc" defines the flag "--my_flag", and
  // contains_help_flags("path/to/my/code.cc") returns true, invoking the
  // program with --help will include information about --my_flag in the
  // program output.
  flags_internal::FlagKindFilter contains_help_flags;

  // Returns true if flags defined in the filename should be reported with
  // --helppackage flag. For example, if the file
  // "path/to/my/code.cc" defines the flag "--my_flag", and
  // contains_helppackage_flags("path/to/my/code.cc") returns true, invoking the
  // program with --helppackage will include information about --my_flag in the
  // program output.
  flags_internal::FlagKindFilter contains_helppackage_flags;

  // Generates string containing program version. This is the string reported
  // when user specifies --version in a command line.
  std::function<std::string()> version_string;

  // Normalizes the filename specific to the build system/filesystem used. This
  // routine is used when we report the information about the flag definition
  // location. For instance, if your build resides at some location you do not
  // want to expose in the usage output, you can trim it to show only relevant
  // part.
  // For example:
  //   normalize_filename("/my_company/some_long_path/src/project/file.cc")
  // might produce
  //   "project/file.cc".
  std::function<std::string(absl::string_view)> normalize_filename;
};

// SetFlagsUsageConfig()
//
// Sets the usage reporting configuration callbacks. If any of the callbacks are
// not set in usage_config instance, then the default value of the callback is
// used.
void SetFlagsUsageConfig(FlagsUsageConfig usage_config);

namespace flags_internal {

FlagsUsageConfig GetUsageConfig();

void ReportUsageError(absl::string_view msg, bool is_fatal);

}  // namespace flags_internal
ABSL_NAMESPACE_END
}  // namespace absl

extern "C" {

// Additional report of fatal usage error message before we std::exit. Error is
// fatal if is_fatal argument to ReportUsageError is true.
void AbslInternalReportFatalUsageError(absl::string_view);

}  // extern "C"

#endif  // ABSL_FLAGS_USAGE_CONFIG_H_


text:
cask :v1 => 'macbreakz' do
  version :latest
  sha256 :no_check

  url 'http://www.publicspace.net/download/MacBreakZ5.dmg'
  appcast 'http://www.publicspace.net/app/signed_mb5.xml'
  name 'MacBreakZ'
  homepage 'http://www.publicspace.net/MacBreakZ/'
  license :commercial

  app 'MacBreakZ 5.app'
end


text:
/** @module array */

/**
 * Converts a NodeList to an Array.
 *
 * @param nodeList - A NodeList.
 *
 * @example
 * ```js
 *
 * // => [div, div, …]
 * toArray(document.querySelectorAll('div'));
 * ```
 */
export function nodeListToArray(nodeList: NodeList): any[] {
  return Array.prototype.slice.call(nodeList);
}


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import os
import sys

import six

from asv import results

def test_results(tmpdir):
    envdir = six.text_type(tmpdir.join("env"))
    version = "{0[0]}.{0[1]}".format(sys.version_info)

    resultsdir = six.text_type(tmpdir.join("results"))
    for i in six.moves.xrange(10):
        r = results.Results(
            {'machine': 'foo',
             'arch': 'x86_64'},
            {},
            hex(i),
            i * 1000000,
            '2.7')
        for key, val in {
            'suite1.benchmark1': float(i * 0.001),
            'suite1.benchmark2': float(i * i * 0.001),
            'suite2.benchmark1': float((i + 1) ** -1)}.items():
            r.add_time(key, val)
        r.save(resultsdir)

        r2 = results.Results.load(
            os.path.join(resultsdir, r._filename))

        assert r2._results == r._results
        assert r2.date == r.date
        assert r2.commit_hash == r.commit_hash


text:
Docker Swarm
============

.. versionadded:: 1.3

`Docker Swarm <https://www.docker.com/products/docker-swarm/>`_ "provides
native clustering capabilities to turn a group of Docker engines into a single,
virtual Docker Engine."

As Swarm integration with Mesos is experimental, we haven't yet enabled that
feature.

Swarm is shipped as an addon, so please run this role after running the core
playbook (sample.yml or mantl.yml). The addon playbook (addons/docker-swarm.yml)
has to be copied to the project's root directory to be run.

Variables
---------

You can use these variables to customize your Swarm installation.

.. data:: swarm_manager_port

   The port that the swarm managers listen on. This is the port via which you'll
   communicate with the Swarm's Docker daemon, e.g.
   ``sudo docker -H :<swarm-manager-port> info``. Defaults to 4000.

.. data:: swarm_tls

   Use TLS to protect the agents' Docker socket exposed over TCP. It is highly
   recommended that you keep this as its default ``true``. This overrides the
   Docker role's ``docker_tcp_tls`` variable.

   Caution: If you didn't have Docker configured for TCP/TLS before installing
   this addon, this can stop all of your containers! See :docs:`docker`
   for more details.


text:
layout:     post
title:      "Wildlife Safaris-ii"
subtitle:   "Wildlife Safaris-Tigers"
author:     "Dinesh Balakrishnan"
header-thumb-img: "img/2016-01-13/Wildlife-safaris-Tigers-LaughingDove-Dinesh-Balakrishnan-thumb.jpg"
tags:       ["Wildlife Destinations", "Tiger Destinations", "Leopard Destinations"]
seo: 		["Wildlife Destinations", "Leopard Destinations", "Tiger Destinations"]
comments:   true
sharing-img: "img/2016-01-13/Wildlife-safaris-Tigers-LaughingDove-Dinesh-Balakrishnan.jpg"
---

We call it most famous tigers just because they are photographers friendly ? :)

See you next week.. Stay crazy.. :)


text:
package com.twitter.zipkin.common.json

import com.twitter.zipkin.common.Annotation

case class JsonSpan(
  traceId: String,
  name: String,
  id: String,
  parentId: Option[String],
  services: Set[String],
  startTimestamp: Long,
  duration: Long,
  annotations: List[Annotation],
  binaryAnnotations: Seq[JsonBinaryAnnotation])


text:
<?php

namespace Base;

use \Rfid as ChildRfid;
use \RfidQuery as ChildRfidQuery;
use \Exception;
use \PDO;
use Map\RfidTableMap;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;

/**
 * Base class that represents a query for the 'rfid' table.
 *
 *
 *
 * @method     ChildRfidQuery orderByRfid($order = Criteria::ASC) Order by the rfid column
 * @method     ChildRfidQuery orderByLdap($order = Criteria::ASC) Order by the ldap column
 *
 * @method     ChildRfidQuery groupByRfid() Group by the rfid column
 * @method     ChildRfidQuery groupByLdap() Group by the ldap column
 *
 * @method     ChildRfidQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
 * @method     ChildRfidQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
 * @method     ChildRfidQuery innerJoin($relation) Adds a INNER JOIN clause to the query
 *
 * @method     ChildRfidQuery leftJoinWith($relation) Adds a LEFT JOIN clause and with to the query
 * @method     ChildRfidQuery rightJoinWith($relation) Adds a RIGHT JOIN clause and with to the query
 * @method     ChildRfidQuery innerJoinWith($relation) Adds a INNER JOIN clause and with to the query
 *
 * @method     ChildRfid findOne(ConnectionInterface $con = null) Return the first ChildRfid matching the query
 * @method     ChildRfid findOneOrCreate(ConnectionInterface $con = null) Return the first ChildRfid matching the query, or a new ChildRfid object populated from the query conditions when no match is found
 *
 * @method     ChildRfid findOneByRfid(string $rfid) Return the first ChildRfid filtered by the rfid column
 * @method     ChildRfid findOneByLdap(string $ldap) Return the first ChildRfid filtered by the ldap column *

 * @method     ChildRfid requirePk($key, ConnectionInterface $con = null) Return the ChildRfid by primary key and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 * @method     ChildRfid requireOne(ConnectionInterface $con = null) Return the first ChildRfid matching the query and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 *
 * @method     ChildRfid requireOneByRfid(string $rfid) Return the first ChildRfid filtered by the rfid column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 * @method     ChildRfid requireOneByLdap(string $ldap) Return the first ChildRfid filtered by the ldap column and throws \Propel\Runtime\Exception\EntityNotFoundException when not found
 *
 * @method     ChildRfid[]|ObjectCollection find(ConnectionInterface $con = null) Return ChildRfid objects based on current ModelCriteria
 * @method     ChildRfid[]|ObjectCollection findByRfid(string $rfid) Return ChildRfid objects filtered by the rfid column
 * @method     ChildRfid[]|ObjectCollection findByLdap(string $ldap) Return ChildRfid objects filtered by the ldap column
 * @method     ChildRfid[]|\Propel\Runtime\Util\PropelModelPager paginate($page = 1, $maxPerPage = 10, ConnectionInterface $con = null) Issue a SELECT query based on the current ModelCriteria and uses a page and a maximum number of results per page to compute an offset and a limit
 *
 */
abstract class RfidQuery extends ModelCriteria
{
    protected $entityNotFoundExceptionClass = '\\Propel\\Runtime\\Exception\\EntityNotFoundException';

    /**
     * Initializes internal state of \Base\RfidQuery object.
     *
     * @param     string $dbName The database name
     * @param     string $modelName The phpName of a model, e.g. 'Book'
     * @param     string $modelAlias The alias for the model in this query, e.g. 'b'
     */
    public function __construct($dbName = 'soapy', $modelName = '\\Rfid', $modelAlias = null)
    {
        parent::__construct($dbName, $modelName, $modelAlias);
    }

    /**
     * Returns a new ChildRfidQuery object.
     *
     * @param     string $modelAlias The alias of a model in the query
     * @param     Criteria $criteria Optional Criteria to build the query from
     *
     * @return ChildRfidQuery
     */
    public static function create($modelAlias = null, Criteria $criteria = null)
    {
        if ($criteria instanceof ChildRfidQuery) {
            return $criteria;
        }
        $query = new ChildRfidQuery();
        if (null !== $modelAlias) {
            $query->setModelAlias($modelAlias);
        }
        if ($criteria instanceof Criteria) {
            $query->mergeWith($criteria);
        }

        return $query;
    }

    /**
     * Find object by primary key.
     * Propel uses the instance pool to skip the database if the object exists.
     * Go fast if the query is untouched.
     *
     *
     * $obj  = $c->findPk(12, $con);
     *
     *
     * @param mixed $key Primary key to use for the query
     * @param ConnectionInterface $con an optional connection object
     *
     * @return ChildRfid|array|mixed the result, formatted by the current formatter
     */
    public function findPk($key, ConnectionInterface $con = null)
    {
        if ($key === null) {
            return null;
        }
        if ((null !== ($obj = RfidTableMap::getInstanceFromPool(null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key))) && !$this->formatter) {
            // the object is already in the instance pool
            return $obj;
        }
        if ($con === null) {
            $con = Propel::getServiceContainer()->getReadConnection(RfidTableMap::DATABASE_NAME);
        }
        $this->basePreSelect($con);
        if ($this->formatter || $this->modelAlias || $this->with || $this->select
         || $this->selectColumns || $this->asColumns || $this->selectModifiers
         || $this->map || $this->having || $this->joins) {
            return $this->findPkComplex($key, $con);
        } else {
            return $this->findPkSimple($key, $con);
        }
    }

    /**
     * Find object by primary key using raw SQL to go fast.
     * Bypass doSelect() and the object formatter by using generated code.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     ConnectionInterface $con A connection object
     *
     * @throws \Propel\Runtime\Exception\PropelException
     *
     * @return ChildRfid A model object, or null if the key is not found
     */
    protected function findPkSimple($key, ConnectionInterface $con)
    {
        $sql = 'SELECT rfid, ldap FROM rfid WHERE rfid = :p0';
        try {
            $stmt = $con->prepare($sql);
            $stmt->bindValue(':p0', $key, PDO::PARAM_STR);
            $stmt->execute();
        } catch (Exception $e) {
            Propel::log($e->getMessage(), Propel::LOG_ERR);
            throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e);
        }
        $obj = null;
        if ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
            /** @var ChildRfid $obj */
            $obj = new ChildRfid();
            $obj->hydrate($row);
            RfidTableMap::addInstanceToPool($obj, null === $key || is_scalar($key) || is_callable([$key, '__toString']) ? (string) $key : $key);
        }
        $stmt->closeCursor();

        return $obj;
    }

    /**
     * Find object by primary key.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     ConnectionInterface $con A connection object
     *
     * @return ChildRfid|array|mixed the result, formatted by the current formatter
     */
    protected function findPkComplex($key, ConnectionInterface $con)
    {
        // As the query uses a PK condition, no limit(1) is necessary.
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $dataFetcher = $criteria
            ->filterByPrimaryKey($key)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher);
    }

    /**
     * Find objects by primary key
     *
     * $objs = $c->findPks(array(12, 56, 832), $con);
     *
     * @param     array $keys Primary keys to use for the query
     * @param     ConnectionInterface $con an optional connection object
     *
     * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter
     */
    public function findPks($keys, ConnectionInterface $con = null)
    {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getReadConnection($this->getDbName());
        }
        $this->basePreSelect($con);
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $dataFetcher = $criteria
            ->filterByPrimaryKeys($keys)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->format($dataFetcher);
    }

    /**
     * Filter the query by primary key
     *
     * @param     mixed $key Primary key to use for the query
     *
     * @return $this|ChildRfidQuery The current query, for fluid interface
     */
    public function filterByPrimaryKey($key)
    {

        return $this->addUsingAlias(RfidTableMap::COL_RFID, $key, Criteria::EQUAL);
    }

    /**
     * Filter the query by a list of primary keys
     *
     * @param     array $keys The list of primary key to use for the query
     *
     * @return $this|ChildRfidQuery The current query, for fluid interface
     */
    public function filterByPrimaryKeys($keys)
    {

        return $this->addUsingAlias(RfidTableMap::COL_RFID, $keys, Criteria::IN);
    }

    /**
     * Filter the query on the rfid column
     *
     * Example usage:
     *
     * $query->filterByRfid('fooValue');   // WHERE rfid = 'fooValue'
     * $query->filterByRfid('%fooValue%'); // WHERE rfid LIKE '%fooValue%'
     *
     *
     * @param     string $rfid The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return $this|ChildRfidQuery The current query, for fluid interface
     */
    public function filterByRfid($rfid = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($rfid)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $rfid)) {
                $rfid = str_replace('*', '%', $rfid);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(RfidTableMap::COL_RFID, $rfid, $comparison);
    }

    /**
     * Filter the query on the ldap column
     *
     * Example usage:
     *
     * $query->filterByLdap('fooValue');   // WHERE ldap = 'fooValue'
     * $query->filterByLdap('%fooValue%'); // WHERE ldap LIKE '%fooValue%'
     *
     *
     * @param     string $ldap The value to use as filter.
     *              Accepts wildcards (* and % trigger a LIKE)
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return $this|ChildRfidQuery The current query, for fluid interface
     */
    public function filterByLdap($ldap = null, $comparison = null)
    {
        if (null === $comparison) {
            if (is_array($ldap)) {
                $comparison = Criteria::IN;
            } elseif (preg_match('/[\%\*]/', $ldap)) {
                $ldap = str_replace('*', '%', $ldap);
                $comparison = Criteria::LIKE;
            }
        }

        return $this->addUsingAlias(RfidTableMap::COL_LDAP, $ldap, $comparison);
    }

    /**
     * Exclude object from result
     *
     * @param   ChildRfid $rfid Object to remove from the list of results
     *
     * @return $this|ChildRfidQuery The current query, for fluid interface
     */
    public function prune($rfid = null)
    {
        if ($rfid) {
            $this->addUsingAlias(RfidTableMap::COL_RFID, $rfid->getRfid(), Criteria::NOT_EQUAL);
        }

        return $this;
    }

    /**
     * Deletes all rows from the rfid table.
     *
     * @param ConnectionInterface $con the connection to use
     * @return int The number of affected rows (if supported by underlying database driver).
     */
    public function doDeleteAll(ConnectionInterface $con = null)
    {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getWriteConnection(RfidTableMap::DATABASE_NAME);
        }

        // use transaction because $criteria could contain info
        // for more than one table or we could emulating ON DELETE CASCADE, etc.
        return $con->transaction(function () use ($con) {
            $affectedRows = 0; // initialize var to track total num of affected rows
            $affectedRows += parent::doDeleteAll($con);
            // Because this db requires some delete cascade/set null emulation, we have to
            // clear the cached instance *after* the emulation has happened (since
            // instances get re-added by the select statement contained therein).
            RfidTableMap::clearInstancePool();
            RfidTableMap::clearRelatedInstancePool();

            return $affectedRows;
        });
    }

    /**
     * Performs a DELETE on the database based on the current ModelCriteria
     *
     * @param ConnectionInterface $con the connection to use
     * @return int             The number of affected rows (if supported by underlying database driver).  This includes CASCADE-related rows
     *                         if supported by native driver or if emulated using Propel.
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
    public function delete(ConnectionInterface $con = null)
    {
        if (null === $con) {
            $con = Propel::getServiceContainer()->getWriteConnection(RfidTableMap::DATABASE_NAME);
        }

        $criteria = $this;

        // Set the correct dbName
        $criteria->setDbName(RfidTableMap::DATABASE_NAME);

        // use transaction because $criteria could contain info
        // for more than one table or we could emulating ON DELETE CASCADE, etc.
        return $con->transaction(function () use ($con, $criteria) {
            $affectedRows = 0; // initialize var to track total num of affected rows

            RfidTableMap::removeInstanceFromPool($criteria);

            $affectedRows += ModelCriteria::delete($con);
            RfidTableMap::clearRelatedInstancePool();

            return $affectedRows;
        });
    }

} // RfidQuery


text:
describe('unit test:permissions dao', function () {

    var permissionsDao;
    var RESOURCE;
    var server;

    var settingsParams = {

    };

    // inject the main module
    beforeEach(m('artifactory.dao'));

    // run this code before each case
    beforeEach(inject(function ($injector) {
        permissionsDao = $injector.get('PermissionsDao').getInstance();
        RESOURCE = $injector.get('RESOURCE');
        server = $injector.get('$httpBackend');
    }));

    it('permissionsDao should return a resource object', function () {
        expect(permissionsDao.name).toBe('Resource');
    });
    it('permissionsDao should return a resource object', function () {
        server.expectGET(RESOURCE.API_URL +RESOURCE.TARGET_PERMISSIONS +'/crud/Anything').respond(200);
        permissionsDao.getPermission({name: 'Anything'});
        server.flush();
    });
});


text:
#ifndef INCLUDES_BEE_RANDOM_H
#define INCLUDES_BEE_RANDOM_H

#include <stddef.h>

#if defined(__cplusplus)
extern "C" {
#endif
void
random_init(void);

void
random_free(void);

void
random_bytes(char *buf, size_t size);

#if defined(__cplusplus)
}
#endif /* extern "C" */
#endif /* INCLUDES_BEE_RANDOM_H */


text:
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { toastr } from 'react-redux-toastr';

import remark from 'remark';
import remarkReact from 'remark-react';
import githubSanitize from 'hast-util-sanitize/lib/github.json';

import merge from 'deepmerge';

import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

import inlineMath from './inline-math';
import { Equation, InlineEquation } from './equation';

import './markdown.scss';

const escape = (html, encode) => (
  html
  .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
  .replace(/</g, '<')
  .replace(/>/g, '>')
  .replace(/"/g, '"')
  .replace(/'/g, ''')
);

// Code
// Renders code highilighted according to its language. Custom languages are:
//  - equation: render Latex equation with katex
//  - warning: render a warning block
const renderCode = (code, lang, key) => {
  // Equation
  if (lang === 'equation') {
    return <Equation equation={code} key={key} />;
  }

  if (lang === 'inlineEquation') {
    return <InlineEquation equation={code} key={key} />;
  }

  // Warning
  if (lang === 'warning') {
    const warning = (

        {code}

    );
    return warning;
  }

  // Standard code
  const codeClass = {};
  if (lang) {
    codeClass[escape(lang, true)] = true;
  }
  let escapedCode = code;
  if (lang) {
    try {
      escapedCode = hljs.highlight(lang, code).value;
    } catch (e) {
      toastr.error('', `Error highlighting syntax: ${e}`);
    }
  } else {
    escapedCode = escape(code, true);
  }
  return (

  );
};

const createElement = (name, attrs, children) => {
  const langPrefix = 'language-';
  switch (name) {
    case 'code':
      return renderCode(
        children[0],
        attrs.className ? attrs.className.substring(langPrefix.length) : undefined,
        attrs.key,
      );
    default:
  }
  return React.createElement(name, attrs, children);
};

const Markdown = ({ text, className }) => {
  const sanitize = merge(githubSanitize, { attributes: { '*': ['className'] } });
  const md = remark().use(inlineMath).use(remarkReact, {
    createElement,
    sanitize,
  }).process(text).contents;

  return <div className={`Markdown ${className}`}>{md}
;
};

Markdown.propTypes = {
  className: PropTypes.string,
  text: PropTypes.string.isRequired,
};

Markdown.defaultProps = {
  className: '',
};

export default Markdown;


text:
module VMware
module Vix

  class Host < Handle
    def self.connect_workstation
      job = Vix::Job.call(
          :VixHost_Connect,
          LibVix::API_VERSION,
          :vmware_workstation,
          nil, 0, # no connection info
          nil, nil, # no auth info
          0, # options
          LibVix::INVALID_HANDLE # no properties
        )

      job.property :job_result_handle
    end

    def self.finalizer (handle)
      # for reasons I don't entirely understand, hosts require
      # VixHost_Disconnect but not Vix_ReleaseRef
      proc { LibVix.VixHost_Disconnect( handle ) }
    end

    def open (path)
      job = Vix::Job.call(
          :VixHost_OpenVM,
          @handle, path,
          :normal, # no options
          LibVix::INVALID_HANDLE # no properties
        )

      job.property :job_result_handle
    end
  end

end # module Vix
end # module VMware


text:
module Searchgasm
  module Modifiers
    class Hex < Base
      class << self
        def return_type
          :string
        end
      end
    end
  end
end


text:
namespace NLog.LayoutRenderers
{
    using System;
    using System.Globalization;
    using System.Text;
    using NLog.Config;

    /// <summary>
    /// Log event context data.
    /// </summary>
    /// <remarks>This class was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks>
    [LayoutRenderer("event-context")]
    [Obsolete("Use EventPropertiesLayoutRenderer class instead. Marked obsolete on NLog 2.0")]
    public class EventContextLayoutRenderer : LayoutRenderer
    {
        /// <summary>
        /// Gets or sets the name of the item.
        /// </summary>
        /// <docgen category='Rendering Options' order='10' />
        [RequiredParameter]
        [DefaultParameter]
        public string Item { get; set; }

        /// <summary>
        /// Renders the specified log event context item and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            object value;

            if (logEvent.HasProperties && logEvent.Properties.TryGetValue(this.Item, out value))
            {
                var formatProvider = GetFormatProvider(logEvent);
                builder.Append(Convert.ToString(value, formatProvider));
            }
        }
    }
}


text:
package com.amazonaws.services.keyspaces.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.keyspaces.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * RestoreTableRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RestoreTableRequestMarshaller {

    private static final MarshallingInfo<String> SOURCEKEYSPACENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("sourceKeyspaceName").build();
    private static final MarshallingInfo<String> SOURCETABLENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("sourceTableName").build();
    private static final MarshallingInfo<String> TARGETKEYSPACENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("targetKeyspaceName").build();
    private static final MarshallingInfo<String> TARGETTABLENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("targetTableName").build();
    private static final MarshallingInfo<java.util.Date> RESTORETIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("restoreTimestamp").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<StructuredPojo> CAPACITYSPECIFICATIONOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("capacitySpecificationOverride").build();
    private static final MarshallingInfo<StructuredPojo> ENCRYPTIONSPECIFICATIONOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("encryptionSpecificationOverride").build();
    private static final MarshallingInfo<StructuredPojo> POINTINTIMERECOVERYOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("pointInTimeRecoveryOverride").build();
    private static final MarshallingInfo<List> TAGSOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("tagsOverride").build();

    private static final RestoreTableRequestMarshaller instance = new RestoreTableRequestMarshaller();

    public static RestoreTableRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(RestoreTableRequest restoreTableRequest, ProtocolMarshaller protocolMarshaller) {

        if (restoreTableRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(restoreTableRequest.getSourceKeyspaceName(), SOURCEKEYSPACENAME_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getSourceTableName(), SOURCETABLENAME_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getTargetKeyspaceName(), TARGETKEYSPACENAME_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getTargetTableName(), TARGETTABLENAME_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getRestoreTimestamp(), RESTORETIMESTAMP_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getCapacitySpecificationOverride(), CAPACITYSPECIFICATIONOVERRIDE_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getEncryptionSpecificationOverride(), ENCRYPTIONSPECIFICATIONOVERRIDE_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getPointInTimeRecoveryOverride(), POINTINTIMERECOVERYOVERRIDE_BINDING);
            protocolMarshaller.marshall(restoreTableRequest.getTagsOverride(), TAGSOVERRIDE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
# Commerce Admin

> see https://aka.ms/autorest

This is the AutoRest configuration file for Commerce Admin. We do not ship any language SDKs for AzureStack Administrator APIs and these APIs do not exist in azure.

---
## Getting Started
To build the SDK for Commerce Admin, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`
---

## Configuration

### Basic Information
These are the global settings for the Commerce API.

``` yaml
title: CommerceAdminClient
description: Commerce Admin Client
openapi-type: arm
tag: package-2015-06-01-preview
```

### Tag: package-2015-06-01-preview

These settings apply only when `--tag=package-2015-06-01-preview` is specified on the command line.

``` yaml $(tag) == 'package-2015-06-01-preview'
input-file:
    - Microsoft.Commerce.Admin/preview/2015-06-01-preview/Commerce.json
```

---
# Code Generation

## C#

``` yaml $(csharp)
csharp:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: Microsoft.AzureStack.Management.Commerce.Admin
  payload-flattening-threshold: 1
  output-folder: $(csharp-sdks-folder)/Generated
  clear-output-folder: true
```

## Multi-API/Profile support for AutoRest v3 generators

AutoRest V3 generators require the use of `--tag=all-api-versions` to select api files.

This block is updated by an automatic script. Edits may be lost!

``` yaml $(tag) == 'all-api-versions' /* autogenerated */
# include the azure profile definitions from the standard location
require: $(this-folder)/../../../../profiles/readme.md

# all the input files across all versions
input-file:
  - $(this-folder)/Microsoft.Commerce.Admin/preview/2015-06-01-preview/Commerce.json

```

If there are files that should not be in the `all-api-versions` set,
uncomment the  `exclude-file` section below and add the file paths.

``` yaml $(tag) == 'all-api-versions'
#exclude-file:
#  - $(this-folder)/Microsoft.Example/stable/2010-01-01/somefile.json
```


text:
package edu.gemini.spModel.core

import scalaz._, Scalaz._

/**
 * Unique Horizons designation, which should allow for reproduceable ephemeris queries <b>if</b> the
 * values passed to the constructors are extracted correctly from search results. See `horizons.md`
 * in the bundle source for more information.
 */
sealed abstract class HorizonsDesignation(val queryString: String)
  extends Product with Serializable {
    def des: String // designation, human readable

    import edu.gemini.spModel.core.HorizonsDesignation._

    /** Exports an HorizonsDesignation to a String in a format that can be read
      * by the `HorizonsDesignation.read` method.
      */
    def show: String =
      this match {
        case Comet(des)            => s"Comet_$des"
        case AsteroidNewStyle(des) => s"AsteroidNew_$des"
        case AsteroidOldStyle(num) => s"AsteroidOld_$num"
        case MajorBody(num)        => s"MajorBody_$num"
      }
  }

object HorizonsDesignation {

  /**
   * Designation for a comet, in the current apparition. Example: `C/1973 E1` for Kohoutek, yielding
   * the query string `NAME=C/1973 E1;CAP`.
   */
  final case class Comet(des: String) extends HorizonsDesignation(s"NAME=$des;CAP")
  object Comet {
    val des: Comet @> String = Lens.lensu((a, b) => a.copy(des = b), _.des)
  }

  sealed abstract class Asteroid(s: String) extends HorizonsDesignation(s)

  /**
   * Designation for an asteroid under modern naming conventions. Example: `1971 UC1` for
   * 1896 Beer, yielding a query string `ASTNAM=1971 UC1`.
   */
  final case class AsteroidNewStyle(des: String) extends Asteroid(s"ASTNAM=$des")
  object AsteroidNewStyle {
    val des: AsteroidNewStyle @> String = Lens.lensu((a, b) => a.copy(des = b), _.des)
  }

  /**
   * Designation for an asteroid under "old" naming conventions. These are small numbers. Example:
   * `4` for Vesta, yielding a query string `4;`
   */
  final case class AsteroidOldStyle(num: Int) extends Asteroid(s"$num;") {
    def des = num.toString
  }
  object AsteroidOldStyle {
    val num: AsteroidOldStyle @> Int = Lens.lensu((a, b) => a.copy(num = b), _.num)
  }

  /**
   * Designation for a major body (planet or satellite thereof). These have small numbers. Example:
   * `606` for Titan, yielding a query string `606`.
   */
  final case class MajorBody(num: Int) extends HorizonsDesignation(s"$num") {
    def des = num.toString
  }
  object MajorBody {
    val num: MajorBody @> Int = Lens.lensu((a, b) => a.copy(num = b), _.num)
  }

  private val CometRegex       = """Comet_(.+)""".r
  private val AsteroidRegex    = """AsteroidNew_(.+)""".r
  private val AsteroidNumRegex = """AsteroidOld_(-?\d+)""".r
  private val MajorRegex       = """MajorBody_(-?\d+)""".r

  /** Extracts an HorizonsDesignation from a String written by the `show`
    * method, if possible.
    */
  def read(s: String): Option[HorizonsDesignation] = s match {
    case CometRegex(des)     => some(Comet(des))
    case AsteroidRegex(des)  => some(AsteroidNewStyle(des))
    case AsteroidNumRegex(i) => some(AsteroidOldStyle(i.toInt))
    case MajorRegex(i)       => some(MajorBody(i.toInt))
    case _                   => none
  }
}


text:
<?php

/**
 * Setup the configuration for your database.
 */

// MySQL constants
const SQL_DRIVER    = 'mysql';
const DB_ROOT_USER  = 'root_username';
const DB_ROOT_PASS  = 'root_password';
const DB_HOST       = 'localhost';
const DB_USER       = 'username';
const DB_PASS       = 'password';
const DB_NAME       = 'customer_solutions';

/**
 *  NOTE: Make sure the key value for your array entry matches the
 *  name of your table for your CREATE TABLE statement. (case-sensative)
 */
// setup database data (MySQL syntax)
$database = array(
  // !!! DO NOT REMOVE/ALTER THE 'admins' TABLE!!!
  'admins' =>
  'CREATE TABLE IF NOT EXISTS admins(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    fullname TEXT NOT NULL,
    email TEXT NOT NULL,
    username TEXT NOT NULL,
    password TEXT NOT NULL,
    PRIMARY KEY (id)
  ) ENGINE = InnoDB;',
  // !!! DO NOT REMOVE/ALTER THE 'admins' TABLE!!!

  'customer_tools' =>
  'CREATE TABLE IF NOT EXISTS customer_tools(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    filename TEXT NOT NULL,
    toolname TEXT NOT NULL,
    description TEXT NOT NULL,
    PRIMARY KEY (id)
  ) ENGINE = InnoDB;',

  'customers' =>
  'CREATE TABLE IF NOT EXISTS customers(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    company_name TEXT NOT NULL,
    contact_name TEXT NOT NULL,
    phone TEXT NOT NULL,
    email TEXT NOT NULL,
    password TEXT NOT NULL,
    PRIMARY KEY (id)
  ) ENGINE = InnoDB;',

  'customer_data_status' =>
  'CREATE TABLE IF NOT EXISTS customer_data_status(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    status TEXT NOT NULL,
    PRIMARY KEY (id)
  ) ENGINE = InnoDB;',

  'customer_data' =>
  'CREATE TABLE IF NOT EXISTS customer_data(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    customer INT UNSIGNED NOT NULL,
    filename TEXT NOT NULL,
    filesize INT UNSIGNED NOT NULL,
    filetype TEXT NOT NULL,
    status INT UNSIGNED NOT NULL,
    upload_date INT UNSIGNED NOT NULL,
    completed_date INT UNSIGNED NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY(customer) REFERENCES customers(id),
    FOREIGN KEY(status) REFERENCES customer_data_status(id)
  ) ENGINE = InnoDB;',
);

// setup table inserts
$inserts = array(
  'needs_review' =>
  'INSERT INTO customer_data_status(id, status)
    VALUES(1, "Needs Review")',

  'under_review' =>
  'INSERT INTO customer_data_status(id, status)
    VALUES(2, "Under Review")',

  'file_repaired' =>
  'INSERT INTO customer_data_status(id, status)
    VALUES(3, "File Repaired")',

  'file_corrupted' =>
  'INSERT INTO customer_data_status(id, status)
    VALUES(4, "File Corrupted")',

  'no_problem_found' =>
  'INSERT INTO customer_data_status(id, status)
    VALUES(5, "No Problem Found")',
);

?>


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

<title>commands Class Hierarchy</title>
<meta name="date" content="2015-03-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package commands

Class Hierarchy

java.lang.Object

tree.TreeNode

tree.CommandNode

commands.And

commands.ArcTangent

commands.Ask

commands.Backward

commands.ClearScreen

commands.ClearStamp

commands.Cosine

commands.Difference

commands.DoTimes

commands.For

commands.Repeat

commands.Equal

commands.Forward

commands.GreaterThan

commands.Heading

commands.HideTurtle

commands.Home

commands.ID

commands.If

commands.IfElse

commands.IsPenDown

commands.IsShowing

commands.Left

commands.LessThan

commands.MakeUserInstruction

commands.MakeVariable

commands.Minus

commands.NaturalLog

commands.Not

commands.NotEqual

commands.Or

commands.PenColor

commands.PenDown

commands.PenUp

commands.Pi

commands.Power

commands.Product

commands.Quotient

commands.Random

commands.Remainder

commands.Right

commands.SetBackground

commands.SetHeading

commands.SetPallet

commands.SetPenColor

commands.SetPenSize

commands.SetPosition

commands.SetShape

commands.SetTowards

commands.Shape

commands.ShowTurtle

commands.Sine

commands.Stamp

commands.Sum

commands.Tangent

commands.Tell

commands.Turtles

commands.XCoordinate

commands.YCoordinate

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
define([
    'underscore',
    'jquery',
    'backbone',
    'find/app/util/search-data-util',
    'find/app/page/search/filters/parametric/parametric-select-modal-list-view',
    './parametric-paginator',
    'text!find/templates/app/page/search/filters/parametric/parametric-select-modal-view.html',
    'iCheck'
], function(_, $, Backbone, searchDataUtil, ParametricSelectModalListView, ParametricPaginator, template) {
    'use strict';

    return Backbone.View.extend({
        template: _.template(template),
        className: 'full-height',

        events: {
            'click .fields-list a': function(e) {
                e.preventDefault();
                this.fieldSelectionModel.set('field', $(e.currentTarget).closest('[data-field]').attr('data-field'));
            }
        },

        initialize: function(options) {
            const fetchRestrictions = {
                databases: options.queryModel.get('indexes'),
                queryText: options.queryModel.get('autoCorrect') && options.queryModel.get('correctedQuery')
                    ? options.queryModel.get('correctedQuery')
                    : options.queryModel.get('queryText'),
                fieldText: options.queryModel.get('fieldText'),
                minDate: options.queryModel.getIsoDate('minDate'),
                maxDate: options.queryModel.getIsoDate('maxDate'),
                minScore: options.queryModel.get('minScore'),
                stateTokens: options.queryModel.get('stateMatchIds')
            };

            const allIndexes = searchDataUtil.buildIndexes(options.indexesCollection.map(function(model) {
                return model.pick('domain', 'name');
            }));

            this.fieldData = options.parametricFieldsCollection.where({type: 'Parametric'}).map(function(fieldModel) {
                const paginator = new ParametricPaginator({
                    fieldName: fieldModel.id,
                    fieldDisplayName: fieldModel.get('displayName'),
                    allIndexes: allIndexes,
                    selectedValues: options.selectedParametricValues,
                    fetchRestrictions: fetchRestrictions,
                    fetchFunction: function(origData) {
                        const data = _.extend({
                            sort: options.parametricValuesSort
                        }, origData);

                        return $.ajax({url: 'api/public/parametric/values', traditional: true, data: data})
                            .then(function(response) {
                                return {
                                    totalValues: response[0] ? response[0].totalValues : 0,
                                    values: response[0] ? response[0].values : []
                                };
                            });
                    }
                });

                return {
                    id: fieldModel.id,
                    displayName: fieldModel.get('displayName'),
                    view: new ParametricSelectModalListView({paginator: paginator})
                };
            }.bind(this));

            this.fieldSelectionModel = new Backbone.Model({field: options.initialField});
            this.listenTo(this.fieldSelectionModel, 'change', this.updateSelectedField);
        },

        render: function() {
            this.$el.html(this.template({
                initialField: this.initialField,
                fields: this.fieldData
            }));

            const $tabContent = this.$('.tab-content');

            this.fieldData.forEach(function(data) {
                $tabContent.append(data.view.$el);
                data.view.render();
            });

            this.updateSelectedField();

            this.$el.tooltip({
                selector: '[data-toggle="tooltip"]',
                container: this.$el
            })
        },

        checkScroll: function() {
            _.findWhere(this.fieldData, {id: this.fieldSelectionModel.get('field')}).view.checkScroll();
        },

        updateSelectedField: function() {
            const currentField = this.fieldSelectionModel.get('field');

            this.$('.fields-list li:not([data-field="' + currentField + '"])').removeClass('active');
            this.$('.fields-list li[data-field="' + currentField + '"]').addClass('active');

            this.fieldData.forEach(function(data) {
                const isCurrentField = data.id === currentField;
                data.view.$el.toggleClass('active', isCurrentField);

                if(isCurrentField) {
                    // Check scroll after showing the view so it can check if more values need to be fetched
                    data.view.checkScroll();
                }
            });
        },

        remove: function() {
            this.fieldData.forEach(function(data) {
                data.view.remove();
            });

            Backbone.View.prototype.remove.call(this);
        }
    });
});